utils.inc.php 46 KB

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