utils.inc.php 38 KB

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