utils.inc.php 38 KB

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