utils.inc.php 44 KB

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