Switch to actual public/private/protected indicators instead of @access ones
[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 * Globalized Functions
24 * functions.php
25 *
26 * @package ISSO
27 */
28
29 /**
30 * Globalized Functions
31 *
32 * This framework is a set of functions that are commonly used in most
33 * applications.
34 *
35 * @author Blue Static
36 * @copyright Copyright ©2002 - [#]year[#], Blue Static
37 * @version $Revision$
38 * @package ISSO
39 *
40 */
41 class Functions
42 {
43 /**
44 * Framework registry object
45 * @var object
46 */
47 private $registry = null;
48
49 /**
50 * The path that is used to set cookies
51 * @var string
52 */
53 private $cookiepath = '/';
54
55 /**
56 * The domain used for cookie setting
57 * @var string
58 */
59 private $cookiedom = '';
60
61 /**
62 * The time it takes for a cookie to expire
63 * @var integer
64 */
65 private $cookieexp = 900;
66
67 /**
68 * State of the current background colour during alternation
69 * @var string
70 */
71 public $bgcolour = '';
72
73 /**
74 * Fields array that is used in this module
75 * @var array
76 */
77 private $fields = array(
78 'cookiepath' => array(REQ_YES, null, true),
79 'cookiedom' => array(REQ_YES, null, true),
80 'cookieexp' => array(REQ_YES, null, true)
81 );
82
83 // ###################################################################
84 /**
85 * Constructor
86 */
87 function __construct(&$registry)
88 {
89 $this->registry =& $registry;
90 }
91
92 // ###################################################################
93 /**
94 * (PHP 4) Constructor
95 */
96 function Functions(&$registry)
97 {
98 $this->__construct($registry);
99 }
100
101 // ###################################################################
102 /**
103 * Sets an ISSO field
104 *
105 * @access public
106 *
107 * @param string Field name
108 * @param mixed Value of the field
109 */
110 function set($name, $value)
111 {
112 $this->registry->do_set($name, $value, 'functions');
113 }
114
115 // ###################################################################
116 /**
117 * Gets an ISSO field
118 *
119 * @access public
120 *
121 * @param string Field name
122 *
123 * @return mixed Value of the field
124 */
125 function get($fieldname)
126 {
127 return $this->registry->do_get($fieldname, 'functions');
128 }
129
130 // ###################################################################
131 /**
132 * Sets a cookie with a friendly interface
133 *
134 * @access public
135 *
136 * @param string The name of the cookie
137 * @param string Value of the cookie
138 * @param bool Is the cookie permanent?
139 */
140 function cookie($name, $value = '', $sticky = true)
141 {
142 $this->registry->check_isso_fields(get_class($this));
143
144 // expire the cookie
145 if (!$value)
146 {
147 setcookie($name, $value, time() - (2 * $this->cookieexp), $this->cookiepath, $this->cookiedom);
148 }
149 // set the cookie
150 else
151 {
152 if ($sticky)
153 {
154 $expire = time() + 60 * 60 * 24 * 365;
155 }
156 else
157 {
158 $expire = time() + $this->cookieexp;
159 }
160
161 setcookie($name, $value, $expire, $this->cookiepath, $this->cookiedom);
162 }
163 }
164
165 // ###################################################################
166 /**
167 * Alternate between two background colours
168 *
169 * @access public
170 *
171 * @param string First CSS class name
172 * @param string Second CSS class name
173 */
174 function exec_swap_bg($class1 = 'alt1', $class2 = 'alt2')
175 {
176 static $count;
177
178 $this->bgcolour = ($count % 2) ? $class1 : $class2;
179 $count++;
180 }
181
182 // ###################################################################
183 /**
184 * Force-download a file by sending application/octetstream
185 *
186 * @access public
187 *
188 * @param string The text of the file to be streamed
189 * @param string File name of the new file
190 * @param bool Whether or not to die after stringeaming the file
191 */
192 function download_file($file, $name, $exit = true)
193 {
194 if ($this->is_browser('ie') OR $this->is_browser('opera') OR $this->is_browser('safari'))
195 {
196 $mime = 'application/octetstream';
197 }
198 else
199 {
200 $mime = 'application/octet-stream';
201 }
202
203 header("Content-Type: $mime");
204 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
205 header('Content-Disposition: attachment; filename="' . $name . '"');
206 header('Content-length: ' . strlen($file));
207 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
208 header('Pragma: public');
209
210 print($file);
211
212 if ($exit)
213 {
214 exit;
215 }
216 }
217
218 // ###################################################################
219 /**
220 * Verify that an email address is valid via regex
221 *
222 * @access public
223 *
224 * @param string An email address
225 *
226 * @return bool Validity of the email address
227 */
228 function is_valid_email($email)
229 {
230 if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
231 {
232 return true;
233 }
234 else
235 {
236 return false;
237 }
238 }
239
240 // ###################################################################
241 /**
242 * Check a browser's user agent against a pre-determined list
243 *
244 * @access public
245 *
246 * @param string Browser name
247 * @param string The browser's version
248 *
249 * @param mixed False if there is no match, the version if there is
250 */
251 function is_browser($check, $version = '')
252 {
253 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
254 $browser = array();
255 $matches = array();
256
257 // -------------------------------------------------------------------
258 // -- Opera
259 // -------------------------------------------------------------------
260 # Opera/6.05 (Windows 98; U) [en]
261 # Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 6.0 [en]
262 # Mozilla/5.0 (Windows 98; U) Opera 6.0 [en]
263 # Mozilla/4.0 (compatible; MSIE, 6.0; Windows 98) Opera 7.0 [en]
264 if (preg_match('#opera ([0-9\.]+)#', $useragent, $matches) !== false)
265 {
266 if (isset($matches[1]))
267 {
268 $browser['opera'] = $matches[1];
269 }
270 }
271
272 // -------------------------------------------------------------------
273 // -- Mac browser
274 // -------------------------------------------------------------------
275 if (strpos($useragent, 'mac') !== false)
276 {
277 $browser['mac'] = true;
278 }
279
280 // -------------------------------------------------------------------
281 // -- Internet explorer
282 // -------------------------------------------------------------------
283 # Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1; .NET CLR 1.0.2914)
284 # Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
285 if (preg_match('#msie ([0-9\.]+)#', $useragent, $matches) !== false AND !isset($browser['opera']))
286 {
287 if (isset($matches[1]))
288 {
289 $browser['ie'] = $matches[1];
290 }
291 }
292
293 // -------------------------------------------------------------------
294 // -- Safari
295 // -------------------------------------------------------------------
296 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.4 (KHTML, like Gecko) Safari/125.9
297 if (preg_match('#safari/([0-9\.]+)#', $useragent, $matches) !== false)
298 {
299 if (isset($matches[1]))
300 {
301 $browser['safari'] = $matches[1];
302 }
303 }
304
305 // -------------------------------------------------------------------
306 // -- Konqueror
307 // -------------------------------------------------------------------
308 # Mozilla/5.0 (compatible; Konqueror/3)
309 # Mozilla/5.0 (compatible; Konqueror/3.1; i686 Linux; 20020628)
310 if (preg_match('#konqueror/([0-9\.]+)#', $useragent, $matches) !== false)
311 {
312 if (isset($matches[1]))
313 {
314 $browser['konqueror'] = $matches[1];
315 }
316 }
317
318 // -------------------------------------------------------------------
319 // -- Mozilla
320 // -------------------------------------------------------------------
321 # Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101
322 # Mozilla/5.001 (Macintosh; N; PPC; ja) Gecko/25250101 MegaCorpBrowser/1.0 (MegaCorp, Inc.)
323 if (preg_match('#gecko/([0-9]+)#', $useragent, $matches) !== false AND !isset($browser['safari']))
324 {
325 if (isset($matches[1]))
326 {
327 $browser['mozilla'] = $matches[1];
328 }
329
330 // -------------------------------------------------------------------
331 // -- Firefox
332 // -------------------------------------------------------------------
333 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040628 Firefox/0.9.1
334 # Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4a) Gecko/20030423 Firebird Browser/0.6
335 if (preg_match('#(firebird|firefox)( browser)?/([0-9\.]+)#', $useragent, $matches) !== false)
336 {
337 if (isset($matches[3]))
338 {
339 $browser['firefox'] = $matches[3];
340 }
341 }
342
343 // -------------------------------------------------------------------
344 // -- Netscape
345 // -------------------------------------------------------------------
346 # Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:0.9.4.1) Gecko/20020318 Netscape6/6.2.2
347 if (preg_match('#netscape([0-9].*?)?/([0-9\.]+)#', $useragent, $matches) !== false)
348 {
349 if (isset($matches[2]))
350 {
351 $browser['netscape'] = $matches[2];
352 }
353 }
354
355 // -------------------------------------------------------------------
356 // -- Camino
357 // -------------------------------------------------------------------
358 # Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040623 Camino/0.8
359 if (preg_match('#camino/([0-9\.]+)#', $useragent, $matches) !== false)
360 {
361 if (isset($matches[1]))
362 {
363 $browser['camino'] = $matches[1];
364 }
365 }
366 }
367
368 if (isset($browser["$check"]))
369 {
370 if ($version)
371 {
372 if ($browser["$check"] >= $version)
373 {
374 return $browser["$check"];
375 }
376 else
377 {
378 return false;
379 }
380 }
381 else
382 {
383 return $browser["$check"];
384 }
385 }
386 else
387 {
388 return false;
389 }
390 }
391
392 // ###################################################################
393 /**
394 * Generates a random string of random length (unless otherwise
395 * specified)
396 *
397 * @access public
398 *
399 * @param integer Optional length
400 *
401 * @return string A random string
402 */
403 function rand($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 // Gimme a length!
413 $length = rand(20, 65);
414 }
415
416 // Number of ints in our salt
417 $intcount = rand(1, intval($length / 2));
418
419 // Number of chars
420 $charcount = $length - $intcount;
421
422 // Upper-case chars
423 $upperchars = rand(1, intval($charcount / 2));
424
425 // Lower-case chars
426 $lowerchars = $charcount - $upperchars;
427
428 // Generate ints
429 for ($i = 0; $i < $intcount; $i++)
430 {
431 $string[ mt_rand() ] = rand(0, 9);
432 }
433
434 // Generate upper chars
435 for ($i = 0; $i < $upperchars; $i++)
436 {
437 $string[ mt_rand() ] = chr(rand(65, 90));
438 }
439
440 // Generate lower chars
441 for ($i = 0; $i < $lowerchars; $i++)
442 {
443 $string[ mt_rand() ] = chr(rand(97, 122));
444 }
445
446 if ($length != sizeof($string))
447 {
448 return $this->rand($length);
449 }
450
451 // Sort the chars by thier random assignment
452 ksort($string);
453
454 // Flatten the array
455 $return = '';
456 foreach ($string AS $char)
457 {
458 $return .= $char;
459 }
460
461 return $return;
462 }
463
464 // ###################################################################
465 /**
466 * Sets the current array position to be the specified key. This
467 * function should be avoided on large arrays.
468 *
469 * @access public
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 function array_set_current(&$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 * @access public
496 *
497 * @param string The start microtime
498 *
499 * @return float Microtime difference
500 */
501 function fetch_microtime_diff($mtstart)
502 {
503 $mtend = microtime();
504 list ($starttime['micro'], $starttime['sec']) = explode(' ', $mtstart);
505 list ($endtime['micro'], $endtime['sec']) = explode(' ', $mtend);
506 return ($endtime['micro'] + $endtime['sec']) - ($starttime['micro'] + $starttime['sec']);
507 }
508
509 // ###################################################################
510 /**
511 * Fetches the extension of a file by extracting everything after the
512 * last period
513 *
514 * @access public
515 *
516 * @param string Filename
517 *
518 * @return string The extension for the specifid file name
519 */
520 function fetch_extension($filename)
521 {
522 return strval(end(explode('.', $filename)));
523 }
524
525 // ###################################################################
526 /**
527 * Gets the maximum file size for attachment uploading, as specified by
528 * PHP. If no value is present, 10 MB (represented in bytes) is
529 * returned.
530 *
531 * @access public
532 *
533 * @return integer The maximum file upload size in bytes
534 */
535 function fetch_max_attachment_size()
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 * @access public
560 *
561 * @param string Path to scan
562 * @param bool Whether or not to recursively scan the directories encountered
563 * @param bool Ignore files beginning with a dot
564 * @param bool Ignore 'CVS' dirctories
565 *
566 * @return array A list of all the files in the specified path
567 */
568 function scandir($path, $recurse = true, $ignoredot = true, $ignorecvs = true, $basepath = '', $unset = 1)
569 {
570 static $filelist;
571
572 if ($unset)
573 {
574 $filelist = array();
575 }
576
577 if (substr($path, (strlen($path) - 1), 1) != '/')
578 {
579 $path .= '/';
580 }
581
582 if ($handle = opendir($path))
583 {
584 while (($file = readdir($handle)) !== false)
585 {
586 $isdot = ((substr($file, 0, 1) == '.') ? true : false);
587 $isdot = (($ignoredot) ? $isdot : true);
588 $iscvs = (($file == 'CVS') ? true : false);
589 $iscvs = (($ignorecvs) ? $iscvs : true);
590 if (!$isdot AND !$iscvs)
591 {
592 if (is_dir($path . $file))
593 {
594 $filelist["$basepath"][] = "$file/";
595 if ($recurse)
596 {
597 $this->scandir("$path$file", true, $ignoredot, $ignorecvs, "$basepath$file/", 0);
598 }
599 }
600 else
601 {
602 $filelist["$basepath"][] = $file;
603 }
604 }
605 }
606 closedir($handle);
607 }
608 return $filelist;
609 }
610
611 // ###################################################################
612 /**
613 * Changes line breaks into one format
614 *
615 * @access public
616 *
617 * @param string Text
618 * @param string New line break (default is UNIX format)
619 *
620 * @return string Text with one type of line break
621 */
622 function convert_line_breaks($text, $convert_to = "\n")
623 {
624 $text = trim($text);
625 $text = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
626 $text = str_replace("\n", $convert_to, $text);
627 return $text;
628 }
629
630 // ###################################################################
631 /**
632 * Removes all empty() [by PHP's standards] elements in an array. This
633 * can be used in place of using PREG_SPLIT_NO_EMPTY.
634 *
635 * @access public
636 *
637 * @param array An array to strip empties from
638 *
639 * @return array Full-valued array
640 */
641 function array_strip_empty($array)
642 {
643 foreach ($array AS $key => $value)
644 {
645 if (is_array($array["$key"]))
646 {
647 $array["$key"] = $this->array_strip_empty($array["$key"]);
648 }
649 else if (empty($value) OR is_null($value))
650 {
651 unset($array["$key"]);
652 }
653 }
654 return $array;
655 }
656 }
657
658 /*=====================================================================*\
659 || ###################################################################
660 || # $HeadURL$
661 || # $Id$
662 || ###################################################################
663 \*=====================================================================*/
664 ?>