utils.inc.php 40 KB

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