utils.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Static class utils
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once(APPROOT.'/core/config.class.inc.php');
  25. require_once(APPROOT.'/application/transaction.class.inc.php');
  26. define('ITOP_CONFIG_FILE', APPROOT.'/config-itop.php');
  27. class FileUploadException extends Exception
  28. {
  29. }
  30. /**
  31. * Helper functions to interact with forms: read parameters, upload files...
  32. * @package iTop
  33. */
  34. class utils
  35. {
  36. private static $m_sConfigFile = ITOP_CONFIG_FILE;
  37. private static $m_oConfig = null;
  38. // Parameters loaded from a file, parameters of the page/command line still have precedence
  39. private static $m_aParamsFromFile = null;
  40. protected static function LoadParamFile($sParamFile)
  41. {
  42. if (!file_exists($sParamFile))
  43. {
  44. throw new Exception("Could not find the parameter file: '$sParamFile'");
  45. }
  46. if (!is_readable($sParamFile))
  47. {
  48. throw new Exception("Could not load parameter file: '$sParamFile'");
  49. }
  50. $sParams = file_get_contents($sParamFile);
  51. if (is_null(self::$m_aParamsFromFile))
  52. {
  53. self::$m_aParamsFromFile = array();
  54. }
  55. $aParamLines = explode("\n", $sParams);
  56. foreach ($aParamLines as $sLine)
  57. {
  58. $sLine = trim($sLine);
  59. // Ignore the line after a '#'
  60. if (($iCommentPos = strpos($sLine, '#')) !== false)
  61. {
  62. $sLine = substr($sLine, 0, $iCommentPos);
  63. $sLine = trim($sLine);
  64. }
  65. // Note: the line is supposed to be already trimmed
  66. if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches))
  67. {
  68. $sParam = $aMatches[1];
  69. $value = trim($aMatches[2]);
  70. self::$m_aParamsFromFile[$sParam] = $value;
  71. }
  72. }
  73. }
  74. public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
  75. {
  76. $sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI);
  77. foreach(explode(',', $sFileSpec) as $sFile)
  78. {
  79. $sFile = trim($sFile);
  80. if (!empty($sFile))
  81. {
  82. self::LoadParamFile($sFile);
  83. }
  84. }
  85. }
  86. public static function IsModeCLI()
  87. {
  88. $sSAPIName = php_sapi_name();
  89. $sCleanName = strtolower(trim($sSAPIName));
  90. if ($sCleanName == 'cli')
  91. {
  92. return true;
  93. }
  94. else
  95. {
  96. return false;
  97. }
  98. }
  99. public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false)
  100. {
  101. global $argv;
  102. $retValue = $defaultValue;
  103. if (!is_null(self::$m_aParamsFromFile))
  104. {
  105. if (isset(self::$m_aParamsFromFile[$sName]))
  106. {
  107. $retValue = self::$m_aParamsFromFile[$sName];
  108. }
  109. }
  110. if (isset($_REQUEST[$sName]))
  111. {
  112. $retValue = $_REQUEST[$sName];
  113. }
  114. elseif ($bAllowCLI && isset($argv))
  115. {
  116. foreach($argv as $iArg => $sArg)
  117. {
  118. if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
  119. {
  120. $retValue = $aMatches[1];
  121. }
  122. }
  123. }
  124. return $retValue;
  125. }
  126. public static function ReadPostedParam($sName, $defaultValue = "")
  127. {
  128. return isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  129. }
  130. /**
  131. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  132. * @param string $sName Name of the input used from uploading the file
  133. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  134. */
  135. public static function ReadPostedDocument($sName)
  136. {
  137. $oDocument = new ormDocument(); // an empty document
  138. if(isset($_FILES[$sName]))
  139. {
  140. switch($_FILES[$sName]['error'])
  141. {
  142. case UPLOAD_ERR_OK:
  143. $doc_content = file_get_contents($_FILES[$sName]['tmp_name']);
  144. $sMimeType = $_FILES[$sName]['type'];
  145. if (function_exists('finfo_file'))
  146. {
  147. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  148. // in which case we don't trust the mime type provided by the browser
  149. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  150. if ($rInfo !== false)
  151. {
  152. $sType = @finfo_file($rInfo, $file);
  153. if ( ($sType !== false)
  154. && is_string($sType)
  155. && (strlen($sType)>0))
  156. {
  157. $sMimeType = $sType;
  158. }
  159. }
  160. @finfo_close($rInfo);
  161. }
  162. $oDocument = new ormDocument($doc_content, $sMimeType, $_FILES[$sName]['name']);
  163. break;
  164. case UPLOAD_ERR_NO_FILE:
  165. // no file to load, it's a normal case, just return an empty document
  166. break;
  167. case UPLOAD_ERR_FORM_SIZE:
  168. case UPLOAD_ERR_INI_SIZE:
  169. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  170. break;
  171. case UPLOAD_ERR_PARTIAL:
  172. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  173. break;
  174. case UPLOAD_ERR_NO_TMP_DIR:
  175. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  176. break;
  177. case UPLOAD_ERR_CANT_WRITE:
  178. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  179. break;
  180. case UPLOAD_ERR_EXTENSION:
  181. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $_FILES[$sName]['name']));
  182. break;
  183. default:
  184. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $_FILES[$sName]['error']));
  185. break;
  186. }
  187. }
  188. return $oDocument;
  189. }
  190. public static function GetNewTransactionId()
  191. {
  192. return privUITransaction::GetNewTransactionId();
  193. }
  194. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  195. {
  196. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  197. }
  198. public static function RemoveTransaction($sId)
  199. {
  200. return privUITransaction::RemoveTransaction($sId);
  201. }
  202. public static function ReadFromFile($sFileName)
  203. {
  204. if (!file_exists($sFileName)) return false;
  205. return file_get_contents($sFileName);
  206. }
  207. /**
  208. * Helper function to convert a value expressed in a 'user friendly format'
  209. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  210. * @param mixed $value The value as read from php.ini
  211. * @return number
  212. */
  213. public static function ConvertToBytes( $value )
  214. {
  215. $iReturn = $value;
  216. if ( !is_numeric( $value ) )
  217. {
  218. $iLength = strlen( $value );
  219. $iReturn = substr( $value, 0, $iLength - 1 );
  220. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  221. switch ( $sUnit )
  222. {
  223. case 'G':
  224. $iReturn *= 1024;
  225. case 'M':
  226. $iReturn *= 1024;
  227. case 'K':
  228. $iReturn *= 1024;
  229. }
  230. }
  231. return $iReturn;
  232. }
  233. /**
  234. * Helper function to convert a string to a date, given a format specification. It replaces strtotime which does not allow for specifying a date in a french format (for instance)
  235. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  236. * @param string $sDate
  237. * @param string $sFormat
  238. * @return timestamp or false if the input format is not correct
  239. */
  240. public static function StringToTime($sDate, $sFormat)
  241. {
  242. // Source: http://php.net/manual/fr/function.strftime.php
  243. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  244. static $aDateTokens = null;
  245. static $aDateRegexps = null;
  246. if (is_null($aDateTokens))
  247. {
  248. $aSpec = array(
  249. '%d' =>'(?<day>[0-9]{2})',
  250. '%m' => '(?<month>[0-9]{2})',
  251. '%y' => '(?<year>[0-9]{2})',
  252. '%Y' => '(?<year>[0-9]{4})',
  253. '%H' => '(?<hour>[0-2][0-9])',
  254. '%i' => '(?<minute>[0-5][0-9])',
  255. '%s' => '(?<second>[0-5][0-9])',
  256. );
  257. $aDateTokens = array_keys($aSpec);
  258. $aDateRegexps = array_values($aSpec);
  259. }
  260. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  261. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  262. {
  263. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  264. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  265. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  266. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  267. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  268. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  269. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  270. }
  271. else
  272. {
  273. return false;
  274. }
  275. // http://www.spaweditor.com/scripts/regex/index.php
  276. }
  277. /**
  278. * Returns an absolute URL to the current page
  279. * @param $bQueryString bool True to also get the query string, false otherwise
  280. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  281. * @return string The absolute URL to the current page
  282. */
  283. static public function GetAbsoluteUrl($bQueryString = true, $bForceHTTPS = false)
  284. {
  285. // Build an absolute URL to this page on this server/port
  286. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  287. if (MetaModel::GetConfig()->GetSecureConnectionRequired() || MetaModel::GetConfig()->GetHttpsHyperlinks())
  288. {
  289. // If a secure connection is required, or if the URL is requested to start with HTTPS
  290. // then any URL must start with https !
  291. $bForceHTTPS = true;
  292. }
  293. if ($bForceHTTPS)
  294. {
  295. $sProtocol = 'https';
  296. $sPort = '';
  297. }
  298. else
  299. {
  300. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  301. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  302. if ($sProtocol == 'http')
  303. {
  304. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  305. }
  306. else
  307. {
  308. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  309. }
  310. }
  311. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  312. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  313. if (!empty($_SERVER['REQUEST_URI']))
  314. {
  315. $sPath = $_SERVER['REQUEST_URI'];
  316. }
  317. else
  318. {
  319. $sPath = $_SERVER['SCRIPT_NAME'];
  320. if (!empty($_SERVER['QUERY_STRING']))
  321. {
  322. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  323. }
  324. $_SERVER['REQUEST_URI'] = $sPath;
  325. }
  326. $sPath = $_SERVER['REQUEST_URI'];
  327. if (!$bQueryString)
  328. {
  329. // remove all the parameters from the query string
  330. $iQuestionMarkPos = strpos($sPath, '?');
  331. if ($iQuestionMarkPos !== false)
  332. {
  333. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  334. }
  335. }
  336. $sUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  337. return $sUrl;
  338. }
  339. /**
  340. * Returns the absolute URL PATH of the current page
  341. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  342. * @return string The absolute URL to the current page
  343. */
  344. static public function GetAbsoluteUrlPath($bForceHTTPS = false)
  345. {
  346. $sAbsoluteUrl = self::GetAbsoluteUrl(false, $bForceHTTPS); // False => Don't get the query string
  347. $sAbsoluteUrl = substr($sAbsoluteUrl, 0, 1+strrpos($sAbsoluteUrl, '/')); // remove the current page, keep just the path, up to the last /
  348. return $sAbsoluteUrl;
  349. }
  350. /**
  351. * Returns the absolute URL to the server's root path
  352. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  353. * @return string The absolute URL to the server's root, without the first slash
  354. */
  355. static public function GetAbsoluteUrlAppRoot($sCurrentRelativePath = '', $bForceHTTPS = false)
  356. {
  357. $sAbsoluteUrl = self::GetAbsoluteUrl(false, $bForceHTTPS); // False => Don't get the query string
  358. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  359. if ($sAppRootPos !== false)
  360. {
  361. $sAbsoluteUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  362. }
  363. else
  364. {
  365. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath)");
  366. }
  367. return $sAbsoluteUrl;
  368. }
  369. /**
  370. * Tells whether or not log off operation is supported.
  371. * Actually in only one case:
  372. * 1) iTop is using an internal authentication
  373. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  374. * @return boolean True if logoff is supported, false otherwise
  375. */
  376. static function CanLogOff()
  377. {
  378. return (isset($_SESSION['login_mode']) && $_SESSION['login_mode'] == 'form');
  379. }
  380. }
  381. ?>