utils.inc.php 46 KB

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