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