utils.inc.php 46 KB

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