utils.inc.php 58 KB

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