]>
src.bluestatic.org Git - isso.git/blob - Functions.php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 Blue Static
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.
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
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 \*=====================================================================*/
23 * Static functions (Functions.php)
31 * This is a bunch of static functions. This class is singleton so it
32 * can store data while remaining static.
35 * @copyright Copyright (c)2005 - 2008, Blue Static
45 private static $instance;
51 private $cookiePath = '/';
54 * Cookie domain setting
57 private $cookieDomain = '';
60 * Cookie expiration time
63 private $cookieTimeout = 900;
66 * Current swapped CSS class
69 public static $cssClass = '';
71 // ###################################################################
75 private function __construct() {}
77 // ###################################################################
79 * Returns the shared instance for singleton
81 * @return object Shared instance
83 private function _instance()
87 self
::$instance = new BSFunctions();
89 return self
::$instance;
92 // ###################################################################
94 * Sets the cookie path
96 * @param string New path
98 public static function set_cookie_path($path)
100 self
::_instance()->cookiePath
= $path;
103 // ###################################################################
105 * Sets the cookie domain setting
107 * @param string Cookie domain
109 public static function set_cookie_domain($domain)
111 self
::_instance()->cookieDomain
= $domain;
114 // ###################################################################
116 * Sets the cookie timeout
118 * @param integer Cookie timeout
120 public static function set_cookie_timeout($timeout)
122 self
::_instance()->cookieTimeout
= intval($timeout);
125 // ###################################################################
127 * Sets a cookie in the user's computer/browing session
129 * @param string Name of the cookie
130 * @param string Value of the cookie, FALSE to clear
131 * @param bool Is the cookie permanent?
133 public static function cookie($name, $value, $sticky = true)
136 if ($value === false)
138 setcookie($name, $value, time() - (2 * self
::_instance()->cookieTimeout
), self
::_instance()->cookiePath
, self
::_instance()->cookieDomain
);
145 $expire = time() +
60 * 60 * 24 * 365;
149 $expire = time() + self
::_instance()->cookieTimeout
;
152 setcookie($name, $value, $expire, self
::_instance()->cookiePath
, self
::_instance()->cookieDomain
);
156 // ###################################################################
158 * Alternate between two CSS classes
160 * @param string First CSS class name
161 * @param string Second CSS class name
163 public function SwapCssClasses($class1 = 'alt1', $class2 = 'alt2')
167 self
::$cssClass = ($count %
2) ? $class1 : $class2;
171 // ###################################################################
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
179 * @return string Path with directory separator ending
181 public static function fetch_source_path($source)
183 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
185 $source .= DIRECTORY_SEPARATOR
;
190 // ###################################################################
192 * Force-download a file by sending application/octetstream
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
198 public static function download_file($file, $name, $exit = true)
200 if (self
::is_browser('ie') OR self
::is_browser('opera') OR self
::is_browser('safari'))
202 $mime = 'application/octetstream';
206 $mime = 'application/octet-stream';
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');
224 // ###################################################################
226 * Verify that an email address is valid via regex
228 * @param string An email address
230 * @return bool Validity of the email address
232 public static function is_valid_email($email)
234 if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
244 // ###################################################################
246 * Check a browser's user agent against a pre-determined list
248 * @param string Browser name
249 * @param string The browser's version
251 * @param mixed False if there is no match, the version if there is
253 public static function is_browser($check, $version = '')
255 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
259 // -------------------------------------------------------------------
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)
268 if (isset($matches[1]))
270 $browser['opera'] = $matches[1];
274 // -------------------------------------------------------------------
276 // -------------------------------------------------------------------
277 if (strpos($useragent, 'mac') !== false)
279 $browser['mac'] = true;
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 AND !isset($browser['opera']))
289 if (isset($matches[1]))
291 $browser['ie'] = $matches[1];
295 // -------------------------------------------------------------------
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)
301 if (isset($matches[1]))
303 $browser['safari'] = $matches[1];
307 // -------------------------------------------------------------------
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)
314 if (isset($matches[1]))
316 $browser['konqueror'] = $matches[1];
320 // -------------------------------------------------------------------
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 AND !isset($browser['safari']))
327 if (isset($matches[1]))
329 $browser['mozilla'] = $matches[1];
332 // -------------------------------------------------------------------
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)
339 if (isset($matches[3]))
341 $browser['firefox'] = $matches[3];
345 // -------------------------------------------------------------------
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)
351 if (isset($matches[2]))
353 $browser['netscape'] = $matches[2];
357 // -------------------------------------------------------------------
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)
363 if (isset($matches[1]))
365 $browser['camino'] = $matches[1];
370 if (isset($browser["$check"]))
374 if ($browser["$check"] >= $version)
376 return $browser["$check"];
385 return $browser["$check"];
394 // ###################################################################
396 * Generates a random string of random length (unless otherwise
399 * @param integer Optional length
401 * @return string A random string
403 public static function random($length = 0)
405 // custom high and lows
406 if (is_array($length))
408 $length = rand($length[0], $length[1]);
412 $length = rand(20, 65);
416 while (strlen($string) < $length)
418 $type = rand(0, 300);
421 $string .= rand(0, 9);
423 else if ($type < 200)
425 $string .= chr(rand(65, 90));
429 $string .= chr(rand(97, 122));
436 // ###################################################################
438 * Sets the current array position to be the specified key. This
439 * function should be avoided on large arrays.
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
444 * @return mixed Return the elelment of the array that we just put the counter to
446 public static function array_set_current(&$array, $key)
449 while (current($array) !== false)
451 if (key($array) == $key)
457 return current($array);
460 // ###################################################################
462 * Calculates the microtime difference by taking a given microtime and
463 * subtracting it from the current one
465 * @param string The start microtime
467 * @return float Microtime difference
469 public static function fetch_microtime_diff($mtstart)
471 $mtend = microtime();
472 list($startMicro, $startSec) = explode(' ', $mtstart);
473 list($endMicro, $endSec) = explode(' ', $mtend);
474 return ($endMicro + $endSec) - ($startMicro + $startSec);
477 // ###################################################################
479 * Fetches the extension of a file by extracting everything after the
482 * @param string Filename
484 * @return string The extension for the specifid file name
486 public static function fetch_extension($filename)
488 $array = explode('.', $filename);
490 if (sizeof($array) == 1)
495 return strval(end($array));
498 // ###################################################################
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
504 * @return integer The maximum file upload size in bytes
506 public static function fetch_max_php_file_size()
508 if ($size = @ini_get('upload_max_filesize'))
510 if (preg_match('#[^0-9].#', $size))
516 return intval($size) * 1048576;
525 // ###################################################################
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 "/"
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
534 * @return array A list of all the files in the specified path
536 public static function scan_directory($path, $recurse = true, $ignoreDot = true)
538 return self::_helpscan_directory($path, $recurse, $ignoreDot, '');
541 // ###################################################################
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 "/"
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
551 * @return array A list of all the files in the specified path
553 private static function _help_scan_directory($path, $recurse = true, $ignoreDot = true, $pathAdd = '')
556 $path = self::fetch_source_path($path);
558 $dir = new DirectoryIterator($path);
559 foreach ($dir AS $file)
561 $name = $file->getFilename();
562 if (($file->isDot() OR $name[0] == '.') AND $ignoreDot)
567 if ($file->isDir() AND $recurse)
569 $filelist = array_merge($filelist, self::_helpscan_directory($path . $name, $recurse, $ignoreDot, $pathAdd . BSFunctions::fetch_source_path(str_replace($path, '', $file->getPathname()))));
573 $filelist[] = $pathAdd . $name;
579 // ###################################################################
581 * Changes line breaks into one format
584 * @param string New line break (default is UNIX \n format)
586 * @return string Text with one type of line break
588 public static function convert_line_breaks($text, $convert_to = "\n
")
591 $text = str_replace(array("\r\n
", "\r
", "\n
"), "\n
", $text);
592 $text = str_replace("\n
", $convert_to, $text);
596 // ###################################################################
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.
601 * @param array An array to strip empties from
603 * @return array Full-valued array
605 public static function array_strip_empty($array)
607 foreach ($array AS $key => $value)
609 if (is_array($array["$key"]))
611 $array["$key"] = self::array_strip_empty($array["$key"]);
613 else if (empty($value) OR is_null($value))
615 unset($array["$key"]);
621 // ###################################################################
623 * A backtrace formatter.
625 * This is very slightly modified from PEAR/PHP_Compat (PHP license)
627 * @author Laurent Laville <pear@laurent-laville.org>
628 * @author Aidan Lister <aidan@php.net>
630 * @param array The backtrace from debug_backtrace() to format
632 * @return string Formatted output
634 public static function format_backtrace($backtrace)
636 // Unset call to debug_print_backtrace
637 array_shift($backtrace);
638 if (empty($backtrace))
645 foreach ($backtrace AS $i => $call)
647 if (!isset($call['file']))
649 $call['file'] = '(null)';
651 if (!isset($call['line']))
655 $location = $call['file'] . ':' . $call['line'];
656 $function = (isset($call['class'])) ? $call['class'] . (isset($call['type']) ? $call['type'] : '.') . $call['function'] : $call['function'];
659 if (isset($call['args']))
662 foreach ($call['args'] AS $arg)
668 elseif (is_object($arg))
670 $args[] = get_class($arg);
677 $params = implode(', ', $args);
680 $calls[] = sprintf('#%d %s(%s) called at [%s]', $i, $function, $params, $location);
683 return implode("\n
", $calls);
686 // ###################################################################
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.
692 * @param string The string
693 * @param integer Start position
694 * @param integer End position
696 * @return string Part of a string
698 public static function substring($string, $start, $end)
700 return substr($string, $start, $end - $start);