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