utils.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. // Parameters loaded from a file, parameters of the page/command line still have precedence
  39. private static $m_aParamsFromFile = null;
  40. protected static function LoadParamFile($sParamFile)
  41. {
  42. if (!file_exists($sParamFile))
  43. {
  44. throw new Exception("Could not find the parameter file: '$sParamFile'");
  45. }
  46. if (!is_readable($sParamFile))
  47. {
  48. throw new Exception("Could not load parameter file: '$sParamFile'");
  49. }
  50. $sParams = file_get_contents($sParamFile);
  51. if (is_null(self::$m_aParamsFromFile))
  52. {
  53. self::$m_aParamsFromFile = array();
  54. }
  55. $aParamLines = explode("\n", $sParams);
  56. foreach ($aParamLines as $sLine)
  57. {
  58. $sLine = trim($sLine);
  59. // Ignore the line after a '#'
  60. if (($iCommentPos = strpos($sLine, '#')) !== false)
  61. {
  62. $sLine = substr($sLine, 0, $iCommentPos);
  63. $sLine = trim($sLine);
  64. }
  65. // Note: the line is supposed to be already trimmed
  66. if (preg_match('/^(\S*)\s*=(.*)$/', $sLine, $aMatches))
  67. {
  68. $sParam = $aMatches[1];
  69. $value = trim($aMatches[2]);
  70. self::$m_aParamsFromFile[$sParam] = $value;
  71. }
  72. }
  73. }
  74. public static function UseParamFile($sParamFileArgName = 'param_file', $bAllowCLI = true)
  75. {
  76. $sFileSpec = self::ReadParam($sParamFileArgName, '', $bAllowCLI);
  77. foreach(explode(',', $sFileSpec) as $sFile)
  78. {
  79. $sFile = trim($sFile);
  80. if (!empty($sFile))
  81. {
  82. self::LoadParamFile($sFile);
  83. }
  84. }
  85. }
  86. public static function IsModeCLI()
  87. {
  88. $sSAPIName = php_sapi_name();
  89. $sCleanName = strtolower(trim($sSAPIName));
  90. if ($sCleanName == 'cli')
  91. {
  92. return true;
  93. }
  94. else
  95. {
  96. return false;
  97. }
  98. }
  99. public static function ReadParam($sName, $defaultValue = "", $bAllowCLI = false)
  100. {
  101. global $argv;
  102. $retValue = $defaultValue;
  103. if (!is_null(self::$m_aParamsFromFile))
  104. {
  105. if (isset(self::$m_aParamsFromFile[$sName]))
  106. {
  107. $retValue = self::$m_aParamsFromFile[$sName];
  108. }
  109. }
  110. if (isset($_REQUEST[$sName]))
  111. {
  112. $retValue = $_REQUEST[$sName];
  113. }
  114. elseif ($bAllowCLI && isset($argv))
  115. {
  116. foreach($argv as $iArg => $sArg)
  117. {
  118. if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
  119. {
  120. $retValue = $aMatches[1];
  121. }
  122. }
  123. }
  124. return $retValue;
  125. }
  126. public static function ReadPostedParam($sName, $defaultValue = "")
  127. {
  128. return isset($_POST[$sName]) ? $_POST[$sName] : $defaultValue;
  129. }
  130. /**
  131. * Reads an uploaded file and turns it into an ormDocument object - Triggers an exception in case of error
  132. * @param string $sName Name of the input used from uploading the file
  133. * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
  134. */
  135. public static function ReadPostedDocument($sName)
  136. {
  137. $oDocument = new ormDocument(); // an empty document
  138. if(isset($_FILES[$sName]))
  139. {
  140. switch($_FILES[$sName]['error'])
  141. {
  142. case UPLOAD_ERR_OK:
  143. $doc_content = file_get_contents($_FILES[$sName]['tmp_name']);
  144. $sMimeType = $_FILES[$sName]['type'];
  145. if (function_exists('finfo_file'))
  146. {
  147. // as of PHP 5.3 the fileinfo extension is bundled within PHP
  148. // in which case we don't trust the mime type provided by the browser
  149. $rInfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  150. if ($rInfo !== false)
  151. {
  152. $sType = @finfo_file($rInfo, $file);
  153. if ( ($sType !== false)
  154. && is_string($sType)
  155. && (strlen($sType)>0))
  156. {
  157. $sMimeType = $sType;
  158. }
  159. }
  160. @finfo_close($rInfo);
  161. }
  162. $oDocument = new ormDocument($doc_content, $sMimeType, $_FILES[$sName]['name']);
  163. break;
  164. case UPLOAD_ERR_NO_FILE:
  165. // no file to load, it's a normal case, just return an empty document
  166. break;
  167. case UPLOAD_ERR_FORM_SIZE:
  168. case UPLOAD_ERR_INI_SIZE:
  169. throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
  170. break;
  171. case UPLOAD_ERR_PARTIAL:
  172. throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
  173. break;
  174. case UPLOAD_ERR_NO_TMP_DIR:
  175. throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
  176. break;
  177. case UPLOAD_ERR_CANT_WRITE:
  178. throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
  179. break;
  180. case UPLOAD_ERR_EXTENSION:
  181. throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $_FILES[$sName]['name']));
  182. break;
  183. default:
  184. throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $_FILES[$sName]['error']));
  185. break;
  186. }
  187. }
  188. return $oDocument;
  189. }
  190. public static function GetNewTransactionId()
  191. {
  192. return privUITransaction::GetNewTransactionId();
  193. }
  194. public static function IsTransactionValid($sId, $bRemoveTransaction = true)
  195. {
  196. return privUITransaction::IsTransactionValid($sId, $bRemoveTransaction);
  197. }
  198. public static function RemoveTransaction($sId)
  199. {
  200. return privUITransaction::RemoveTransaction($sId);
  201. }
  202. public static function ReadFromFile($sFileName)
  203. {
  204. if (!file_exists($sFileName)) return false;
  205. return file_get_contents($sFileName);
  206. }
  207. /**
  208. * Helper function to convert a value expressed in a 'user friendly format'
  209. * as in php.ini, e.g. 256k, 2M, 1G etc. Into a number of bytes
  210. * @param mixed $value The value as read from php.ini
  211. * @return number
  212. */
  213. public static function ConvertToBytes( $value )
  214. {
  215. $iReturn = $value;
  216. if ( !is_numeric( $value ) )
  217. {
  218. $iLength = strlen( $value );
  219. $iReturn = substr( $value, 0, $iLength - 1 );
  220. $sUnit = strtoupper( substr( $value, $iLength - 1 ) );
  221. switch ( $sUnit )
  222. {
  223. case 'G':
  224. $iReturn *= 1024;
  225. case 'M':
  226. $iReturn *= 1024;
  227. case 'K':
  228. $iReturn *= 1024;
  229. }
  230. }
  231. return $iReturn;
  232. }
  233. /**
  234. * Returns an absolute URL to the current page
  235. * @param $bQueryString bool True to also get the query string, false otherwise
  236. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  237. * @return string The absolute URL to the current page
  238. */
  239. static public function GetAbsoluteUrl($bQueryString = true, $bForceHTTPS = false)
  240. {
  241. // Build an absolute URL to this page on this server/port
  242. $sServerName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  243. if (MetaModel::GetConfig()->GetSecureConnectionRequired() || MetaModel::GetConfig()->GetHttpsHyperlinks())
  244. {
  245. // If a secure connection is required, or if the URL is requested to start with HTTPS
  246. // then any URL must start with https !
  247. $bForceHTTPS = true;
  248. }
  249. if ($bForceHTTPS)
  250. {
  251. $sProtocol = 'https';
  252. $sPort = '';
  253. }
  254. else
  255. {
  256. $sProtocol = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!="off")) ? 'https' : 'http';
  257. $iPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
  258. if ($sProtocol == 'http')
  259. {
  260. $sPort = ($iPort == 80) ? '' : ':'.$iPort;
  261. }
  262. else
  263. {
  264. $sPort = ($iPort == 443) ? '' : ':'.$iPort;
  265. }
  266. }
  267. // $_SERVER['REQUEST_URI'] is empty when running on IIS
  268. // Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
  269. if (!empty($_SERVER['REQUEST_URI']))
  270. {
  271. $sPath = $_SERVER['REQUEST_URI'];
  272. }
  273. else
  274. {
  275. $sPath = $_SERVER['SCRIPT_NAME'];
  276. if (!empty($_SERVER['QUERY_STRING']))
  277. {
  278. $sPath .= '?'.$_SERVER['QUERY_STRING'];
  279. }
  280. $_SERVER['REQUEST_URI'] = $sPath;
  281. }
  282. $sPath = $_SERVER['REQUEST_URI'];
  283. if (!$bQueryString)
  284. {
  285. // remove all the parameters from the query string
  286. $iQuestionMarkPos = strpos($sPath, '?');
  287. if ($iQuestionMarkPos !== false)
  288. {
  289. $sPath = substr($sPath, 0, $iQuestionMarkPos);
  290. }
  291. }
  292. $sUrl = "$sProtocol://{$sServerName}{$sPort}{$sPath}";
  293. return $sUrl;
  294. }
  295. /**
  296. * Returns the absolute URL PATH of the current page
  297. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  298. * @return string The absolute URL to the current page
  299. */
  300. static public function GetAbsoluteUrlPath($bForceHTTPS = false)
  301. {
  302. $sAbsoluteUrl = self::GetAbsoluteUrl(false, $bForceHTTPS); // False => Don't get the query string
  303. $sAbsoluteUrl = substr($sAbsoluteUrl, 0, 1+strrpos($sAbsoluteUrl, '/')); // remove the current page, keep just the path, up to the last /
  304. return $sAbsoluteUrl;
  305. }
  306. /**
  307. * Returns the absolute URL to the server's root path
  308. * @param $bForceHTTPS bool True to force HTTPS, false otherwise
  309. * @return string The absolute URL to the server's root, without the first slash
  310. */
  311. static public function GetAbsoluteUrlAppRoot($sCurrentRelativePath = '', $bForceHTTPS = false)
  312. {
  313. $sAbsoluteUrl = self::GetAbsoluteUrl(false, $bForceHTTPS); // False => Don't get the query string
  314. $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
  315. if ($sAppRootPos !== false)
  316. {
  317. $sAbsoluteUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
  318. }
  319. else
  320. {
  321. throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath)");
  322. }
  323. return $sAbsoluteUrl;
  324. }
  325. /**
  326. * Tells whether or not log off operation is supported.
  327. * Actually in only one case:
  328. * 1) iTop is using an internal authentication
  329. * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
  330. * @return boolean True if logoff is supported, false otherwise
  331. */
  332. static function CanLogOff()
  333. {
  334. return (isset($_SESSION['login_mode']) && $_SESSION['login_mode'] == 'form');
  335. }
  336. }
  337. ?>