utils.inc.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Static class utils
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  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 $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 'context_param':
  188. case 'parameter':
  189. case 'field_name':
  190. if (is_array($value))
  191. {
  192. $retValue = array();
  193. foreach($value as $key => $val)
  194. {
  195. $retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays
  196. if ($retValue[$key] === false)
  197. {
  198. $retValue = false;
  199. break;
  200. }
  201. }
  202. }
  203. else
  204. {
  205. switch($sSanitizationFilter)
  206. {
  207. case 'parameter':
  208. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[ A-Za-z0-9_=-]*$/'))); // the '=' equal character is used in serialized filters
  209. break;
  210. case 'field_name':
  211. $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
  212. break;
  213. case 'context_param':
  214. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[ A-Za-z0-9_=%:+-]*$/')));
  215. break;
  216. }
  217. }
  218. break;
  219. default:
  220. case 'raw_data':
  221. $retValue = $value;
  222. // Do nothing
  223. }
  224. return $retValue;
  225. }
  226. /**
  227. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  228. * @param string $sName Name of the input used from uploading the file
  229. * @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
  230. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  231. */
  232. public static function ReadPostedDocument($sName, $sIndex = null)
  233. {
  234. $oDocument = new ormDocument(); // an empty document
  235. if(isset($_FILES[$sName]))
  236. {
  237. $aFileInfo = $_FILES[$sName];
  238. $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
  239. switch($sError)
  240. {
  241. case UPLOAD_ERR_OK:
  242. $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
  243. $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
  244. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  245. $doc_content = file_get_contents($sTmpName);
  246. if (function_exists('finfo_file'))
  247. {
  248. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  249. // in which case we don't trust the mime type provided by the browser
  250. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  251. if ($rInfo !== false)
  252. {
  253. $sType = @finfo_file($rInfo, $file);
  254. if ( ($sType !== false)
  255. && is_string($sType)
  256. && (strlen($sType)>0))
  257. {
  258. $sMimeType = $sType;
  259. }
  260. }
  261. @finfo_close($rInfo);
  262. }
  263. $oDocument = new ormDocument($doc_content, $sMimeType, $sName);
  264. break;
  265. case UPLOAD_ERR_NO_FILE:
  266. // no file to load, it's a normal case, just return an empty document
  267. break;
  268. case UPLOAD_ERR_FORM_SIZE:
  269. case UPLOAD_ERR_INI_SIZE:
  270. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  271. break;
  272. case UPLOAD_ERR_PARTIAL:
  273. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  274. break;
  275. case UPLOAD_ERR_NO_TMP_DIR:
  276. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  277. break;
  278. case UPLOAD_ERR_CANT_WRITE:
  279. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  280. break;
  281. case UPLOAD_ERR_EXTENSION:
  282. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  283. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
  284. break;
  285. default:
  286. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
  287. break;
  288. }
  289. }
  290. return $oDocument;
  291. }
  292. /**
  293. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  294. * @param $oFullSetFilter DBObjectSearch The criteria defining the whole sets of objects being selected
  295. * @return Array An arry of object IDs corresponding to the objects selected in the set
  296. */
  297. public static function ReadMultipleSelection($oFullSetFilter)
  298. {
  299. $aSelectedObj = utils::ReadParam('selectObject', array());
  300. $sSelectionMode = utils::ReadParam('selectionMode', '');
  301. if ($sSelectionMode != '')
  302. {
  303. // Paginated selection
  304. $aExceptions = utils::ReadParam('storedSelection', array());
  305. if ($sSelectionMode == 'positive')
  306. {
  307. // Only the explicitely listed items are selected
  308. $aSelectedObj = $aExceptions;
  309. }
  310. else
  311. {
  312. // All items of the set are selected, except the one explicitely listed
  313. $aSelectedObj = array();
  314. $oFullSet = new DBObjectSet($oFullSetFilter);
  315. $sClassAlias = $oFullSetFilter->GetClassAlias();
  316. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  317. while($oObj = $oFullSet->Fetch())
  318. {
  319. if (!in_array($oObj->GetKey(), $aExceptions))
  320. {
  321. $aSelectedObj[] = $oObj->GetKey();
  322. }
  323. }
  324. }
  325. }
  326. return $aSelectedObj;
  327. }
  328. public static function GetNewTransactionId()
  329. {
  330. return privUITransaction::GetNewTransactionId();
  331. }
  332. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  333. {
  334. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  335. }
  336. public static function RemoveTransaction($sId)
  337. {
  338. return privUITransaction::RemoveTransaction($sId);
  339. }
  340. public static function ReadFromFile($sFileName)
  341. {
  342. if (!file_exists($sFileName)) return false;
  343. return file_get_contents($sFileName);
  344. }
  345. /**
  346. * Helper function to convert a value expressed in a 'user friendly format'
  347. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  348. * @param mixed $value The value as read from php.ini
  349. * @return number
  350. */
  351. public static function ConvertToBytes( $value )
  352. {
  353. $iReturn = $value;
  354. if ( !is_numeric( $value ) )
  355. {
  356. $iLength = strlen( $value );
  357. $iReturn = substr( $value, 0, $iLength - 1 );
  358. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  359. switch ( $sUnit )
  360. {
  361. case 'G':
  362. $iReturn *= 1024;
  363. case 'M':
  364. $iReturn *= 1024;
  365. case 'K':
  366. $iReturn *= 1024;
  367. }
  368. }
  369. return $iReturn;
  370. }
  371. /**
  372. * 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)
  373. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  374. * @param string $sDate
  375. * @param string $sFormat
  376. * @return timestamp or false if the input format is not correct
  377. */
  378. public static function StringToTime($sDate, $sFormat)
  379. {
  380. // Source: http://php.net/manual/fr/function.strftime.php
  381. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  382. static $aDateTokens = null;
  383. static $aDateRegexps = null;
  384. if (is_null($aDateTokens))
  385. {
  386. $aSpec = array(
  387. '%d' =>'(?<day>[0-9]{2})',
  388. '%m' => '(?<month>[0-9]{2})',
  389. '%y' => '(?<year>[0-9]{2})',
  390. '%Y' => '(?<year>[0-9]{4})',
  391. '%H' => '(?<hour>[0-2][0-9])',
  392. '%i' => '(?<minute>[0-5][0-9])',
  393. '%s' => '(?<second>[0-5][0-9])',
  394. );
  395. $aDateTokens = array_keys($aSpec);
  396. $aDateRegexps = array_values($aSpec);
  397. }
  398. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  399. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  400. {
  401. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  402. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  403. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  404. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  405. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  406. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  407. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  408. }
  409. else
  410. {
  411. return false;
  412. }
  413. // http://www.spaweditor.com/scripts/regex/index.php
  414. }
  415. static public function GetConfig()
  416. {
  417. if (self::$oConfig == null)
  418. {
  419. $sConfigFile = self::GetConfigFilePath();
  420. if (file_exists($sConfigFile))
  421. {
  422. self::$oConfig = new Config($sConfigFile);
  423. }
  424. else
  425. {
  426. // When executing the setup, the config file may be still missing
  427. self::$oConfig = new Config();
  428. }
  429. }
  430. return self::$oConfig;
  431. }
  432. /**
  433. * Returns the absolute URL to the application root path
  434. * @return string The absolute URL to the application root, without the first slash
  435. */
  436. static public function GetAbsoluteUrlAppRoot()
  437. {
  438. $sUrl = self::GetConfig()->Get('app_root_url');
  439. if (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
  440. {
  441. if (isset($_SERVER['SERVER_NAME']))
  442. {
  443. $sServerName = $_SERVER['SERVER_NAME'];
  444. }
  445. else
  446. {
  447. // CLI mode ?
  448. $sServerName = php_uname('n');
  449. }
  450. $sUrl = str_replace(SERVER_NAME_PLACEHOLDER, $sServerName, $sUrl);
  451. }
  452. return $sUrl;
  453. }
  454. static public function GetDefaultUrlAppRoot()
  455. {
  456. // Build an absolute URL to this page on this server/port
  457. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  458. $sProtocol = self::IsConnectionSecure() ? 'https' : 'http';
  459. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  460. if ($sProtocol == 'http')
  461. {
  462. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  463. }
  464. else
  465. {
  466. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  467. }
  468. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  469. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  470. if (!empty($_SERVER['REQUEST_URI']))
  471. {
  472. $sPath = $_SERVER['REQUEST_URI'];
  473. }
  474. else
  475. {
  476. $sPath = $_SERVER['SCRIPT_NAME'];
  477. if (!empty($_SERVER['QUERY_STRING']))
  478. {
  479. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  480. }
  481. $_SERVER['REQUEST_URI'] = $sPath;
  482. }
  483. $sPath = $_SERVER['REQUEST_URI'];
  484. // remove all the parameters from the query string
  485. $iQuestionMarkPos = strpos($sPath, '?');
  486. if ($iQuestionMarkPos !== false)
  487. {
  488. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  489. }
  490. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  491. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  492. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  493. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  494. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  495. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  496. if ($sAppRootPos !== false)
  497. {
  498. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  499. }
  500. else
  501. {
  502. // Second attempt without index.php at the end...
  503. $sCurrentRelativePath = str_replace('index.php', '', $sCurrentRelativePath);
  504. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  505. if ($sAppRootPos !== false)
  506. {
  507. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  508. }
  509. else
  510. {
  511. // No luck...
  512. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  513. }
  514. }
  515. return $sAppRootUrl;
  516. }
  517. /**
  518. * Helper to handle the variety of HTTP servers
  519. * See #286 (fixed in [896]), and #634 (this fix)
  520. *
  521. * Though the official specs says 'a non empty string', some servers like IIS do set it to 'off' !
  522. * nginx set it to an empty string
  523. * Others might leave it unset (no array entry)
  524. */
  525. static public function IsConnectionSecure()
  526. {
  527. $bSecured = false;
  528. if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off'))
  529. {
  530. $bSecured = true;
  531. }
  532. return $bSecured;
  533. }
  534. /**
  535. * Tells whether or not log off operation is supported.
  536. * Actually in only one case:
  537. * 1) iTop is using an internal authentication
  538. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  539. * @return boolean True if logoff is supported, false otherwise
  540. */
  541. static function CanLogOff()
  542. {
  543. $bResult = false;
  544. if(isset($_SESSION['login_mode']))
  545. {
  546. $sLoginMode = $_SESSION['login_mode'];
  547. switch($sLoginMode)
  548. {
  549. case 'external':
  550. $bResult = false;
  551. break;
  552. case 'form':
  553. case 'basic':
  554. case 'url':
  555. case 'cas':
  556. default:
  557. $bResult = true;
  558. }
  559. }
  560. return $bResult;
  561. }
  562. /**
  563. * Initializes the CAS client
  564. */
  565. static function InitCASClient()
  566. {
  567. $sCASIncludePath = self::GetConfig()->Get('cas_include_path');
  568. include_once($sCASIncludePath.'/CAS.php');
  569. $bCASDebug = self::GetConfig()->Get('cas_debug');
  570. if ($bCASDebug)
  571. {
  572. phpCAS::setDebug(APPROOT.'log/error.log');
  573. }
  574. if (!self::$m_bCASClient)
  575. {
  576. // Initialize phpCAS
  577. $sCASVersion = self::GetConfig()->Get('cas_version');
  578. $sCASHost = self::GetConfig()->Get('cas_host');
  579. $iCASPort = self::GetConfig()->Get('cas_port');
  580. $sCASContext = self::GetConfig()->Get('cas_context');
  581. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  582. self::$m_bCASClient = true;
  583. $sCASCACertPath = self::GetConfig()->Get('cas_server_ca_cert_path');
  584. if (empty($sCASCACertPath))
  585. {
  586. // If no certificate authority is provided, do not attempt to validate
  587. // the server's certificate
  588. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  589. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  590. phpCAS::setNoCasServerValidation();
  591. }
  592. else
  593. {
  594. phpCAS::setCasServerCACert($sCASCACertPath);
  595. }
  596. }
  597. }
  598. static function DebugBacktrace($iLimit = 5)
  599. {
  600. $aFullTrace = debug_backtrace();
  601. $aLightTrace = array();
  602. for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
  603. {
  604. $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
  605. }
  606. echo "<p><pre>".print_r($aLightTrace, true)."</pre></p>\n";
  607. }
  608. /**
  609. * Execute the given iTop PHP script, passing it the current credentials
  610. * Only CLI mode is supported, because of the need to hand the credentials over to the next process
  611. * Throws an exception if the execution fails or could not be attempted (config issue)
  612. * @param string $sScript Name and relative path to the file (relative to the iTop root dir)
  613. * @param hash $aArguments Associative array of 'arg' => 'value'
  614. * @return array(iCode, array(output lines))
  615. */
  616. /**
  617. */
  618. static function ExecITopScript($sScriptName, $aArguments)
  619. {
  620. $aDisabled = explode(', ', ini_get('disable_functions'));
  621. if (in_array('exec', $aDisabled))
  622. {
  623. throw new Exception("The PHP exec() function has been disabled on this server");
  624. }
  625. $sPHPExec = trim(self::GetConfig()->Get('php_path'));
  626. if (strlen($sPHPExec) == 0)
  627. {
  628. throw new Exception("The path to php must not be empty. Please set a value for 'php_path' in your configuration file.");
  629. }
  630. $sAuthUser = self::ReadParam('auth_user', '', 'raw_data');
  631. $sAuthPwd = self::ReadParam('auth_pwd', '', 'raw_data');
  632. $sParamFile = self::GetParamSourceFile('auth_user');
  633. if (is_null($sParamFile))
  634. {
  635. $aArguments['auth_user'] = $sAuthUser;
  636. $aArguments['auth_pwd'] = $sAuthPwd;
  637. }
  638. else
  639. {
  640. $aArguments['param_file'] = $sParamFile;
  641. }
  642. $aArgs = array();
  643. foreach($aArguments as $sName => $value)
  644. {
  645. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  646. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  647. $aArgs[] = "--$sName=".escapeshellarg($value);
  648. }
  649. $sArgs = implode(' ', $aArgs);
  650. $sScript = realpath(APPROOT.$sScriptName);
  651. if (!file_exists($sScript))
  652. {
  653. throw new Exception("Could not find the script file '$sScriptName' from the directory '".APPROOT."'");
  654. }
  655. $sCommand = '"'.$sPHPExec.'" '.escapeshellarg($sScript).' -- '.$sArgs;
  656. if (version_compare(phpversion(), '5.3.0', '<'))
  657. {
  658. if (substr(PHP_OS,0,3) == 'WIN')
  659. {
  660. // Under Windows, and for PHP 5.2.x, the whole command has to be quoted
  661. // Cf PHP doc: http://php.net/manual/fr/function.exec.php, comment from the 27-Dec-2010
  662. $sCommand = '"'.$sCommand.'"';
  663. }
  664. }
  665. $sLastLine = exec($sCommand, $aOutput, $iRes);
  666. if ($iRes == 1)
  667. {
  668. throw new Exception(Dict::S('Core:ExecProcess:Code1')." - ".$sCommand);
  669. }
  670. elseif ($iRes == 255)
  671. {
  672. $sErrors = implode("\n", $aOutput);
  673. throw new Exception(Dict::S('Core:ExecProcess:Code255')." - ".$sCommand.":\n".$sErrors);
  674. }
  675. //$aOutput[] = $sCommand;
  676. return array($iRes, $aOutput);
  677. }
  678. /**
  679. * Get the current environment
  680. */
  681. public static function GetCurrentEnvironment()
  682. {
  683. if (isset($_SESSION['itop_env']))
  684. {
  685. return $_SESSION['itop_env'];
  686. }
  687. else
  688. {
  689. return ITOP_DEFAULT_ENV;
  690. }
  691. }
  692. /**
  693. * Merge standard menu items with plugin provided menus items
  694. */
  695. public static function GetPopupMenuItems($oPage, $iMenuId, $param, &$aActions, $sTableId = null, $sDataTableId = null)
  696. {
  697. // 1st - add standard built-in menu items
  698. //
  699. switch($iMenuId)
  700. {
  701. case iPopupMenuExtension::MENU_OBJLIST_TOOLKIT:
  702. // $param is a DBObjectSet
  703. $oAppContext = new ApplicationContext();
  704. $sContext = $oAppContext->GetForLink();
  705. $sDataTableId = is_null($sDataTableId) ? '' : $sDataTableId;
  706. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($param->GetFilter()->GetClass());
  707. $sOQL = addslashes($param->GetFilter()->ToOQL(true));
  708. $sFilter = urlencode($param->GetFilter()->serialize());
  709. $sUrl = utils::GetAbsoluteUrlAppRoot()."pages/$sUIPage?operation=search&filter=".$sFilter."&{$sContext}";
  710. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/xlsx-export.js');
  711. $sXlsxFilter = $param->GetFilter()->serialize();
  712. $sXlsxJSFilter = addslashes($sXlsxFilter);
  713. $aResult = array(
  714. new SeparatorPopupMenuItem(),
  715. // Static menus: Email this page, CSV Export & Add to Dashboard
  716. new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), "mailto:?body=".urlencode($sUrl).' '), // Add an extra space to make it work in Outlook
  717. new URLPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), $sUrl."&format=csv"),
  718. new JSPopupMenuItem('xlsx-export', Dict::S('ExcelExporter:ExportMenu'), "XlsxExportDialog('$sXlsxJSFilter');", array()),
  719. new JSPopupMenuItem('UI:Menu:AddToDashboard', Dict::S('UI:Menu:AddToDashboard'), "DashletCreationDlg('$sOQL')"),
  720. new JSPopupMenuItem('UI:Menu:ShortcutList', Dict::S('UI:Menu:ShortcutList'), "ShortcutListDlg('$sOQL', '$sDataTableId', '$sContext')"),
  721. );
  722. break;
  723. case iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS:
  724. // $param is a DBObject
  725. $oObj = $param;
  726. $oFilter = DBobjectSearch::FromOQL("SELECT ".get_class($oObj)." WHERE id=".$oObj->GetKey());
  727. $sFilter = $oFilter->serialize();
  728. $sUrl = ApplicationContext::MakeObjectUrl(get_class($oObj), $oObj->GetKey());
  729. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage(get_class($oObj));
  730. $oAppContext = new ApplicationContext();
  731. $sContext = $oAppContext->GetForLink();
  732. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/xlsx-export.js');
  733. $sXlsxFilter = $param->GetFilter()->serialize();
  734. $sXlsxJSFilter = addslashes($sXlsxFilter);
  735. $aResult = array(
  736. new SeparatorPopupMenuItem(),
  737. // Static menus: Email this page & CSV Export
  738. new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl).' '), // Add an extra space to make it work in Outlook
  739. new URLPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), utils::GetAbsoluteUrlAppRoot()."pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv&{$sContext}"),
  740. new JSPopupMenuItem('xlsx-export', Dict::S('ExcelExporter:ExportMenu'), "XlsxExportDialog('$sXlsxJSFilter');", array()),
  741. );
  742. break;
  743. case iPopupMenuExtension::MENU_DASHBOARD_ACTIONS:
  744. // $param is a Dashboard
  745. $oAppContext = new ApplicationContext();
  746. $aParams = $oAppContext->GetAsHash();
  747. $sMenuId = ApplicationMenu::GetActiveNodeId();
  748. $sDlgTitle = addslashes(Dict::S('UI:ImportDashboardTitle'));
  749. $sDlgText = addslashes(Dict::S('UI:ImportDashboardText'));
  750. $sCloseBtn = addslashes(Dict::S('UI:Button:Cancel'));
  751. $aResult = array(
  752. new SeparatorPopupMenuItem(),
  753. new URLPopupMenuItem('UI:ExportDashboard', Dict::S('UI:ExportDashBoard'), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=export_dashboard&id='.$sMenuId),
  754. new JSPopupMenuItem('UI:ImportDashboard', Dict::S('UI:ImportDashBoard'), "UploadDashboard({dashboard_id: '$sMenuId', title: '$sDlgTitle', text: '$sDlgText', close_btn: '$sCloseBtn' })"),
  755. );
  756. break;
  757. default:
  758. // Unknown type of menu, do nothing
  759. $aResult = array();
  760. }
  761. foreach($aResult as $oMenuItem)
  762. {
  763. $aActions[$oMenuItem->GetUID()] = $oMenuItem->GetMenuItem();
  764. }
  765. // Invoke the plugins
  766. //
  767. foreach (MetaModel::EnumPlugins('iPopupMenuExtension') as $oExtensionInstance)
  768. {
  769. if (is_object($param) && !($param instanceof DBObject))
  770. {
  771. $tmpParam = clone $param; // In case the parameter is an DBObjectSet, clone it to prevent alterations
  772. }
  773. else
  774. {
  775. $tmpParam = $param;
  776. }
  777. foreach($oExtensionInstance->EnumItems($iMenuId, $tmpParam) as $oMenuItem)
  778. {
  779. if (is_object($oMenuItem))
  780. {
  781. $aActions[$oMenuItem->GetUID()] = $oMenuItem->GetMenuItem();
  782. foreach($oMenuItem->GetLinkedScripts() as $sLinkedScript)
  783. {
  784. $oPage->add_linked_script($sLinkedScript);
  785. }
  786. }
  787. }
  788. }
  789. }
  790. /**
  791. * Get target configuration file name (including full path)
  792. */
  793. public static function GetConfigFilePath($sEnvironment = null)
  794. {
  795. if (is_null($sEnvironment))
  796. {
  797. $sEnvironment = self::GetCurrentEnvironment();
  798. }
  799. return APPCONF.$sEnvironment.'/'.ITOP_CONFIG_FILE;
  800. }
  801. /**
  802. * Returns the absolute URL to the modules root path
  803. * @return string ...
  804. */
  805. static public function GetAbsoluteUrlModulesRoot()
  806. {
  807. $sUrl = self::GetAbsoluteUrlAppRoot().'env-'.self::GetCurrentEnvironment().'/';
  808. return $sUrl;
  809. }
  810. /**
  811. * Returns the URL to a page that will execute the requested module page
  812. *
  813. * To be compatible with this mechanism, the called page must include approot
  814. * with an absolute path OR not include it at all (losing the direct access to the page)
  815. * if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  816. * require_once(__DIR__.'/../../approot.inc.php');
  817. *
  818. * @return string ...
  819. */
  820. static public function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = array(), $sEnvironment = null)
  821. {
  822. $sEnvironment = is_null($sEnvironment) ? self::GetCurrentEnvironment() : $sEnvironment;
  823. $aArgs = array();
  824. $aArgs[] = 'exec_module='.$sModule;
  825. $aArgs[] = 'exec_page='.$sPage;
  826. $aArgs[] = 'exec_env='.$sEnvironment;
  827. foreach($aArguments as $sName => $sValue)
  828. {
  829. if (($sName == 'exec_module')||($sName == 'exec_page')||($sName == 'exec_env'))
  830. {
  831. throw new Exception("Module page: $sName is a reserved page argument name");
  832. }
  833. $aArgs[] = $sName.'='.urlencode($sValue);
  834. }
  835. $sArgs = implode('&', $aArgs);
  836. return self::GetAbsoluteUrlAppRoot().'pages/exec.php?'.$sArgs;
  837. }
  838. /**
  839. * Returns a name unique amongst the given list
  840. * @param string $sProposed The default value
  841. * @param array $aExisting An array of existing values (strings)
  842. */
  843. static public function MakeUniqueName($sProposed, $aExisting)
  844. {
  845. if (in_array($sProposed, $aExisting))
  846. {
  847. $i = 1;
  848. while (in_array($sProposed.$i, $aExisting) && ($i < 50))
  849. {
  850. $i++;
  851. }
  852. return $sProposed.$i;
  853. }
  854. else
  855. {
  856. return $sProposed;
  857. }
  858. }
  859. /**
  860. * Some characters cause troubles with jQuery when used inside DOM IDs, so let's replace them by the safe _ (underscore)
  861. * @param string $sId The ID to sanitize
  862. * @return string The sanitized ID
  863. */
  864. static public function GetSafeId($sId)
  865. {
  866. return str_replace(array(':', '[', ']', '+', '-'), '_', $sId);
  867. }
  868. /**
  869. * Helper to execute an HTTP POST request
  870. * Source: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
  871. * originaly named after do_post_request
  872. * Does not require cUrl but requires openssl for performing https POSTs.
  873. *
  874. * @param string $sUrl The URL to POST the data to
  875. * @param hash $aData The data to POST as an array('param_name' => value)
  876. * @param string $sOptionnalHeaders Additional HTTP headers as a string with newlines between headers
  877. * @param hash $aResponseHeaders An array to be filled with reponse headers: WARNING: the actual content of the array depends on the library used: cURL or fopen, test with both !! See: http://fr.php.net/manual/en/function.curl-getinfo.php
  878. * @return string The result of the POST request
  879. * @throws Exception
  880. */
  881. static public function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null)
  882. {
  883. // $sOptionnalHeaders is a string containing additional HTTP headers that you would like to send in your request.
  884. if (function_exists('curl_init'))
  885. {
  886. // If cURL is available, let's use it, since it provides a greater control over the various HTTP/SSL options
  887. // For instance fopen does not allow to work around the bug: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
  888. // by setting the SSLVERSION to 3 as done below.
  889. $aHeaders = explode("\n", $sOptionnalHeaders);
  890. $aHTTPHeaders = array();
  891. foreach($aHeaders as $sHeaderString)
  892. {
  893. if(preg_match('/^([^:]): (.+)$/', $sHeaderString, $aMatches))
  894. {
  895. $aHTTPHeaders[$aMatches[1]] = $aMatches[2];
  896. }
  897. }
  898. $aOptions = array(
  899. CURLOPT_RETURNTRANSFER => true, // return the content of the request
  900. CURLOPT_HEADER => false, // don't return the headers in the output
  901. CURLOPT_FOLLOWLOCATION => true, // follow redirects
  902. CURLOPT_ENCODING => "", // handle all encodings
  903. CURLOPT_USERAGENT => "spider", // who am i
  904. CURLOPT_AUTOREFERER => true, // set referer on redirect
  905. CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
  906. CURLOPT_TIMEOUT => 120, // timeout on response
  907. CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
  908. CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
  909. CURLOPT_SSLVERSION => 3, // MUST to prevent a strange SSL error: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
  910. CURLOPT_POST => count($aData),
  911. CURLOPT_POSTFIELDS => http_build_query($aData),
  912. CURLOPT_HTTPHEADER => $aHTTPHeaders,
  913. );
  914. $ch = curl_init($sUrl);
  915. curl_setopt_array($ch, $aOptions);
  916. $response = curl_exec($ch);
  917. $iErr = curl_errno($ch);
  918. $sErrMsg = curl_error( $ch );
  919. $aHeaders = curl_getinfo( $ch );
  920. if ($iErr !== 0)
  921. {
  922. throw new Exception("Problem opening URL: $sUrl, $sErrMsg");
  923. }
  924. if (is_array($aResponseHeaders))
  925. {
  926. $aHeaders = curl_getinfo($ch);
  927. foreach($aHeaders as $sCode => $sValue)
  928. {
  929. $sName = str_replace(' ' , '-', ucwords(str_replace('_', ' ', $sCode))); // Transform "content_type" into "Content-Type"
  930. $aResponseHeaders[$sName] = $sValue;
  931. }
  932. }
  933. curl_close( $ch );
  934. }
  935. else
  936. {
  937. // cURL is not available let's try with streams and fopen...
  938. $sData = http_build_query($aData);
  939. $aParams = array('http' => array(
  940. 'method' => 'POST',
  941. 'content' => $sData,
  942. 'header'=> "Content-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($sData)."\r\n",
  943. ));
  944. if ($sOptionnalHeaders !== null)
  945. {
  946. $aParams['http']['header'] .= $sOptionnalHeaders;
  947. }
  948. $ctx = stream_context_create($aParams);
  949. $fp = @fopen($sUrl, 'rb', false, $ctx);
  950. if (!$fp)
  951. {
  952. global $php_errormsg;
  953. if (isset($php_errormsg))
  954. {
  955. throw new Exception("Wrong URL: $sUrl, $php_errormsg");
  956. }
  957. elseif ((strtolower(substr($sUrl, 0, 5)) == 'https') && !extension_loaded('openssl'))
  958. {
  959. throw new Exception("Cannot connect to $sUrl: missing module 'openssl'");
  960. }
  961. else
  962. {
  963. throw new Exception("Wrong URL: $sUrl");
  964. }
  965. }
  966. $response = @stream_get_contents($fp);
  967. if ($response === false)
  968. {
  969. throw new Exception("Problem reading data from $sUrl, $php_errormsg");
  970. }
  971. if (is_array($aResponseHeaders))
  972. {
  973. $aMeta = stream_get_meta_data($fp);
  974. $aHeaders = $aMeta['wrapper_data'];
  975. foreach($aHeaders as $sHeaderString)
  976. {
  977. if(preg_match('/^([^:]+): (.+)$/', $sHeaderString, $aMatches))
  978. {
  979. $aResponseHeaders[$aMatches[1]] = trim($aMatches[2]);
  980. }
  981. }
  982. }
  983. }
  984. return $response;
  985. }
  986. }
  987. ?>