utils.inc.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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', 'config-itop.php');
  27. define('ITOP_DEFAULT_CONFIG_FILE', APPCONF.ITOP_DEFAULT_ENV.'/'.ITOP_CONFIG_FILE);
  28. define('SERVER_NAME_PLACEHOLDER', '$SERVER_NAME$');
  29. class FileUploadException extends Exception
  30. {
  31. }
  32. /**
  33. * Helper functions to interact with forms: read parameters, upload files...
  34. * @package iTop
  35. */
  36. class utils
  37. {
  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. private static $m_aParamSource = array();
  43. protected static function LoadParamFile($sParamFile)
  44. {
  45. if (!file_exists($sParamFile))
  46. {
  47. throw new Exception("Could not find the parameter file: '$sParamFile'");
  48. }
  49. if (!is_readable($sParamFile))
  50. {
  51. throw new Exception("Could not load parameter file: '$sParamFile'");
  52. }
  53. $sParams = file_get_contents($sParamFile);
  54. if (is_null(self::$m_aParamsFromFile))
  55. {
  56. self::$m_aParamsFromFile = array();
  57. }
  58. $aParamLines = explode("\n", $sParams);
  59. foreach ($aParamLines as $sLine)
  60. {
  61. $sLine = trim($sLine);
  62. // Ignore the line after a '#'
  63. if (($iCommentPos = strpos($sLine, '#')) !== false)
  64. {
  65. $sLine = substr($sLine, 0, $iCommentPos);
  66. $sLine = trim($sLine);
  67. }
  68. // Note: the line is supposed to be already trimmed
  69. if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches))
  70. {
  71. $sParam = $aMatches[1];
  72. $value = trim($aMatches[2]);
  73. self::$m_aParamsFromFile[$sParam] = $value;
  74. self::$m_aParamSource[$sParam] = $sParamFile;
  75. }
  76. }
  77. }
  78. public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
  79. {
  80. $sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI, 'raw_data');
  81. foreach(explode(',', $sFileSpec) as $sFile)
  82. {
  83. $sFile = trim($sFile);
  84. if (!empty($sFile))
  85. {
  86. self::LoadParamFile($sFile);
  87. }
  88. }
  89. }
  90. /**
  91. * Return the source file from which the parameter has been found,
  92. * usefull when it comes to pass user credential to a process executed
  93. * in the background
  94. * @param $sName Parameter name
  95. * @return The file name if any, or null
  96. */
  97. public static function GetParamSourceFile($sName)
  98. {
  99. if (array_key_exists($sName, self::$m_aParamSource))
  100. {
  101. return self::$m_aParamSource[$sName];
  102. }
  103. else
  104. {
  105. return null;
  106. }
  107. }
  108. public static function IsModeCLI()
  109. {
  110. $sSAPIName = php_sapi_name();
  111. $sCleanName = strtolower(trim($sSAPIName));
  112. if ($sCleanName == 'cli')
  113. {
  114. return true;
  115. }
  116. else
  117. {
  118. return false;
  119. }
  120. }
  121. public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false, $sSanitizationFilter = 'parameter')
  122. {
  123. global $argv;
  124. $retValue = $defaultValue;
  125. if (!is_null(self::$m_aParamsFromFile))
  126. {
  127. if (isset(self::$m_aParamsFromFile[$sName]))
  128. {
  129. $retValue = self::$m_aParamsFromFile[$sName];
  130. }
  131. }
  132. if (isset($_REQUEST[$sName]))
  133. {
  134. $retValue = $_REQUEST[$sName];
  135. }
  136. elseif ($bAllowCLI && isset($argv))
  137. {
  138. foreach($argv as $iArg => $sArg)
  139. {
  140. if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
  141. {
  142. $retValue = $aMatches[1];
  143. }
  144. }
  145. }
  146. return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
  147. }
  148. public static function ReadPostedParam($sName, $defaultValue = '', $sSanitizationFilter = 'parameter')
  149. {
  150. $retValue = isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  151. return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
  152. }
  153. public static function Sanitize($value, $defaultValue, $sSanitizationFilter)
  154. {
  155. if ($value === $defaultValue)
  156. {
  157. // Preserve the real default value (can be used to detect missing mandatory parameters)
  158. $retValue = $value;
  159. }
  160. else
  161. {
  162. $retValue = self::Sanitize_Internal($value, $sSanitizationFilter);
  163. if ($retValue === false)
  164. {
  165. $retValue = $defaultValue;
  166. }
  167. }
  168. return $retValue;
  169. }
  170. protected static function Sanitize_Internal($value, $sSanitizationFilter)
  171. {
  172. switch($sSanitizationFilter)
  173. {
  174. case 'integer':
  175. $retValue = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
  176. break;
  177. case 'class':
  178. $retValue = $value;
  179. if (!MetaModel::IsValidClass($value))
  180. {
  181. $retValue = false;
  182. }
  183. break;
  184. case 'string':
  185. $retValue = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
  186. break;
  187. case 'parameter':
  188. case 'field_name':
  189. if (is_array($value))
  190. {
  191. $retValue = array();
  192. foreach($value as $key => $val)
  193. {
  194. $retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays
  195. if ($retValue[$key] === false)
  196. {
  197. $retValue = false;
  198. break;
  199. }
  200. }
  201. }
  202. else
  203. {
  204. switch($sSanitizationFilter)
  205. {
  206. case 'parameter':
  207. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[ A-Za-z0-9_=-]*$/'))); // the '=' equal character is used in serialized filters
  208. break;
  209. case 'field_name':
  210. $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
  211. break;
  212. }
  213. }
  214. break;
  215. break;
  216. default:
  217. case 'raw_data':
  218. $retValue = $value;
  219. // Do nothing
  220. }
  221. return $retValue;
  222. }
  223. /**
  224. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  225. * @param string $sName Name of the input used from uploading the file
  226. * @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
  227. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  228. */
  229. public static function ReadPostedDocument($sName, $sIndex = null)
  230. {
  231. $oDocument = new ormDocument(); // an empty document
  232. if(isset($_FILES[$sName]))
  233. {
  234. $aFileInfo = $_FILES[$sName];
  235. $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
  236. switch($sError)
  237. {
  238. case UPLOAD_ERR_OK:
  239. $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
  240. $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
  241. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  242. $doc_content = file_get_contents($sTmpName);
  243. if (function_exists('finfo_file'))
  244. {
  245. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  246. // in which case we don't trust the mime type provided by the browser
  247. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  248. if ($rInfo !== false)
  249. {
  250. $sType = @finfo_file($rInfo, $file);
  251. if ( ($sType !== false)
  252. && is_string($sType)
  253. && (strlen($sType)>0))
  254. {
  255. $sMimeType = $sType;
  256. }
  257. }
  258. @finfo_close($rInfo);
  259. }
  260. $oDocument = new ormDocument($doc_content, $sMimeType, $sName);
  261. break;
  262. case UPLOAD_ERR_NO_FILE:
  263. // no file to load, it's a normal case, just return an empty document
  264. break;
  265. case UPLOAD_ERR_FORM_SIZE:
  266. case UPLOAD_ERR_INI_SIZE:
  267. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  268. break;
  269. case UPLOAD_ERR_PARTIAL:
  270. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  271. break;
  272. case UPLOAD_ERR_NO_TMP_DIR:
  273. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  274. break;
  275. case UPLOAD_ERR_CANT_WRITE:
  276. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  277. break;
  278. case UPLOAD_ERR_EXTENSION:
  279. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  280. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
  281. break;
  282. default:
  283. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
  284. break;
  285. }
  286. }
  287. return $oDocument;
  288. }
  289. /**
  290. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  291. * @param $oFullSetFilter DBObjectSearch The criteria defining the whole sets of objects being selected
  292. * @return Array An arry of object IDs corresponding to the objects selected in the set
  293. */
  294. public static function ReadMultipleSelection($oFullSetFilter)
  295. {
  296. $aSelectedObj = utils::ReadParam('selectObject', array());
  297. $sSelectionMode = utils::ReadParam('selectionMode', '');
  298. if ($sSelectionMode != '')
  299. {
  300. // Paginated selection
  301. $aExceptions = utils::ReadParam('storedSelection', array());
  302. if ($sSelectionMode == 'positive')
  303. {
  304. // Only the explicitely listed items are selected
  305. $aSelectedObj = $aExceptions;
  306. }
  307. else
  308. {
  309. // All items of the set are selected, except the one explicitely listed
  310. $aSelectedObj = array();
  311. $oFullSet = new DBObjectSet($oFullSetFilter);
  312. $sClassAlias = $oFullSetFilter->GetClassAlias();
  313. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  314. while($oObj = $oFullSet->Fetch())
  315. {
  316. if (!in_array($oObj->GetKey(), $aExceptions))
  317. {
  318. $aSelectedObj[] = $oObj->GetKey();
  319. }
  320. }
  321. }
  322. }
  323. return $aSelectedObj;
  324. }
  325. public static function GetNewTransactionId()
  326. {
  327. return privUITransaction::GetNewTransactionId();
  328. }
  329. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  330. {
  331. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  332. }
  333. public static function RemoveTransaction($sId)
  334. {
  335. return privUITransaction::RemoveTransaction($sId);
  336. }
  337. public static function ReadFromFile($sFileName)
  338. {
  339. if (!file_exists($sFileName)) return false;
  340. return file_get_contents($sFileName);
  341. }
  342. /**
  343. * Helper function to convert a value expressed in a 'user friendly format'
  344. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  345. * @param mixed $value The value as read from php.ini
  346. * @return number
  347. */
  348. public static function ConvertToBytes( $value )
  349. {
  350. $iReturn = $value;
  351. if ( !is_numeric( $value ) )
  352. {
  353. $iLength = strlen( $value );
  354. $iReturn = substr( $value, 0, $iLength - 1 );
  355. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  356. switch ( $sUnit )
  357. {
  358. case 'G':
  359. $iReturn *= 1024;
  360. case 'M':
  361. $iReturn *= 1024;
  362. case 'K':
  363. $iReturn *= 1024;
  364. }
  365. }
  366. return $iReturn;
  367. }
  368. /**
  369. * 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)
  370. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  371. * @param string $sDate
  372. * @param string $sFormat
  373. * @return timestamp or false if the input format is not correct
  374. */
  375. public static function StringToTime($sDate, $sFormat)
  376. {
  377. // Source: http://php.net/manual/fr/function.strftime.php
  378. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  379. static $aDateTokens = null;
  380. static $aDateRegexps = null;
  381. if (is_null($aDateTokens))
  382. {
  383. $aSpec = array(
  384. '%d' =>'(?<day>[0-9]{2})',
  385. '%m' => '(?<month>[0-9]{2})',
  386. '%y' => '(?<year>[0-9]{2})',
  387. '%Y' => '(?<year>[0-9]{4})',
  388. '%H' => '(?<hour>[0-2][0-9])',
  389. '%i' => '(?<minute>[0-5][0-9])',
  390. '%s' => '(?<second>[0-5][0-9])',
  391. );
  392. $aDateTokens = array_keys($aSpec);
  393. $aDateRegexps = array_values($aSpec);
  394. }
  395. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  396. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  397. {
  398. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  399. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  400. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  401. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  402. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  403. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  404. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  405. }
  406. else
  407. {
  408. return false;
  409. }
  410. // http://www.spaweditor.com/scripts/regex/index.php
  411. }
  412. /**
  413. * Returns the absolute URL to the server's root path
  414. * @param $sCurrentRelativePath string NO MORE USED, kept for backward compatibility only !
  415. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  416. * @return string The absolute URL to the server's root, without the first slash
  417. */
  418. static public function GetAbsoluteUrlAppRoot()
  419. {
  420. $sUrl = MetaModel::GetConfig()->Get('app_root_url');
  421. if (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
  422. {
  423. if (isset($_SERVER['SERVER_NAME']))
  424. {
  425. $sServerName = $_SERVER['SERVER_NAME'];
  426. }
  427. else
  428. {
  429. // CLI mode ?
  430. $sServerName = php_uname('n');
  431. }
  432. $sUrl = str_replace(SERVER_NAME_PLACEHOLDER, $sServerName, $sUrl);
  433. }
  434. return $sUrl;
  435. }
  436. static public function GetDefaultUrlAppRoot()
  437. {
  438. // Build an absolute URL to this page on this server/port
  439. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  440. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  441. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  442. if ($sProtocol == 'http')
  443. {
  444. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  445. }
  446. else
  447. {
  448. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  449. }
  450. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  451. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  452. if (!empty($_SERVER['REQUEST_URI']))
  453. {
  454. $sPath = $_SERVER['REQUEST_URI'];
  455. }
  456. else
  457. {
  458. $sPath = $_SERVER['SCRIPT_NAME'];
  459. if (!empty($_SERVER['QUERY_STRING']))
  460. {
  461. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  462. }
  463. $_SERVER['REQUEST_URI'] = $sPath;
  464. }
  465. $sPath = $_SERVER['REQUEST_URI'];
  466. // remove all the parameters from the query string
  467. $iQuestionMarkPos = strpos($sPath, '?');
  468. if ($iQuestionMarkPos !== false)
  469. {
  470. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  471. }
  472. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  473. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  474. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  475. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  476. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  477. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  478. if ($sAppRootPos !== false)
  479. {
  480. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  481. }
  482. else
  483. {
  484. // Second attempt without index.php at the end...
  485. $sCurrentRelativePath = str_replace('index.php', '', $sCurrentRelativePath);
  486. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  487. if ($sAppRootPos !== false)
  488. {
  489. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  490. }
  491. else
  492. {
  493. // No luck...
  494. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  495. }
  496. }
  497. return $sAppRootUrl;
  498. }
  499. /**
  500. * Tells whether or not log off operation is supported.
  501. * Actually in only one case:
  502. * 1) iTop is using an internal authentication
  503. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  504. * @return boolean True if logoff is supported, false otherwise
  505. */
  506. static function CanLogOff()
  507. {
  508. $bResult = false;
  509. if(isset($_SESSION['login_mode']))
  510. {
  511. $sLoginMode = $_SESSION['login_mode'];
  512. switch($sLoginMode)
  513. {
  514. case 'external':
  515. $bResult = false;
  516. break;
  517. case 'form':
  518. case 'basic':
  519. case 'url':
  520. case 'cas':
  521. default:
  522. $bResult = true;
  523. }
  524. }
  525. return $bResult;
  526. }
  527. /**
  528. * Initializes the CAS client
  529. */
  530. static function InitCASClient()
  531. {
  532. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  533. include_once($sCASIncludePath.'/CAS.php');
  534. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  535. if ($bCASDebug)
  536. {
  537. phpCAS::setDebug(APPROOT.'/error.log');
  538. }
  539. if (!self::$m_bCASClient)
  540. {
  541. // Initialize phpCAS
  542. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  543. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  544. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  545. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  546. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  547. self::$m_bCASClient = true;
  548. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  549. if (empty($sCASCACertPath))
  550. {
  551. // If no certificate authority is provided, do not attempt to validate
  552. // the server's certificate
  553. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  554. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  555. phpCAS::setNoCasServerValidation();
  556. }
  557. else
  558. {
  559. phpCAS::setCasServerCACert($sCASCACertPath);
  560. }
  561. }
  562. }
  563. static function DebugBacktrace($iLimit = 5)
  564. {
  565. $aFullTrace = debug_backtrace();
  566. $aLightTrace = array();
  567. for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
  568. {
  569. $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
  570. }
  571. echo "<p><pre>".print_r($aLightTrace, true)."</pre></p>\n";
  572. }
  573. /**
  574. * Execute the given iTop PHP script, passing it the current credentials
  575. * Only CLI mode is supported, because of the need to hand the credentials over to the next process
  576. * Throws an exception if the execution fails or could not be attempted (config issue)
  577. * @param string $sScript Name and relative path to the file (relative to the iTop root dir)
  578. * @param hash $aArguments Associative array of 'arg' => 'value'
  579. * @return array(iCode, array(output lines))
  580. */
  581. /**
  582. */
  583. static function ExecITopScript($sScriptName, $aArguments)
  584. {
  585. $aDisabled = explode(', ', ini_get('disable_functions'));
  586. if (in_array('exec', $aDisabled))
  587. {
  588. throw new Exception("The PHP exec() function has been disabled on this server");
  589. }
  590. $sPHPExec = trim(MetaModel::GetConfig()->Get('php_path'));
  591. if (strlen($sPHPExec) == 0)
  592. {
  593. throw new Exception("The path to php must not be empty. Please set a value for 'php_path' in your configuration file.");
  594. }
  595. $sAuthUser = self::ReadParam('auth_user', '', 'raw_data');
  596. $sAuthPwd = self::ReadParam('auth_pwd', '', 'raw_data');
  597. $sParamFile = self::GetParamSourceFile('auth_user');
  598. if (is_null($sParamFile))
  599. {
  600. $aArguments['auth_user'] = $sAuthUser;
  601. $aArguments['auth_pwd'] = $sAuthPwd;
  602. }
  603. else
  604. {
  605. $aArguments['param_file'] = $sParamFile;
  606. }
  607. $aArgs = array();
  608. foreach($aArguments as $sName => $value)
  609. {
  610. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  611. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  612. $aArgs[] = "--$sName=".escapeshellarg($value);
  613. }
  614. $sArgs = implode(' ', $aArgs);
  615. $sScript = realpath(APPROOT.$sScriptName);
  616. if (!file_exists($sScript))
  617. {
  618. throw new Exception("Could not find the script file '$sScriptName' from the directory '".APPROOT."'");
  619. }
  620. $sCommand = '"'.$sPHPExec.'" '.escapeshellarg($sScript).' -- '.$sArgs;
  621. if (version_compare(phpversion(), '5.3.0', '<'))
  622. {
  623. if (substr(PHP_OS,0,3) == 'WIN')
  624. {
  625. // Under Windows, and for PHP 5.2.x, the whole command has to be quoted
  626. // Cf PHP doc: http://php.net/manual/fr/function.exec.php, comment from the 27-Dec-2010
  627. $sCommand = '"'.$sCommand.'"';
  628. }
  629. }
  630. $sLastLine = exec($sCommand, $aOutput, $iRes);
  631. if ($iRes == 1)
  632. {
  633. throw new Exception(Dict::S('Core:ExecProcess:Code1')." - ".$sCommand);
  634. }
  635. elseif ($iRes == 255)
  636. {
  637. $sErrors = implode("\n", $aOutput);
  638. throw new Exception(Dict::S('Core:ExecProcess:Code255')." - ".$sCommand.":\n".$sErrors);
  639. }
  640. //$aOutput[] = $sCommand;
  641. return array($iRes, $aOutput);
  642. }
  643. /**
  644. * Get the current environment
  645. */
  646. public static function GetCurrentEnvironment()
  647. {
  648. if (isset($_SESSION['itop_env']))
  649. {
  650. return $_SESSION['itop_env'];
  651. }
  652. else
  653. {
  654. return ITOP_DEFAULT_ENV;
  655. }
  656. }
  657. /**
  658. * Get the "Back" button to go out of the current environment
  659. */
  660. public static function GetEnvironmentBackButton()
  661. {
  662. if (isset($_SESSION['itop_return_env']))
  663. {
  664. if (isset($_SESSION['itop_return_url']))
  665. {
  666. $sReturnUrl = $_SESSION['itop_return_url'];
  667. }
  668. else
  669. {
  670. $sReturnUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?switch_env='.$_SESSION['itop_return_env'];
  671. }
  672. return '&nbsp;<button onclick="window;location.href=\''.addslashes($sReturnUrl).'\'">'.Dict::S('UI:Button:Back').'</button>';
  673. }
  674. else
  675. {
  676. return '';
  677. }
  678. }
  679. /**
  680. * Get target configuration file name (including full path)
  681. */
  682. public static function GetConfigFilePath()
  683. {
  684. return APPCONF.self::GetCurrentEnvironment().'/'.ITOP_CONFIG_FILE;
  685. }
  686. }
  687. ?>