utils.inc.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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. static public function GetConfig()
  434. {
  435. if (self::$oConfig == null)
  436. {
  437. $sConfigFile = self::GetConfigFilePath();
  438. if (file_exists($sConfigFile))
  439. {
  440. self::$oConfig = new Config($sConfigFile);
  441. }
  442. else
  443. {
  444. // When executing the setup, the config file may be still missing
  445. self::$oConfig = new Config();
  446. }
  447. }
  448. return self::$oConfig;
  449. }
  450. /**
  451. * Returns the absolute URL to the application root path
  452. * @return string The absolute URL to the application root, without the first slash
  453. */
  454. static public function GetAbsoluteUrlAppRoot()
  455. {
  456. static $sUrl = null;
  457. if ($sUrl === null)
  458. {
  459. $sUrl = self::GetConfig()->Get('app_root_url');
  460. if ($sUrl == '')
  461. {
  462. $sUrl = self::GetDefaultUrlAppRoot();
  463. }
  464. elseif (strpos($sUrl, SERVER_NAME_PLACEHOLDER) > -1)
  465. {
  466. if (isset($_SERVER['SERVER_NAME']))
  467. {
  468. $sServerName = $_SERVER['SERVER_NAME'];
  469. }
  470. else
  471. {
  472. // CLI mode ?
  473. $sServerName = php_uname('n');
  474. }
  475. $sUrl = str_replace(SERVER_NAME_PLACEHOLDER, $sServerName, $sUrl);
  476. }
  477. }
  478. return $sUrl;
  479. }
  480. static public function GetDefaultUrlAppRoot()
  481. {
  482. // Build an absolute URL to this page on this server/port
  483. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  484. $sProtocol = self::IsConnectionSecure() ? 'https' : 'http';
  485. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  486. if ($sProtocol == 'http')
  487. {
  488. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  489. }
  490. else
  491. {
  492. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  493. }
  494. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  495. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  496. if (!empty($_SERVER['REQUEST_URI']))
  497. {
  498. $sPath = $_SERVER['REQUEST_URI'];
  499. }
  500. else
  501. {
  502. $sPath = $_SERVER['SCRIPT_NAME'];
  503. if (!empty($_SERVER['QUERY_STRING']))
  504. {
  505. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  506. }
  507. $_SERVER['REQUEST_URI'] = $sPath;
  508. }
  509. $sPath = $_SERVER['REQUEST_URI'];
  510. // remove all the parameters from the query string
  511. $iQuestionMarkPos = strpos($sPath, '?');
  512. if ($iQuestionMarkPos !== false)
  513. {
  514. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  515. }
  516. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  517. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  518. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  519. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  520. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  521. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  522. if ($sAppRootPos !== false)
  523. {
  524. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  525. }
  526. else
  527. {
  528. // Second attempt without index.php at the end...
  529. $sCurrentRelativePath = str_replace('index.php', '', $sCurrentRelativePath);
  530. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  531. if ($sAppRootPos !== false)
  532. {
  533. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  534. }
  535. else
  536. {
  537. // No luck...
  538. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  539. }
  540. }
  541. return $sAppRootUrl;
  542. }
  543. /**
  544. * Helper to handle the variety of HTTP servers
  545. * See #286 (fixed in [896]), and #634 (this fix)
  546. *
  547. * Though the official specs says 'a non empty string', some servers like IIS do set it to 'off' !
  548. * nginx set it to an empty string
  549. * Others might leave it unset (no array entry)
  550. */
  551. static public function IsConnectionSecure()
  552. {
  553. $bSecured = false;
  554. if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off'))
  555. {
  556. $bSecured = true;
  557. }
  558. return $bSecured;
  559. }
  560. /**
  561. * Tells whether or not log off operation is supported.
  562. * Actually in only one case:
  563. * 1) iTop is using an internal authentication
  564. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  565. * @return boolean True if logoff is supported, false otherwise
  566. */
  567. static function CanLogOff()
  568. {
  569. $bResult = false;
  570. if(isset($_SESSION['login_mode']))
  571. {
  572. $sLoginMode = $_SESSION['login_mode'];
  573. switch($sLoginMode)
  574. {
  575. case 'external':
  576. $bResult = false;
  577. break;
  578. case 'form':
  579. case 'basic':
  580. case 'url':
  581. case 'cas':
  582. default:
  583. $bResult = true;
  584. }
  585. }
  586. return $bResult;
  587. }
  588. /**
  589. * Initializes the CAS client
  590. */
  591. static function InitCASClient()
  592. {
  593. $sCASIncludePath = self::GetConfig()->Get('cas_include_path');
  594. include_once($sCASIncludePath.'/CAS.php');
  595. $bCASDebug = self::GetConfig()->Get('cas_debug');
  596. if ($bCASDebug)
  597. {
  598. phpCAS::setDebug(APPROOT.'log/error.log');
  599. }
  600. if (!self::$m_bCASClient)
  601. {
  602. // Initialize phpCAS
  603. $sCASVersion = self::GetConfig()->Get('cas_version');
  604. $sCASHost = self::GetConfig()->Get('cas_host');
  605. $iCASPort = self::GetConfig()->Get('cas_port');
  606. $sCASContext = self::GetConfig()->Get('cas_context');
  607. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  608. self::$m_bCASClient = true;
  609. $sCASCACertPath = self::GetConfig()->Get('cas_server_ca_cert_path');
  610. if (empty($sCASCACertPath))
  611. {
  612. // If no certificate authority is provided, do not attempt to validate
  613. // the server's certificate
  614. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  615. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  616. phpCAS::setNoCasServerValidation();
  617. }
  618. else
  619. {
  620. phpCAS::setCasServerCACert($sCASCACertPath);
  621. }
  622. }
  623. }
  624. static function DebugBacktrace($iLimit = 5)
  625. {
  626. $aFullTrace = debug_backtrace();
  627. $aLightTrace = array();
  628. for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
  629. {
  630. $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
  631. }
  632. echo "<p><pre>".print_r($aLightTrace, true)."</pre></p>\n";
  633. }
  634. /**
  635. * Execute the given iTop PHP script, passing it the current credentials
  636. * Only CLI mode is supported, because of the need to hand the credentials over to the next process
  637. * Throws an exception if the execution fails or could not be attempted (config issue)
  638. * @param string $sScript Name and relative path to the file (relative to the iTop root dir)
  639. * @param hash $aArguments Associative array of 'arg' => 'value'
  640. * @return array(iCode, array(output lines))
  641. */
  642. /**
  643. */
  644. static function ExecITopScript($sScriptName, $aArguments)
  645. {
  646. $aDisabled = explode(', ', ini_get('disable_functions'));
  647. if (in_array('exec', $aDisabled))
  648. {
  649. throw new Exception("The PHP exec() function has been disabled on this server");
  650. }
  651. $sPHPExec = trim(self::GetConfig()->Get('php_path'));
  652. if (strlen($sPHPExec) == 0)
  653. {
  654. throw new Exception("The path to php must not be empty. Please set a value for 'php_path' in your configuration file.");
  655. }
  656. $sAuthUser = self::ReadParam('auth_user', '', 'raw_data');
  657. $sAuthPwd = self::ReadParam('auth_pwd', '', 'raw_data');
  658. $sParamFile = self::GetParamSourceFile('auth_user');
  659. if (is_null($sParamFile))
  660. {
  661. $aArguments['auth_user'] = $sAuthUser;
  662. $aArguments['auth_pwd'] = $sAuthPwd;
  663. }
  664. else
  665. {
  666. $aArguments['param_file'] = $sParamFile;
  667. }
  668. $aArgs = array();
  669. foreach($aArguments as $sName => $value)
  670. {
  671. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  672. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  673. $aArgs[] = "--$sName=".escapeshellarg($value);
  674. }
  675. $sArgs = implode(' ', $aArgs);
  676. $sScript = realpath(APPROOT.$sScriptName);
  677. if (!file_exists($sScript))
  678. {
  679. throw new Exception("Could not find the script file '$sScriptName' from the directory '".APPROOT."'");
  680. }
  681. $sCommand = '"'.$sPHPExec.'" '.escapeshellarg($sScript).' -- '.$sArgs;
  682. if (version_compare(phpversion(), '5.3.0', '<'))
  683. {
  684. if (substr(PHP_OS,0,3) == 'WIN')
  685. {
  686. // Under Windows, and for PHP 5.2.x, the whole command has to be quoted
  687. // Cf PHP doc: http://php.net/manual/fr/function.exec.php, comment from the 27-Dec-2010
  688. $sCommand = '"'.$sCommand.'"';
  689. }
  690. }
  691. $sLastLine = exec($sCommand, $aOutput, $iRes);
  692. if ($iRes == 1)
  693. {
  694. throw new Exception(Dict::S('Core:ExecProcess:Code1')." - ".$sCommand);
  695. }
  696. elseif ($iRes == 255)
  697. {
  698. $sErrors = implode("\n", $aOutput);
  699. throw new Exception(Dict::S('Core:ExecProcess:Code255')." - ".$sCommand.":\n".$sErrors);
  700. }
  701. //$aOutput[] = $sCommand;
  702. return array($iRes, $aOutput);
  703. }
  704. /**
  705. * Get the current environment
  706. */
  707. public static function GetCurrentEnvironment()
  708. {
  709. if (isset($_SESSION['itop_env']))
  710. {
  711. return $_SESSION['itop_env'];
  712. }
  713. else
  714. {
  715. return ITOP_DEFAULT_ENV;
  716. }
  717. }
  718. /**
  719. * Returns a path to a folder into which any module can store cache data
  720. * The corresponding folder is created or cleaned upon code compilation
  721. * @return string
  722. */
  723. public static function GetCachePath()
  724. {
  725. return APPROOT.'data/cache-'.self::GetCurrentEnvironment().'/';
  726. }
  727. /**
  728. * Merge standard menu items with plugin provided menus items
  729. */
  730. public static function GetPopupMenuItems($oPage, $iMenuId, $param, &$aActions, $sTableId = null, $sDataTableId = null)
  731. {
  732. // 1st - add standard built-in menu items
  733. //
  734. switch($iMenuId)
  735. {
  736. case iPopupMenuExtension::MENU_OBJLIST_TOOLKIT:
  737. // $param is a DBObjectSet
  738. $oAppContext = new ApplicationContext();
  739. $sContext = $oAppContext->GetForLink();
  740. $sDataTableId = is_null($sDataTableId) ? '' : $sDataTableId;
  741. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($param->GetFilter()->GetClass());
  742. $sOQL = addslashes($param->GetFilter()->ToOQL(true));
  743. $sFilter = urlencode($param->GetFilter()->serialize());
  744. $sUrl = utils::GetAbsoluteUrlAppRoot()."pages/$sUIPage?operation=search&filter=".$sFilter."&{$sContext}";
  745. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  746. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  747. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  748. $aResult = array(
  749. new SeparatorPopupMenuItem(),
  750. // Static menus: Email this page, CSV Export & Add to Dashboard
  751. new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), "mailto:?body=".urlencode($sUrl).' '), // Add an extra space to make it work in Outlook
  752. );
  753. if (UserRights::IsActionAllowed($param->GetFilter()->GetClass(), UR_ACTION_BULK_READ, $param) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  754. {
  755. // Bulk export actions
  756. $aResult[] = new JSPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), "ExportListDlg('$sOQL', '$sDataTableId', 'csv', ".json_encode(Dict::S('UI:Menu:CSVExport')).")");
  757. $aResult[] = new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '$sDataTableId', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")");
  758. $aResult[] = new JSPopupMenuItem('UI:Menu:ExportPDF', Dict::S('UI:Menu:ExportPDF'), "ExportListDlg('$sOQL', '$sDataTableId', 'pdf', ".json_encode(Dict::S('UI:Menu:ExportPDF')).")");
  759. }
  760. $aResult[] = new JSPopupMenuItem('UI:Menu:AddToDashboard', Dict::S('UI:Menu:AddToDashboard'), "DashletCreationDlg('$sOQL')");
  761. $aResult[] = new JSPopupMenuItem('UI:Menu:ShortcutList', Dict::S('UI:Menu:ShortcutList'), "ShortcutListDlg('$sOQL', '$sDataTableId', '$sContext')");
  762. break;
  763. case iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS:
  764. // $param is a DBObject
  765. $oObj = $param;
  766. $sOQL = "SELECT ".get_class($oObj)." WHERE id=".$oObj->GetKey();
  767. $oFilter = DBObjectSearch::FromOQL($sOQL);
  768. $sFilter = $oFilter->serialize();
  769. $sUrl = ApplicationContext::MakeObjectUrl(get_class($oObj), $oObj->GetKey());
  770. $sUIPage = cmdbAbstractObject::ComputeStandardUIPage(get_class($oObj));
  771. $oAppContext = new ApplicationContext();
  772. $sContext = $oAppContext->GetForLink();
  773. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  774. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  775. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  776. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  777. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  778. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  779. $aResult = array(
  780. new SeparatorPopupMenuItem(),
  781. // Static menus: Email this page & CSV Export
  782. 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
  783. new JSPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), "ExportListDlg('$sOQL', '', 'csv', ".json_encode(Dict::S('UI:Menu:CSVExport')).")"),
  784. new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")"),
  785. new SeparatorPopupMenuItem(),
  786. new URLPopupMenuItem('UI:Menu:PrintableVersion', Dict::S('UI:Menu:PrintableVersion'), $sUrl.'&printable=1', '_blank'),
  787. );
  788. break;
  789. case iPopupMenuExtension::MENU_DASHBOARD_ACTIONS:
  790. // $param is a Dashboard
  791. $oAppContext = new ApplicationContext();
  792. $aParams = $oAppContext->GetAsHash();
  793. $sMenuId = ApplicationMenu::GetActiveNodeId();
  794. $sDlgTitle = addslashes(Dict::S('UI:ImportDashboardTitle'));
  795. $sDlgText = addslashes(Dict::S('UI:ImportDashboardText'));
  796. $sCloseBtn = addslashes(Dict::S('UI:Button:Cancel'));
  797. $aResult = array(
  798. new SeparatorPopupMenuItem(),
  799. new URLPopupMenuItem('UI:ExportDashboard', Dict::S('UI:ExportDashBoard'), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=export_dashboard&id='.$sMenuId),
  800. new JSPopupMenuItem('UI:ImportDashboard', Dict::S('UI:ImportDashBoard'), "UploadDashboard({dashboard_id: '$sMenuId', title: '$sDlgTitle', text: '$sDlgText', close_btn: '$sCloseBtn' })"),
  801. );
  802. break;
  803. default:
  804. // Unknown type of menu, do nothing
  805. $aResult = array();
  806. }
  807. foreach($aResult as $oMenuItem)
  808. {
  809. $aActions[$oMenuItem->GetUID()] = $oMenuItem->GetMenuItem();
  810. }
  811. // Invoke the plugins
  812. //
  813. foreach (MetaModel::EnumPlugins('iPopupMenuExtension') as $oExtensionInstance)
  814. {
  815. if (is_object($param) && !($param instanceof DBObject))
  816. {
  817. $tmpParam = clone $param; // In case the parameter is an DBObjectSet, clone it to prevent alterations
  818. }
  819. else
  820. {
  821. $tmpParam = $param;
  822. }
  823. foreach($oExtensionInstance->EnumItems($iMenuId, $tmpParam) as $oMenuItem)
  824. {
  825. if (is_object($oMenuItem))
  826. {
  827. $aActions[$oMenuItem->GetUID()] = $oMenuItem->GetMenuItem();
  828. foreach($oMenuItem->GetLinkedScripts() as $sLinkedScript)
  829. {
  830. $oPage->add_linked_script($sLinkedScript);
  831. }
  832. }
  833. }
  834. }
  835. }
  836. /**
  837. * Get target configuration file name (including full path)
  838. */
  839. public static function GetConfigFilePath($sEnvironment = null)
  840. {
  841. if (is_null($sEnvironment))
  842. {
  843. $sEnvironment = self::GetCurrentEnvironment();
  844. }
  845. return APPCONF.$sEnvironment.'/'.ITOP_CONFIG_FILE;
  846. }
  847. /**
  848. * Returns the absolute URL to the modules root path
  849. * @return string ...
  850. */
  851. static public function GetAbsoluteUrlModulesRoot()
  852. {
  853. $sUrl = self::GetAbsoluteUrlAppRoot().'env-'.self::GetCurrentEnvironment().'/';
  854. return $sUrl;
  855. }
  856. /**
  857. * Returns the URL to a page that will execute the requested module page
  858. *
  859. * To be compatible with this mechanism, the called page must include approot
  860. * with an absolute path OR not include it at all (losing the direct access to the page)
  861. * if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  862. * require_once(__DIR__.'/../../approot.inc.php');
  863. *
  864. * @return string ...
  865. */
  866. static public function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = array(), $sEnvironment = null)
  867. {
  868. $sEnvironment = is_null($sEnvironment) ? self::GetCurrentEnvironment() : $sEnvironment;
  869. $aArgs = array();
  870. $aArgs[] = 'exec_module='.$sModule;
  871. $aArgs[] = 'exec_page='.$sPage;
  872. $aArgs[] = 'exec_env='.$sEnvironment;
  873. foreach($aArguments as $sName => $sValue)
  874. {
  875. if (($sName == 'exec_module')||($sName == 'exec_page')||($sName == 'exec_env'))
  876. {
  877. throw new Exception("Module page: $sName is a reserved page argument name");
  878. }
  879. $aArgs[] = $sName.'='.urlencode($sValue);
  880. }
  881. $sArgs = implode('&', $aArgs);
  882. return self::GetAbsoluteUrlAppRoot().'pages/exec.php?'.$sArgs;
  883. }
  884. /**
  885. * Returns a name unique amongst the given list
  886. * @param string $sProposed The default value
  887. * @param array $aExisting An array of existing values (strings)
  888. */
  889. static public function MakeUniqueName($sProposed, $aExisting)
  890. {
  891. if (in_array($sProposed, $aExisting))
  892. {
  893. $i = 1;
  894. while (in_array($sProposed.$i, $aExisting) && ($i < 50))
  895. {
  896. $i++;
  897. }
  898. return $sProposed.$i;
  899. }
  900. else
  901. {
  902. return $sProposed;
  903. }
  904. }
  905. /**
  906. * Some characters cause troubles with jQuery when used inside DOM IDs, so let's replace them by the safe _ (underscore)
  907. * @param string $sId The ID to sanitize
  908. * @return string The sanitized ID
  909. */
  910. static public function GetSafeId($sId)
  911. {
  912. return str_replace(array(':', '[', ']', '+', '-'), '_', $sId);
  913. }
  914. /**
  915. * Helper to execute an HTTP POST request
  916. * Source: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
  917. * originaly named after do_post_request
  918. * Does not require cUrl but requires openssl for performing https POSTs.
  919. *
  920. * @param string $sUrl The URL to POST the data to
  921. * @param hash $aData The data to POST as an array('param_name' => value)
  922. * @param string $sOptionnalHeaders Additional HTTP headers as a string with newlines between headers
  923. * @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
  924. * @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
  925. * @return string The result of the POST request
  926. * @throws Exception
  927. */
  928. static public function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null, $aCurlOptions = array())
  929. {
  930. // $sOptionnalHeaders is a string containing additional HTTP headers that you would like to send in your request.
  931. if (function_exists('curl_init'))
  932. {
  933. // If cURL is available, let's use it, since it provides a greater control over the various HTTP/SSL options
  934. // For instance fopen does not allow to work around the bug: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
  935. // by setting the SSLVERSION to 3 as done below.
  936. $aHeaders = explode("\n", $sOptionnalHeaders);
  937. $aHTTPHeaders = array();
  938. foreach($aHeaders as $sHeaderString)
  939. {
  940. if(preg_match('/^([^:]): (.+)$/', $sHeaderString, $aMatches))
  941. {
  942. $aHTTPHeaders[$aMatches[1]] = $aMatches[2];
  943. }
  944. }
  945. // Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions
  946. $aOptions = array(
  947. CURLOPT_RETURNTRANSFER => true, // return the content of the request
  948. CURLOPT_HEADER => false, // don't return the headers in the output
  949. CURLOPT_FOLLOWLOCATION => true, // follow redirects
  950. CURLOPT_ENCODING => "", // handle all encodings
  951. CURLOPT_USERAGENT => "spider", // who am i
  952. CURLOPT_AUTOREFERER => true, // set referer on redirect
  953. CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
  954. CURLOPT_TIMEOUT => 120, // timeout on response
  955. CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
  956. CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
  957. // SSLV3 (CURL_SSLVERSION_SSLv3 = 3) is now considered as obsolete/dangerous: http://disablessl3.com/#why
  958. // 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
  959. // CURLOPT_SSLVERSION => 3,
  960. CURLOPT_POST => count($aData),
  961. CURLOPT_POSTFIELDS => http_build_query($aData),
  962. CURLOPT_HTTPHEADER => $aHTTPHeaders,
  963. );
  964. $aAllOptions = $aCurlOptions + $aOptions;
  965. $ch = curl_init($sUrl);
  966. curl_setopt_array($ch, $aAllOptions);
  967. $response = curl_exec($ch);
  968. $iErr = curl_errno($ch);
  969. $sErrMsg = curl_error( $ch );
  970. $aHeaders = curl_getinfo( $ch );
  971. if ($iErr !== 0)
  972. {
  973. throw new Exception("Problem opening URL: $sUrl, $sErrMsg");
  974. }
  975. if (is_array($aResponseHeaders))
  976. {
  977. $aHeaders = curl_getinfo($ch);
  978. foreach($aHeaders as $sCode => $sValue)
  979. {
  980. $sName = str_replace(' ' , '-', ucwords(str_replace('_', ' ', $sCode))); // Transform "content_type" into "Content-Type"
  981. $aResponseHeaders[$sName] = $sValue;
  982. }
  983. }
  984. curl_close( $ch );
  985. }
  986. else
  987. {
  988. // cURL is not available let's try with streams and fopen...
  989. $sData = http_build_query($aData);
  990. $aParams = array('http' => array(
  991. 'method' => 'POST',
  992. 'content' => $sData,
  993. 'header'=> "Content-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($sData)."\r\n",
  994. ));
  995. if ($sOptionnalHeaders !== null)
  996. {
  997. $aParams['http']['header'] .= $sOptionnalHeaders;
  998. }
  999. $ctx = stream_context_create($aParams);
  1000. $fp = @fopen($sUrl, 'rb', false, $ctx);
  1001. if (!$fp)
  1002. {
  1003. global $php_errormsg;
  1004. if (isset($php_errormsg))
  1005. {
  1006. throw new Exception("Wrong URL: $sUrl, $php_errormsg");
  1007. }
  1008. elseif ((strtolower(substr($sUrl, 0, 5)) == 'https') && !extension_loaded('openssl'))
  1009. {
  1010. throw new Exception("Cannot connect to $sUrl: missing module 'openssl'");
  1011. }
  1012. else
  1013. {
  1014. throw new Exception("Wrong URL: $sUrl");
  1015. }
  1016. }
  1017. $response = @stream_get_contents($fp);
  1018. if ($response === false)
  1019. {
  1020. throw new Exception("Problem reading data from $sUrl, $php_errormsg");
  1021. }
  1022. if (is_array($aResponseHeaders))
  1023. {
  1024. $aMeta = stream_get_meta_data($fp);
  1025. $aHeaders = $aMeta['wrapper_data'];
  1026. foreach($aHeaders as $sHeaderString)
  1027. {
  1028. if(preg_match('/^([^:]+): (.+)$/', $sHeaderString, $aMatches))
  1029. {
  1030. $aResponseHeaders[$aMatches[1]] = trim($aMatches[2]);
  1031. }
  1032. }
  1033. }
  1034. }
  1035. return $response;
  1036. }
  1037. /**
  1038. * Get a standard list of character sets
  1039. *
  1040. * @param array $aAdditionalEncodings Additional values
  1041. * @return array of iconv code => english label, sorted by label
  1042. */
  1043. public static function GetPossibleEncodings($aAdditionalEncodings = array())
  1044. {
  1045. // Encodings supported:
  1046. // ICONV_CODE => Display Name
  1047. // Each iconv installation supports different encodings
  1048. // Some reasonably common and useful encodings are listed here
  1049. $aPossibleEncodings = array(
  1050. 'UTF-8' => 'Unicode (UTF-8)',
  1051. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  1052. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  1053. 'WINDOWS-1252' => 'Western (Windows 1252)',
  1054. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  1055. );
  1056. $aPossibleEncodings = array_merge($aPossibleEncodings, $aAdditionalEncodings);
  1057. asort($aPossibleEncodings);
  1058. return $aPossibleEncodings;
  1059. }
  1060. /**
  1061. * Convert a string containing some (valid) HTML markup to plain text
  1062. * @param string $sHtml
  1063. * @return string
  1064. */
  1065. public static function HtmlToText($sHtml)
  1066. {
  1067. try
  1068. {
  1069. //return '<?xml encoding="UTF-8">'.$sHtml;
  1070. return \Html2Text\Html2Text::convert('<?xml encoding="UTF-8">'.$sHtml);
  1071. }
  1072. catch(Exception $e)
  1073. {
  1074. return $e->getMessage();
  1075. }
  1076. }
  1077. /**
  1078. * Convert (?) plain text to some HTML markup by replacing newlines by </br> tags
  1079. * and escaping HTML entities
  1080. * @param string $sText
  1081. * @return string
  1082. */
  1083. public static function TextToHtml($sText)
  1084. {
  1085. $sText = str_replace("\r\n", "\n", $sText);
  1086. $sText = str_replace("\r", "\n", $sText);
  1087. return str_replace("\n", '</br>', htmlentities($sText, ENT_QUOTES, 'UTF-8'));
  1088. }
  1089. }