utils.inc.php 9.6 KB

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