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