utils.inc.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. <?php
  2. use Html2Text\Html2Text;
  3. use Leafo\ScssPhp\Compiler;
  4. // Copyright (C) 2010-2017 Combodo SARL
  5. //
  6. // This file is part of iTop.
  7. //
  8. // iTop is free software; you can redistribute it and/or modify
  9. // it under the terms of the GNU Affero General Public License as published by
  10. // the Free Software Foundation, either version 3 of the License, or
  11. // (at your option) any later version.
  12. //
  13. // iTop is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  20. /**
  21. * Static class utils
  22. *
  23. * @copyright Copyright (C) 2010-2017 Combodo SARL
  24. * @license http://opensource.org/licenses/AGPL-3.0
  25. */
  26. require_once(APPROOT.'/core/config.class.inc.php');
  27. require_once(APPROOT.'/application/transaction.class.inc.php');
  28. require_once(APPROOT.'application/Html2Text.php');
  29. require_once(APPROOT.'application/Html2TextException.php');
  30. define('ITOP_CONFIG_FILE', 'config-itop.php');
  31. define('ITOP_DEFAULT_CONFIG_FILE', APPCONF.ITOP_DEFAULT_ENV.'/'.ITOP_CONFIG_FILE);
  32. define('SERVER_NAME_PLACEHOLDER', '$SERVER_NAME$');
  33. class FileUploadException extends Exception
  34. {
  35. }
  36. /**
  37. * Helper functions to interact with forms: read parameters, upload files...
  38. * @package iTop
  39. */
  40. class utils
  41. {
  42. private static $oConfig = null;
  43. private static $m_bCASClient = false;
  44. // Parameters loaded from a file, parameters of the page/command line still have precedence
  45. private static $m_aParamsFromFile = null;
  46. private static $m_aParamSource = array();
  47. protected static function LoadParamFile($sParamFile)
  48. {
  49. if (!file_exists($sParamFile))
  50. {
  51. throw new Exception("Could not find the parameter file: '$sParamFile'");
  52. }
  53. if (!is_readable($sParamFile))
  54. {
  55. throw new Exception("Could not load parameter file: '$sParamFile'");
  56. }
  57. $sParams = file_get_contents($sParamFile);
  58. if (is_null(self::$m_aParamsFromFile))
  59. {
  60. self::$m_aParamsFromFile = array();
  61. }
  62. $aParamLines = explode("\n", $sParams);
  63. foreach ($aParamLines as $sLine)
  64. {
  65. $sLine = trim($sLine);
  66. // Ignore the line after a '#'
  67. if (($iCommentPos = strpos($sLine, '#')) !== false)
  68. {
  69. $sLine = substr($sLine, 0, $iCommentPos);
  70. $sLine = trim($sLine);
  71. }
  72. // Note: the line is supposed to be already trimmed
  73. if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches))
  74. {
  75. $sParam = $aMatches[1];
  76. $value = trim($aMatches[2]);
  77. self::$m_aParamsFromFile[$sParam] = $value;
  78. self::$m_aParamSource[$sParam] = $sParamFile;
  79. }
  80. }
  81. }
  82. public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
  83. {
  84. $sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI, 'raw_data');
  85. foreach(explode(',', $sFileSpec) as $sFile)
  86. {
  87. $sFile = trim($sFile);
  88. if (!empty($sFile))
  89. {
  90. self::LoadParamFile($sFile);
  91. }
  92. }
  93. }
  94. /**
  95. * Return the source file from which the parameter has been found,
  96. * usefull when it comes to pass user credential to a process executed
  97. * in the background
  98. * @param $sName Parameter name
  99. * @return The file name if any, or null
  100. */
  101. public static function GetParamSourceFile($sName)
  102. {
  103. if (array_key_exists($sName, self::$m_aParamSource))
  104. {
  105. return self::$m_aParamSource[$sName];
  106. }
  107. else
  108. {
  109. return null;
  110. }
  111. }
  112. public static function IsModeCLI()
  113. {
  114. $sSAPIName = php_sapi_name();
  115. $sCleanName = strtolower(trim($sSAPIName));
  116. if ($sCleanName == 'cli')
  117. {
  118. return true;
  119. }
  120. else
  121. {
  122. return false;
  123. }
  124. }
  125. protected static $bPageMode = null;
  126. protected static $aModes = array();
  127. public static function InitArchiveMode()
  128. {
  129. if (isset($_SESSION['archive_mode']))
  130. {
  131. $iDefault = $_SESSION['archive_mode'];
  132. }
  133. else
  134. {
  135. $iDefault = 0;
  136. }
  137. // Read and record the value for switching the archive mode
  138. $iCurrent = self::ReadParam('with-archive', $iDefault);
  139. $_SESSION['archive_mode'] = $iCurrent;
  140. // Read and use the value for the current page (web services)
  141. $iCurrent = self::ReadParam('with_archive', $iCurrent, true);
  142. self::$bPageMode = ($iCurrent == 1);
  143. }
  144. public static function PushArchiveMode($bMode)
  145. {
  146. array_push(self::$aModes, $bMode);
  147. }
  148. public static function PopArchiveMode()
  149. {
  150. array_pop(self::$aModes);
  151. }
  152. public static function IsArchiveMode()
  153. {
  154. if (count(self::$aModes) > 0)
  155. {
  156. $bRet = end(self::$aModes);
  157. }
  158. else
  159. {
  160. if (self::$bPageMode === null)
  161. {
  162. self::InitArchiveMode();
  163. }
  164. $bRet = self::$bPageMode;
  165. }
  166. return $bRet;
  167. }
  168. /**
  169. * Helper to be called by the GUI and define if the user will see obsolete data (otherwise, the user will have to dig further)
  170. * @return bool
  171. */
  172. public static function ShowObsoleteData()
  173. {
  174. $bDefault = MetaModel::GetConfig()->Get('obsolescence.show_obsolete_data'); // default is false
  175. $bShow = appUserPreferences::GetPref('show_obsolete_data', $bDefault);
  176. if (static::IsArchiveMode())
  177. {
  178. $bShow = true;
  179. }
  180. return $bShow;
  181. }
  182. public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false, $sSanitizationFilter = 'parameter')
  183. {
  184. global $argv;
  185. $retValue = $defaultValue;
  186. if (!is_null(self::$m_aParamsFromFile))
  187. {
  188. if (isset(self::$m_aParamsFromFile[$sName]))
  189. {
  190. $retValue = self::$m_aParamsFromFile[$sName];
  191. }
  192. }
  193. if (isset($_REQUEST[$sName]))
  194. {
  195. $retValue = $_REQUEST[$sName];
  196. }
  197. elseif ($bAllowCLI && isset($argv))
  198. {
  199. foreach($argv as $iArg => $sArg)
  200. {
  201. if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
  202. {
  203. $retValue = $aMatches[1];
  204. }
  205. }
  206. }
  207. return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
  208. }
  209. public static function ReadPostedParam($sName, $defaultValue = '', $sSanitizationFilter = 'parameter')
  210. {
  211. $retValue = isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  212. return self::Sanitize($retValue, $defaultValue, $sSanitizationFilter);
  213. }
  214. public static function Sanitize($value, $defaultValue, $sSanitizationFilter)
  215. {
  216. if ($value === $defaultValue)
  217. {
  218. // Preserve the real default value (can be used to detect missing mandatory parameters)
  219. $retValue = $value;
  220. }
  221. else
  222. {
  223. $retValue = self::Sanitize_Internal($value, $sSanitizationFilter);
  224. if ($retValue === false)
  225. {
  226. $retValue = $defaultValue;
  227. }
  228. }
  229. return $retValue;
  230. }
  231. protected static function Sanitize_Internal($value, $sSanitizationFilter)
  232. {
  233. switch($sSanitizationFilter)
  234. {
  235. case 'integer':
  236. $retValue = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
  237. break;
  238. case 'class':
  239. $retValue = $value;
  240. if (!MetaModel::IsValidClass($value))
  241. {
  242. $retValue = false;
  243. }
  244. break;
  245. case 'string':
  246. $retValue = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
  247. break;
  248. case 'context_param':
  249. case 'parameter':
  250. case 'field_name':
  251. if (is_array($value))
  252. {
  253. $retValue = array();
  254. foreach($value as $key => $val)
  255. {
  256. $retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays
  257. if ($retValue[$key] === false)
  258. {
  259. $retValue = false;
  260. break;
  261. }
  262. }
  263. }
  264. else
  265. {
  266. switch($sSanitizationFilter)
  267. {
  268. case 'parameter':
  269. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[ A-Za-z0-9_=-]*$/'))); // the '=' equal character is used in serialized filters
  270. break;
  271. case 'field_name':
  272. $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
  273. break;
  274. case 'context_param':
  275. $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>'/^[ A-Za-z0-9_=%:+-]*$/')));
  276. break;
  277. }
  278. }
  279. break;
  280. default:
  281. case 'raw_data':
  282. $retValue = $value;
  283. // Do nothing
  284. }
  285. return $retValue;
  286. }
  287. /**
  288. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  289. * @param string $sName Name of the input used from uploading the file
  290. * @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
  291. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  292. */
  293. public static function ReadPostedDocument($sName, $sIndex = null)
  294. {
  295. $oDocument = new ormDocument(); // an empty document
  296. if(isset($_FILES[$sName]))
  297. {
  298. $aFileInfo = $_FILES[$sName];
  299. $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
  300. switch($sError)
  301. {
  302. case UPLOAD_ERR_OK:
  303. $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
  304. $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
  305. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  306. $doc_content = file_get_contents($sTmpName);
  307. if (function_exists('finfo_file'))
  308. {
  309. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  310. // in which case we don't trust the mime type provided by the browser
  311. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  312. if ($rInfo !== false)
  313. {
  314. $sType = @finfo_file($rInfo, $sTmpName);
  315. if ( ($sType !== false)
  316. && is_string($sType)
  317. && (strlen($sType)>0))
  318. {
  319. $sMimeType = $sType;
  320. }
  321. }
  322. @finfo_close($rInfo);
  323. }
  324. $oDocument = new ormDocument($doc_content, $sMimeType, $sName);
  325. break;
  326. case UPLOAD_ERR_NO_FILE:
  327. // no file to load, it's a normal case, just return an empty document
  328. break;
  329. case UPLOAD_ERR_FORM_SIZE:
  330. case UPLOAD_ERR_INI_SIZE:
  331. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  332. break;
  333. case UPLOAD_ERR_PARTIAL:
  334. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  335. break;
  336. case UPLOAD_ERR_NO_TMP_DIR:
  337. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  338. break;
  339. case UPLOAD_ERR_CANT_WRITE:
  340. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  341. break;
  342. case UPLOAD_ERR_EXTENSION:
  343. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  344. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
  345. break;
  346. default:
  347. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
  348. break;
  349. }
  350. }
  351. return $oDocument;
  352. }
  353. /**
  354. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  355. * @param $oFullSetFilter DBSearch The criteria defining the whole sets of objects being selected
  356. * @return Array An arry of object IDs corresponding to the objects selected in the set
  357. */
  358. public static function ReadMultipleSelection($oFullSetFilter)
  359. {
  360. $aSelectedObj = utils::ReadParam('selectObject', array());
  361. $sSelectionMode = utils::ReadParam('selectionMode', '');
  362. if ($sSelectionMode != '')
  363. {
  364. // Paginated selection
  365. $aExceptions = utils::ReadParam('storedSelection', array());
  366. if ($sSelectionMode == 'positive')
  367. {
  368. // Only the explicitely listed items are selected
  369. $aSelectedObj = $aExceptions;
  370. }
  371. else
  372. {
  373. // All items of the set are selected, except the one explicitely listed
  374. $aSelectedObj = array();
  375. $oFullSet = new DBObjectSet($oFullSetFilter);
  376. $sClassAlias = $oFullSetFilter->GetClassAlias();
  377. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  378. while($oObj = $oFullSet->Fetch())
  379. {
  380. if (!in_array($oObj->GetKey(), $aExceptions))
  381. {
  382. $aSelectedObj[] = $oObj->GetKey();
  383. }
  384. }
  385. }
  386. }
  387. return $aSelectedObj;
  388. }
  389. public static function GetNewTransactionId()
  390. {
  391. return privUITransaction::GetNewTransactionId();
  392. }
  393. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  394. {
  395. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  396. }
  397. public static function RemoveTransaction($sId)
  398. {
  399. return privUITransaction::RemoveTransaction($sId);
  400. }
  401. /**
  402. * Returns a unique tmp id for the current upload based on the transaction system (db).
  403. *
  404. * Build as session_id() . '_' . static::GetNewTransactionId()
  405. *
  406. * @return string
  407. */
  408. public static function GetUploadTempId($sTransactionId = null)
  409. {
  410. if ($sTransactionId === null)
  411. {
  412. $sTransactionId = static::GetNewTransactionId();
  413. }
  414. return session_id() . '_' . $sTransactionId;
  415. }
  416. public static function ReadFromFile($sFileName)
  417. {
  418. if (!file_exists($sFileName)) return false;
  419. return file_get_contents($sFileName);
  420. }
  421. /**
  422. * Helper function to convert a value expressed in a 'user friendly format'
  423. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  424. * @param mixed $value The value as read from php.ini
  425. * @return number
  426. */
  427. public static function ConvertToBytes( $value )
  428. {
  429. $iReturn = $value;
  430. if ( !is_numeric( $value ) )
  431. {
  432. $iLength = strlen( $value );
  433. $iReturn = substr( $value, 0, $iLength - 1 );
  434. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  435. switch ( $sUnit )
  436. {
  437. case 'G':
  438. $iReturn *= 1024;
  439. case 'M':
  440. $iReturn *= 1024;
  441. case 'K':
  442. $iReturn *= 1024;
  443. }
  444. }
  445. return $iReturn;
  446. }
  447. /**
  448. * Format a value into a more friendly format (KB, MB, GB, TB) instead a juste a Bytes amount.
  449. *
  450. * @param type $value
  451. * @return string
  452. */
  453. public static function BytesToFriendlyFormat($value)
  454. {
  455. $sReturn = '';
  456. // Kilobytes
  457. if ($value >= 1024)
  458. {
  459. $sReturn = 'K';
  460. $value = $value / 1024;
  461. }
  462. // Megabytes
  463. if ($value >= 1024)
  464. {
  465. $sReturn = 'M';
  466. $value = $value / 1024;
  467. }
  468. // Gigabytes
  469. if ($value >= 1024)
  470. {
  471. $sReturn = 'G';
  472. $value = $value / 1024;
  473. }
  474. // Terabytes
  475. if ($value >= 1024)
  476. {
  477. $sReturn = 'T';
  478. $value = $value / 1024;
  479. }
  480. $value = round($value, 1);
  481. return $value . '' . $sReturn . 'B';
  482. }
  483. /**
  484. * 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)
  485. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  486. * @param string $sDate
  487. * @param string $sFormat
  488. * @return timestamp or false if the input format is not correct
  489. */
  490. public static function StringToTime($sDate, $sFormat)
  491. {
  492. // Source: http://php.net/manual/fr/function.strftime.php
  493. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  494. static $aDateTokens = null;
  495. static $aDateRegexps = null;
  496. if (is_null($aDateTokens))
  497. {
  498. $aSpec = array(
  499. '%d' =>'(?<day>[0-9]{2})',
  500. '%m' => '(?<month>[0-9]{2})',
  501. '%y' => '(?<year>[0-9]{2})',
  502. '%Y' => '(?<year>[0-9]{4})',
  503. '%H' => '(?<hour>[0-2][0-9])',
  504. '%i' => '(?<minute>[0-5][0-9])',
  505. '%s' => '(?<second>[0-5][0-9])',
  506. );
  507. $aDateTokens = array_keys($aSpec);
  508. $aDateRegexps = array_values($aSpec);
  509. }
  510. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  511. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  512. {
  513. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  514. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  515. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  516. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  517. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  518. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  519. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  520. }
  521. else
  522. {
  523. return false;
  524. }
  525. // http://www.spaweditor.com/scripts/regex/index.php
  526. }
  527. /**
  528. * Convert an old date/time format specifciation (using % placeholders)
  529. * to a format compatible with DateTime::createFromFormat
  530. * @param string $sOldDateTimeFormat
  531. * @return string
  532. */
  533. static public function DateTimeFormatToPHP($sOldDateTimeFormat)
  534. {
  535. $aSearch = array('%d', '%m', '%y', '%Y', '%H', '%i', '%s');
  536. $aReplacement = array('d', 'm', 'y', 'Y', 'H', 'i', 's');
  537. return str_replace($aSearch, $aReplacement, $sOldDateTimeFormat);
  538. }
  539. static public function GetConfig()
  540. {
  541. if (self::$oConfig == null)
  542. {
  543. $sConfigFile = self::GetConfigFilePath();
  544. if (file_exists($sConfigFile))
  545. {
  546. self::$oConfig = new Config($sConfigFile);
  547. }
  548. else
  549. {
  550. // When executing the setup, the config file may be still missing
  551. self::$oConfig = new Config();
  552. }
  553. }
  554. return self::$oConfig;
  555. }
  556. /**
  557. * Returns the absolute URL to the application root path
  558. * @return string The absolute URL to the application root, without the first slash
  559. */
  560. static public function GetAbsoluteUrlAppRoot()
  561. {
  562. static $sUrl = null;
  563. if ($sUrl === null)
  564. {
  565. $sUrl = self::GetConfig()->Get('app_root_url');
  566. if ($sUrl == '')
  567. {
  568. $sUrl = self::GetDefaultUrlAppRoot();
  569. }
  570. elseif (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
  571. {
  572. if (isset($_SERVER['SERVER_NAME']))
  573. {
  574. $sServerName = $_SERVER['SERVER_NAME'];
  575. }
  576. else
  577. {
  578. // CLI mode ?
  579. $sServerName = php_uname('n');
  580. }
  581. $sUrl = str_replace(SERVER_NAME_PLACEHOLDER, $sServerName, $sUrl);
  582. }
  583. }
  584. return $sUrl;
  585. }
  586. static public function GetDefaultUrlAppRoot()
  587. {
  588. // Build an absolute URL to this page on this server/port
  589. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  590. $sProtocol = self::IsConnectionSecure() ? 'https' : 'http';
  591. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  592. if ($sProtocol == 'http')
  593. {
  594. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  595. }
  596. else
  597. {
  598. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  599. }
  600. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  601. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  602. if (!empty($_SERVER['REQUEST_URI']))
  603. {
  604. $sPath = $_SERVER['REQUEST_URI'];
  605. }
  606. else
  607. {
  608. $sPath = $_SERVER['SCRIPT_NAME'];
  609. if (!empty($_SERVER['QUERY_STRING']))
  610. {
  611. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  612. }
  613. $_SERVER['REQUEST_URI'] = $sPath;
  614. }
  615. $sPath = $_SERVER['REQUEST_URI'];
  616. // remove all the parameters from the query string
  617. $iQuestionMarkPos = strpos($sPath, '?');
  618. if ($iQuestionMarkPos !== false)
  619. {
  620. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  621. }
  622. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  623. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  624. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  625. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  626. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  627. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  628. if ($sAppRootPos !== false)
  629. {
  630. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  631. }
  632. else
  633. {
  634. // Second attempt without index.php at the end...
  635. $sCurrentRelativePath = str_replace('index.php', '', $sCurrentRelativePath);
  636. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  637. if ($sAppRootPos !== false)
  638. {
  639. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  640. }
  641. else
  642. {
  643. // No luck...
  644. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  645. }
  646. }
  647. return $sAppRootUrl;
  648. }
  649. /**
  650. * Helper to handle the variety of HTTP servers
  651. * See #286 (fixed in [896]), and #634 (this fix)
  652. *
  653. * Though the official specs says 'a non empty string', some servers like IIS do set it to 'off' !
  654. * nginx set it to an empty string
  655. * Others might leave it unset (no array entry)
  656. */
  657. static public function IsConnectionSecure()
  658. {
  659. $bSecured = false;
  660. if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off'))
  661. {
  662. $bSecured = true;
  663. }
  664. return $bSecured;
  665. }
  666. /**
  667. * Tells whether or not log off operation is supported.
  668. * Actually in only one case:
  669. * 1) iTop is using an internal authentication
  670. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  671. * @return boolean True if logoff is supported, false otherwise
  672. */
  673. static function CanLogOff()
  674. {
  675. $bResult = false;
  676. if(isset($_SESSION['login_mode']))
  677. {
  678. $sLoginMode = $_SESSION['login_mode'];
  679. switch($sLoginMode)
  680. {
  681. case 'external':
  682. $bResult = false;
  683. break;
  684. case 'form':
  685. case 'basic':
  686. case 'url':
  687. case 'cas':
  688. default:
  689. $bResult = true;
  690. }
  691. }
  692. return $bResult;
  693. }
  694. /**
  695. * Initializes the CAS client
  696. */
  697. static function InitCASClient()
  698. {
  699. $sCASIncludePath = self::GetConfig()->Get('cas_include_path');
  700. include_once($sCASIncludePath.'/CAS.php');
  701. $bCASDebug = self::GetConfig()->Get('cas_debug');
  702. if ($bCASDebug)
  703. {
  704. phpCAS::setDebug(APPROOT.'log/error.log');
  705. }
  706. if (!self::$m_bCASClient)
  707. {
  708. // Initialize phpCAS
  709. $sCASVersion = self::GetConfig()->Get('cas_version');
  710. $sCASHost = self::GetConfig()->Get('cas_host');
  711. $iCASPort = self::GetConfig()->Get('cas_port');
  712. $sCASContext = self::GetConfig()->Get('cas_context');
  713. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  714. self::$m_bCASClient = true;
  715. $sCASCACertPath = self::GetConfig()->Get('cas_server_ca_cert_path');
  716. if (empty($sCASCACertPath))
  717. {
  718. // If no certificate authority is provided, do not attempt to validate
  719. // the server's certificate
  720. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  721. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  722. phpCAS::setNoCasServerValidation();
  723. }
  724. else
  725. {
  726. phpCAS::setCasServerCACert($sCASCACertPath);
  727. }
  728. }
  729. }
  730. static function DebugBacktrace($iLimit = 5)
  731. {
  732. $aFullTrace = debug_backtrace();
  733. $aLightTrace = array();
  734. for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
  735. {
  736. $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
  737. }
  738. echo "<p><pre>".print_r($aLightTrace, true)."</pre></p>\n";
  739. }
  740. /**
  741. * Execute the given iTop PHP script, passing it the current credentials
  742. * Only CLI mode is supported, because of the need to hand the credentials over to the next process
  743. * Throws an exception if the execution fails or could not be attempted (config issue)
  744. * @param string $sScript Name and relative path to the file (relative to the iTop root dir)
  745. * @param hash $aArguments Associative array of 'arg' => 'value'
  746. * @return array(iCode, array(output lines))
  747. */
  748. /**
  749. */
  750. static function ExecITopScript($sScriptName, $aArguments)
  751. {
  752. $aDisabled = explode(', ', ini_get('disable_functions'));
  753. if (in_array('exec', $aDisabled))
  754. {
  755. throw new Exception("The PHP exec() function has been disabled on this server");
  756. }
  757. $sPHPExec = trim(self::GetConfig()->Get('php_path'));
  758. if (strlen($sPHPExec) == 0)
  759. {
  760. throw new Exception("The path to php must not be empty. Please set a value for 'php_path' in your configuration file.");
  761. }
  762. $sAuthUser = self::ReadParam('auth_user', '', 'raw_data');
  763. $sAuthPwd = self::ReadParam('auth_pwd', '', 'raw_data');
  764. $sParamFile = self::GetParamSourceFile('auth_user');
  765. if (is_null($sParamFile))
  766. {
  767. $aArguments['auth_user'] = $sAuthUser;
  768. $aArguments['auth_pwd'] = $sAuthPwd;
  769. }
  770. else
  771. {
  772. $aArguments['param_file'] = $sParamFile;
  773. }
  774. $aArgs = array();
  775. foreach($aArguments as $sName => $value)
  776. {
  777. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  778. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  779. $aArgs[] = "--$sName=".escapeshellarg($value);
  780. }
  781. $sArgs = implode(' ', $aArgs);
  782. $sScript = realpath(APPROOT.$sScriptName);
  783. if (!file_exists($sScript))
  784. {
  785. throw new Exception("Could not find the script file '$sScriptName' from the directory '".APPROOT."'");
  786. }
  787. $sCommand = '"'.$sPHPExec.'" '.escapeshellarg($sScript).' -- '.$sArgs;
  788. if (version_compare(phpversion(), '5.3.0', '<'))
  789. {
  790. if (substr(PHP_OS,0,3) == 'WIN')
  791. {
  792. // Under Windows, and for PHP 5.2.x, the whole command has to be quoted
  793. // Cf PHP doc: http://php.net/manual/fr/function.exec.php, comment from the 27-Dec-2010
  794. $sCommand = '"'.$sCommand.'"';
  795. }
  796. }
  797. $sLastLine = exec($sCommand, $aOutput, $iRes);
  798. if ($iRes == 1)
  799. {
  800. throw new Exception(Dict::S('Core:ExecProcess:Code1')." - ".$sCommand);
  801. }
  802. elseif ($iRes == 255)
  803. {
  804. $sErrors = implode("\n", $aOutput);
  805. throw new Exception(Dict::S('Core:ExecProcess:Code255')." - ".$sCommand.":\n".$sErrors);
  806. }
  807. //$aOutput[] = $sCommand;
  808. return array($iRes, $aOutput);
  809. }
  810. /**
  811. * Get the current environment
  812. */
  813. public static function GetCurrentEnvironment()
  814. {
  815. if (isset($_SESSION['itop_env']))
  816. {
  817. return $_SESSION['itop_env'];
  818. }
  819. else
  820. {
  821. return ITOP_DEFAULT_ENV;
  822. }
  823. }
  824. /**
  825. * Returns a path to a folder into which any module can store cache data
  826. * The corresponding folder is created or cleaned upon code compilation
  827. * @return string
  828. */
  829. public static function GetCachePath()
  830. {
  831. return APPROOT.'data/cache-'.self::GetCurrentEnvironment().'/';
  832. }
  833. /**
  834. * Merge standard menu items with plugin provided menus items
  835. */
  836. public static function GetPopupMenuItems($oPage, $iMenuId, $param, &$aActions, $sTableId = null, $sDataTableId = null)
  837. {
  838. // 1st - add standard built-in menu items
  839. //
  840. switch($iMenuId)
  841. {
  842. case iPopupMenuExtension::MENU_OBJLIST_TOOLKIT:
  843. // $param is a DBObjectSet
  844. $oAppContext = new ApplicationContext();
  845. $sContext = $oAppContext->GetForLink();
  846. $sDataTableId = is_null($sDataTableId) ? '' : $sDataTableId;
  847. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($param->GetFilter()->GetClass());
  848. $sOQL = addslashes($param->GetFilter()->ToOQL(true));
  849. $sFilter = urlencode($param->GetFilter()->serialize());
  850. $sUrl = utils::GetAbsoluteUrlAppRoot()."pages/$sUIPage?operation=search&filter=".$sFilter."&{$sContext}";
  851. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  852. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  853. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  854. $aResult = array(
  855. new SeparatorPopupMenuItem(),
  856. // Static menus: Email this page, CSV Export & Add to Dashboard
  857. new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), "mailto:?body=".urlencode($sUrl).' '), // Add an extra space to make it work in Outlook
  858. );
  859. if (UserRights::IsActionAllowed($param->GetFilter()->GetClass(), UR_ACTION_BULK_READ, $param) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  860. {
  861. // Bulk export actions
  862. $aResult[] = new JSPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), "ExportListDlg('$sOQL', '$sDataTableId', 'csv', ".json_encode(Dict::S('UI:Menu:CSVExport')).")");
  863. $aResult[] = new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '$sDataTableId', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")");
  864. if (extension_loaded('gd'))
  865. {
  866. // PDF export requires GD
  867. $aResult[] = new JSPopupMenuItem('UI:Menu:ExportPDF', Dict::S('UI:Menu:ExportPDF'), "ExportListDlg('$sOQL', '$sDataTableId', 'pdf', ".json_encode(Dict::S('UI:Menu:ExportPDF')).")");
  868. }
  869. }
  870. $aResult[] = new JSPopupMenuItem('UI:Menu:AddToDashboard', Dict::S('UI:Menu:AddToDashboard'), "DashletCreationDlg('$sOQL')");
  871. $aResult[] = new JSPopupMenuItem('UI:Menu:ShortcutList', Dict::S('UI:Menu:ShortcutList'), "ShortcutListDlg('$sOQL', '$sDataTableId', '$sContext')");
  872. break;
  873. case iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS:
  874. // $param is a DBObject
  875. $oObj = $param;
  876. $sOQL = "SELECT ".get_class($oObj)." WHERE id=".$oObj->GetKey();
  877. $oFilter = DBObjectSearch::FromOQL($sOQL);
  878. $sFilter = $oFilter->serialize();
  879. $sUrl = ApplicationContext::MakeObjectUrl(get_class($oObj), $oObj->GetKey());
  880. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage(get_class($oObj));
  881. $oAppContext = new ApplicationContext();
  882. $sContext = $oAppContext->GetForLink();
  883. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  884. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  885. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  886. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  887. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  888. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  889. $aResult = array(
  890. new SeparatorPopupMenuItem(),
  891. // Static menus: Email this page & CSV Export
  892. 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
  893. new JSPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), "ExportListDlg('$sOQL', '', 'csv', ".json_encode(Dict::S('UI:Menu:CSVExport')).")"),
  894. new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")"),
  895. new SeparatorPopupMenuItem(),
  896. new URLPopupMenuItem('UI:Menu:PrintableVersion', Dict::S('UI:Menu:PrintableVersion'), $sUrl.'&printable=1', '_blank'),
  897. );
  898. break;
  899. case iPopupMenuExtension::MENU_DASHBOARD_ACTIONS:
  900. // $param is a Dashboard
  901. $oAppContext = new ApplicationContext();
  902. $aParams = $oAppContext->GetAsHash();
  903. $sMenuId = ApplicationMenu::GetActiveNodeId();
  904. $sDlgTitle = addslashes(Dict::S('UI:ImportDashboardTitle'));
  905. $sDlgText = addslashes(Dict::S('UI:ImportDashboardText'));
  906. $sCloseBtn = addslashes(Dict::S('UI:Button:Cancel'));
  907. $aResult = array(
  908. new SeparatorPopupMenuItem(),
  909. new URLPopupMenuItem('UI:ExportDashboard', Dict::S('UI:ExportDashBoard'), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=export_dashboard&id='.$sMenuId),
  910. new JSPopupMenuItem('UI:ImportDashboard', Dict::S('UI:ImportDashBoard'), "UploadDashboard({dashboard_id: '$sMenuId', title: '$sDlgTitle', text: '$sDlgText', close_btn: '$sCloseBtn' })"),
  911. );
  912. break;
  913. default:
  914. // Unknown type of menu, do nothing
  915. $aResult = array();
  916. }
  917. foreach($aResult as $oMenuItem)
  918. {
  919. $aActions[$oMenuItem->GetUID()] = $oMenuItem->GetMenuItem();
  920. }
  921. // Invoke the plugins
  922. //
  923. foreach (MetaModel::EnumPlugins('iPopupMenuExtension') as $oExtensionInstance)
  924. {
  925. if (is_object($param) && !($param instanceof DBObject))
  926. {
  927. $tmpParam = clone $param; // In case the parameter is an DBObjectSet, clone it to prevent alterations
  928. }
  929. else
  930. {
  931. $tmpParam = $param;
  932. }
  933. foreach($oExtensionInstance->EnumItems($iMenuId, $tmpParam) as $oMenuItem)
  934. {
  935. if (is_object($oMenuItem))
  936. {
  937. $aActions[$oMenuItem->GetUID()] = $oMenuItem->GetMenuItem();
  938. foreach($oMenuItem->GetLinkedScripts() as $sLinkedScript)
  939. {
  940. $oPage->add_linked_script($sLinkedScript);
  941. }
  942. }
  943. }
  944. }
  945. }
  946. /**
  947. * Get target configuration file name (including full path)
  948. */
  949. public static function GetConfigFilePath($sEnvironment = null)
  950. {
  951. if (is_null($sEnvironment))
  952. {
  953. $sEnvironment = self::GetCurrentEnvironment();
  954. }
  955. return APPCONF.$sEnvironment.'/'.ITOP_CONFIG_FILE;
  956. }
  957. /**
  958. * Returns the absolute URL to the modules root path
  959. * @return string ...
  960. */
  961. static public function GetAbsoluteUrlModulesRoot()
  962. {
  963. $sUrl = self::GetAbsoluteUrlAppRoot().'env-'.self::GetCurrentEnvironment().'/';
  964. return $sUrl;
  965. }
  966. /**
  967. * Returns the URL to a page that will execute the requested module page
  968. *
  969. * To be compatible with this mechanism, the called page must include approot
  970. * with an absolute path OR not include it at all (losing the direct access to the page)
  971. * if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  972. * require_once(__DIR__.'/../../approot.inc.php');
  973. *
  974. * @return string ...
  975. */
  976. static public function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = array(), $sEnvironment = null)
  977. {
  978. $sEnvironment = is_null($sEnvironment) ? self::GetCurrentEnvironment() : $sEnvironment;
  979. $aArgs = array();
  980. $aArgs[] = 'exec_module='.$sModule;
  981. $aArgs[] = 'exec_page='.$sPage;
  982. $aArgs[] = 'exec_env='.$sEnvironment;
  983. foreach($aArguments as $sName => $sValue)
  984. {
  985. if (($sName == 'exec_module')||($sName == 'exec_page')||($sName == 'exec_env'))
  986. {
  987. throw new Exception("Module page: $sName is a reserved page argument name");
  988. }
  989. $aArgs[] = $sName.'='.urlencode($sValue);
  990. }
  991. $sArgs = implode('&', $aArgs);
  992. return self::GetAbsoluteUrlAppRoot().'pages/exec.php?'.$sArgs;
  993. }
  994. /**
  995. * Returns a name unique amongst the given list
  996. * @param string $sProposed The default value
  997. * @param array $aExisting An array of existing values (strings)
  998. */
  999. static public function MakeUniqueName($sProposed, $aExisting)
  1000. {
  1001. if (in_array($sProposed, $aExisting))
  1002. {
  1003. $i = 1;
  1004. while (in_array($sProposed.$i, $aExisting) && ($i < 50))
  1005. {
  1006. $i++;
  1007. }
  1008. return $sProposed.$i;
  1009. }
  1010. else
  1011. {
  1012. return $sProposed;
  1013. }
  1014. }
  1015. /**
  1016. * Some characters cause troubles with jQuery when used inside DOM IDs, so let's replace them by the safe _ (underscore)
  1017. * @param string $sId The ID to sanitize
  1018. * @return string The sanitized ID
  1019. */
  1020. static public function GetSafeId($sId)
  1021. {
  1022. return str_replace(array(':', '[', ']', '+', '-'), '_', $sId);
  1023. }
  1024. /**
  1025. * Helper to execute an HTTP POST request
  1026. * Source: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
  1027. * originaly named after do_post_request
  1028. * Does not require cUrl but requires openssl for performing https POSTs.
  1029. *
  1030. * @param string $sUrl The URL to POST the data to
  1031. * @param hash $aData The data to POST as an array('param_name' => value)
  1032. * @param string $sOptionnalHeaders Additional HTTP headers as a string with newlines between headers
  1033. * @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
  1034. * @param hash $aCurlOptions An (optional) array of options to pass to curl_init. The format is 'option_code' => 'value'. These values have precedence over the default ones. Example: CURLOPT_SSLVERSION => CURL_SSLVERSION_SSLv3
  1035. * @return string The result of the POST request
  1036. * @throws Exception
  1037. */
  1038. static public function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null, $aCurlOptions = array())
  1039. {
  1040. // $sOptionnalHeaders is a string containing additional HTTP headers that you would like to send in your request.
  1041. if (function_exists('curl_init'))
  1042. {
  1043. // If cURL is available, let's use it, since it provides a greater control over the various HTTP/SSL options
  1044. // For instance fopen does not allow to work around the bug: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
  1045. // by setting the SSLVERSION to 3 as done below.
  1046. $aHeaders = explode("\n", $sOptionnalHeaders);
  1047. $aHTTPHeaders = array();
  1048. foreach($aHeaders as $sHeaderString)
  1049. {
  1050. if(preg_match('/^([^:]): (.+)$/', $sHeaderString, $aMatches))
  1051. {
  1052. $aHTTPHeaders[$aMatches[1]] = $aMatches[2];
  1053. }
  1054. }
  1055. // Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions
  1056. $aOptions = array(
  1057. CURLOPT_RETURNTRANSFER => true, // return the content of the request
  1058. CURLOPT_HEADER => false, // don't return the headers in the output
  1059. CURLOPT_FOLLOWLOCATION => true, // follow redirects
  1060. CURLOPT_ENCODING => "", // handle all encodings
  1061. CURLOPT_USERAGENT => "spider", // who am i
  1062. CURLOPT_AUTOREFERER => true, // set referer on redirect
  1063. CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
  1064. CURLOPT_TIMEOUT => 120, // timeout on response
  1065. CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
  1066. CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
  1067. // SSLV3 (CURL_SSLVERSION_SSLv3 = 3) is now considered as obsolete/dangerous: http://disablessl3.com/#why
  1068. // but it used to be a MUST to prevent a strange SSL error: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
  1069. // CURLOPT_SSLVERSION => 3,
  1070. CURLOPT_POST => count($aData),
  1071. CURLOPT_POSTFIELDS => http_build_query($aData),
  1072. CURLOPT_HTTPHEADER => $aHTTPHeaders,
  1073. );
  1074. $aAllOptions = $aCurlOptions + $aOptions;
  1075. $ch = curl_init($sUrl);
  1076. curl_setopt_array($ch, $aAllOptions);
  1077. $response = curl_exec($ch);
  1078. $iErr = curl_errno($ch);
  1079. $sErrMsg = curl_error( $ch );
  1080. $aHeaders = curl_getinfo( $ch );
  1081. if ($iErr !== 0)
  1082. {
  1083. throw new Exception("Problem opening URL: $sUrl, $sErrMsg");
  1084. }
  1085. if (is_array($aResponseHeaders))
  1086. {
  1087. $aHeaders = curl_getinfo($ch);
  1088. foreach($aHeaders as $sCode => $sValue)
  1089. {
  1090. $sName = str_replace(' ' , '-', ucwords(str_replace('_', ' ', $sCode))); // Transform "content_type" into "Content-Type"
  1091. $aResponseHeaders[$sName] = $sValue;
  1092. }
  1093. }
  1094. curl_close( $ch );
  1095. }
  1096. else
  1097. {
  1098. // cURL is not available let's try with streams and fopen...
  1099. $sData = http_build_query($aData);
  1100. $aParams = array('http' => array(
  1101. 'method' => 'POST',
  1102. 'content' => $sData,
  1103. 'header'=> "Content-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($sData)."\r\n",
  1104. ));
  1105. if ($sOptionnalHeaders !== null)
  1106. {
  1107. $aParams['http']['header'] .= $sOptionnalHeaders;
  1108. }
  1109. $ctx = stream_context_create($aParams);
  1110. $fp = @fopen($sUrl, 'rb', false, $ctx);
  1111. if (!$fp)
  1112. {
  1113. global $php_errormsg;
  1114. if (isset($php_errormsg))
  1115. {
  1116. throw new Exception("Wrong URL: $sUrl, $php_errormsg");
  1117. }
  1118. elseif ((strtolower(substr($sUrl, 0, 5)) == 'https') && !extension_loaded('openssl'))
  1119. {
  1120. throw new Exception("Cannot connect to $sUrl: missing module 'openssl'");
  1121. }
  1122. else
  1123. {
  1124. throw new Exception("Wrong URL: $sUrl");
  1125. }
  1126. }
  1127. $response = @stream_get_contents($fp);
  1128. if ($response === false)
  1129. {
  1130. throw new Exception("Problem reading data from $sUrl, $php_errormsg");
  1131. }
  1132. if (is_array($aResponseHeaders))
  1133. {
  1134. $aMeta = stream_get_meta_data($fp);
  1135. $aHeaders = $aMeta['wrapper_data'];
  1136. foreach($aHeaders as $sHeaderString)
  1137. {
  1138. if(preg_match('/^([^:]+): (.+)$/', $sHeaderString, $aMatches))
  1139. {
  1140. $aResponseHeaders[$aMatches[1]] = trim($aMatches[2]);
  1141. }
  1142. }
  1143. }
  1144. }
  1145. return $response;
  1146. }
  1147. /**
  1148. * Get a standard list of character sets
  1149. *
  1150. * @param array $aAdditionalEncodings Additional values
  1151. * @return array of iconv code => english label, sorted by label
  1152. */
  1153. public static function GetPossibleEncodings($aAdditionalEncodings = array())
  1154. {
  1155. // Encodings supported:
  1156. // ICONV_CODE => Display Name
  1157. // Each iconv installation supports different encodings
  1158. // Some reasonably common and useful encodings are listed here
  1159. $aPossibleEncodings = array(
  1160. 'UTF-8' => 'Unicode (UTF-8)',
  1161. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  1162. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  1163. 'WINDOWS-1252' => 'Western (Windows 1252)',
  1164. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  1165. );
  1166. $aPossibleEncodings = array_merge($aPossibleEncodings, $aAdditionalEncodings);
  1167. asort($aPossibleEncodings);
  1168. return $aPossibleEncodings;
  1169. }
  1170. /**
  1171. * Convert a string containing some (valid) HTML markup to plain text
  1172. * @param string $sHtml
  1173. * @return string
  1174. */
  1175. public static function HtmlToText($sHtml)
  1176. {
  1177. try
  1178. {
  1179. //return '<?xml encoding="UTF-8">'.$sHtml;
  1180. return \Html2Text\Html2Text::convert('<?xml encoding="UTF-8">'.$sHtml);
  1181. }
  1182. catch(Exception $e)
  1183. {
  1184. return $e->getMessage();
  1185. }
  1186. }
  1187. /**
  1188. * Convert (?) plain text to some HTML markup by replacing newlines by <br/> tags
  1189. * and escaping HTML entities
  1190. * @param string $sText
  1191. * @return string
  1192. */
  1193. public static function TextToHtml($sText)
  1194. {
  1195. $sText = str_replace("\r\n", "\n", $sText);
  1196. $sText = str_replace("\r", "\n", $sText);
  1197. return str_replace("\n", '<br/>', htmlentities($sText, ENT_QUOTES, 'UTF-8'));
  1198. }
  1199. /**
  1200. * Eventually compiles the SASS (.scss) file into the CSS (.css) file
  1201. *
  1202. * @param string $sSassRelPath Relative path to the SCSS file (must have the extension .scss)
  1203. * @param array $aImportPaths Array of absolute paths to load imports from
  1204. * @return string Relative path to the CSS file (<name>.css)
  1205. */
  1206. static public function GetCSSFromSASS($sSassRelPath, $aImportPaths = null)
  1207. {
  1208. // Avoiding compilation if file is already a css file.
  1209. if (preg_match('/\.css$/', $sSassRelPath))
  1210. {
  1211. return $sSassRelPath;
  1212. }
  1213. // Setting import paths
  1214. if ($aImportPaths === null)
  1215. {
  1216. $aImportPaths = array();
  1217. }
  1218. $aImportPaths[] = APPROOT . '/css';
  1219. $sSassPath = APPROOT.$sSassRelPath;
  1220. $sCssRelPath = preg_replace('/\.scss$/', '.css', $sSassRelPath);
  1221. $sCssPath = APPROOT.$sCssRelPath;
  1222. clearstatcache();
  1223. if (!file_exists($sCssPath) || (is_writable($sCssPath) && (filemtime($sCssPath) < filemtime($sSassPath))))
  1224. {
  1225. require_once(APPROOT.'lib/scssphp/scss.inc.php');
  1226. $oScss = new Compiler();
  1227. $oScss->setImportPaths($aImportPaths);
  1228. $oScss->setFormatter('Leafo\\ScssPhp\\Formatter\\Expanded');
  1229. // Temporary disabling max exec time while compiling
  1230. $iCurrentMaxExecTime = (int) ini_get('max_execution_time');
  1231. set_time_limit(0);
  1232. $sCss = $oScss->compile(file_get_contents($sSassPath));
  1233. set_time_limit($iCurrentMaxExecTime);
  1234. file_put_contents($sCssPath, $sCss);
  1235. }
  1236. return $sCssRelPath;
  1237. }
  1238. static public function GetImageSize($sImageData)
  1239. {
  1240. if (function_exists('getimagesizefromstring')) // PHP 5.4.0 or higher
  1241. {
  1242. $aRet = @getimagesizefromstring($sImageData);
  1243. }
  1244. else if(ini_get('allow_url_fopen'))
  1245. {
  1246. // work around to avoid creating a tmp file
  1247. $sUri = 'data://application/octet-stream;base64,'.base64_encode($sImageData);
  1248. $aRet = @getimagesize($sUri);
  1249. }
  1250. else
  1251. {
  1252. // Damned, need to create a tmp file
  1253. $sTempFile = tempnam(SetupUtils::GetTmpDir(), 'img-');
  1254. @file_put_contents($sTempFile, $sImageData);
  1255. $aRet = @getimagesize($sTempFile);
  1256. @unlink($sTempFile);
  1257. }
  1258. return $aRet;
  1259. }
  1260. /**
  1261. * Resize an image attachment so that it fits in the given dimensions
  1262. * @param ormDocument $oImage The original image stored as an ormDocument
  1263. * @param int $iWidth Image's original width
  1264. * @param int $iHeight Image's original height
  1265. * @param int $iMaxImageWidth Maximum width for the resized image
  1266. * @param int $iMaxImageHeight Maximum height for the resized image
  1267. * @return ormDocument The resampled image
  1268. */
  1269. public static function ResizeImageToFit(ormDocument $oImage, $iWidth, $iHeight, $iMaxImageWidth, $iMaxImageHeight)
  1270. {
  1271. // If image size smaller than maximums, we do nothing
  1272. if (($iWidth <= $iMaxImageWidth) && ($iHeight <= $iMaxImageHeight))
  1273. {
  1274. return $oImage;
  1275. }
  1276. // If gd extension is not loaded, we put a warning in the log and return the image as is
  1277. if (extension_loaded('gd') === false)
  1278. {
  1279. IssueLog::Warning('Image could not be resized as the "gd" extension does not seem to be loaded. It will remain as ' . $iWidth . 'x' . $iHeight . ' instead of ' . $iMaxImageWidth . 'x' . $iMaxImageHeight);
  1280. return $oImage;
  1281. }
  1282. switch($oImage->GetMimeType())
  1283. {
  1284. case 'image/gif':
  1285. case 'image/jpeg':
  1286. case 'image/png':
  1287. $img = @imagecreatefromstring($oImage->GetData());
  1288. break;
  1289. default:
  1290. // Unsupported image type, return the image as-is
  1291. //throw new Exception("Unsupported image type: '".$oImage->GetMimeType()."'. Cannot resize the image, original image will be used.");
  1292. return $oImage;
  1293. }
  1294. if ($img === false)
  1295. {
  1296. //throw new Exception("Warning: corrupted image: '".$oImage->GetFileName()." / ".$oImage->GetMimeType()."'. Cannot resize the image, original image will be used.");
  1297. return $oImage;
  1298. }
  1299. else
  1300. {
  1301. // Let's scale the image, preserving the transparency for GIFs and PNGs
  1302. $fScale = min($iMaxImageWidth / $iWidth, $iMaxImageHeight / $iHeight);
  1303. $iNewWidth = $iWidth * $fScale;
  1304. $iNewHeight = $iHeight * $fScale;
  1305. $new = imagecreatetruecolor($iNewWidth, $iNewHeight);
  1306. // Preserve transparency
  1307. if(($oImage->GetMimeType() == "image/gif") || ($oImage->GetMimeType() == "image/png"))
  1308. {
  1309. imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
  1310. imagealphablending($new, false);
  1311. imagesavealpha($new, true);
  1312. }
  1313. imagecopyresampled($new, $img, 0, 0, 0, 0, $iNewWidth, $iNewHeight, $iWidth, $iHeight);
  1314. ob_start();
  1315. switch ($oImage->GetMimeType())
  1316. {
  1317. case 'image/gif':
  1318. imagegif($new); // send image to output buffer
  1319. break;
  1320. case 'image/jpeg':
  1321. imagejpeg($new, null, 80); // null = send image to output buffer, 80 = good quality
  1322. break;
  1323. case 'image/png':
  1324. imagepng($new, null, 5); // null = send image to output buffer, 5 = medium compression
  1325. break;
  1326. }
  1327. $oResampledImage = new ormDocument(ob_get_contents(), $oImage->GetMimeType(), $oImage->GetFileName());
  1328. @ob_end_clean();
  1329. imagedestroy($img);
  1330. imagedestroy($new);
  1331. return $oResampledImage;
  1332. }
  1333. }
  1334. /**
  1335. * Create a 128 bit UUID in the format: {########-####-####-####-############}
  1336. *
  1337. * Note: this method can be run from the command line as well as from the web server.
  1338. * Note2: this method is not cryptographically secure! If you need a cryptographically secure value
  1339. * consider using open_ssl or PHP 7 methods.
  1340. * @param string $sPrefix
  1341. * @return string
  1342. */
  1343. static public function CreateUUID($sPrefix = '')
  1344. {
  1345. $uid = uniqid("", true);
  1346. $data = $sPrefix;
  1347. $data .= __FILE__;
  1348. $data .= mt_rand();
  1349. $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
  1350. $sUUID = '{' .
  1351. substr($hash, 0, 8) .
  1352. '-' .
  1353. substr($hash, 8, 4) .
  1354. '-' .
  1355. substr($hash, 12, 4) .
  1356. '-' .
  1357. substr($hash, 16, 4) .
  1358. '-' .
  1359. substr($hash, 20, 12) .
  1360. '}';
  1361. return $sUUID;
  1362. }
  1363. /**
  1364. * Returns the name of the module containing the file where the call to this function is made
  1365. * or an empty string if no such module is found (or not called within a module file)
  1366. * @param number $iCallDepth The depth of the module in the callstack. Zero when called directly from within the module
  1367. * @return string
  1368. */
  1369. static public function GetCurrentModuleName($iCallDepth = 0)
  1370. {
  1371. $sCurrentModuleName = '';
  1372. $aCallStack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  1373. $sCallerFile = realpath($aCallStack[$iCallDepth]['file']);
  1374. foreach(GetModulesInfo() as $sModuleName => $aInfo)
  1375. {
  1376. if ($aInfo['root_dir'] !== '')
  1377. {
  1378. $sRootDir = realpath(APPROOT.$aInfo['root_dir']);
  1379. if(substr($sCallerFile, 0, strlen($sRootDir)) === $sRootDir)
  1380. {
  1381. $sCurrentModuleName = $sModuleName;
  1382. break;
  1383. }
  1384. }
  1385. }
  1386. return $sCurrentModuleName;
  1387. }
  1388. /**
  1389. * Returns the relative (to APPROOT) path of the root directory of the module containing the file where the call to this function is made
  1390. * or an empty string if no such module is found (or not called within a module file)
  1391. * @param number $iCallDepth The depth of the module in the callstack. Zero when called directly from within the module
  1392. * @return string
  1393. */
  1394. static public function GetCurrentModuleDir($iCallDepth)
  1395. {
  1396. $sCurrentModuleDir = '';
  1397. $aCallStack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  1398. $sCallerFile = realpath($aCallStack[$iCallDepth]['file']);
  1399. foreach(GetModulesInfo() as $sModuleName => $aInfo)
  1400. {
  1401. if ($aInfo['root_dir'] !== '')
  1402. {
  1403. $sRootDir = realpath(APPROOT.$aInfo['root_dir']);
  1404. if(substr($sCallerFile, 0, strlen($sRootDir)) === $sRootDir)
  1405. {
  1406. $sCurrentModuleDir = basename($sRootDir);
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. return $sCurrentModuleDir;
  1412. }
  1413. /**
  1414. * Returns the base URL for all files in the current module from which this method is called
  1415. * or an empty string if no such module is found (or not called within a module file)
  1416. * @return string
  1417. */
  1418. static public function GetCurrentModuleUrl()
  1419. {
  1420. $sDir = static::GetCurrentModuleDir(1);
  1421. if ( $sDir !== '')
  1422. {
  1423. return static::GetAbsoluteUrlModulesRoot().'/'.$sDir;
  1424. }
  1425. return '';
  1426. }
  1427. /**
  1428. * Get the value of a given setting for the current module
  1429. * @param string $sProperty The name of the property to retrieve
  1430. * @param mixed $defaultvalue
  1431. * @return mixed
  1432. */
  1433. static public function GetCurrentModuleSetting($sProperty, $defaultvalue = null)
  1434. {
  1435. $sModuleName = static::GetCurrentModuleName(1);
  1436. return MetaModel::GetModuleSetting($sModuleName, $sProperty, $defaultvalue);
  1437. }
  1438. /**
  1439. * Get the compiled version of a given module, as it was seen by the compiler
  1440. * @param string $sModuleName
  1441. * @return string|NULL
  1442. */
  1443. static public function GetCompiledModuleVersion($sModuleName)
  1444. {
  1445. $aModulesInfo = GetModulesInfo();
  1446. if (array_key_exists($sModuleName, $aModulesInfo))
  1447. {
  1448. return $aModulesInfo[$sModuleName]['version'];
  1449. }
  1450. return null;
  1451. }
  1452. }