]>
src.bluestatic.org Git - isso.git/blob - Functions.php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright ©2002-[#]year[#] 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 [#]gpl[#] 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 ©2002 - [#]year[#], Blue Static
46 private static $instance;
52 private $cookiePath = '/';
55 * Cookie domain setting
58 private $cookieDomain = '';
61 * Cookie expiration time
64 private $cookieTimeout = 900;
67 * Current swapped CSS class
70 public static $cssClass = '';
72 // ###################################################################
76 private function __construct() {}
78 // ###################################################################
80 * Returns the shared instance for singleton
82 * @return object Shared instance
84 private function SharedInstance()
88 self
::$instance = new BSFunctions
;
90 return self
::$instance;
93 // ###################################################################
95 * Sets the cookie path
97 * @param string New path
99 public static function SetCookiePath($path)
101 self
::SharedInstance()->cookiePath
= $path;
104 // ###################################################################
106 * Sets the cookie domain setting
108 * @param string Cookie domain
110 public static function SetCookieDomain($domain)
112 self
::SharedInstance()->cookieDomain
= $domain;
115 // ###################################################################
117 * Sets the cookie timeout
119 * @param integer Cookie timeout
121 public static function SetCookieTimeout($timeout)
123 self
::SharedInstance()->cookieTimeout
= intval($timeout);
126 // ###################################################################
128 * Sets a cookie in the user's computer/browing session
130 * @param string Name of the cookie
131 * @param string Value of the cookie, FALSE to clear
132 * @param bool Is the cookie permanent?
134 public static function Cookie($name, $value, $sticky = true)
137 if ($value === false)
139 setcookie($name, $value, time() - (2 * self
::SharedInstance()->cookieTimeout
), self
::SharedInstance()->cookiePath
, self
::SharedInstance()->cookieDomain
);
146 $expire = time() +
60 * 60 * 24 * 365;
150 $expire = time() + self
::SharedInstance()->cookieTimeout
;
153 setcookie($name, $value, $expire, self
::SharedInstance()->cookiePath
, self
::SharedInstance()->cookieDomain
);
157 // ###################################################################
159 * Alternate between two CSS classes
161 * @param string First CSS class name
162 * @param string Second CSS class name
164 public function SwapCssClasses($class1 = 'alt1', $class2 = 'alt2')
168 self
::$cssClass = ($count %
2) ? $class1 : $class2;
172 // ###################################################################
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
180 * @return string Path with directory separator ending
182 public static function FetchSourcePath($source)
184 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR
)
186 $source .= DIRECTORY_SEPARATOR
;
191 // ###################################################################
193 * Force-download a file by sending application/octetstream
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
199 public static function DownloadFile($file, $name, $exit = true)
201 if (self
::IsBrowser('ie') OR self
::IsBrowser('opera') OR self
::IsBrowser('safari'))
203 $mime = 'application/octetstream';
207 $mime = 'application/octet-stream';
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');
225 // ###################################################################
227 * Verify that an email address is valid via regex
229 * @param string An email address
231 * @return bool Validity of the email address
233 public static function IsValidEmail($email)
235 if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
245 // ###################################################################
247 * Check a browser's user agent against a pre-determined list
249 * @param string Browser name
250 * @param string The browser's version
252 * @param mixed False if there is no match, the version if there is
254 public static function IsBrowser($check, $version = '')
256 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
260 // -------------------------------------------------------------------
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)
269 if (isset($matches[1]))
271 $browser['opera'] = $matches[1];
275 // -------------------------------------------------------------------
277 // -------------------------------------------------------------------
278 if (strpos($useragent, 'mac') !== false)
280 $browser['mac'] = true;
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']))
290 if (isset($matches[1]))
292 $browser['ie'] = $matches[1];
296 // -------------------------------------------------------------------
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)
302 if (isset($matches[1]))
304 $browser['safari'] = $matches[1];
308 // -------------------------------------------------------------------
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)
315 if (isset($matches[1]))
317 $browser['konqueror'] = $matches[1];
321 // -------------------------------------------------------------------
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']))
328 if (isset($matches[1]))
330 $browser['mozilla'] = $matches[1];
333 // -------------------------------------------------------------------
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)
340 if (isset($matches[3]))
342 $browser['firefox'] = $matches[3];
346 // -------------------------------------------------------------------
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)
352 if (isset($matches[2]))
354 $browser['netscape'] = $matches[2];
358 // -------------------------------------------------------------------
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)
364 if (isset($matches[1]))
366 $browser['camino'] = $matches[1];
371 if (isset($browser["$check"]))
375 if ($browser["$check"] >= $version)
377 return $browser["$check"];
386 return $browser["$check"];
395 // ###################################################################
397 * Generates a random string of random length (unless otherwise
400 * @param integer Optional length
402 * @return string A random string
404 public static function Random($length = 0)
406 // custom high and lows
407 if (is_array($length))
409 $length = rand($length[0], $length[1]);
414 $length = rand(20, 65);
417 // Number of ints in our salt
418 $intcount = rand(1, intval($length / 2));
421 $charcount = $length - $intcount;
424 $upperchars = rand(1, intval($charcount / 2));
427 $lowerchars = $charcount - $upperchars;
430 for ($i = 0; $i < $intcount; $i++)
432 $string[ mt_rand() ] = rand(0, 9);
435 // Generate upper chars
436 for ($i = 0; $i < $upperchars; $i++)
438 $string[ mt_rand() ] = chr(rand(65, 90));
441 // Generate lower chars
442 for ($i = 0; $i < $lowerchars; $i++)
444 $string[ mt_rand() ] = chr(rand(97, 122));
447 if ($length != sizeof($string))
449 return $this->rand($length);
452 // Sort the chars by thier random assignment
457 foreach ($string AS $char)
465 // ###################################################################
467 * Sets the current array position to be the specified key. This
468 * function should be avoided on large arrays.
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
473 * @return mixed Return the elelment of the array that we just put the counter to
475 public static function ArraySetCurrent(&$array, $key)
478 while (current($array) !== false)
480 if (key($array) == $key)
486 return current($array);
489 // ###################################################################
491 * Calculates the microtime difference by taking a given microtime and
492 * subtracting it from the current one
494 * @param string The start microtime
496 * @return float Microtime difference
498 public static function FetchMicrotimeDiff($mtstart)
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']);
506 // ###################################################################
508 * Fetches the extension of a file by extracting everything after the
511 * @param string Filename
513 * @return string The extension for the specifid file name
515 public static function FetchExtension($filename)
517 $array = explode('.', $filename);
519 if (sizeof($array) == 1)
524 return strval(end($array));
527 // ###################################################################
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
533 * @return integer The maximum file upload size in bytes
535 public static function FetchMaxPhpFileSize()
537 if ($size = @ini_get('upload_max_filesize'))
539 if (preg_match('#[^0-9].#', $size))
545 return intval($size) * 1048576;
554 // ###################################################################
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 "/"
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
563 * @return array A list of all the files in the specified path
565 public static function ScanDirectory($path, $recurse = true, $ignoreDot = true)
567 return self::_helpScanDirectory($path, $recurse, $ignoreDot, '');
570 // ###################################################################
572 * Scans a specified directory path and returns an array of all the
573 * items in that directory. Directories found by this are end in a "/"
575 * @param string Path to scan
576 * @param bool Whether or not to recursively scan the directories encountered
577 * @param bool Ignore files beginning with a dot
578 * @param string Add to the beginning of the path
580 * @return array A list of all the files in the specified path
582 private static function _helpScanDirectory($path, $recurse = true, $ignoreDot = true, $pathAdd = '')
585 $path = self::FetchSourcePath($path);
587 $dir = new DirectoryIterator($path);
588 foreach ($dir AS $file)
590 $name = $file->getFilename();
591 if (($file->isDot() OR $name[0] == '.') AND $ignoreDot)
596 if ($file->isDir() AND $recurse)
598 $filelist = array_merge($filelist, self::_helpScanDirectory($path . $name, $recurse, $ignoreDot, $pathAdd . BSFunctions::FetchSourcePath(str_replace($path, '', $file->getPathname()))));
602 $filelist[] = $pathAdd . $name;
608 // ###################################################################
610 * Changes line breaks into one format
613 * @param string New line break (default is UNIX \n format)
615 * @return string Text with one type of line break
617 public static function ConvertLineBreaks($text, $convert_to = "\n
")
620 $text = str_replace(array("\r\n
", "\r
", "\n
"), "\n
", $text);
621 $text = str_replace("\n
", $convert_to, $text);
625 // ###################################################################
627 * Removes all empty() [by PHP's standards] elements in an array. This
628 * can be used in place of using PREG_SPLIT_NO_EMPTY.
630 * @param array An array to strip empties from
632 * @return array Full-valued array
634 public static function ArrayStripEmpty($array)
636 foreach ($array AS $key => $value)
638 if (is_array($array["$key"]))
640 $array["$key"] = self::ArrayStripEmpty($array["$key"]);
642 else if (empty($value) OR is_null($value))
644 unset($array["$key"]);
650 // ###################################################################
652 * A backtrace formatter.
654 * This is very slightly modified from PEAR/PHP_Compat (PHP license)
656 * @author Laurent Laville <pear@laurent-laville.org>
657 * @author Aidan Lister <aidan@php.net>
659 * @param array The backtrace from debug_backtrace() to format
661 * @return string Formatted output
663 public static function FormatBacktrace($backtrace)
665 // Unset call to debug_print_backtrace
666 array_shift($backtrace);
667 if (empty($backtrace))
674 foreach ($backtrace AS $i => $call)
676 if (!isset($call['file']))
678 $call['file'] = '(null)';
680 if (!isset($call['line']))
684 $location = $call['file'] . ':' . $call['line'];
685 $function = (isset($call['class'])) ? $call['class'] . (isset($call['type']) ? $call['type'] : '.') . $call['function'] : $call['function'];
688 if (isset($call['args']))
691 foreach ($call['args'] AS $arg)
697 elseif (is_object($arg))
699 $args[] = get_class($arg);
706 $params = implode(', ', $args);
709 $calls[] = sprintf('#%d %s(%s) called at [%s]', $i, $function, $params, $location);
712 return implode("\n
", $calls);
716 /*=====================================================================*\
717 || ###################################################################
720 || ###################################################################
721 \*=====================================================================*/