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