Optimizing BSFunctions::Random() ever so slightly so we only need one loop instead...
[isso.git] / Functions.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright ©2002-[#]year[#] Blue Static
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version [#]gpl[#] of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Static functions (Functions.php)
24 *
25 * @package ISSO
26 */
27
28 /**
29 * Functions
30 *
31 * This is a bunch of static functions. This class is singleton so it
32 * can store data while remaining static.
33 *
34 * @author Blue Static
35 * @copyright Copyright ©2002 - [#]year[#], Blue Static
36 * @version $Revision$
37 * @package ISSO
38 *
39 */
40 class BSFunctions
41 {
42 /**
43 * Singleton instance
44 * @var object
45 */
46 private static $instance;
47
48 /**
49 * Cookie path
50 * @var string
51 */
52 private $cookiePath = '/';
53
54 /**
55 * Cookie domain setting
56 * @var string
57 */
58 private $cookieDomain = '';
59
60 /**
61 * Cookie expiration time
62 * @var integer
63 */
64 private $cookieTimeout = 900;
65
66 /**
67 * Current swapped CSS class
68 * @var string
69 */
70 public static $cssClass = '';
71
72 // ###################################################################
73 /**
74 * Constructor
75 */
76 private function __construct() {}
77
78 // ###################################################################
79 /**
80 * Returns the shared instance for singleton
81 *
82 * @return object Shared instance
83 */
84 private function _Instance()
85 {
86 if (!self::$instance)
87 {
88 self::$instance = new BSFunctions();
89 }
90 return self::$instance;
91 }
92
93 // ###################################################################
94 /**
95 * Sets the cookie path
96 *
97 * @param string New path
98 */
99 public static function SetCookiePath($path)
100 {
101 self::_Instance()->cookiePath = $path;
102 }
103
104 // ###################################################################
105 /**
106 * Sets the cookie domain setting
107 *
108 * @param string Cookie domain
109 */
110 public static function SetCookieDomain($domain)
111 {
112 self::_Instance()->cookieDomain = $domain;
113 }
114
115 // ###################################################################
116 /**
117 * Sets the cookie timeout
118 *
119 * @param integer Cookie timeout
120 */
121 public static function SetCookieTimeout($timeout)
122 {
123 self::_Instance()->cookieTimeout = intval($timeout);
124 }
125
126 // ###################################################################
127 /**
128 * Sets a cookie in the user's computer/browing session
129 *
130 * @param string Name of the cookie
131 * @param string Value of the cookie, FALSE to clear
132 * @param bool Is the cookie permanent?
133 */
134 public static function Cookie($name, $value, $sticky = true)
135 {
136 // expire the cookie
137 if ($value === false)
138 {
139 setcookie($name, $value, time() - (2 * self::_Instance()->cookieTimeout), self::_Instance()->cookiePath, self::_Instance()->cookieDomain);
140 }
141 // set the cookie
142 else
143 {
144 if ($sticky)
145 {
146 $expire = time() + 60 * 60 * 24 * 365;
147 }
148 else
149 {
150 $expire = time() + self::_Instance()->cookieTimeout;
151 }
152
153 setcookie($name, $value, $expire, self::_Instance()->cookiePath, self::_Instance()->cookieDomain);
154 }
155 }
156
157 // ###################################################################
158 /**
159 * Alternate between two CSS classes
160 *
161 * @param string First CSS class name
162 * @param string Second CSS class name
163 */
164 public function SwapCssClasses($class1 = 'alt1', $class2 = 'alt2')
165 {
166 static $count;
167
168 self::$cssClass = ($count % 2) ? $class1 : $class2;
169 $count++;
170 }
171
172 // ###################################################################
173 /**
174 * Returns the 'source path' version of a file path. It adds a
175 * directory separator to the end of a string if it does not already
176 * exist.
177 *
178 * @param string Path
179 *
180 * @return string Path with directory separator ending
181 */
182 public static function FetchSourcePath($source)
183 {
184 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
185 {
186 $source .= DIRECTORY_SEPARATOR;
187 }
188 return $source;
189 }
190
191 // ###################################################################
192 /**
193 * Force-download a file by sending application/octetstream
194 *
195 * @param string The text of the file to be streamed
196 * @param string File name of the new file
197 * @param bool Whether or not to die after stringeaming the file
198 */
199 public static function DownloadFile($file, $name, $exit = true)
200 {
201 if (self::IsBrowser('ie') OR self::IsBrowser('opera') OR self::IsBrowser('safari'))
202 {
203 $mime = 'application/octetstream';
204 }
205 else
206 {
207 $mime = 'application/octet-stream';
208 }
209
210 header("Content-Type: $mime");
211 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
212 header('Content-Disposition: attachment; filename="' . $name . '"');
213 header('Content-length: ' . strlen($file));
214 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
215 header('Pragma: public');
216
217 print($file);
218
219 if ($exit)
220 {
221 exit;
222 }
223 }
224
225 // ###################################################################
226 /**
227 * Verify that an email address is valid via regex
228 *
229 * @param string An email address
230 *
231 * @return bool Validity of the email address
232 */
233 public static function IsValidEmail($email)
234 {
235 if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
236 {
237 return true;
238 }
239 else
240 {
241 return false;
242 }
243 }
244
245 // ###################################################################
246 /**
247 * Check a browser's user agent against a pre-determined list
248 *
249 * @param string Browser name
250 * @param string The browser's version
251 *
252 * @param mixed False if there is no match, the version if there is
253 */
254 public static function IsBrowser($check, $version = '')
255 {
256 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
257 $browser = array();
258 $matches = array();
259
260 // -------------------------------------------------------------------
261 // -- Opera
262 // -------------------------------------------------------------------
263 # Opera/6.05 (Windows 98; U) [en]
264 # Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 6.0 [en]
265 # Mozilla/5.0 (Windows 98; U) Opera 6.0 [en]
266 # Mozilla/4.0 (compatible; MSIE, 6.0; Windows 98) Opera 7.0 [en]
267 if (preg_match('#opera ([0-9\.]+)#', $useragent, $matches) !== false)
268 {
269 if (isset($matches[1]))
270 {
271 $browser['opera'] = $matches[1];
272 }
273 }
274
275 // -------------------------------------------------------------------
276 // -- Mac browser
277 // -------------------------------------------------------------------
278 if (strpos($useragent, 'mac') !== false)
279 {
280 $browser['mac'] = true;
281 }
282
283 // -------------------------------------------------------------------
284 // -- Internet explorer
285 // -------------------------------------------------------------------
286 # Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1; .NET CLR 1.0.2914)
287 # Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
288 if (preg_match('#msie ([0-9\.]+)#', $useragent, $matches) !== false AND !isset($browser['opera']))
289 {
290 if (isset($matches[1]))
291 {
292 $browser['ie'] = $matches[1];
293 }
294 }
295
296 // -------------------------------------------------------------------
297 // -- Safari
298 // -------------------------------------------------------------------
299 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.4 (KHTML, like Gecko) Safari/125.9
300 if (preg_match('#safari/([0-9\.]+)#', $useragent, $matches) !== false)
301 {
302 if (isset($matches[1]))
303 {
304 $browser['safari'] = $matches[1];
305 }
306 }
307
308 // -------------------------------------------------------------------
309 // -- Konqueror
310 // -------------------------------------------------------------------
311 # Mozilla/5.0 (compatible; Konqueror/3)
312 # Mozilla/5.0 (compatible; Konqueror/3.1; i686 Linux; 20020628)
313 if (preg_match('#konqueror/([0-9\.]+)#', $useragent, $matches) !== false)
314 {
315 if (isset($matches[1]))
316 {
317 $browser['konqueror'] = $matches[1];
318 }
319 }
320
321 // -------------------------------------------------------------------
322 // -- Mozilla
323 // -------------------------------------------------------------------
324 # Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101
325 # Mozilla/5.001 (Macintosh; N; PPC; ja) Gecko/25250101 MegaCorpBrowser/1.0 (MegaCorp, Inc.)
326 if (preg_match('#gecko/([0-9]+)#', $useragent, $matches) !== false AND !isset($browser['safari']))
327 {
328 if (isset($matches[1]))
329 {
330 $browser['mozilla'] = $matches[1];
331 }
332
333 // -------------------------------------------------------------------
334 // -- Firefox
335 // -------------------------------------------------------------------
336 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040628 Firefox/0.9.1
337 # Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4a) Gecko/20030423 Firebird Browser/0.6
338 if (preg_match('#(firebird|firefox)( browser)?/([0-9\.]+)#', $useragent, $matches) !== false)
339 {
340 if (isset($matches[3]))
341 {
342 $browser['firefox'] = $matches[3];
343 }
344 }
345
346 // -------------------------------------------------------------------
347 // -- Netscape
348 // -------------------------------------------------------------------
349 # Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:0.9.4.1) Gecko/20020318 Netscape6/6.2.2
350 if (preg_match('#netscape([0-9].*?)?/([0-9\.]+)#', $useragent, $matches) !== false)
351 {
352 if (isset($matches[2]))
353 {
354 $browser['netscape'] = $matches[2];
355 }
356 }
357
358 // -------------------------------------------------------------------
359 // -- Camino
360 // -------------------------------------------------------------------
361 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040623 Camino/0.8
362 if (preg_match('#camino/([0-9\.]+)#', $useragent, $matches) !== false)
363 {
364 if (isset($matches[1]))
365 {
366 $browser['camino'] = $matches[1];
367 }
368 }
369 }
370
371 if (isset($browser["$check"]))
372 {
373 if ($version)
374 {
375 if ($browser["$check"] >= $version)
376 {
377 return $browser["$check"];
378 }
379 else
380 {
381 return false;
382 }
383 }
384 else
385 {
386 return $browser["$check"];
387 }
388 }
389 else
390 {
391 return false;
392 }
393 }
394
395 // ###################################################################
396 /**
397 * Generates a random string of random length (unless otherwise
398 * specified)
399 *
400 * @param integer Optional length
401 *
402 * @return string A random string
403 */
404 public static function Random($length = 0)
405 {
406 // custom high and lows
407 if (is_array($length))
408 {
409 $length = rand($length[0], $length[1]);
410 }
411 else if (!$length)
412 {
413 $length = rand(20, 65);
414 }
415
416 $string = '';
417 while (strlen($string) < $length)
418 {
419 $type = rand(0, 300);
420 if ($type < 100)
421 {
422 $string .= rand(0, 9);
423 }
424 else if ($type < 200)
425 {
426 $string .= chr(rand(65, 90));
427 }
428 else
429 {
430 $string .= chr(rand(97, 122));
431 }
432 }
433
434 return $string;
435 }
436
437 // ###################################################################
438 /**
439 * Sets the current array position to be the specified key. This
440 * function should be avoided on large arrays.
441 *
442 * @param array The array whose counter is to be updated
443 * @param mixed The key of the element of the array that the counter is to be set to
444 *
445 * @return mixed Return the elelment of the array that we just put the counter to
446 */
447 public static function ArraySetCurrent(&$array, $key)
448 {
449 reset($array);
450 while (current($array) !== false)
451 {
452 if (key($array) == $key)
453 {
454 break;
455 }
456 next($array);
457 }
458 return current($array);
459 }
460
461 // ###################################################################
462 /**
463 * Calculates the microtime difference by taking a given microtime and
464 * subtracting it from the current one
465 *
466 * @param string The start microtime
467 *
468 * @return float Microtime difference
469 */
470 public static function FetchMicrotimeDiff($mtstart)
471 {
472 $mtend = microtime();
473 list ($starttime['micro'], $starttime['sec']) = explode(' ', $mtstart);
474 list ($endtime['micro'], $endtime['sec']) = explode(' ', $mtend);
475 return ($endtime['micro'] + $endtime['sec']) - ($starttime['micro'] + $starttime['sec']);
476 }
477
478 // ###################################################################
479 /**
480 * Fetches the extension of a file by extracting everything after the
481 * last period
482 *
483 * @param string Filename
484 *
485 * @return string The extension for the specifid file name
486 */
487 public static function FetchExtension($filename)
488 {
489 $array = explode('.', $filename);
490
491 if (sizeof($array) == 1)
492 {
493 return '';
494 }
495
496 return strval(end($array));
497 }
498
499 // ###################################################################
500 /**
501 * Gets the maximum file size for attachment uploading, as specified by
502 * PHP. If no value is present, 10 MB (represented in bytes) is
503 * returned.
504 *
505 * @return integer The maximum file upload size in bytes
506 */
507 public static function FetchMaxPhpFileSize()
508 {
509 if ($size = @ini_get('upload_max_filesize'))
510 {
511 if (preg_match('#[^0-9].#', $size))
512 {
513 return $size;
514 }
515 else
516 {
517 return intval($size) * 1048576;
518 }
519 }
520 else
521 {
522 return 10 * 1048576;
523 }
524 }
525
526 // ###################################################################
527 /**
528 * Scans a specified directory path and returns an array of all the
529 * items in that directory. Directories found by this are end in a "/"
530 *
531 * @param string Path to scan
532 * @param bool Whether or not to recursively scan the directories encountered
533 * @param bool Ignore files beginning with a dot
534 *
535 * @return array A list of all the files in the specified path
536 */
537 public static function ScanDirectory($path, $recurse = true, $ignoreDot = true)
538 {
539 return self::_helpScanDirectory($path, $recurse, $ignoreDot, '');
540 }
541
542 // ###################################################################
543 /**
544 * Scans a specified directory path and returns an array of all the
545 * items in that directory. Directories found by this are end in a "/"
546 *
547 * @param string Path to scan
548 * @param bool Whether or not to recursively scan the directories encountered
549 * @param bool Ignore files beginning with a dot
550 * @param string Add to the beginning of the path
551 *
552 * @return array A list of all the files in the specified path
553 */
554 private static function _helpScanDirectory($path, $recurse = true, $ignoreDot = true, $pathAdd = '')
555 {
556 $filelist = array();
557 $path = self::FetchSourcePath($path);
558
559 $dir = new DirectoryIterator($path);
560 foreach ($dir AS $file)
561 {
562 $name = $file->getFilename();
563 if (($file->isDot() OR $name[0] == '.') AND $ignoreDot)
564 {
565 continue;
566 }
567
568 if ($file->isDir() AND $recurse)
569 {
570 $filelist = array_merge($filelist, self::_helpScanDirectory($path . $name, $recurse, $ignoreDot, $pathAdd . BSFunctions::FetchSourcePath(str_replace($path, '', $file->getPathname()))));
571 continue;
572 }
573
574 $filelist[] = $pathAdd . $name;
575 }
576
577 return $filelist;
578 }
579
580 // ###################################################################
581 /**
582 * Changes line breaks into one format
583 *
584 * @param string Text
585 * @param string New line break (default is UNIX \n format)
586 *
587 * @return string Text with one type of line break
588 */
589 public static function ConvertLineBreaks($text, $convert_to = "\n")
590 {
591 $text = trim($text);
592 $text = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
593 $text = str_replace("\n", $convert_to, $text);
594 return $text;
595 }
596
597 // ###################################################################
598 /**
599 * Removes all empty() [by PHP's standards] elements in an array. This
600 * can be used in place of using PREG_SPLIT_NO_EMPTY.
601 *
602 * @param array An array to strip empties from
603 *
604 * @return array Full-valued array
605 */
606 public static function ArrayStripEmpty($array)
607 {
608 foreach ($array AS $key => $value)
609 {
610 if (is_array($array["$key"]))
611 {
612 $array["$key"] = self::ArrayStripEmpty($array["$key"]);
613 }
614 else if (empty($value) OR is_null($value))
615 {
616 unset($array["$key"]);
617 }
618 }
619 return $array;
620 }
621
622 // ###################################################################
623 /**
624 * A backtrace formatter.
625 *
626 * This is very slightly modified from PEAR/PHP_Compat (PHP license)
627 *
628 * @author Laurent Laville <pear@laurent-laville.org>
629 * @author Aidan Lister <aidan@php.net>
630 *
631 * @param array The backtrace from debug_backtrace() to format
632 *
633 * @return string Formatted output
634 */
635 public static function FormatBacktrace($backtrace)
636 {
637 // Unset call to debug_print_backtrace
638 array_shift($backtrace);
639 if (empty($backtrace))
640 {
641 return '';
642 }
643
644 // Iterate backtrace
645 $calls = array();
646 foreach ($backtrace AS $i => $call)
647 {
648 if (!isset($call['file']))
649 {
650 $call['file'] = '(null)';
651 }
652 if (!isset($call['line']))
653 {
654 $call['line'] = '0';
655 }
656 $location = $call['file'] . ':' . $call['line'];
657 $function = (isset($call['class'])) ? $call['class'] . (isset($call['type']) ? $call['type'] : '.') . $call['function'] : $call['function'];
658
659 $params = '';
660 if (isset($call['args']))
661 {
662 $args = array();
663 foreach ($call['args'] AS $arg)
664 {
665 if (is_array($arg))
666 {
667 $args[] = 'Array';
668 }
669 elseif (is_object($arg))
670 {
671 $args[] = get_class($arg);
672 }
673 else
674 {
675 $args[] = $arg;
676 }
677 }
678 $params = implode(', ', $args);
679 }
680
681 $calls[] = sprintf('#%d %s(%s) called at [%s]', $i, $function, $params, $location);
682 }
683
684 return implode("\n", $calls);
685 }
686
687 // ###################################################################
688 /**
689 * A variation of PHP's substr() method that takes in the start
690 * and end position of a string, rather than a start and length. This
691 * mimics Java's String.substring() method.
692 *
693 * @param string The string
694 * @param integer Start position
695 * @param integer End position
696 *
697 * @return string Part of a string
698 */
699 public static function Substring($string, $start, $end)
700 {
701 return substr($string, $start, $end - $start);
702 }
703 }
704
705 /*=====================================================================*\
706 || ###################################################################
707 || # $HeadURL$
708 || # $Id$
709 || ###################################################################
710 \*=====================================================================*/
711 ?>