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