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