utils.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Static class utils
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once(APPROOT.'/core/config.class.inc.php');
  25. require_once(APPROOT.'/application/transaction.class.inc.php');
  26. define('ITOP_CONFIG_FILE', APPROOT.'/config-itop.php');
  27. class FileUploadException extends Exception
  28. {
  29. }
  30. /**
  31. * Helper functions to interact with forms: read parameters, upload files...
  32. * @package iTop
  33. */
  34. class utils
  35. {
  36. private static $m_sConfigFile = ITOP_CONFIG_FILE;
  37. private static $m_oConfig = null;
  38. private static $m_bCASClient = false;
  39. // Parameters loaded from a file, parameters of the page/command line still have precedence
  40. private static $m_aParamsFromFile = null;
  41. protected static function LoadParamFile($sParamFile)
  42. {
  43. if (!file_exists($sParamFile))
  44. {
  45. throw new Exception("Could not find the parameter file: '$sParamFile'");
  46. }
  47. if (!is_readable($sParamFile))
  48. {
  49. throw new Exception("Could not load parameter file: '$sParamFile'");
  50. }
  51. $sParams = file_get_contents($sParamFile);
  52. if (is_null(self::$m_aParamsFromFile))
  53. {
  54. self::$m_aParamsFromFile = array();
  55. }
  56. $aParamLines = explode("\n", $sParams);
  57. foreach ($aParamLines as $sLine)
  58. {
  59. $sLine = trim($sLine);
  60. // Ignore the line after a '#'
  61. if (($iCommentPos = strpos($sLine, '#')) !== false)
  62. {
  63. $sLine = substr($sLine, 0, $iCommentPos);
  64. $sLine = trim($sLine);
  65. }
  66. // Note: the line is supposed to be already trimmed
  67. if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches))
  68. {
  69. $sParam = $aMatches[1];
  70. $value = trim($aMatches[2]);
  71. self::$m_aParamsFromFile[$sParam] = $value;
  72. }
  73. }
  74. }
  75. public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
  76. {
  77. $sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI);
  78. foreach(explode(',', $sFileSpec) as $sFile)
  79. {
  80. $sFile = trim($sFile);
  81. if (!empty($sFile))
  82. {
  83. self::LoadParamFile($sFile);
  84. }
  85. }
  86. }
  87. public static function IsModeCLI()
  88. {
  89. $sSAPIName = php_sapi_name();
  90. $sCleanName = strtolower(trim($sSAPIName));
  91. if ($sCleanName == 'cli')
  92. {
  93. return true;
  94. }
  95. else
  96. {
  97. return false;
  98. }
  99. }
  100. public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false)
  101. {
  102. global $argv;
  103. $retValue = $defaultValue;
  104. if (!is_null(self::$m_aParamsFromFile))
  105. {
  106. if (isset(self::$m_aParamsFromFile[$sName]))
  107. {
  108. $retValue = self::$m_aParamsFromFile[$sName];
  109. }
  110. }
  111. if (isset($_REQUEST[$sName]))
  112. {
  113. $retValue = $_REQUEST[$sName];
  114. }
  115. elseif ($bAllowCLI && isset($argv))
  116. {
  117. foreach($argv as $iArg => $sArg)
  118. {
  119. if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
  120. {
  121. $retValue = $aMatches[1];
  122. }
  123. }
  124. }
  125. return $retValue;
  126. }
  127. public static function ReadPostedParam($sName, $defaultValue = "")
  128. {
  129. return isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  130. }
  131. /**
  132. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  133. * @param string $sName Name of the input used from uploading the file
  134. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  135. */
  136. public static function ReadPostedDocument($sName)
  137. {
  138. $oDocument = new ormDocument(); // an empty document
  139. if(isset($_FILES[$sName]))
  140. {
  141. switch($_FILES[$sName]['error'])
  142. {
  143. case UPLOAD_ERR_OK:
  144. $doc_content = file_get_contents($_FILES[$sName]['tmp_name']);
  145. $sMimeType = $_FILES[$sName]['type'];
  146. if (function_exists('finfo_file'))
  147. {
  148. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  149. // in which case we don't trust the mime type provided by the browser
  150. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  151. if ($rInfo !== false)
  152. {
  153. $sType = @finfo_file($rInfo, $file);
  154. if ( ($sType !== false)
  155. && is_string($sType)
  156. && (strlen($sType)>0))
  157. {
  158. $sMimeType = $sType;
  159. }
  160. }
  161. @finfo_close($rInfo);
  162. }
  163. $oDocument = new ormDocument($doc_content, $sMimeType, $_FILES[$sName]['name']);
  164. break;
  165. case UPLOAD_ERR_NO_FILE:
  166. // no file to load, it's a normal case, just return an empty document
  167. break;
  168. case UPLOAD_ERR_FORM_SIZE:
  169. case UPLOAD_ERR_INI_SIZE:
  170. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  171. break;
  172. case UPLOAD_ERR_PARTIAL:
  173. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  174. break;
  175. case UPLOAD_ERR_NO_TMP_DIR:
  176. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  177. break;
  178. case UPLOAD_ERR_CANT_WRITE:
  179. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  180. break;
  181. case UPLOAD_ERR_EXTENSION:
  182. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $_FILES[$sName]['name']));
  183. break;
  184. default:
  185. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $_FILES[$sName]['error']));
  186. break;
  187. }
  188. }
  189. return $oDocument;
  190. }
  191. /**
  192. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  193. * @param $oFullSetFilter DBObjectSearch The criteria defining the whole sets of objects being selected
  194. * @return Array An arry of object IDs corresponding to the objects selected in the set
  195. */
  196. public static function ReadMultipleSelection($oFullSetFilter)
  197. {
  198. $aSelectedObj = utils::ReadParam('selectObject', array());
  199. $sSelectionMode = utils::ReadParam('selectionMode', '');
  200. if ($sSelectionMode != '')
  201. {
  202. // Paginated selection
  203. $aExceptions = utils::ReadParam('storedSelection', array());
  204. if ($sSelectionMode == 'positive')
  205. {
  206. // Only the explicitely listed items are selected
  207. $aSelectedObj = $aExceptions;
  208. }
  209. else
  210. {
  211. // All items of the set are selected, except the one explicitely listed
  212. $aSelectedObj = array();
  213. $oFullSet = new DBObjectSet($oFullSetFilter);
  214. $sClassAlias = $oFullSetFilter->GetClassAlias();
  215. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  216. while($oObj = $oFullSet->Fetch())
  217. {
  218. if (!in_array($oObj->GetKey(), $aExceptions))
  219. {
  220. $aSelectedObj[] = $oObj->GetKey();
  221. }
  222. }
  223. }
  224. }
  225. return $aSelectedObj;
  226. }
  227. public static function GetNewTransactionId()
  228. {
  229. return privUITransaction::GetNewTransactionId();
  230. }
  231. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  232. {
  233. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  234. }
  235. public static function RemoveTransaction($sId)
  236. {
  237. return privUITransaction::RemoveTransaction($sId);
  238. }
  239. public static function ReadFromFile($sFileName)
  240. {
  241. if (!file_exists($sFileName)) return false;
  242. return file_get_contents($sFileName);
  243. }
  244. /**
  245. * Helper function to convert a value expressed in a 'user friendly format'
  246. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  247. * @param mixed $value The value as read from php.ini
  248. * @return number
  249. */
  250. public static function ConvertToBytes( $value )
  251. {
  252. $iReturn = $value;
  253. if ( !is_numeric( $value ) )
  254. {
  255. $iLength = strlen( $value );
  256. $iReturn = substr( $value, 0, $iLength - 1 );
  257. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  258. switch ( $sUnit )
  259. {
  260. case 'G':
  261. $iReturn *= 1024;
  262. case 'M':
  263. $iReturn *= 1024;
  264. case 'K':
  265. $iReturn *= 1024;
  266. }
  267. }
  268. return $iReturn;
  269. }
  270. /**
  271. * 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)
  272. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  273. * @param string $sDate
  274. * @param string $sFormat
  275. * @return timestamp or false if the input format is not correct
  276. */
  277. public static function StringToTime($sDate, $sFormat)
  278. {
  279. // Source: http://php.net/manual/fr/function.strftime.php
  280. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  281. static $aDateTokens = null;
  282. static $aDateRegexps = null;
  283. if (is_null($aDateTokens))
  284. {
  285. $aSpec = array(
  286. '%d' =>'(?<day>[0-9]{2})',
  287. '%m' => '(?<month>[0-9]{2})',
  288. '%y' => '(?<year>[0-9]{2})',
  289. '%Y' => '(?<year>[0-9]{4})',
  290. '%H' => '(?<hour>[0-2][0-9])',
  291. '%i' => '(?<minute>[0-5][0-9])',
  292. '%s' => '(?<second>[0-5][0-9])',
  293. );
  294. $aDateTokens = array_keys($aSpec);
  295. $aDateRegexps = array_values($aSpec);
  296. }
  297. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  298. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  299. {
  300. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  301. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  302. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  303. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  304. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  305. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  306. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  307. }
  308. else
  309. {
  310. return false;
  311. }
  312. // http://www.spaweditor.com/scripts/regex/index.php
  313. }
  314. /**
  315. * Returns the absolute URL to the server's root path
  316. * @param $sCurrentRelativePath string NO MORE USED, kept for backward compatibility only !
  317. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  318. * @return string The absolute URL to the server's root, without the first slash
  319. */
  320. static public function GetAbsoluteUrlAppRoot()
  321. {
  322. return MetaModel::GetConfig()->Get('app_root_url');
  323. }
  324. static public function GetDefaultUrlAppRoot()
  325. {
  326. // Build an absolute URL to this page on this server/port
  327. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  328. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  329. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  330. if ($sProtocol == 'http')
  331. {
  332. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  333. }
  334. else
  335. {
  336. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  337. }
  338. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  339. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  340. if (!empty($_SERVER['REQUEST_URI']))
  341. {
  342. $sPath = $_SERVER['REQUEST_URI'];
  343. }
  344. else
  345. {
  346. $sPath = $_SERVER['SCRIPT_NAME'];
  347. if (!empty($_SERVER['QUERY_STRING']))
  348. {
  349. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  350. }
  351. $_SERVER['REQUEST_URI'] = $sPath;
  352. }
  353. $sPath = $_SERVER['REQUEST_URI'];
  354. // remove all the parameters from the query string
  355. $iQuestionMarkPos = strpos($sPath, '?');
  356. if ($iQuestionMarkPos !== false)
  357. {
  358. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  359. }
  360. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  361. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  362. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  363. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  364. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  365. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  366. if ($sAppRootPos !== false)
  367. {
  368. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  369. }
  370. else
  371. {
  372. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  373. }
  374. return $sAppRootUrl;
  375. }
  376. /**
  377. * Tells whether or not log off operation is supported.
  378. * Actually in only one case:
  379. * 1) iTop is using an internal authentication
  380. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  381. * @return boolean True if logoff is supported, false otherwise
  382. */
  383. static function CanLogOff()
  384. {
  385. $bResult = false;
  386. if(isset($_SESSION['login_mode']))
  387. {
  388. $sLoginMode = $_SESSION['login_mode'];
  389. switch($sLoginMode)
  390. {
  391. case 'external':
  392. $bResult = false;
  393. break;
  394. case 'form':
  395. case 'basic':
  396. case 'url':
  397. case 'cas':
  398. default:
  399. $bResult = true;
  400. }
  401. }
  402. return $bResult;
  403. }
  404. /**
  405. * Initializes the CAS client
  406. */
  407. static function InitCASClient()
  408. {
  409. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  410. include_once($sCASIncludePath.'/CAS.php');
  411. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  412. if ($bCASDebug)
  413. {
  414. phpCAS::setDebug(APPROOT.'/error.log');
  415. }
  416. if (!self::$m_bCASClient)
  417. {
  418. // Initialize phpCAS
  419. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  420. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  421. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  422. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  423. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  424. self::$m_bCASClient = true;
  425. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  426. if (empty($sCASCACertPath))
  427. {
  428. // If no certificate authority is provided, do not attempt to validate
  429. // the server's certificate
  430. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  431. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  432. phpCAS::setNoCasServerValidation();
  433. }
  434. else
  435. {
  436. phpCAS::setCasServerCACert($sCASCACertPath);
  437. }
  438. }
  439. }
  440. }
  441. ?>