utils.inc.php 8.0 KB

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