utils.inc.php 40 KB

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