Removing the is_browser() function
[isso.git] / Functions.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 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 2 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 (c)2005 - 2008, Blue Static
36 * @package ISSO
37 *
38 */
39 class BSFunctions
40 {
41 /**
42 * Singleton instance
43 * @var object
44 */
45 private static $instance;
46
47 /**
48 * Cookie path
49 * @var string
50 */
51 private $cookiePath = '/';
52
53 /**
54 * Cookie domain setting
55 * @var string
56 */
57 private $cookieDomain = '';
58
59 /**
60 * Cookie expiration time
61 * @var integer
62 */
63 private $cookieTimeout = 900;
64
65 /**
66 * Current swapped CSS class
67 * @var string
68 */
69 public static $cssClass = '';
70
71 // ###################################################################
72 /**
73 * Constructor
74 */
75 private function __construct() {}
76
77 // ###################################################################
78 /**
79 * Returns the shared instance for singleton
80 *
81 * @return object Shared instance
82 */
83 private function _instance()
84 {
85 if (!self::$instance)
86 {
87 self::$instance = new BSFunctions();
88 }
89 return self::$instance;
90 }
91
92 // ###################################################################
93 /**
94 * Sets the cookie path
95 *
96 * @param string New path
97 */
98 public static function set_cookie_path($path)
99 {
100 self::_instance()->cookiePath = $path;
101 }
102
103 // ###################################################################
104 /**
105 * Sets the cookie domain setting
106 *
107 * @param string Cookie domain
108 */
109 public static function set_cookie_domain($domain)
110 {
111 self::_instance()->cookieDomain = $domain;
112 }
113
114 // ###################################################################
115 /**
116 * Sets the cookie timeout
117 *
118 * @param integer Cookie timeout
119 */
120 public static function set_cookie_timeout($timeout)
121 {
122 self::_instance()->cookieTimeout = intval($timeout);
123 }
124
125 // ###################################################################
126 /**
127 * Sets a cookie in the user's computer/browing session
128 *
129 * @param string Name of the cookie
130 * @param string Value of the cookie, FALSE to clear
131 * @param bool Is the cookie permanent?
132 */
133 public static function cookie($name, $value, $sticky = true)
134 {
135 // expire the cookie
136 if ($value === false)
137 {
138 setcookie($name, $value, time() - (2 * self::_instance()->cookieTimeout), self::_instance()->cookiePath, self::_instance()->cookieDomain);
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() + self::_instance()->cookieTimeout;
150 }
151
152 setcookie($name, $value, $expire, self::_instance()->cookiePath, self::_instance()->cookieDomain);
153 }
154 }
155
156 // ###################################################################
157 /**
158 * Alternate between two CSS classes
159 *
160 * @param string First CSS class name
161 * @param string Second CSS class name
162 */
163 public static function swap_css_classes($class1 = 'alt1', $class2 = 'alt2')
164 {
165 static $count;
166
167 self::$cssClass = ($count % 2) ? $class1 : $class2;
168 $count++;
169 }
170
171 // ###################################################################
172 /**
173 * Returns the 'source path' version of a file path. It adds a
174 * directory separator to the end of a string if it does not already
175 * exist.
176 *
177 * @param string Path
178 *
179 * @return string Path with directory separator ending
180 */
181 public static function fetch_source_path($source)
182 {
183 if (substr($source, strlen($source) - 1) != DIRECTORY_SEPARATOR)
184 {
185 $source .= DIRECTORY_SEPARATOR;
186 }
187 return $source;
188 }
189
190 // ###################################################################
191 /**
192 * Force-download a file by sending application/octetstream
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 public static function download_file($file, $name, $exit = true)
199 {
200 header("Content-Type: application/octetstream");
201 header("Content-Type: application/octet-stream");
202 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
203 header('Content-Disposition: attachment; filename="' . $name . '"');
204 header('Content-length: ' . strlen($file));
205 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
206 header('Pragma: public');
207
208 print($file);
209
210 if ($exit)
211 {
212 exit;
213 }
214 }
215
216 // ###################################################################
217 /**
218 * Verify that an email address is valid via regex
219 *
220 * @param string An email address
221 *
222 * @return bool Validity of the email address
223 */
224 public static function is_valid_email($email)
225 {
226 if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
227 {
228 return true;
229 }
230 else
231 {
232 return false;
233 }
234 }
235
236 // ###################################################################
237 /**
238 * Generates a random string of random length (unless otherwise
239 * specified)
240 *
241 * @param integer Optional length
242 *
243 * @return string A random string
244 */
245 public static function random($length = 0)
246 {
247 // custom high and lows
248 if (is_array($length))
249 {
250 $length = rand($length[0], $length[1]);
251 }
252 else if (!$length)
253 {
254 $length = rand(20, 65);
255 }
256
257 $string = '';
258 while (strlen($string) < $length)
259 {
260 $type = rand(0, 300);
261 if ($type < 100)
262 {
263 $string .= rand(0, 9);
264 }
265 else if ($type < 200)
266 {
267 $string .= chr(rand(65, 90));
268 }
269 else
270 {
271 $string .= chr(rand(97, 122));
272 }
273 }
274
275 return $string;
276 }
277
278 // ###################################################################
279 /**
280 * Sets the current array position to be the specified key. This
281 * function should be avoided on large arrays.
282 *
283 * @param array The array whose counter is to be updated
284 * @param mixed The key of the element of the array that the counter is to be set to
285 *
286 * @return mixed Return the elelment of the array that we just put the counter to
287 */
288 public static function array_set_current(&$array, $key)
289 {
290 reset($array);
291 while (current($array) !== false)
292 {
293 if (key($array) == $key)
294 {
295 break;
296 }
297 next($array);
298 }
299 return current($array);
300 }
301
302 // ###################################################################
303 /**
304 * Calculates the microtime difference by taking a given microtime and
305 * subtracting it from the current one
306 *
307 * @param string The start microtime
308 *
309 * @return float Microtime difference
310 */
311 public static function fetch_microtime_diff($mtstart)
312 {
313 $mtend = microtime();
314 list($startMicro, $startSec) = explode(' ', $mtstart);
315 list($endMicro, $endSec) = explode(' ', $mtend);
316 return ($endMicro + $endSec) - ($startMicro + $startSec);
317 }
318
319 // ###################################################################
320 /**
321 * Fetches the extension of a file by extracting everything after the
322 * last period
323 *
324 * @param string Filename
325 *
326 * @return string The extension for the specifid file name
327 */
328 public static function fetch_extension($filename)
329 {
330 $array = explode('.', $filename);
331
332 if (sizeof($array) == 1)
333 {
334 return '';
335 }
336
337 return strval(end($array));
338 }
339
340 // ###################################################################
341 /**
342 * Gets the maximum file size for attachment uploading, as specified by
343 * PHP. If no value is present, 10 MB (represented in bytes) is
344 * returned.
345 *
346 * @return integer The maximum file upload size in bytes
347 */
348 public static function fetch_max_php_file_size()
349 {
350 if ($size = @ini_get('upload_max_filesize'))
351 {
352 if (preg_match('#[^0-9].#', $size))
353 {
354 return $size;
355 }
356 else
357 {
358 return intval($size) * 1048576;
359 }
360 }
361 else
362 {
363 return 10 * 1048576;
364 }
365 }
366
367 // ###################################################################
368 /**
369 * Scans a specified directory path and returns an array of all the
370 * items in that directory. Directories found by this are end in a "/"
371 *
372 * @param string Path to scan
373 * @param bool Whether or not to recursively scan the directories encountered
374 * @param bool Ignore files beginning with a dot
375 *
376 * @return array A list of all the files in the specified path
377 */
378 public static function scan_directory($path, $recurse = true, $ignoreDot = true)
379 {
380 return self::_help_scan_directory($path, $recurse, $ignoreDot, '');
381 }
382
383 // ###################################################################
384 /**
385 * Scans a specified directory path and returns an array of all the
386 * items in that directory. Directories found by this are end in a "/"
387 *
388 * @param string Path to scan
389 * @param bool Whether or not to recursively scan the directories encountered
390 * @param bool Ignore files beginning with a dot
391 * @param string Add to the beginning of the path
392 *
393 * @return array A list of all the files in the specified path
394 */
395 private static function _help_scan_directory($path, $recurse = true, $ignoreDot = true, $pathAdd = '')
396 {
397 $filelist = array();
398 $path = self::fetch_source_path($path);
399
400 $dir = new DirectoryIterator($path);
401 foreach ($dir as $file)
402 {
403 $name = $file->getFilename();
404 if (($file->isDot() || $name[0] == '.') && $ignoreDot)
405 {
406 continue;
407 }
408
409 if ($file->isDir() && $recurse)
410 {
411 $filelist = array_merge($filelist, self::_help_scan_directory($path . $name, $recurse, $ignoreDot, $pathAdd . BSFunctions::fetch_source_path(str_replace($path, '', $file->getPathname()))));
412 continue;
413 }
414
415 $filelist[] = $pathAdd . $name;
416 }
417
418 return $filelist;
419 }
420
421 // ###################################################################
422 /**
423 * Changes line breaks into one format
424 *
425 * @param string Text
426 * @param string New line break (default is UNIX \n format)
427 *
428 * @return string Text with one type of line break
429 */
430 public static function convert_line_breaks($text, $convert_to = "\n")
431 {
432 $text = trim($text);
433 $text = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
434 $text = str_replace("\n", $convert_to, $text);
435 return $text;
436 }
437
438 // ###################################################################
439 /**
440 * Removes all empty() [by PHP's standards] elements in an array. This
441 * can be used in place of using PREG_SPLIT_NO_EMPTY.
442 *
443 * @param array An array to strip empties from
444 *
445 * @return array Full-valued array
446 */
447 public static function array_strip_empty($array)
448 {
449 foreach ($array as $key => $value)
450 {
451 if (is_array($array["$key"]))
452 {
453 $array["$key"] = self::array_strip_empty($array["$key"]);
454 }
455 else if (empty($value) || is_null($value))
456 {
457 unset($array["$key"]);
458 }
459 }
460 return $array;
461 }
462
463 // ###################################################################
464 /**
465 * A backtrace formatter.
466 *
467 * This is very slightly modified from PEAR/PHP_Compat (PHP license)
468 *
469 * @author Laurent Laville <pear@laurent-laville.org>
470 * @author Aidan Lister <aidan@php.net>
471 *
472 * @param array The backtrace from debug_backtrace() to format
473 *
474 * @return string Formatted output
475 */
476 public static function format_backtrace($backtrace)
477 {
478 // Unset call to debug_print_backtrace
479 array_shift($backtrace);
480 if (empty($backtrace))
481 {
482 return '';
483 }
484
485 // Iterate backtrace
486 $calls = array();
487 foreach ($backtrace as $i => $call)
488 {
489 if (!isset($call['file']))
490 {
491 $call['file'] = '(null)';
492 }
493 if (!isset($call['line']))
494 {
495 $call['line'] = '0';
496 }
497 $location = $call['file'] . ':' . $call['line'];
498 $function = (isset($call['class'])) ? $call['class'] . (isset($call['type']) ? $call['type'] : '.') . $call['function'] : $call['function'];
499
500 $params = '';
501 if (isset($call['args']))
502 {
503 $args = array();
504 foreach ($call['args'] as $arg)
505 {
506 if (is_array($arg))
507 {
508 $args[] = 'Array';
509 }
510 elseif (is_object($arg))
511 {
512 $args[] = get_class($arg);
513 }
514 else
515 {
516 $args[] = $arg;
517 }
518 }
519 $params = implode(', ', $args);
520 }
521
522 $calls[] = sprintf('#%d %s(%s) called at [%s]', $i, $function, $params, $location);
523 }
524
525 return implode("\n", $calls);
526 }
527
528 // ###################################################################
529 /**
530 * A variation of PHP's substr() method that takes in the start
531 * and end position of a string, rather than a start and length. This
532 * mimics Java's String.substring() method.
533 *
534 * @param string The string
535 * @param integer Start position
536 * @param integer End position
537 *
538 * @return string Part of a string
539 */
540 public static function substring($string, $start, $end)
541 {
542 return substr($string, $start, $end - $start);
543 }
544 }
545
546 ?>