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