utils.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. * @param string $sIndex If Name is an array of posted files, then the index must be used to point out the file
  135. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  136. */
  137. public static function ReadPostedDocument($sName, $sIndex = null)
  138. {
  139. $oDocument = new ormDocument(); // an empty document
  140. if(isset($_FILES[$sName]))
  141. {
  142. $aFileInfo = $_FILES[$sName];
  143. $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
  144. switch($sError)
  145. {
  146. case UPLOAD_ERR_OK:
  147. $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
  148. $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
  149. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  150. $doc_content = file_get_contents($sTmpName);
  151. if (function_exists('finfo_file'))
  152. {
  153. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  154. // in which case we don't trust the mime type provided by the browser
  155. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  156. if ($rInfo !== false)
  157. {
  158. $sType = @finfo_file($rInfo, $file);
  159. if ( ($sType !== false)
  160. && is_string($sType)
  161. && (strlen($sType)>0))
  162. {
  163. $sMimeType = $sType;
  164. }
  165. }
  166. @finfo_close($rInfo);
  167. }
  168. $oDocument = new ormDocument($doc_content, $sMimeType, $sName);
  169. break;
  170. case UPLOAD_ERR_NO_FILE:
  171. // no file to load, it's a normal case, just return an empty document
  172. break;
  173. case UPLOAD_ERR_FORM_SIZE:
  174. case UPLOAD_ERR_INI_SIZE:
  175. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  176. break;
  177. case UPLOAD_ERR_PARTIAL:
  178. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  179. break;
  180. case UPLOAD_ERR_NO_TMP_DIR:
  181. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  182. break;
  183. case UPLOAD_ERR_CANT_WRITE:
  184. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  185. break;
  186. case UPLOAD_ERR_EXTENSION:
  187. $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
  188. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
  189. break;
  190. default:
  191. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
  192. break;
  193. }
  194. }
  195. return $oDocument;
  196. }
  197. /**
  198. * Interprets the results posted by a normal or paginated list (in multiple selection mode)
  199. * @param $oFullSetFilter DBObjectSearch The criteria defining the whole sets of objects being selected
  200. * @return Array An arry of object IDs corresponding to the objects selected in the set
  201. */
  202. public static function ReadMultipleSelection($oFullSetFilter)
  203. {
  204. $aSelectedObj = utils::ReadParam('selectObject', array());
  205. $sSelectionMode = utils::ReadParam('selectionMode', '');
  206. if ($sSelectionMode != '')
  207. {
  208. // Paginated selection
  209. $aExceptions = utils::ReadParam('storedSelection', array());
  210. if ($sSelectionMode == 'positive')
  211. {
  212. // Only the explicitely listed items are selected
  213. $aSelectedObj = $aExceptions;
  214. }
  215. else
  216. {
  217. // All items of the set are selected, except the one explicitely listed
  218. $aSelectedObj = array();
  219. $oFullSet = new DBObjectSet($oFullSetFilter);
  220. $sClassAlias = $oFullSetFilter->GetClassAlias();
  221. $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
  222. while($oObj = $oFullSet->Fetch())
  223. {
  224. if (!in_array($oObj->GetKey(), $aExceptions))
  225. {
  226. $aSelectedObj[] = $oObj->GetKey();
  227. }
  228. }
  229. }
  230. }
  231. return $aSelectedObj;
  232. }
  233. public static function GetNewTransactionId()
  234. {
  235. return privUITransaction::GetNewTransactionId();
  236. }
  237. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  238. {
  239. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  240. }
  241. public static function RemoveTransaction($sId)
  242. {
  243. return privUITransaction::RemoveTransaction($sId);
  244. }
  245. public static function ReadFromFile($sFileName)
  246. {
  247. if (!file_exists($sFileName)) return false;
  248. return file_get_contents($sFileName);
  249. }
  250. /**
  251. * Helper function to convert a value expressed in a 'user friendly format'
  252. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  253. * @param mixed $value The value as read from php.ini
  254. * @return number
  255. */
  256. public static function ConvertToBytes( $value )
  257. {
  258. $iReturn = $value;
  259. if ( !is_numeric( $value ) )
  260. {
  261. $iLength = strlen( $value );
  262. $iReturn = substr( $value, 0, $iLength - 1 );
  263. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  264. switch ( $sUnit )
  265. {
  266. case 'G':
  267. $iReturn *= 1024;
  268. case 'M':
  269. $iReturn *= 1024;
  270. case 'K':
  271. $iReturn *= 1024;
  272. }
  273. }
  274. return $iReturn;
  275. }
  276. /**
  277. * 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)
  278. * Example: StringToTime('01/05/11 12:03:45', '%d/%m/%y %H:%i:%s')
  279. * @param string $sDate
  280. * @param string $sFormat
  281. * @return timestamp or false if the input format is not correct
  282. */
  283. public static function StringToTime($sDate, $sFormat)
  284. {
  285. // Source: http://php.net/manual/fr/function.strftime.php
  286. // (alternative: http://www.php.net/manual/fr/datetime.formats.date.php)
  287. static $aDateTokens = null;
  288. static $aDateRegexps = null;
  289. if (is_null($aDateTokens))
  290. {
  291. $aSpec = array(
  292. '%d' =>'(?<day>[0-9]{2})',
  293. '%m' => '(?<month>[0-9]{2})',
  294. '%y' => '(?<year>[0-9]{2})',
  295. '%Y' => '(?<year>[0-9]{4})',
  296. '%H' => '(?<hour>[0-2][0-9])',
  297. '%i' => '(?<minute>[0-5][0-9])',
  298. '%s' => '(?<second>[0-5][0-9])',
  299. );
  300. $aDateTokens = array_keys($aSpec);
  301. $aDateRegexps = array_values($aSpec);
  302. }
  303. $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
  304. if (preg_match('!^(?<head>)'.$sDateRegexp.'(?<tail>)$!', $sDate, $aMatches))
  305. {
  306. $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
  307. $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
  308. $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
  309. $sHour = isset($aMatches['hour']) ? $aMatches['hour'] : 0;
  310. $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
  311. $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
  312. return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
  313. }
  314. else
  315. {
  316. return false;
  317. }
  318. // http://www.spaweditor.com/scripts/regex/index.php
  319. }
  320. /**
  321. * Returns the absolute URL to the server's root path
  322. * @param $sCurrentRelativePath string NO MORE USED, kept for backward compatibility only !
  323. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  324. * @return string The absolute URL to the server's root, without the first slash
  325. */
  326. static public function GetAbsoluteUrlAppRoot()
  327. {
  328. return MetaModel::GetConfig()->Get('app_root_url');
  329. }
  330. static public function GetDefaultUrlAppRoot()
  331. {
  332. // Build an absolute URL to this page on this server/port
  333. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  334. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  335. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  336. if ($sProtocol == 'http')
  337. {
  338. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  339. }
  340. else
  341. {
  342. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  343. }
  344. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  345. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  346. if (!empty($_SERVER['REQUEST_URI']))
  347. {
  348. $sPath = $_SERVER['REQUEST_URI'];
  349. }
  350. else
  351. {
  352. $sPath = $_SERVER['SCRIPT_NAME'];
  353. if (!empty($_SERVER['QUERY_STRING']))
  354. {
  355. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  356. }
  357. $_SERVER['REQUEST_URI'] = $sPath;
  358. }
  359. $sPath = $_SERVER['REQUEST_URI'];
  360. // remove all the parameters from the query string
  361. $iQuestionMarkPos = strpos($sPath, '?');
  362. if ($iQuestionMarkPos !== false)
  363. {
  364. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  365. }
  366. $sAbsoluteUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  367. $sCurrentScript = realpath($_SERVER['SCRIPT_FILENAME']);
  368. $sCurrentScript = str_replace('\\', '/', $sCurrentScript); // canonical path
  369. $sAppRoot = str_replace('\\', '/', APPROOT); // canonical path
  370. $sCurrentRelativePath = str_replace($sAppRoot, '', $sCurrentScript);
  371. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  372. if ($sAppRootPos !== false)
  373. {
  374. $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  375. }
  376. else
  377. {
  378. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
  379. }
  380. return $sAppRootUrl;
  381. }
  382. /**
  383. * Tells whether or not log off operation is supported.
  384. * Actually in only one case:
  385. * 1) iTop is using an internal authentication
  386. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  387. * @return boolean True if logoff is supported, false otherwise
  388. */
  389. static function CanLogOff()
  390. {
  391. $bResult = false;
  392. if(isset($_SESSION['login_mode']))
  393. {
  394. $sLoginMode = $_SESSION['login_mode'];
  395. switch($sLoginMode)
  396. {
  397. case 'external':
  398. $bResult = false;
  399. break;
  400. case 'form':
  401. case 'basic':
  402. case 'url':
  403. case 'cas':
  404. default:
  405. $bResult = true;
  406. }
  407. }
  408. return $bResult;
  409. }
  410. /**
  411. * Initializes the CAS client
  412. */
  413. static function InitCASClient()
  414. {
  415. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  416. include_once($sCASIncludePath.'/CAS.php');
  417. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  418. if ($bCASDebug)
  419. {
  420. phpCAS::setDebug(APPROOT.'/error.log');
  421. }
  422. if (!self::$m_bCASClient)
  423. {
  424. // Initialize phpCAS
  425. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  426. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  427. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  428. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  429. phpCAS::client($sCASVersion, $sCASHost, $iCASPort, $sCASContext, false /* session already started */);
  430. self::$m_bCASClient = true;
  431. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  432. if (empty($sCASCACertPath))
  433. {
  434. // If no certificate authority is provided, do not attempt to validate
  435. // the server's certificate
  436. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  437. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  438. phpCAS::setNoCasServerValidation();
  439. }
  440. else
  441. {
  442. phpCAS::setCasServerCACert($sCASCACertPath);
  443. }
  444. }
  445. }
  446. }
  447. ?>