Moving error handling stuff into Loader and Functions
[isso.git] / Functions.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework [#]issoversion[#]
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 SharedInstance()
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::SharedInstance()->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::SharedInstance()->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::SharedInstance()->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::SharedInstance()->cookieTimeout), self::SharedInstance()->cookiePath, self::SharedInstance()->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::SharedInstance()->cookieTimeout;
151 }
152
153 setcookie($name, $value, $expire, self::SharedInstance()->cookiePath, self::SharedInstance()->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 // Gimme a length!
414 $length = rand(20, 65);
415 }
416
417 // Number of ints in our salt
418 $intcount = rand(1, intval($length / 2));
419
420 // Number of chars
421 $charcount = $length - $intcount;
422
423 // Upper-case chars
424 $upperchars = rand(1, intval($charcount / 2));
425
426 // Lower-case chars
427 $lowerchars = $charcount - $upperchars;
428
429 // Generate ints
430 for ($i = 0; $i < $intcount; $i++)
431 {
432 $string[ mt_rand() ] = rand(0, 9);
433 }
434
435 // Generate upper chars
436 for ($i = 0; $i < $upperchars; $i++)
437 {
438 $string[ mt_rand() ] = chr(rand(65, 90));
439 }
440
441 // Generate lower chars
442 for ($i = 0; $i < $lowerchars; $i++)
443 {
444 $string[ mt_rand() ] = chr(rand(97, 122));
445 }
446
447 if ($length != sizeof($string))
448 {
449 return $this->rand($length);
450 }
451
452 // Sort the chars by thier random assignment
453 ksort($string);
454
455 // Flatten the array
456 $return = '';
457 foreach ($string AS $char)
458 {
459 $return .= $char;
460 }
461
462 return $return;
463 }
464
465 // ###################################################################
466 /**
467 * Sets the current array position to be the specified key. This
468 * function should be avoided on large arrays.
469 *
470 * @param array The array whose counter is to be updated
471 * @param mixed The key of the element of the array that the counter is to be set to
472 *
473 * @return mixed Return the elelment of the array that we just put the counter to
474 */
475 public static function ArraySetCurrent(&$array, $key)
476 {
477 reset($array);
478 while (current($array) !== false)
479 {
480 if (key($array) == $key)
481 {
482 break;
483 }
484 next($array);
485 }
486 return current($array);
487 }
488
489 // ###################################################################
490 /**
491 * Calculates the microtime difference by taking a given microtime and
492 * subtracting it from the current one
493 *
494 * @param string The start microtime
495 *
496 * @return float Microtime difference
497 */
498 public static function FetchMicrotimeDiff($mtstart)
499 {
500 $mtend = microtime();
501 list ($starttime['micro'], $starttime['sec']) = explode(' ', $mtstart);
502 list ($endtime['micro'], $endtime['sec']) = explode(' ', $mtend);
503 return ($endtime['micro'] + $endtime['sec']) - ($starttime['micro'] + $starttime['sec']);
504 }
505
506 // ###################################################################
507 /**
508 * Fetches the extension of a file by extracting everything after the
509 * last period
510 *
511 * @param string Filename
512 *
513 * @return string The extension for the specifid file name
514 */
515 public static function FetchExtension($filename)
516 {
517 $array = explode('.', $filename);
518
519 if (sizeof($array) == 1)
520 {
521 return '';
522 }
523
524 return strval(end($array));
525 }
526
527 // ###################################################################
528 /**
529 * Gets the maximum file size for attachment uploading, as specified by
530 * PHP. If no value is present, 10 MB (represented in bytes) is
531 * returned.
532 *
533 * @return integer The maximum file upload size in bytes
534 */
535 public static function FetchMaxPhpFileSize()
536 {
537 if ($size = @ini_get('upload_max_filesize'))
538 {
539 if (preg_match('#[^0-9].#', $size))
540 {
541 return $size;
542 }
543 else
544 {
545 return intval($size) * 1048576;
546 }
547 }
548 else
549 {
550 return 10 * 1048576;
551 }
552 }
553
554 // ###################################################################
555 /**
556 * Scans a specified directory path and returns an array of all the
557 * items in that directory. Directories found by this are end in a "/"
558 *
559 * @param string Path to scan
560 * @param bool Whether or not to recursively scan the directories encountered
561 * @param bool Ignore files beginning with a dot
562 * @param bool Ignore 'CVS' dirctories
563 *
564 * @return array A list of all the files in the specified path
565 */
566 public static function ScanDirectory($path, $recurse = true, $ignoredot = true, $ignorecvs = true, $basepath = '', $unset = 1)
567 {
568 static $filelist;
569
570 if ($unset)
571 {
572 $filelist = array();
573 }
574
575 if (substr($path, (strlen($path) - 1), 1) != '/')
576 {
577 $path .= '/';
578 }
579
580 if ($handle = opendir($path))
581 {
582 while (($file = readdir($handle)) !== false)
583 {
584 $isdot = ((substr($file, 0, 1) == '.') ? true : false);
585 $isdot = (($ignoredot) ? $isdot : true);
586 $iscvs = (($file == 'CVS') ? true : false);
587 $iscvs = (($ignorecvs) ? $iscvs : true);
588 if (!$isdot AND !$iscvs)
589 {
590 if (is_dir($path . $file))
591 {
592 $filelist["$basepath"][] = "$file/";
593 if ($recurse)
594 {
595 self::ScanDirectory("$path$file", true, $ignoredot, $ignorecvs, "$basepath$file/", 0);
596 }
597 }
598 else
599 {
600 $filelist["$basepath"][] = $file;
601 }
602 }
603 }
604 closedir($handle);
605 }
606 return $filelist;
607 }
608
609 // ###################################################################
610 /**
611 * Changes line breaks into one format
612 *
613 * @param string Text
614 * @param string New line break (default is UNIX \n format)
615 *
616 * @return string Text with one type of line break
617 */
618 public static function ConvertLineBreaks($text, $convert_to = "\n")
619 {
620 $text = trim($text);
621 $text = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
622 $text = str_replace("\n", $convert_to, $text);
623 return $text;
624 }
625
626 // ###################################################################
627 /**
628 * Removes all empty() [by PHP's standards] elements in an array. This
629 * can be used in place of using PREG_SPLIT_NO_EMPTY.
630 *
631 * @param array An array to strip empties from
632 *
633 * @return array Full-valued array
634 */
635 public static function ArrayStripEmpty($array)
636 {
637 foreach ($array AS $key => $value)
638 {
639 if (is_array($array["$key"]))
640 {
641 $array["$key"] = self::ArrayStripEmpty($array["$key"]);
642 }
643 else if (empty($value) OR is_null($value))
644 {
645 unset($array["$key"]);
646 }
647 }
648 return $array;
649 }
650
651 // ###################################################################
652 /**
653 * Prepares a debug_backtrace() array for output to the browser by
654 * compressing the array into visible text. This still has value because
655 * debug_print_backtrace() can't return data
656 *
657 * @param array debug_backtrace() array
658 *
659 * @return array Formatted trace output
660 */
661 public static function FormatDebugTrace($backtrace)
662 {
663 $trace = array();
664 foreach ($backtrace AS $i => $step)
665 {
666 $args = '';
667 $file = $step['file'] . ':' . $step['line'];
668 $funct = (isset($step['class']) ? $step['class'] . '::' . $step['function'] : $step['function']);
669
670 if (isset($step['args']) AND is_array($step['args']))
671 {
672 // we need to do this so we don't get "Array to string conversion" notices
673 foreach ($step['args'] AS $id => $arg)
674 {
675 if (is_array($arg))
676 {
677 $step['args']["$id"] = 'Array';
678 }
679 }
680 $args = implode(', ', $step['args']);
681 }
682
683 $trace[] = "#$i $funct($args) called at [$file]";
684 }
685
686 return $trace;
687 }
688 }
689
690 /*=====================================================================*\
691 || ###################################################################
692 || # $HeadURL$
693 || # $Id$
694 || ###################################################################
695 \*=====================================================================*/
696 ?>