utils.inc.php 58 KB

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