PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/class/class.global.php

http://candydolldb.googlecode.com/
PHP | 539 lines | 359 code | 63 blank | 117 comment | 38 complexity | 85f85f1776ee9c35647bb288095c7560 MD5 | raw file
  1. <?php
  2. class Rights
  3. {
  4. /**
  5. * Returns an array containing all defined right related constants.
  6. * @return array(int)
  7. */
  8. public static function getDefinedRights()
  9. {
  10. $c = get_defined_constants();
  11. foreach ($c as $k => $v){
  12. if(stripos($k, 'RIGHT_') !== 0){
  13. unset($c[$k]);
  14. }
  15. }
  16. uasort($c, function($a, $b){
  17. return $a == $b ? 0 :
  18. $a < $b ? -1 : 1;
  19. });
  20. return $c;
  21. }
  22. /**
  23. * Returns an array of all defined right-constants.
  24. * @return array(int)
  25. */
  26. public static function getTotalRights()
  27. {
  28. return self::getDefinedRights();
  29. }
  30. }
  31. class Authentication
  32. {
  33. /**
  34. * Authenticates this session's User, and returns its object.
  35. * @return User
  36. */
  37. public static function Authenticate()
  38. {
  39. global $lang;
  40. if(array_key_exists('CurrentUser', $_SESSION))
  41. {
  42. /* @var $User User */
  43. $User = unserialize($_SESSION['CurrentUser']);
  44. $Users = User::GetUsers(new UserSearchParameters(
  45. $User->getID(),
  46. FALSE,
  47. FALSE,
  48. $User->getPassword()
  49. ));
  50. if($Users)
  51. {
  52. $User = $Users[0];
  53. $User->setLastActive(time());
  54. User::Update($User, $User);
  55. $lang->setLanguages(array($User->getLanguage()));
  56. if($User->hasPermission(RIGHT_ACCOUNT_LOGIN))
  57. {
  58. return $User;
  59. }
  60. else
  61. {
  62. $e = new Error(RIGHTS_ERR_USERNOTALLOWED);
  63. Error::AddError($e);
  64. header('location:login.php#2');
  65. exit;
  66. }
  67. }
  68. else
  69. {
  70. header('location:login.php#1');
  71. exit;
  72. }
  73. }
  74. else
  75. {
  76. global $argv, $argc;
  77. if(isset($argv) && $argc > 0)
  78. {
  79. foreach($argv as $arg)
  80. {
  81. $kv = explode('=', $arg);
  82. if(count($kv) > 1)
  83. { $_GET[$kv[0]] = $kv[1]; }
  84. unset($kv);
  85. }
  86. /* Authenticate on the commandline as Default User */
  87. $Users = User::GetUsers(new UserSearchParameters(CMDLINE_USERID));
  88. if($Users)
  89. {
  90. $User = $Users[0];
  91. return $User;
  92. }
  93. else
  94. {
  95. return NULL;
  96. }
  97. }
  98. else
  99. {
  100. /* If not on the commandline, the Session expired */
  101. header('location:login.php?url='.urlencode($_SERVER['REQUEST_URI']));
  102. exit;
  103. }
  104. }
  105. }
  106. }
  107. class BusyIndicator
  108. {
  109. private static $chars = '-\|/';
  110. private $stringPrefix;
  111. private $currentCharIndex;
  112. private $maxValue;
  113. private $currentValue;
  114. /**
  115. * Creates a new busy-indicator from the supplied arguments.
  116. * @param int $maxValue
  117. * @param int $startValue
  118. * @param string $prefix
  119. */
  120. public function BusyIndicator($maxValue = 100, $startValue = 0, $prefix = '')
  121. {
  122. $this->currentCharIndex = 0;
  123. $this->maxValue = $maxValue;
  124. $this->currentValue = $startValue;
  125. $this->stringPrefix = $prefix;
  126. }
  127. /**
  128. * Calculates the current value of the busy-indicator.
  129. * @return float
  130. */
  131. private function CalcValue()
  132. {
  133. return (
  134. ($this->currentValue ? $this->currentValue : 0) /
  135. ($this->maxValue ? $this->maxValue : 100)
  136. );
  137. }
  138. /**
  139. * Prints a number of BACKSPACE-characters equal in length to the input string.
  140. * @param string $inString
  141. */
  142. private static function SweepItClean($inString)
  143. {
  144. for($i = 0; $i < strlen($inString); $i++)
  145. { printf("\x08"); }
  146. }
  147. /**
  148. * Advances the busy-indicator by the given amount and draws all output to screen.
  149. * @param int $step
  150. */
  151. public function Next($step = 1)
  152. {
  153. $toWrite = sprintf('%1$s %2$s %3$6.2f%%',
  154. $this->stringPrefix,
  155. substr(self::$chars, $this->currentCharIndex, 1),
  156. $this->CalcValue() * 100
  157. );
  158. echo $toWrite;
  159. echo self::SweepItClean($toWrite);
  160. $this->currentCharIndex++;
  161. if($this->currentCharIndex > strlen(self::$chars) - 1)
  162. { $this->currentCharIndex = 0; }
  163. $this->currentValue += $step;
  164. }
  165. /**
  166. * Draws the word 'Finished' and a trailing newline to the commandline.
  167. */
  168. public function Finish()
  169. {
  170. global $lang;
  171. printf(
  172. "%1\$s %2\$s\n",
  173. $this->stringPrefix,
  174. $lang->g('CLIFinished')
  175. );
  176. }
  177. }
  178. class Utils
  179. {
  180. /**
  181. * Calculates the crc32 polynomial of a filename on disk
  182. * @param string $filename
  183. * @return string
  184. */
  185. public static function CalculateCRC32($filename)
  186. {
  187. if(file_exists($filename))
  188. {
  189. $crc = hash_file('crc32b', $filename);
  190. return str_pad(strtoupper($crc), 8, '0');
  191. }
  192. return NULL;
  193. }
  194. /**
  195. * Calculates the MD5 checksum of a filename on disk
  196. * @param string $filename
  197. * @return string
  198. */
  199. public static function CalculateMD5($filename)
  200. {
  201. if(file_exists($filename))
  202. {
  203. return hash_file('md5', $filename);
  204. }
  205. return NULL;
  206. }
  207. /**
  208. * Returns a human readable string of a filesize, e.g. 2,43 MiB.
  209. * @param int $SizeInBytes
  210. * @return string
  211. */
  212. public static function ReadableFilesize($SizeInBytes)
  213. {
  214. $OutString = sprintf('%1$d B', $SizeInBytes);
  215. if($SizeInBytes >= 1024)
  216. { $OutString = sprintf('%1$.0f KiB', $SizeInBytes / 1024); }
  217. if($SizeInBytes >= pow(1024, 2))
  218. { $OutString = sprintf('%1$.2f MiB', $SizeInBytes / pow(1024, 2)); }
  219. if($SizeInBytes >= pow(1024, 3))
  220. { $OutString = sprintf('%1$.2f GiB', $SizeInBytes / pow(1024, 3)); }
  221. if($SizeInBytes >= pow(1024, 4))
  222. { $OutString = sprintf('%1$.2f TiB', $SizeInBytes / pow(1024, 4)); }
  223. if($SizeInBytes >= pow(1024, 5))
  224. { $OutString = sprintf('%1$.2f PiB', $SizeInBytes / pow(1024, 5)); }
  225. if($SizeInBytes >= pow(1024, 6))
  226. { $OutString = sprintf('%1$.2f EiB', $SizeInBytes / pow(1024, 6)); }
  227. if($SizeInBytes >= pow(1024, 7))
  228. { $OutString = sprintf('%1$.2f ZiB', $SizeInBytes / pow(1024, 7)); }
  229. if($SizeInBytes >= pow(1024, 8))
  230. { $OutString = sprintf('%1$.2f YiB', $SizeInBytes / pow(1024, 8)); }
  231. return $OutString;
  232. }
  233. /**
  234. * Searches the GET-array for a key named $name and returns its absolute integer value, or NULL on failure.
  235. * @param string $name
  236. * @return int
  237. */
  238. public static function SafeIntFromQS($name)
  239. {
  240. if(array_key_exists($name, $_GET) && isset($_GET[$name]) && is_numeric($_GET[$name]))
  241. { return abs((int)$_GET[$name]); }
  242. return NULL;
  243. }
  244. /**
  245. * Searches the GET-array for a key named $name and returns its value (TRUE or FALSE), or FALSE on failure.
  246. * @param string $name
  247. * @return bool
  248. */
  249. public static function SafeBoolFromQS($name)
  250. {
  251. return (
  252. array_key_exists($name, $_GET) &&
  253. isset($_GET[$name]) &&
  254. ($_GET[$name] == 'true' || $_GET[$name] == '1')
  255. );
  256. }
  257. /**
  258. * Returns an array of integers, safe to be processed in, for example, an SQL-in-query
  259. * @param array $inArray
  260. * @return array
  261. */
  262. public static function SafeInts($inArray)
  263. {
  264. $outArray = array();
  265. if(is_array($inArray)){
  266. foreach ($inArray as $value) {
  267. $outArray[] = abs(intval($value));
  268. }
  269. }
  270. return array_unique($outArray);
  271. }
  272. /**
  273. * Validates the given string to be a valid emailaddress.
  274. * @param string $InAddress
  275. * @return bool
  276. */
  277. public static function ValidateEmail($InAddress)
  278. {
  279. if(strlen($InAddress) > 253) { return FALSE; }
  280. $EmailPattern = "/^[a-z0-9] ( [-a-z0-9_] | \.(?!\.) )* [a-z0-9] @ [a-z0-9]{2,} ( [-a-z0-9_] | \.(?!\.) )* \.[a-z]{2,} $ /ix";
  281. return preg_match($EmailPattern, $InAddress) > 0;
  282. }
  283. /**
  284. * @param int $TimeStamp
  285. * @return float
  286. */
  287. public static function CalculateAge($TimeStamp)
  288. {
  289. $diff = time() - (int)$TimeStamp;
  290. $age = (float)($diff / 60 / 60 / 24 / 365.25);
  291. return $age;
  292. }
  293. /**
  294. * @param int $GarbageLength
  295. * @return string
  296. */
  297. public static function GenerateGarbage($GarbageLength)
  298. {
  299. $Garbage = '';
  300. $CharsToChooseFrom = 'abcdefghijklmnopqrstuvwxyz';
  301. $CharsToChooseFrom .= strtoupper($CharsToChooseFrom);
  302. $CharsToChooseFrom .= '0123456789';
  303. $CharsToChooseFromLength = strlen($CharsToChooseFrom);
  304. for($i = 0; $i < $GarbageLength; $i++){
  305. $Garbage .= substr($CharsToChooseFrom, rand(0, $CharsToChooseFromLength -1), 1);
  306. }
  307. return $Garbage;
  308. }
  309. /**
  310. * Returns a Universally Unique IDentifier, as described in RFC 4122.
  311. * @return string
  312. */
  313. public static function UUID()
  314. {
  315. if (function_exists('com_create_guid') === TRUE)
  316. { return strtolower(trim(com_create_guid(), '{}')); }
  317. return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  318. mt_rand(0, 65535),
  319. mt_rand(0, 65535),
  320. mt_rand(0, 65535),
  321. mt_rand(16384, 20479),
  322. mt_rand(32768, 49151),
  323. mt_rand(0, 65535),
  324. mt_rand(0, 65535),
  325. mt_rand(0, 65535)
  326. );
  327. }
  328. /**
  329. * Returns a hashed and salted version of the input string.
  330. * @param string $PlainTextString
  331. * @param string $Salt
  332. * @return string
  333. */
  334. public static function HashString($PlainTextString, $Salt)
  335. {
  336. $OutHash = $PlainTextString;
  337. for ($i = 0; $i < 20000; $i++)
  338. {
  339. if($i % 2 == 0) { $OutHash = hash('sha512', $OutHash.$Salt, FALSE); }
  340. else { $OutHash = hash('sha512', $Salt.$OutHash, FALSE); }
  341. }
  342. return $OutHash;
  343. }
  344. /**
  345. * Generates a download-prompt for the given ZIP-file on-disk.
  346. * @param string $filenameOnDisk
  347. * @param string $filenameToBe
  348. * @param bool $DeleteOriginal
  349. */
  350. public static function DownloadZip($filenameOnDisk, $filenameToBe, $DeleteOriginal = FALSE)
  351. {
  352. if(file_exists($filenameOnDisk))
  353. {
  354. header('Content-Description: File Transfer');
  355. header(sprintf('Content-Type: %1$s', Utils::GetMime('zip')));
  356. header(sprintf('Content-Disposition: attachment; filename="%1$s"', $filenameToBe));
  357. header('Content-Transfer-Encoding: binary');
  358. header('Expires: 0');
  359. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  360. header('Pragma: public');
  361. header('Content-Length: '.filesize($filenameOnDisk));
  362. @ob_clean();
  363. $f = fopen($filenameOnDisk, "r");
  364. if($f !== FALSE)
  365. {
  366. while($chunk = fread($f, 16777216))
  367. { echo $chunk; }
  368. fclose($f);
  369. }
  370. if($DeleteOriginal)
  371. { unlink($filenameOnDisk); }
  372. }
  373. exit;
  374. }
  375. /**
  376. * Determine whether a variable, or function call is empty
  377. * @param mixed $val
  378. * @return bool
  379. */
  380. public static function _empty($val)
  381. { return empty($val); }
  382. /**
  383. * Returns NULL or $val, depending on whether $val is empty
  384. * @param mixed $val
  385. * @return mixed
  386. */
  387. public static function NullIfEmpty($val)
  388. { return empty($val) ? NULL : $val; }
  389. /**
  390. * An array containing file extensions and their corresponding MIME-types.
  391. * @var array
  392. */
  393. private static $MimeArray = array(
  394. 'doc' => 'application/msword',
  395. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  396. 'pdf' => 'application/pdf',
  397. 'pps' => 'application/vnd.ms-powerpoint',
  398. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  399. 'ppt' => 'application/vnd.ms-powerpoint',
  400. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  401. 'pub' => 'application/x-mspublisher',
  402. 'rtf' => 'application/rtf',
  403. 'txt' => 'text/plain',
  404. 'odt' => 'application/vnd.oasis.opendocument.text',
  405. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  406. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  407. 'odf' => 'application/vnd.oasis.opendocument.formula',
  408. 'xls' => 'application/vnd.ms-excel',
  409. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  410. 'csv' => 'text/csv',
  411. 'sfv' => 'text/x-sfv',
  412. 'bmp' => 'image/bmp',
  413. 'gif' => 'image/gif',
  414. 'png' => 'image/png',
  415. 'jpg' => 'image/jpeg',
  416. 'jpeg' => 'image/jpeg',
  417. 'jpe' => 'image/jpeg',
  418. 'tif' => 'image/tiff',
  419. 'tiff' => 'image/tiff',
  420. 'flac' => 'audio/flac',
  421. 'mp3' => 'audio/mpeg',
  422. 'm3u' => 'audio/x-mpegurl',
  423. 'wav' => 'audio/x-wav',
  424. 'wma' => 'audio/x-ms-wma',
  425. 'oga' => 'audio/ogg',
  426. 'ogg' => 'audio/ogg',
  427. 'asf' => 'video/x-ms-asf',
  428. 'asx' => 'video/x-ms-asf',
  429. 'avi' => 'video/x-msvideo',
  430. 'ogv' => 'video/ogg',
  431. 'qt' => 'video/quicktime',
  432. 'mov' => 'video/quicktime',
  433. 'mp4' => 'video/mp4',
  434. 'mpg' => 'video/mpeg',
  435. 'mpe' => 'video/mpeg',
  436. 'mpeg' => 'video/mpeg',
  437. 'wmv' => 'video/x-ms-wmv',
  438. '7z' => 'application/x-7z-compressed',
  439. 'bz2' => 'application/x-bzip2',
  440. 'cpio' => 'application/x-cpio',
  441. 'gz' => 'application/x-gzip',
  442. 'par2' => 'application/x-par2',
  443. 'par' => 'application/x-par2',
  444. 'rar' => 'application/x-rar-compressed',
  445. 'sit' => 'application/x-stuffit',
  446. 'sitx' => 'application/x-stuffitx',
  447. 'tar' => 'application/x-tar',
  448. 'tgz' => 'application/x-compressed',
  449. 'zip' => 'application/zip',
  450. 'zipx' => 'application/zip',
  451. 'xml' => 'text/xml',
  452. 'html' => 'text/html',
  453. 'htm' => 'text/html'
  454. );
  455. /**
  456. * Gets the extension's corresponding MIME-type
  457. * @param string $extension
  458. */
  459. public static function GetMime($extension)
  460. {
  461. return array_key_exists($extension, self::$MimeArray) ?
  462. self::$MimeArray[$extension] :
  463. 'application/octet-stream';
  464. }
  465. /**
  466. * Gets the MIME-type's corresponding extension
  467. * @param string $mimetype
  468. */
  469. public static function GetExtension($mimetype)
  470. {
  471. return in_array($mimetype, self::$MimeArray) ?
  472. array_search($mimetype, self::$MimeArray) :
  473. 'bin';
  474. }
  475. }
  476. ?>