utils.inc.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. define('SERVER_NAME_PLACEHOLDER', '$SERVER_NAME$');
  28. class FileUploadException extends Exception
  29. {
  30. }
  31. /**
  32. * Helper functions to interact with forms: read parameters, upload files...
  33. * @package iTop
  34. */
  35. class utils
  36. {
  37. private static $m_sConfigFile = ITOP_CONFIG_FILE;
  38. private static $m_oConfig = null;
  39. private static $m_bCASClient = false;
  40. // Parameters loaded from a file, parameters of the page/command line still have precedence
  41. private static $m_aParamsFromFile = null;
  42. protected static function LoadParamFile($sParamFile)
  43. {
  44. if (!file_exists($sParamFile))
  45. {
  46. throw new Exception("Could not find the parameter file: '$sParamFile'");
  47. }
  48. if (!is_readable($sParamFile))
  49. {
  50. throw new Exception("Could not load parameter file: '$sParamFile'");
  51. }
  52. $sParams = file_get_contents($sParamFile);
  53. if (is_null(self::$m_aParamsFromFile))
  54. {
  55. self::$m_aParamsFromFile = array();
  56. }
  57. $aParamLines = explode("\n", $sParams);
  58. foreach ($aParamLines as $sLine)
  59. {
  60. $sLine = trim($sLine);
  61. // Ignore the line after a '#'
  62. if (($iCommentPos = strpos($sLine, '#')) !== false)
  63. {
  64. $sLine = substr($sLine, 0, $iCommentPos);
  65. $sLine = trim($sLine);
  66. }
  67. // Note: the line is supposed to be already trimmed
  68. if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches))
  69. {
  70. $sParam = $aMatches[1];
  71. $value = trim($aMatches[2]);
  72. self::$m_aParamsFromFile[$sParam] = $value;
  73. }
  74. }
  75. }
  76. public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
  77. {
  78. $sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI, 'raw_data');
  79. foreach(explode(',', $sFileSpec) as $sFile)
  80. {
  81. $sFile = trim($sFile);
  82. if (!empty($sFile))
  83. {
  84. self::LoadParamFile($sFile);
  85. }
  86. }
  87. }
  88. public static function IsModeCLI()
  89. {
  90. $sSAPIName = php_sapi_name();
  91. $sCleanName = strtolower(trim($sSAPIName));
  92. if ($sCleanName == 'cli')
  93. {
  94. return true;
  95. }
  96. else
  97. {
  98. return false;
  99. }
  100. }
  101. public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false, $sSanitizationFilter = 'parameter')
  102. {
  103. global $argv;
  104. $retValue = $defaultValue;
  105. if (!is_null(self::$m_aParamsFromFile))
  106. {
  107. if (isset(self::$m_aParamsFromFile[$sName]))
  108. {
  109. $retValue = self::$m_aParamsFromFile[$sName];
  110. }
  111. }
  112. if (isset($_REQUEST[$sName]))
  113. {
  114. $retValue = $_REQUEST[$sName];
  115. }
  116. elseif ($bAllowCLI && isset($argv))
  117. {
  118. foreach($argv as $iArg => $sArg)
  119. {
  120. if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
  121. {
  122. $retValue = $aMatches[1];
  123. }
  124. }
  125. }
  126. return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
  127. }
  128. public static function ReadPostedParam($sName, $defaultValue = '', $sSanitizationFilter = 'parameter')
  129. {
  130. $retValue = isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  131. return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
  132. }
  133. public static function Sanitize($value, $defaultValue, $sSanitizationFilter)
  134. {
  135. $retValue = self::Sanitize_Internal($value, $sSanitizationFilter);
  136. if ($retValue === false)
  137. {
  138. $retValue = $defaultValue;
  139. }
  140. return $retValue;
  141. }
  142. protected static function Sanitize_Internal($value, $sSanitizationFilter)
  143. {
  144. switch($sSanitizationFilter)
  145. {
  146. case 'integer':
  147. $retValue = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
  148. break;
  149. case 'class':
  150. $retValue = $value;
  151. if (!MetaModel::IsValidClass($value))
  152. {
  153. $retValue = false;
  154. }
  155. break;
  156. case 'string':
  157. $retValue = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
  158. break;
  159. case 'parameter':
  160. case 'field_name':
  161. if (is_array($value))
  162. {
  163. $retValue = array();
  164. foreach($value as $key => $val)
  165. {
  166. $retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays
  167. if ($retValue[$key] === false)
  168. {
  169. $retValue = false;
  170. break;
  171. }
  172. }
  173. }
  174. else
  175. {
  176. switch($sSanitizationFilter)
  177. {
  178. case 'parameter':
  179. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[ A-Za-z0-9_=-]*$/'))); // the '=' equal character is used in serialized filters
  180. break;
  181. case 'field_name':
  182. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[A-Za-z0-9_]+(->[A-Za-z0-9_]+)*$/'))); // att_code or att_code->name or AttCode->Name or AttCode->Key2->Name
  183. break;
  184. }
  185. }
  186. break;
  187. break;
  188. default:
  189. case 'raw_data':
  190. $retValue = $value;
  191. // Do nothing
  192. }
  193. return $retValue;
  194. }
  195. /**
  196. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  197. * @param string $sName Name of the input used from uploading the file
  198. * @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
  199. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  200. */
  201. public static function ReadPostedDocument($sName, $sIndex = null)
  202. {
  203. $oDocument = new ormDocument(); // an empty document
  204. if(isset($_FILES[$sName]))
  205. {
  206. $aFileInfo = $_FILES[$sName];
  207. $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
  208. switch($sError)
  209. {
  210. case UPLOAD_ERR_OK:
  211. $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
  212. $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
  213. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  214. $doc_content = file_get_contents($sTmpName);
  215. if (function_exists('finfo_file'))
  216. {
  217. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  218. // in which case we don't trust the mime type provided by the browser
  219. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  220. if ($rInfo !== false)
  221. {
  222. $sType = @finfo_file($rInfo, $file);
  223. if ( ($sType !== false)
  224. && is_string($sType)
  225. && (strlen($sType)>0))
  226. {
  227. $sMimeType = $sType;
  228. }
  229. }
  230. @finfo_close($rInfo);
  231. }
  232. $oDocument = new ormDocument($doc_content, $sMimeType, $sName);
  233. break;
  234. case UPLOAD_ERR_NO_FILE:
  235. // no file to load, it's a normal case, just return an empty document
  236. break;
  237. case UPLOAD_ERR_FORM_SIZE:
  238. case UPLOAD_ERR_INI_SIZE:
  239. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  240. break;
  241. case UPLOAD_ERR_PARTIAL:
  242. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  243. break;
  244. case UPLOAD_ERR_NO_TMP_DIR:
  245. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  246. break;
  247. case UPLOAD_ERR_CANT_WRITE:
  248. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  249. break;
  250. case UPLOAD_ERR_EXTENSION:
  251. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  252. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
  253. break;
  254. default:
  255. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
  256. break;
  257. }
  258. }
  259. return $oDocument;
  260. }
  261. /**
  262. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  263. * @param $oFullSetFilter DBObjectSearch The criteria defining the whole sets of objects being selected
  264. * @return Array An arry of object IDs corresponding to the objects selected in the set
  265. */
  266. public static function ReadMultipleSelection($oFullSetFilter)
  267. {
  268. $aSelectedObj = utils::ReadParam('selectObject', array());
  269. $sSelectionMode = utils::ReadParam('selectionMode', '');
  270. if ($sSelectionMode != '')
  271. {
  272. // Paginated selection
  273. $aExceptions = utils::ReadParam('storedSelection', array());
  274. if ($sSelectionMode == 'positive')
  275. {
  276. // Only the explicitely listed items are selected
  277. $aSelectedObj = $aExceptions;
  278. }
  279. else
  280. {
  281. // All items of the set are selected, except the one explicitely listed
  282. $aSelectedObj = array();
  283. $oFullSet = new DBObjectSet($oFullSetFilter);
  284. $sClassAlias = $oFullSetFilter->GetClassAlias();
  285. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  286. while($oObj = $oFullSet->Fetch())
  287. {
  288. if (!in_array($oObj->GetKey(), $aExceptions))
  289. {
  290. $aSelectedObj[] = $oObj->GetKey();
  291. }
  292. }
  293. }
  294. }
  295. return $aSelectedObj;
  296. }
  297. public static function GetNewTransactionId()
  298. {
  299. return privUITransaction::GetNewTransactionId();
  300. }
  301. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  302. {
  303. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  304. }
  305. public static function RemoveTransaction($sId)
  306. {
  307. return privUITransaction::RemoveTransaction($sId);
  308. }
  309. public static function ReadFromFile($sFileName)
  310. {
  311. if (!file_exists($sFileName)) return false;
  312. return file_get_contents($sFileName);
  313. }
  314. /**
  315. * Helper function to convert a value expressed in a 'user friendly format'
  316. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  317. * @param mixed $value The value as read from php.ini
  318. * @return number
  319. */
  320. public static function ConvertToBytes( $value )
  321. {
  322. $iReturn = $value;
  323. if ( !is_numeric( $value ) )
  324. {
  325. $iLength = strlen( $value );
  326. $iReturn = substr( $value, 0, $iLength - 1 );
  327. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  328. switch ( $sUnit )
  329. {
  330. case 'G':
  331. $iReturn *= 1024;
  332. case 'M':
  333. $iReturn *= 1024;
  334. case 'K':
  335. $iReturn *= 1024;
  336. }
  337. }
  338. return $iReturn;
  339. }
  340. /**
  341. * 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)
  342. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  343. * @param string $sDate
  344. * @param string $sFormat
  345. * @return timestamp or false if the input format is not correct
  346. */
  347. public static function StringToTime($sDate, $sFormat)
  348. {
  349. // Source: http://php.net/manual/fr/function.strftime.php
  350. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  351. static $aDateTokens = null;
  352. static $aDateRegexps = null;
  353. if (is_null($aDateTokens))
  354. {
  355. $aSpec = array(
  356. '%d' =>'(?<day>[0-9]{2})',
  357. '%m' => '(?<month>[0-9]{2})',
  358. '%y' => '(?<year>[0-9]{2})',
  359. '%Y' => '(?<year>[0-9]{4})',
  360. '%H' => '(?<hour>[0-2][0-9])',
  361. '%i' => '(?<minute>[0-5][0-9])',
  362. '%s' => '(?<second>[0-5][0-9])',
  363. );
  364. $aDateTokens = array_keys($aSpec);
  365. $aDateRegexps = array_values($aSpec);
  366. }
  367. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  368. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  369. {
  370. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  371. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  372. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  373. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  374. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  375. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  376. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  377. }
  378. else
  379. {
  380. return false;
  381. }
  382. // http://www.spaweditor.com/scripts/regex/index.php
  383. }
  384. /**
  385. * Returns the absolute URL to the server's root path
  386. * @param $sCurrentRelativePath string NO MORE USED, kept for backward compatibility only !
  387. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  388. * @return string The absolute URL to the server's root, without the first slash
  389. */
  390. static public function GetAbsoluteUrlAppRoot()
  391. {
  392. $sUrl = MetaModel::GetConfig()->Get('app_root_url');
  393. if (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
  394. {
  395. if (isset($_SERVER['SERVER_NAME']))
  396. {
  397. $sServerName = $_SERVER['SERVER_NAME'];
  398. }
  399. else
  400. {
  401. // CLI mode ?
  402. $sServerName = php_uname('n');
  403. }
  404. $sUrl = str_replace(SERVER_NAME_PLACEHOLDER, $sServerName, $sUrl);
  405. }
  406. return $sUrl;
  407. }
  408. static public function GetDefaultUrlAppRoot()
  409. {
  410. // Build an absolute URL to this page on this server/port
  411. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  412. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  413. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  414. if ($sProtocol == 'http')
  415. {
  416. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  417. }
  418. else
  419. {
  420. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  421. }
  422. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  423. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  424. if (!empty($_SERVER['REQUEST_URI']))
  425. {
  426. $sPath = $_SERVER['REQUEST_URI'];
  427. }
  428. else
  429. {
  430. $sPath = $_SERVER['SCRIPT_NAME'];
  431. if (!empty($_SERVER['QUERY_STRING']))
  432. {
  433. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  434. }
  435. $_SERVER['REQUEST_URI'] = $sPath;
  436. }
  437. $sPath = $_SERVER['REQUEST_URI'];
  438. // remove all the parameters from the query string
  439. $iQuestionMarkPos = strpos($sPath, '?');
  440. if ($iQuestionMarkPos !== false)
  441. {
  442. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  443. }
  444. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  445. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  446. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  447. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  448. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  449. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  450. if ($sAppRootPos !== false)
  451. {
  452. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  453. }
  454. else
  455. {
  456. // Second attempt without index.php at the end...
  457. $sCurrentRelativePath = str_replace('index.php', '', $sCurrentRelativePath);
  458. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  459. if ($sAppRootPos !== false)
  460. {
  461. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  462. }
  463. else
  464. {
  465. // No luck...
  466. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  467. }
  468. }
  469. return $sAppRootUrl;
  470. }
  471. /**
  472. * Tells whether or not log off operation is supported.
  473. * Actually in only one case:
  474. * 1) iTop is using an internal authentication
  475. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  476. * @return boolean True if logoff is supported, false otherwise
  477. */
  478. static function CanLogOff()
  479. {
  480. $bResult = false;
  481. if(isset($_SESSION['login_mode']))
  482. {
  483. $sLoginMode = $_SESSION['login_mode'];
  484. switch($sLoginMode)
  485. {
  486. case 'external':
  487. $bResult = false;
  488. break;
  489. case 'form':
  490. case 'basic':
  491. case 'url':
  492. case 'cas':
  493. default:
  494. $bResult = true;
  495. }
  496. }
  497. return $bResult;
  498. }
  499. /**
  500. * Initializes the CAS client
  501. */
  502. static function InitCASClient()
  503. {
  504. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  505. include_once($sCASIncludePath.'/CAS.php');
  506. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  507. if ($bCASDebug)
  508. {
  509. phpCAS::setDebug(APPROOT.'/error.log');
  510. }
  511. if (!self::$m_bCASClient)
  512. {
  513. // Initialize phpCAS
  514. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  515. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  516. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  517. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  518. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  519. self::$m_bCASClient = true;
  520. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  521. if (empty($sCASCACertPath))
  522. {
  523. // If no certificate authority is provided, do not attempt to validate
  524. // the server's certificate
  525. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  526. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  527. phpCAS::setNoCasServerValidation();
  528. }
  529. else
  530. {
  531. phpCAS::setCasServerCACert($sCASCACertPath);
  532. }
  533. }
  534. }
  535. static function DebugBacktrace($iLimit = 5)
  536. {
  537. $aFullTrace = debug_backtrace();
  538. $aLightTrace = array();
  539. for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
  540. {
  541. $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
  542. }
  543. echo "<p><pre>".print_r($aLightTrace, true)."</pre></p>\n";
  544. }
  545. }
  546. ?>