utils.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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);
  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)
  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 $retValue;
  127. }
  128. public static function ReadPostedParam($sName, $defaultValue = "")
  129. {
  130. return isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  131. }
  132. /**
  133. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  134. * @param string $sName Name of the input used from uploading the file
  135. * @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
  136. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  137. */
  138. public static function ReadPostedDocument($sName, $sIndex = null)
  139. {
  140. $oDocument = new ormDocument(); // an empty document
  141. if(isset($_FILES[$sName]))
  142. {
  143. $aFileInfo = $_FILES[$sName];
  144. $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
  145. switch($sError)
  146. {
  147. case UPLOAD_ERR_OK:
  148. $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
  149. $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
  150. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  151. $doc_content = file_get_contents($sTmpName);
  152. if (function_exists('finfo_file'))
  153. {
  154. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  155. // in which case we don't trust the mime type provided by the browser
  156. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  157. if ($rInfo !== false)
  158. {
  159. $sType = @finfo_file($rInfo, $file);
  160. if ( ($sType !== false)
  161. && is_string($sType)
  162. && (strlen($sType)>0))
  163. {
  164. $sMimeType = $sType;
  165. }
  166. }
  167. @finfo_close($rInfo);
  168. }
  169. $oDocument = new ormDocument($doc_content, $sMimeType, $sName);
  170. break;
  171. case UPLOAD_ERR_NO_FILE:
  172. // no file to load, it's a normal case, just return an empty document
  173. break;
  174. case UPLOAD_ERR_FORM_SIZE:
  175. case UPLOAD_ERR_INI_SIZE:
  176. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  177. break;
  178. case UPLOAD_ERR_PARTIAL:
  179. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  180. break;
  181. case UPLOAD_ERR_NO_TMP_DIR:
  182. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  183. break;
  184. case UPLOAD_ERR_CANT_WRITE:
  185. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  186. break;
  187. case UPLOAD_ERR_EXTENSION:
  188. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  189. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
  190. break;
  191. default:
  192. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
  193. break;
  194. }
  195. }
  196. return $oDocument;
  197. }
  198. /**
  199. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  200. * @param $oFullSetFilter DBObjectSearch The criteria defining the whole sets of objects being selected
  201. * @return Array An arry of object IDs corresponding to the objects selected in the set
  202. */
  203. public static function ReadMultipleSelection($oFullSetFilter)
  204. {
  205. $aSelectedObj = utils::ReadParam('selectObject', array());
  206. $sSelectionMode = utils::ReadParam('selectionMode', '');
  207. if ($sSelectionMode != '')
  208. {
  209. // Paginated selection
  210. $aExceptions = utils::ReadParam('storedSelection', array());
  211. if ($sSelectionMode == 'positive')
  212. {
  213. // Only the explicitely listed items are selected
  214. $aSelectedObj = $aExceptions;
  215. }
  216. else
  217. {
  218. // All items of the set are selected, except the one explicitely listed
  219. $aSelectedObj = array();
  220. $oFullSet = new DBObjectSet($oFullSetFilter);
  221. $sClassAlias = $oFullSetFilter->GetClassAlias();
  222. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  223. while($oObj = $oFullSet->Fetch())
  224. {
  225. if (!in_array($oObj->GetKey(), $aExceptions))
  226. {
  227. $aSelectedObj[] = $oObj->GetKey();
  228. }
  229. }
  230. }
  231. }
  232. return $aSelectedObj;
  233. }
  234. public static function GetNewTransactionId()
  235. {
  236. return privUITransaction::GetNewTransactionId();
  237. }
  238. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  239. {
  240. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  241. }
  242. public static function RemoveTransaction($sId)
  243. {
  244. return privUITransaction::RemoveTransaction($sId);
  245. }
  246. public static function ReadFromFile($sFileName)
  247. {
  248. if (!file_exists($sFileName)) return false;
  249. return file_get_contents($sFileName);
  250. }
  251. /**
  252. * Helper function to convert a value expressed in a 'user friendly format'
  253. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  254. * @param mixed $value The value as read from php.ini
  255. * @return number
  256. */
  257. public static function ConvertToBytes( $value )
  258. {
  259. $iReturn = $value;
  260. if ( !is_numeric( $value ) )
  261. {
  262. $iLength = strlen( $value );
  263. $iReturn = substr( $value, 0, $iLength - 1 );
  264. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  265. switch ( $sUnit )
  266. {
  267. case 'G':
  268. $iReturn *= 1024;
  269. case 'M':
  270. $iReturn *= 1024;
  271. case 'K':
  272. $iReturn *= 1024;
  273. }
  274. }
  275. return $iReturn;
  276. }
  277. /**
  278. * 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)
  279. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  280. * @param string $sDate
  281. * @param string $sFormat
  282. * @return timestamp or false if the input format is not correct
  283. */
  284. public static function StringToTime($sDate, $sFormat)
  285. {
  286. // Source: http://php.net/manual/fr/function.strftime.php
  287. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  288. static $aDateTokens = null;
  289. static $aDateRegexps = null;
  290. if (is_null($aDateTokens))
  291. {
  292. $aSpec = array(
  293. '%d' =>'(?<day>[0-9]{2})',
  294. '%m' => '(?<month>[0-9]{2})',
  295. '%y' => '(?<year>[0-9]{2})',
  296. '%Y' => '(?<year>[0-9]{4})',
  297. '%H' => '(?<hour>[0-2][0-9])',
  298. '%i' => '(?<minute>[0-5][0-9])',
  299. '%s' => '(?<second>[0-5][0-9])',
  300. );
  301. $aDateTokens = array_keys($aSpec);
  302. $aDateRegexps = array_values($aSpec);
  303. }
  304. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  305. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  306. {
  307. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  308. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  309. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  310. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  311. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  312. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  313. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  314. }
  315. else
  316. {
  317. return false;
  318. }
  319. // http://www.spaweditor.com/scripts/regex/index.php
  320. }
  321. /**
  322. * Returns the absolute URL to the server's root path
  323. * @param $sCurrentRelativePath string NO MORE USED, kept for backward compatibility only !
  324. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  325. * @return string The absolute URL to the server's root, without the first slash
  326. */
  327. static public function GetAbsoluteUrlAppRoot()
  328. {
  329. $sUrl = MetaModel::GetConfig()->Get('app_root_url');
  330. if (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
  331. {
  332. if (isset($_SERVER['SERVER_NAME']))
  333. {
  334. $sServerName = $_SERVER['SERVER_NAME'];
  335. }
  336. else
  337. {
  338. // CLI mode ?
  339. $sServerName = php_uname('n');
  340. }
  341. $sUrl = str_replace(SERVER_NAME_PLACEHOLDER, $sServerName, $sUrl);
  342. }
  343. return $sUrl;
  344. }
  345. static public function GetDefaultUrlAppRoot()
  346. {
  347. // Build an absolute URL to this page on this server/port
  348. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  349. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  350. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  351. if ($sProtocol == 'http')
  352. {
  353. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  354. }
  355. else
  356. {
  357. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  358. }
  359. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  360. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  361. if (!empty($_SERVER['REQUEST_URI']))
  362. {
  363. $sPath = $_SERVER['REQUEST_URI'];
  364. }
  365. else
  366. {
  367. $sPath = $_SERVER['SCRIPT_NAME'];
  368. if (!empty($_SERVER['QUERY_STRING']))
  369. {
  370. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  371. }
  372. $_SERVER['REQUEST_URI'] = $sPath;
  373. }
  374. $sPath = $_SERVER['REQUEST_URI'];
  375. // remove all the parameters from the query string
  376. $iQuestionMarkPos = strpos($sPath, '?');
  377. if ($iQuestionMarkPos !== false)
  378. {
  379. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  380. }
  381. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  382. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  383. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  384. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  385. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  386. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  387. if ($sAppRootPos !== false)
  388. {
  389. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  390. }
  391. else
  392. {
  393. // Second attempt without index.php at the end...
  394. $sCurrentRelativePath = str_replace('index.php', '', $sCurrentRelativePath);
  395. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  396. if ($sAppRootPos !== false)
  397. {
  398. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  399. }
  400. else
  401. {
  402. // No luck...
  403. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  404. }
  405. }
  406. return $sAppRootUrl;
  407. }
  408. /**
  409. * Tells whether or not log off operation is supported.
  410. * Actually in only one case:
  411. * 1) iTop is using an internal authentication
  412. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  413. * @return boolean True if logoff is supported, false otherwise
  414. */
  415. static function CanLogOff()
  416. {
  417. $bResult = false;
  418. if(isset($_SESSION['login_mode']))
  419. {
  420. $sLoginMode = $_SESSION['login_mode'];
  421. switch($sLoginMode)
  422. {
  423. case 'external':
  424. $bResult = false;
  425. break;
  426. case 'form':
  427. case 'basic':
  428. case 'url':
  429. case 'cas':
  430. default:
  431. $bResult = true;
  432. }
  433. }
  434. return $bResult;
  435. }
  436. /**
  437. * Initializes the CAS client
  438. */
  439. static function InitCASClient()
  440. {
  441. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  442. include_once($sCASIncludePath.'/CAS.php');
  443. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  444. if ($bCASDebug)
  445. {
  446. phpCAS::setDebug(APPROOT.'/error.log');
  447. }
  448. if (!self::$m_bCASClient)
  449. {
  450. // Initialize phpCAS
  451. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  452. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  453. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  454. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  455. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  456. self::$m_bCASClient = true;
  457. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  458. if (empty($sCASCACertPath))
  459. {
  460. // If no certificate authority is provided, do not attempt to validate
  461. // the server's certificate
  462. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  463. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  464. phpCAS::setNoCasServerValidation();
  465. }
  466. else
  467. {
  468. phpCAS::setCasServerCACert($sCASCACertPath);
  469. }
  470. }
  471. }
  472. static function DebugBacktrace($iLimit = 5)
  473. {
  474. $aFullTrace = debug_backtrace();
  475. $aLightTrace = array();
  476. for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
  477. {
  478. $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
  479. }
  480. echo "<p><pre>".print_r($aLightTrace, true)."</pre></p>\n";
  481. }
  482. }
  483. ?>