Same change as the last commit
[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 /**
81 * Returns the shared instance for singleton
82 *
83 * @return object Shared instance
84 */
85 private function SharedInstance()
86 {
87 if (!self::$instance)
88 {
89 self::$instance = new BSFunctions;
90 }
91 return self::$instance;
92 }
93
94 // ###################################################################
95 /**
96 * Sets the cookie path
97 *
98 * @param string New path
99 */
100 public static function SetCookiePath($path)
101 {
102 self::SharedInstance()->cookiePath = $path;
103 }
104
105 // ###################################################################
106 /**
107 * Sets the cookie domain setting
108 *
109 * @param string Cookie domain
110 */
111 public static function SetCookieDomain($domain)
112 {
113 self::SharedInstance()->cookieDomain = $domain;
114 }
115
116 // ###################################################################
117 /**
118 * Sets the cookie timeout
119 *
120 * @param integer Cookie timeout
121 */
122 public static function SetCookieTimeout($timeout)
123 {
124 self::SharedInstance()->cookieTimeout = intval($timeout);
125 }
126
127 // ###################################################################
128 /**
129 * Sets a cookie in the user's computer/browing session
130 *
131 * @param string Name of the cookie
132 * @param string Value of the cookie, FALSE to clear
133 * @param bool Is the cookie permanent?
134 */
135 public static function Cookie($name, $value, $sticky = true)
136 {
137 // expire the cookie
138 if ($value === false)
139 {
140 setcookie($name, $value, time() - (2 * self::SharedInstance()->cookieTimeout), self::SharedInstance()->cookiePath, self::SharedInstance()->cookieDomain);
141 }
142 // set the cookie
143 else
144 {
145 if ($sticky)
146 {
147 $expire = time() + 60 * 60 * 24 * 365;
148 }
149 else
150 {
151 $expire = time() + self::SharedInstance()->cookieTimeout;
152 }
153
154 setcookie($name, $value, $expire, self::SharedInstance()->cookiePath, self::SharedInstance()->cookieDomain);
155 }
156 }
157
158 // ###################################################################
159 /**
160 * Alternate between two CSS classes
161 *
162 * @param string First CSS class name
163 * @param string Second CSS class name
164 */
165 public function SwapCssClasses($class1 = 'alt1', $class2 = 'alt2')
166 {
167 static $count;
168
169 self::$cssClass = ($count % 2) ? $class1 : $class2;
170 $count++;
171 }
172
173 // ###################################################################
174 /**
175 * Returns the 'source path' version of a file path. It adds a
176 * directory separator to the end of a string if it does not already
177 * exist.
178 *
179 * @param string Path
180 *
181 * @return string Path with directory separator ending
182 */
183 public static function FetchSourcePath($source)
184 {
185 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
186 {
187 $source .= DIRECTORY_SEPARATOR;
188 }
189 return $source;
190 }
191
192 // ###################################################################
193 /**
194 * Force-download a file by sending application/octetstream
195 *
196 * @param string The text of the file to be streamed
197 * @param string File name of the new file
198 * @param bool Whether or not to die after stringeaming the file
199 */
200 public static function DownloadFile($file, $name, $exit = true)
201 {
202 if (self::IsBrowser('ie') OR self::IsBrowser('opera') OR self::IsBrowser('safari'))
203 {
204 $mime = 'application/octetstream';
205 }
206 else
207 {
208 $mime = 'application/octet-stream';
209 }
210
211 header("Content-Type: $mime");
212 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
213 header('Content-Disposition: attachment; filename="' . $name . '"');
214 header('Content-length: ' . strlen($file));
215 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
216 header('Pragma: public');
217
218 print($file);
219
220 if ($exit)
221 {
222 exit;
223 }
224 }
225
226 // ###################################################################
227 /**
228 * Verify that an email address is valid via regex
229 *
230 * @param string An email address
231 *
232 * @return bool Validity of the email address
233 */
234 public static function IsValidEmail($email)
235 {
236 if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
237 {
238 return true;
239 }
240 else
241 {
242 return false;
243 }
244 }
245
246 // ###################################################################
247 /**
248 * Check a browser's user agent against a pre-determined list
249 *
250 * @param string Browser name
251 * @param string The browser's version
252 *
253 * @param mixed False if there is no match, the version if there is
254 */
255 public static function IsBrowser($check, $version = '')
256 {
257 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
258 $browser = array();
259 $matches = array();
260
261 // -------------------------------------------------------------------
262 // -- Opera
263 // -------------------------------------------------------------------
264 # Opera/6.05 (Windows 98; U) [en]
265 # Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 6.0 [en]
266 # Mozilla/5.0 (Windows 98; U) Opera 6.0 [en]
267 # Mozilla/4.0 (compatible; MSIE, 6.0; Windows 98) Opera 7.0 [en]
268 if (preg_match('#opera ([0-9\.]+)#', $useragent, $matches) !== false)
269 {
270 if (isset($matches[1]))
271 {
272 $browser['opera'] = $matches[1];
273 }
274 }
275
276 // -------------------------------------------------------------------
277 // -- Mac browser
278 // -------------------------------------------------------------------
279 if (strpos($useragent, 'mac') !== false)
280 {
281 $browser['mac'] = true;
282 }
283
284 // -------------------------------------------------------------------
285 // -- Internet explorer
286 // -------------------------------------------------------------------
287 # Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1; .NET CLR 1.0.2914)
288 # Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
289 if (preg_match('#msie ([0-9\.]+)#', $useragent, $matches) !== false AND !isset($browser['opera']))
290 {
291 if (isset($matches[1]))
292 {
293 $browser['ie'] = $matches[1];
294 }
295 }
296
297 // -------------------------------------------------------------------
298 // -- Safari
299 // -------------------------------------------------------------------
300 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.4 (KHTML, like Gecko) Safari/125.9
301 if (preg_match('#safari/([0-9\.]+)#', $useragent, $matches) !== false)
302 {
303 if (isset($matches[1]))
304 {
305 $browser['safari'] = $matches[1];
306 }
307 }
308
309 // -------------------------------------------------------------------
310 // -- Konqueror
311 // -------------------------------------------------------------------
312 # Mozilla/5.0 (compatible; Konqueror/3)
313 # Mozilla/5.0 (compatible; Konqueror/3.1; i686 Linux; 20020628)
314 if (preg_match('#konqueror/([0-9\.]+)#', $useragent, $matches) !== false)
315 {
316 if (isset($matches[1]))
317 {
318 $browser['konqueror'] = $matches[1];
319 }
320 }
321
322 // -------------------------------------------------------------------
323 // -- Mozilla
324 // -------------------------------------------------------------------
325 # Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101
326 # Mozilla/5.001 (Macintosh; N; PPC; ja) Gecko/25250101 MegaCorpBrowser/1.0 (MegaCorp, Inc.)
327 if (preg_match('#gecko/([0-9]+)#', $useragent, $matches) !== false AND !isset($browser['safari']))
328 {
329 if (isset($matches[1]))
330 {
331 $browser['mozilla'] = $matches[1];
332 }
333
334 // -------------------------------------------------------------------
335 // -- Firefox
336 // -------------------------------------------------------------------
337 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040628 Firefox/0.9.1
338 # Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4a) Gecko/20030423 Firebird Browser/0.6
339 if (preg_match('#(firebird|firefox)( browser)?/([0-9\.]+)#', $useragent, $matches) !== false)
340 {
341 if (isset($matches[3]))
342 {
343 $browser['firefox'] = $matches[3];
344 }
345 }
346
347 // -------------------------------------------------------------------
348 // -- Netscape
349 // -------------------------------------------------------------------
350 # Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:0.9.4.1) Gecko/20020318 Netscape6/6.2.2
351 if (preg_match('#netscape([0-9].*?)?/([0-9\.]+)#', $useragent, $matches) !== false)
352 {
353 if (isset($matches[2]))
354 {
355 $browser['netscape'] = $matches[2];
356 }
357 }
358
359 // -------------------------------------------------------------------
360 // -- Camino
361 // -------------------------------------------------------------------
362 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040623 Camino/0.8
363 if (preg_match('#camino/([0-9\.]+)#', $useragent, $matches) !== false)
364 {
365 if (isset($matches[1]))
366 {
367 $browser['camino'] = $matches[1];
368 }
369 }
370 }
371
372 if (isset($browser["$check"]))
373 {
374 if ($version)
375 {
376 if ($browser["$check"] >= $version)
377 {
378 return $browser["$check"];
379 }
380 else
381 {
382 return false;
383 }
384 }
385 else
386 {
387 return $browser["$check"];
388 }
389 }
390 else
391 {
392 return false;
393 }
394 }
395
396 // ###################################################################
397 /**
398 * Generates a random string of random length (unless otherwise
399 * specified)
400 *
401 * @param integer Optional length
402 *
403 * @return string A random string
404 */
405 public static function Random($length = 0)
406 {
407 // custom high and lows
408 if (is_array($length))
409 {
410 $length = rand($length[0], $length[1]);
411 }
412 else if (!$length)
413 {
414 // Gimme a length!
415 $length = rand(20, 65);
416 }
417
418 // Number of ints in our salt
419 $intcount = rand(1, intval($length / 2));
420
421 // Number of chars
422 $charcount = $length - $intcount;
423
424 // Upper-case chars
425 $upperchars = rand(1, intval($charcount / 2));
426
427 // Lower-case chars
428 $lowerchars = $charcount - $upperchars;
429
430 // Generate ints
431 for ($i = 0; $i < $intcount; $i++)
432 {
433 $string[ mt_rand() ] = rand(0, 9);
434 }
435
436 // Generate upper chars
437 for ($i = 0; $i < $upperchars; $i++)
438 {
439 $string[ mt_rand() ] = chr(rand(65, 90));
440 }
441
442 // Generate lower chars
443 for ($i = 0; $i < $lowerchars; $i++)
444 {
445 $string[ mt_rand() ] = chr(rand(97, 122));
446 }
447
448 if ($length != sizeof($string))
449 {
450 return $this->rand($length);
451 }
452
453 // Sort the chars by thier random assignment
454 ksort($string);
455
456 // Flatten the array
457 $return = '';
458 foreach ($string AS $char)
459 {
460 $return .= $char;
461 }
462
463 return $return;
464 }
465
466 // ###################################################################
467 /**
468 * Sets the current array position to be the specified key. This
469 * function should be avoided on large arrays.
470 *
471 * @param array The array whose counter is to be updated
472 * @param mixed The key of the element of the array that the counter is to be set to
473 *
474 * @return mixed Return the elelment of the array that we just put the counter to
475 */
476 public static function ArraySetCurrent(&$array, $key)
477 {
478 reset($array);
479 while (current($array) !== false)
480 {
481 if (key($array) == $key)
482 {
483 break;
484 }
485 next($array);
486 }
487 return current($array);
488 }
489
490 // ###################################################################
491 /**
492 * Calculates the microtime difference by taking a given microtime and
493 * subtracting it from the current one
494 *
495 * @param string The start microtime
496 *
497 * @return float Microtime difference
498 */
499 public static function FetchMicrotimeDiff($mtstart)
500 {
501 $mtend = microtime();
502 list ($starttime['micro'], $starttime['sec']) = explode(' ', $mtstart);
503 list ($endtime['micro'], $endtime['sec']) = explode(' ', $mtend);
504 return ($endtime['micro'] + $endtime['sec']) - ($starttime['micro'] + $starttime['sec']);
505 }
506
507 // ###################################################################
508 /**
509 * Fetches the extension of a file by extracting everything after the
510 * last period
511 *
512 * @param string Filename
513 *
514 * @return string The extension for the specifid file name
515 */
516 public static function FetchExtension($filename)
517 {
518 $array = explode('.', $filename);
519
520 if (sizeof($array) == 1)
521 {
522 return '';
523 }
524
525 return strval(end($array));
526 }
527
528 // ###################################################################
529 /**
530 * Gets the maximum file size for attachment uploading, as specified by
531 * PHP. If no value is present, 10 MB (represented in bytes) is
532 * returned.
533 *
534 * @return integer The maximum file upload size in bytes
535 */
536 public static function FetchMaxPhpFileSize()
537 {
538 if ($size = @ini_get('upload_max_filesize'))
539 {
540 if (preg_match('#[^0-9].#', $size))
541 {
542 return $size;
543 }
544 else
545 {
546 return intval($size) * 1048576;
547 }
548 }
549 else
550 {
551 return 10 * 1048576;
552 }
553 }
554
555 // ###################################################################
556 /**
557 * Scans a specified directory path and returns an array of all the
558 * items in that directory. Directories found by this are end in a "/"
559 *
560 * @param string Path to scan
561 * @param bool Whether or not to recursively scan the directories encountered
562 * @param bool Ignore files beginning with a dot
563 * @param bool Ignore 'CVS' dirctories
564 *
565 * @return array A list of all the files in the specified path
566 */
567 public static function ScanDirectory($path, $recurse = true, $ignoredot = true, $ignorecvs = true, $basepath = '', $unset = 1)
568 {
569 static $filelist;
570
571 if ($unset)
572 {
573 $filelist = array();
574 }
575
576 if (substr($path, (strlen($path) - 1), 1) != '/')
577 {
578 $path .= '/';
579 }
580
581 if ($handle = opendir($path))
582 {
583 while (($file = readdir($handle)) !== false)
584 {
585 $isdot = ((substr($file, 0, 1) == '.') ? true : false);
586 $isdot = (($ignoredot) ? $isdot : true);
587 $iscvs = (($file == 'CVS') ? true : false);
588 $iscvs = (($ignorecvs) ? $iscvs : true);
589 if (!$isdot AND !$iscvs)
590 {
591 if (is_dir($path . $file))
592 {
593 $filelist["$basepath"][] = "$file/";
594 if ($recurse)
595 {
596 self::ScanDirectory("$path$file", true, $ignoredot, $ignorecvs, "$basepath$file/", 0);
597 }
598 }
599 else
600 {
601 $filelist["$basepath"][] = $file;
602 }
603 }
604 }
605 closedir($handle);
606 }
607 return $filelist;
608 }
609
610 // ###################################################################
611 /**
612 * Changes line breaks into one format
613 *
614 * @param string Text
615 * @param string New line break (default is UNIX \n format)
616 *
617 * @return string Text with one type of line break
618 */
619 public static function ConvertLineBreaks($text, $convert_to = "\n")
620 {
621 $text = trim($text);
622 $text = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
623 $text = str_replace("\n", $convert_to, $text);
624 return $text;
625 }
626
627 // ###################################################################
628 /**
629 * Removes all empty() [by PHP's standards] elements in an array. This
630 * can be used in place of using PREG_SPLIT_NO_EMPTY.
631 *
632 * @param array An array to strip empties from
633 *
634 * @return array Full-valued array
635 */
636 public static function ArrayStripEmpty($array)
637 {
638 foreach ($array AS $key => $value)
639 {
640 if (is_array($array["$key"]))
641 {
642 $array["$key"] = self::ArrayStripEmpty($array["$key"]);
643 }
644 else if (empty($value) OR is_null($value))
645 {
646 unset($array["$key"]);
647 }
648 }
649 return $array;
650 }
651 }
652
653 /*=====================================================================*\
654 || ###################################################################
655 || # $HeadURL$
656 || # $Id$
657 || ###################################################################
658 \*=====================================================================*/
659 ?>