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