source: trunk/lib/Utilities.inc.php @ 400

Last change on this file since 400 was 400, checked in by anonymous, 12 years ago

Comment updates.

File size: 37.2 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * Utilities.inc.php
25 */
26
27
28/**
29 * Print variable dump.
30 *
31 * @param  mixed $var      Variable to dump.
32 * @param  bool  $display   Hide the dump in HTML comments?
33 * @param  bool  $var_dump Use var_dump instead of print_r.
34 */
35function dump($var, $display=false, $var_dump=false)
36{
37    if (defined('_CLI')) {
38        echo "\n";
39    } else {       
40        echo $display ? "\n<br /><pre>\n" : "\n\n\n<!--\n";
41    }
42    if ($var_dump) {
43        var_dump($var);
44    } else {
45        print_r($var);
46    }
47    if (defined('_CLI')) {
48        echo "\n";
49    } else {       
50        echo $display ?  "\n</pre><br />\n" : "\n-->\n\n\n";
51    }
52}
53
54/**
55 * Return dump as variable.
56 *
57 * @param  mixed $var           Variable to dump.
58 * @param  bool  $serialize     Remove line-endings. Useful for logging variables.
59 * @return string Dump of var.
60 */
61function getDump($var, $serialize=false)
62{
63    ob_start();
64    print_r($var);
65    $d = ob_get_contents();
66    ob_end_clean();
67    return $serialize ? preg_replace('/\s+/m', '', $d) : $d;
68}
69
70/**
71 * Return dump as cleaned text. Useful for dumping data into emails.
72 *
73 * @param  array    $var        Variable to dump.
74 * @param  strong   $indent     A string to prepend indented lines (tab for example).
75 * @return string Dump of var.
76 */
77function fancyDump($var, $indent='')
78{
79    $output = '';
80    if (is_array($var)) {
81        foreach ($var as $k=>$v) {
82            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
83            if (is_array($v)) {
84                $output .= sprintf("\n%s%s: %s\n", $indent, $k, fancyDump($v, $indent . $indent));
85            } else {
86                $output .= sprintf("%s%s: %s\n", $indent, $k, $v);
87            }
88        }
89    } else {
90        $output .= sprintf("%s%s\n", $indent, $var);
91    }
92    return $output;
93}
94
95/**
96 * Returns text with appropriate html translations.
97 *
98 * @param  string $text             Text to clean.
99 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
100 *                                  characters into HTML entities. This allows HTML to pass through unmunged.
101 * @return string                   Cleaned text.
102 */
103function oTxt($text, $preserve_html=false)
104{
105    $app =& App::getInstance();
106
107    $search = array();
108    $replace = array();
109
110    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
111    $search['retain_ampersand']     = '/&amp;/';
112    $replace['retain_ampersand']    = '&';
113
114    if ($preserve_html) {
115        // Convert characters that must remain non-entities for displaying HTML.
116        $search['retain_left_angle']       = '/&lt;/';
117        $replace['retain_left_angle']      = '<';
118
119        $search['retain_right_angle']      = '/&gt;/';
120        $replace['retain_right_angle']     = '>';
121
122        $search['retain_single_quote']     = '/&#039;/';
123        $replace['retain_single_quote']    = "'";
124
125        $search['retain_double_quote']     = '/&quot;/';
126        $replace['retain_double_quote']    = '"';
127    }
128
129    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
130    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
131    $replace['ampersand']       = '&amp;';
132
133    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
134}
135
136/**
137 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
138 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
139 *
140 * @param  string   $text Text to clean.
141 * @return string         Cleaned text.
142 */
143function fancyTxt($text)
144{
145    $search = array();
146    $replace = array();
147
148    // "double quoted text"  becomes  &ldquo;double quoted text&rdquo;
149    $search['double_quotes']    = '/(^|[^\w=])(?:"|&quot;|&#34;|&#x22;|&ldquo;)([^"]+?)(?:"|&quot;|&#34;|&#x22;|&rdquo;)([^\w]|$)/ms'; // " is the same as &quot; and &#34; and &#x22;
150    $replace['double_quotes']   = '$1&ldquo;$2&rdquo;$3';
151
152    // text's apostrophes  become  text&rsquo;s apostrophes
153    $search['apostrophe']       = '/(\w)(?:\'|&#39;|&#039;)(\w)/ms';
154    $replace['apostrophe']      = '$1&rsquo;$2';
155
156    // 'single quoted text'  becomes  &lsquo;single quoted text&rsquo;
157    $search['single_quotes']    = '/(^|[^\w=])(?:\'|&#39;|&lsquo;)([^\']+?)(?:\'|&#39;|&rsquo;)([^\w]|$)/ms';
158    $replace['single_quotes']   = '$1&lsquo;$2&rsquo;$3';
159
160    // plural posessives' apostrophes become posessives&rsquo;
161    $search['apostrophes']      = '/(s)(?:\'|&#39;|&#039;)(\s)/ms';
162    $replace['apostrophes']     = '$1&rsquo;$2';
163
164    // em--dashes  become em&mdash;dashes
165    $search['em_dash']          = '/(\s*[^!<-])--([^>-]\s*)/';
166    $replace['em_dash']         = '$1&mdash;$2';
167
168    return preg_replace($search, $replace, $text);
169}
170
171/**
172 * Applies a class to search terms to highlight them ala google results.
173 *
174 * @param  string   $text   Input text to search.
175 * @param  string   $search String of word(s) that will be highlighted.
176 * @param  string   $class  CSS class to apply.
177 * @return string           Text with searched words wrapped in <span>.
178 */
179function highlightWords($text, $search, $class='sc-highlightwords')
180{
181    $words = preg_split('/[^\w]/', $search, -1, PREG_SPLIT_NO_EMPTY);
182   
183    $search = array();
184    $replace = array();
185   
186    foreach ($words as $w) {
187        if ('' != trim($w)) {
188            $search[] = '/\b(' . preg_quote($w) . ')\b/i';
189            $replace[] = '<span class="' . $class . '">$1</span>';
190        }
191    }
192
193    return empty($replace) ? $text : preg_replace($search, $replace, $text);
194}
195
196/**
197 * Generates a hexadecimal html color based on provided word.
198 *
199 * @access public
200 * @param  string $text  A string for which to convert to color.
201 * @return string  A hexadecimal html color.
202 */
203function getTextColor($text, $method=1)
204{
205    $hash = md5($text);
206    $rgb = array(
207        mb_substr($hash, 0, 1),
208        mb_substr($hash, 1, 1),
209        mb_substr($hash, 2, 1),
210        mb_substr($hash, 3, 1),
211        mb_substr($hash, 4, 1),
212        mb_substr($hash, 5, 1),
213    );
214
215    switch ($method) {
216    case 1 :
217    default :
218        // Reduce all hex values slightly to avoid all white.
219        array_walk($rgb, create_function('&$v', '$v = dechex(round(hexdec($v) * 0.87));'));
220        break;
221    case 2 :
222        foreach ($rgb as $i => $v) {
223            if (hexdec($v) > hexdec('c')) {
224                $rgb[$i] = dechex(hexdec('f') - hexdec($v));
225            }
226        }
227        break;
228    }
229
230    return join('', $rgb);
231}
232
233/**
234 * Encodes a string into unicode values 128-255.
235 * Useful for hiding an email address from spambots.
236 *
237 * @access  public
238 * @param   string   $text   A line of text to encode.
239 * @return  string   Encoded text.
240 */
241function encodeAscii($text)
242{
243    $output = '';
244    $num = mb_strlen($text);
245    for ($i=0; $i<$num; $i++) {
246        $output .= sprintf('&#%03s', ord($text{$i}));
247    }
248    return $output;
249}
250
251/**
252 * Encodes an email into a "user at domain dot com" format.
253 *
254 * @access  public
255 * @param   string   $email   An email to encode.
256 * @param   string   $at      Replaces the @.
257 * @param   string   $dot     Replaces the ..
258 * @return  string   Encoded email.
259 */
260function encodeEmail($email, $at=' at ', $dot=' dot ')
261{
262    $search = array('/@/', '/\./');
263    $replace = array($at, $dot);
264    return preg_replace($search, $replace, $email);
265}
266
267/**
268 * Turns "a really long string" into "a rea...string"
269 *
270 * @access  public
271 * @param   string  $str    Input string
272 * @param   int     $len    Maximum string length.
273 * @param   string  $where  Where to cut the string. One of: 'start', 'middle', or 'end'.
274 * @return  string          Truncated output string
275 * @author  Quinn Comendant <quinn@strangecode.com>
276 * @since   29 Mar 2006 13:48:49
277 */
278function truncate($str, $len, $where='middle', $delim='&hellip;')
279{
280    if ($len <= 3 || mb_strlen($str) <= 3) {
281        return '';
282    }
283    $part1 = floor(($len - 3) / 2);
284    $part2 = ceil(($len - 3) / 2);
285    switch ($where) {
286    case 'start' :
287        return preg_replace(array(sprintf('/^.{4,}(.{%s})$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array($delim . '$1', $delim), $str);
288        break;
289    default :
290    case 'middle' :
291        return preg_replace(array(sprintf('/^(.{%s}).{4,}(.{%s})$/sU', $part1, $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim . '$2', $delim), $str);
292        break;   
293    case 'end' :
294        return preg_replace(array(sprintf('/^(.{%s}).{4,}$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim, $delim), $str);
295        break;
296    }
297}
298
299/*
300* A substitution for the missing mb_ucfirst function.
301*
302* @access   public
303* @param    string  $strong The string
304* @return   string          String with uper-cased first character.
305* @author   Quinn Comendant <quinn@strangecode.com>
306* @version  1.0
307* @since    06 Dec 2008 17:04:01
308*/
309if (!function_exists('mb_ucfirst')) {   
310    function mb_ucfirst($string)
311    {
312        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1, mb_strlen($string));
313    }
314}
315
316/**
317 * Return a human readable disk space measurement. Input value measured in bytes.
318 *
319 * @param       int    $size        Size in bytes.
320 * @param       int    $unit        The maximum unit
321 * @param       int    $format      The return string format
322 * @author      Aidan Lister <aidan@php.net>
323 * @author      Quinn Comendant <quinn@strangecode.com>
324 * @version     1.2.0
325 */
326function humanFileSize($size, $format='%01.2f %s', $max_unit=null, $multiplier=1024)
327{
328    // Units
329    $units = array('B', 'KB', 'MB', 'GB', 'TB');
330    $ii = count($units) - 1;
331
332    // Max unit
333    $max_unit = array_search((string) $max_unit, $units);
334    if ($max_unit === null || $max_unit === false) {
335        $max_unit = $ii;
336    }
337
338    // Loop
339    $i = 0;
340    while ($max_unit != $i && $size >= $multiplier && $i < $ii) {
341        $size /= $multiplier;
342        $i++;
343    }
344
345    return sprintf($format, $size, $units[$i]);
346}
347
348/*
349* Returns a human readable amount of time for the given amount of seconds.
350*
351* 45 seconds
352* 12 minutes
353* 3.5 hours
354* 2 days
355* 1 week
356* 4 months
357*
358* Months are calculated using the real number of days in a year: 365.2422 / 12.
359*
360* @access   public
361* @param    int $seconds Seconds of time.
362* @param    string $max_unit Key value from the $units array.
363* @param    string $format Sprintf formatting string.
364* @return   string Value of units elapsed.
365* @author   Quinn Comendant <quinn@strangecode.com>
366* @version  1.0
367* @since    23 Jun 2006 12:15:19
368*/
369function humanTime($seconds, $max_unit=null, $format='%01.1f')
370{
371    // Units: array of seconds in the unit, singular and plural unit names.
372    $units = array(
373        'second' => array(1, _("second"), _("seconds")),
374        'minute' => array(60, _("minute"), _("minutes")),
375        'hour' => array(3600, _("hour"), _("hours")),
376        'day' => array(86400, _("day"), _("days")),
377        'week' => array(604800, _("week"), _("weeks")),
378        'month' => array(2629743.84, _("month"), _("months")),
379        'year' => array(31556926.08, _("year"), _("years")),
380        'decade' => array(315569260.8, _("decade"), _("decades")),
381        'century' => array(3155692608, _("century"), _("centuries")),
382    );
383   
384    // Max unit to calculate.
385    $max_unit = isset($units[$max_unit]) ? $max_unit : 'year';
386
387    $final_time = $seconds;
388    $final_unit = 'second';
389    foreach ($units as $k => $v) {
390        if ($seconds >= $v[0]) {
391            $final_time = $seconds / $v[0];
392            $final_unit = $k;
393        }
394        if ($max_unit == $final_unit) {
395            break;
396        }
397    }
398    $final_time = sprintf($format, $final_time);
399    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2]));   
400}
401
402/**
403 * Tests the existence of a file anywhere in the include path.
404 *
405 * @param   string  $file   File in include path.
406 * @return  mixed           False if file not found, the path of the file if it is found.
407 * @author  Quinn Comendant <quinn@strangecode.com>
408 * @since   03 Dec 2005 14:23:26
409 */
410function fileExistsIncludePath($file)
411{
412    $app =& App::getInstance();
413   
414    foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) {
415        $fullpath = $path . DIRECTORY_SEPARATOR . $file;
416        if (file_exists($fullpath)) {
417            $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__);
418            return $fullpath;
419        } else {
420            $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__);
421            return false;
422        }
423    }
424}
425
426/**
427 * Returns stats of a file from the include path.
428 *
429 * @param   string  $file   File in include path.
430 * @param   mixed   $stat   Which statistic to return (or null to return all).
431 * @return  mixed           Value of requested key from fstat(), or false on error.
432 * @author  Quinn Comendant <quinn@strangecode.com>
433 * @since   03 Dec 2005 14:23:26
434 */
435function statIncludePath($file, $stat=null)
436{
437    // Open file pointer read-only using include path.
438    if ($fp = fopen($file, 'r', true)) {
439        // File opened successfully, get stats.
440        $stats = fstat($fp);
441        fclose($fp);
442        // Return specified stats.
443        return is_null($stat) ? $stats : $stats[$stat];
444    } else {
445        return false;
446    }
447}
448
449/*
450* Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5.
451* It makes an exclusive lock on the file while writing.
452*
453* @access   public
454* @param    string  $filename   Path to file.
455* @param    string  $content    Data to write into file.
456* @return   bool                Success or failure.
457* @author   Quinn Comendant <quinn@strangecode.com>
458* @since    11 Apr 2006 22:48:30
459*/
460function filePutContents($filename, $content)
461{
462    $app =& App::getInstance();
463
464    // Open file for writing and truncate to zero length.
465    if ($fp = fopen($filename, 'w')) {
466        if (flock($fp, LOCK_EX)) {
467            if (!fwrite($fp, $content, mb_strlen($content))) {
468                $app->logMsg(sprintf('Failed writing to file: %s', $filename), LOG_ERR, __FILE__, __LINE__);
469                fclose($fp);
470                return false;
471            }
472            flock($fp, LOCK_UN);
473        } else {
474            $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
475            fclose($fp);
476            return false;
477        }
478        fclose($fp);
479        // Success!
480        $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
481        return true;
482    } else {
483        $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
484        return false;
485    }
486}
487
488/**
489 * If $var is net set or null, set it to $default. Otherwise leave it alone.
490 * Returns the final value of $var. Use to find a default value of one is not available.
491 *
492 * @param  mixed $var       The variable that is being set.
493 * @param  mixed $default   What to set it to if $val is not currently set.
494 * @return mixed            The resulting value of $var.
495 */
496function setDefault(&$var, $default='')
497{
498    if (!isset($var)) {
499        $var = $default;
500    }
501    return $var;
502}
503
504/**
505 * Like preg_quote() except for arrays, it takes an array of strings and puts
506 * a backslash in front of every character that is part of the regular
507 * expression syntax.
508 *
509 * @param  array $array    input array
510 * @param  array $delim    optional character that will also be escaped.
511 * @return array    an array with the same values as $array1 but shuffled
512 */
513function pregQuoteArray($array, $delim='/')
514{
515    if (!empty($array)) {
516        if (is_array($array)) {
517            foreach ($array as $key=>$val) {
518                $quoted_array[$key] = preg_quote($val, $delim);
519            }
520            return $quoted_array;
521        } else {
522            return preg_quote($array, $delim);
523        }
524    }
525}
526
527/**
528 * Converts a PHP Array into encoded URL arguments and return them as an array.
529 *
530 * @param  mixed $data        An array to transverse recursively, or a string
531 *                            to use directly to create url arguments.
532 * @param  string $prefix     The name of the first dimension of the array.
533 *                            If not specified, the first keys of the array will be used.
534 * @return array              URL with array elements as URL key=value arguments.
535 */
536function urlEncodeArray($data, $prefix='', $_return=true)
537{
538    // Data is stored in static variable.
539    static $args;
540
541    if (is_array($data)) {
542        foreach ($data as $key => $val) {
543            // If the prefix is empty, use the $key as the name of the first dimension of the "array".
544            // ...otherwise, append the key as a new dimension of the "array".
545            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
546            // Enter recursion.
547            urlEncodeArray($val, $new_prefix, false);
548        }
549    } else {
550        // We've come to the last dimension of the array, save the "array" and its value.
551        $args[$prefix] = urlencode($data);
552    }
553
554    if ($_return) {
555        // This is not a recursive execution. All recursion is complete.
556        // Reset static var and return the result.
557        $ret = $args;
558        $args = array();
559        return is_array($ret) ? $ret : array();
560    }
561}
562
563/**
564 * Converts a PHP Array into encoded URL arguments and return them in a string.
565 *
566 * @param  mixed $data        An array to transverse recursively, or a string
567 *                            to use directly to create url arguments.
568 * @param  string $prefix     The name of the first dimension of the array.
569 *                            If not specified, the first keys of the array will be used.
570 * @return string url         A string ready to append to a url.
571 */
572function urlEncodeArrayToString($data, $prefix='')
573{
574
575    $array_args = urlEncodeArray($data, $prefix);
576    $url_args = '';
577    $delim = '';
578    foreach ($array_args as $key=>$val) {
579        $url_args .= $delim . $key . '=' . $val;
580        $delim = ini_get('arg_separator.output');
581    }
582    return $url_args;
583}
584
585/**
586 * Fills an array with the result from a multiple ereg search.
587 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
588 *
589 * @param  mixed $pattern   regular expression needle
590 * @param  mixed $string   haystack
591 * @return array    populated with each found result
592 */
593function eregAll($pattern, $string)
594{
595    do {
596        if (!mb_ereg($pattern, $string, $temp)) {
597             continue;
598        }
599        $string = str_replace($temp[0], '', $string);
600        $results[] = $temp;
601    } while (mb_ereg($pattern, $string, $temp));
602    return $results;
603}
604
605/**
606 * Prints the word "checked" if a variable is set, and optionally matches
607 * the desired value, otherwise prints nothing,
608 * used for printing the word "checked" in a checkbox form input.
609 *
610 * @param  mixed $var     the variable to compare
611 * @param  mixed $value   optional, what to compare with if a specific value is required.
612 */
613function frmChecked($var, $value=null)
614{
615    if (func_num_args() == 1 && $var) {
616        // 'Checked' if var is true.
617        echo ' checked="checked" ';
618    } else if (func_num_args() == 2 && $var == $value) {
619        // 'Checked' if var and value match.
620        echo ' checked="checked" ';
621    } else if (func_num_args() == 2 && is_array($var)) {
622        // 'Checked' if the value is in the key or the value of an array.
623        if (isset($var[$value])) {
624            echo ' checked="checked" ';
625        } else if (in_array($value, $var)) {
626            echo ' checked="checked" ';
627        }
628    }
629}
630
631/**
632 * prints the word "selected" if a variable is set, and optionally matches
633 * the desired value, otherwise prints nothing,
634 * otherwise prints nothing, used for printing the word "checked" in a
635 * select form input
636 *
637 * @param  mixed $var     the variable to compare
638 * @param  mixed $value   optional, what to compare with if a specific value is required.
639 */
640function frmSelected($var, $value=null)
641{
642    if (func_num_args() == 1 && $var) {
643        // 'selected' if var is true.
644        echo ' selected="selected" ';
645    } else if (func_num_args() == 2 && $var == $value) {
646        // 'selected' if var and value match.
647        echo ' selected="selected" ';
648    } else if (func_num_args() == 2 && is_array($var)) {
649        // 'selected' if the value is in the key or the value of an array.
650        if (isset($var[$value])) {
651            echo ' selected="selected" ';
652        } else if (in_array($value, $var)) {
653            echo ' selected="selected" ';
654        }
655    }
656}
657
658/**
659 * Adds slashes to values of an array and converts the array to a comma
660 * delimited list. If value provided is a string return the string
661 * escaped.  This is useful for putting values coming in from posted
662 * checkboxes into a SET column of a database.
663 *
664 *
665 * @param  array $in      Array to convert.
666 * @return string         Comma list of array values.
667 */
668function escapedList($in, $separator="', '")
669{
670    $db =& DB::getInstance();
671   
672    if (is_array($in) && !empty($in)) {
673        return join($separator, array_map(array($db, 'escapeString'), $in));
674    } else {
675        return $db->escapeString($in);
676    }
677}
678
679/**
680 * Converts a human string date into a SQL-safe date.  Dates nearing
681 * infinity use the date 2038-01-01 so conversion to unix time format
682 * remain within valid range.
683 *
684 * @param  array $date     String date to convert.
685 * @param  array $format   Date format to pass to date().
686 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
687 * @return string          SQL-safe date.
688 */
689function strToSQLDate($date, $format='Y-m-d H:i:s')
690{
691    // Translate the human string date into SQL-safe date format.
692    if (empty($date) || mb_strpos($date, '0000-00-00') !== false || strtotime($date) === -1 || strtotime($date) === false) {
693        // Return a string of zero time, formatted the same as $format.
694        return strtr($format, array(
695            'Y' => '0000',
696            'm' => '00',
697            'd' => '00',
698            'H' => '00',
699            'i' => '00',
700            's' => '00',
701        ));
702    } else {
703        return date($format, strtotime($date));
704    }
705}
706
707/**
708 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
709 * array, stripslashes is run on each value, recursively, and the stripped
710 * array is returned.
711 *
712 * @param  mixed $var   The string or array to un-quote, if necessary.
713 * @return mixed        $var, minus any magic quotes.
714 */
715function dispelMagicQuotes($var)
716{
717    static $magic_quotes_gpc;
718
719    if (!isset($magic_quotes_gpc)) {
720        $magic_quotes_gpc = get_magic_quotes_gpc();
721    }
722
723    if ($magic_quotes_gpc) {
724        if (!is_array($var)) {
725            $var = stripslashes($var);
726        } else {
727            foreach ($var as $key=>$val) {
728                if (is_array($val)) {
729                    $var[$key] = dispelMagicQuotes($val);
730                } else {
731                    $var[$key] = stripslashes($val);
732                }
733            }
734        }
735    }
736    return $var;
737}
738
739/**
740 * Get a form variable from GET or POST data, stripped of magic
741 * quotes if necessary.
742 *
743 * @param string $var (optional) The name of the form variable to look for.
744 * @param string $default (optional) The value to return if the
745 *                                   variable is not there.
746 * @return mixed      A cleaned GET or POST if no $var specified.
747 * @return string     A cleaned form $var if found, or $default.
748 */
749function getFormData($var=null, $default=null)
750{
751    if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) {
752        return dispelMagicQuotes($_POST);
753    } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) {
754        return dispelMagicQuotes($_GET);
755    }
756    if (isset($_POST[$var])) {
757        return dispelMagicQuotes($_POST[$var]);
758    } else if (isset($_GET[$var])) {
759        return dispelMagicQuotes($_GET[$var]);
760    } else {
761        return $default;
762    }
763}
764function getPost($var=null, $default=null)
765{
766    if (is_null($var)) {
767        return dispelMagicQuotes($_POST);
768    }
769    if (isset($_POST[$var])) {
770        return dispelMagicQuotes($_POST[$var]);
771    } else {
772        return $default;
773    }
774}
775function getGet($var=null, $default=null)
776{
777    if (is_null($var)) {
778        return dispelMagicQuotes($_GET);
779    }
780    if (isset($_GET[$var])) {
781        return dispelMagicQuotes($_GET[$var]);
782    } else {
783        return $default;
784    }
785}
786
787/*
788* Sets a $_GET or $_POST variable.
789*
790* @access   public
791* @param    string  $key    The key of the request array to set.
792* @param    mixed   $val    The value to save in the request array.
793* @return   void
794* @author   Quinn Comendant <quinn@strangecode.com>
795* @version  1.0
796* @since    01 Nov 2009 12:25:29
797*/
798function putFormData($key, $val)
799{
800    if ('POST' == getenv('REQUEST_METHOD')) {
801        $_POST[$key] = $val;
802    } else if ('GET' == getenv('REQUEST_METHOD')) {
803        $_GET[$key] = $val;
804    }
805}
806
807/**
808 * Signs a value using md5 and a simple text key. In order for this
809 * function to be useful (i.e. secure) the key must be kept secret, which
810 * means keeping it as safe as database credentials. Putting it into an
811 * environment variable set in httpd.conf is a good place.
812 *
813 * @access  public
814 * @param   string  $val    The string to sign.
815 * @param   string  $salt   (Optional) A text key to use for computing the signature.
816 * @param   string  $length (Optional) The length of the added signature. Longer signatures are safer. Must match the length passed to verifySignature() for the signatures to match.
817 * @return  string  The original value with a signature appended.
818 */
819function addSignature($val, $salt=null, $length=18)
820{
821    $app =& App::getInstance();
822   
823    if ('' == trim($val)) {
824        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
825        return '';
826    }
827
828    if (!isset($salt)) {
829        $salt = $app->getParam('signing_key');
830    }
831   
832    // TODO: consider using more bits-per-character, such as done with:
833    // http://www.php.net/manual/en/function.sha1.php#86239
834    // http://blog.kevburnsjr.com/php-unique-hash
835    return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
836}
837
838/**
839 * Strips off the signature appended by addSignature().
840 *
841 * @access  public
842 * @param   string  $signed_val     The string to sign.
843 * @return  string  The original value with a signature removed.
844 */
845function removeSignature($signed_val)
846{
847    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
848        return '';
849    }
850    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
851}
852
853/**
854 * Verifies a signature appened to a value by addSignature().
855 *
856 * @access  public
857 * @param   string  $signed_val A value with appended signature.
858 * @param   string  $salt       (Optional) A text key to use for computing the signature.
859 * @return  bool    True if the signature matches the var.
860 */
861function verifySignature($signed_val, $salt=null, $length=18)
862{
863    // All comparisons are done using lower-case strings.
864    $signed_val = mb_strtolower($signed_val);
865    // Strip the value from the signed value.
866    $val = removeSignature($signed_val);
867    // If the signed value matches the original signed value we consider the value safe.
868    if ($signed_val == addSignature($val, $salt, $length)) {
869        // Signature verified.
870        return true;
871    } else {
872        return false;
873    }
874}
875
876/**
877 * Sends empty output to the browser and flushes the php buffer so the client
878 * will see data before the page is finished processing.
879 */
880function flushBuffer()
881{
882    echo str_repeat('          ', 205);
883    flush();
884}
885
886/**
887 * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
888 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
889 *
890 * @access  public
891 * @param   string  $email     Email address to add.
892 * @param   string  $list      Name of list to add to.
893 * @param   bool    $send_welcome_message   True to send welcome message to subscriber.
894 * @return  bool    True on success, false on failure.
895 */
896function mailmanAddMember($email, $list, $send_welcome_message=false)
897{
898    $app =& App::getInstance();
899   
900    $add_members = '/usr/lib/mailman/bin/add_members';
901    /// FIXME: checking of executable is disabled.
902    if (true || is_executable($add_members) && is_readable($add_members)) {
903        $welcome_msg = $send_welcome_message ? 'y' : 'n';
904        exec(sprintf("/bin/echo '%s' | /usr/bin/sudo %s -r - --welcome-msg=%s --admin-notify=n '%s'", escapeshellarg($email), escapeshellarg($add_members), $welcome_msg, escapeshellarg($list)), $stdout, $return_code);
905        if (0 == $return_code) {
906            $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
907            return true;
908        } else {
909            $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, getDump($stdout)), LOG_WARNING, __FILE__, __LINE__);
910            return false;
911        }
912    } else {
913        $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
914        return false;
915    }
916}
917
918/**
919 * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
920 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
921 *
922 * @access  public
923 * @param   string  $email     Email address to add.
924 * @param   string  $list      Name of list to add to.
925 * @param   bool    $send_user_ack   True to send goodbye message to subscriber.
926 * @return  bool    True on success, false on failure.
927 */
928function mailmanRemoveMember($email, $list, $send_user_ack=false)
929{
930    $app =& App::getInstance();
931   
932    $remove_members = '/usr/lib/mailman/bin/remove_members';
933    /// FIXME: checking of executable is disabled.
934    if (true || is_executable($remove_members) && is_readable($remove_members)) {
935        $userack = $send_user_ack ? '' : '--nouserack';
936        exec(sprintf("/usr/bin/sudo %s %s --noadminack '%s' '%s'", escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
937        if (0 == $return_code) {
938            $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
939            return true;
940        } else {
941            $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
942            return false;
943        }
944    } else {
945        $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
946        return false;
947    }
948}
949
950/**
951 * Returns the remote IP address, taking into consideration proxy servers.
952 *
953 * @param  bool $dolookup   If true we resolve to IP to a host name,
954 *                          if false we don't.
955 * @return string    IP address if $dolookup is false or no arg
956 *                   Hostname if $dolookup is true
957 */
958function getRemoteAddr($dolookup=false)
959{
960    $ip = getenv('HTTP_CLIENT_IP');
961    if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) {
962        $ip = getenv('HTTP_X_FORWARDED_FOR');
963        if (mb_strpos($ip, ',') !== false) {
964            // If HTTP_X_FORWARDED_FOR returns a comma-delimited list of IPs then return the first one (assuming the first is the original).
965            $ips = explode(',', $ip, 2);
966            $ip = $ips[0];
967        }
968        if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) {
969            $ip = getenv('REMOTE_ADDR');
970        }
971    }
972    return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip;
973}
974
975/**
976 * Tests whether a given IP address can be found in an array of IP address networks.
977 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
978 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
979 *
980 * @access  public
981 * @param   string  IP address to search for.
982 * @param   array   Array of networks to search within.
983 * @return  mixed   Returns the network that matched on success, false on failure.
984 */
985function ipInRange($ip, $networks)
986{
987    if (!is_array($networks)) {
988        $networks = array($networks);
989    }
990
991    $ip_binary = sprintf('%032b', ip2long($ip));
992    foreach ($networks as $network) {
993        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) {
994            // IP is in CIDR notation.
995            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
996            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
997            if (mb_substr($ip_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
998               // IP address is within the specified IP range.
999               return $network;
1000            }
1001        } else {
1002            if ($ip === $network) {
1003               // IP address exactly matches.
1004               return $network;
1005            }
1006        }
1007    }
1008
1009    return false;
1010}
1011
1012/**
1013 * If the given $url is on the same web site, return true. This can be used to
1014 * prevent from sending sensitive info in a get query (like the SID) to another
1015 * domain.
1016 *
1017 * @param  string $url    the URI to test.
1018 * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another.
1019 */
1020function isMyDomain($url)
1021{
1022    static $urls = array();
1023
1024    if (!isset($urls[$url])) {
1025        if (!preg_match('|https?://[\w.]+/|', $url)) {
1026            // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg").
1027            $urls[$url] = true;
1028        } else {
1029            $urls[$url] = preg_match('|https?://[\w.]*' . preg_quote(getenv('HTTP_HOST'), '|') . '|i', $url);
1030        }
1031    }
1032    return $urls[$url];
1033}
1034
1035/**
1036 * Takes a URL and returns it without the query or anchor portion
1037 *
1038 * @param  string $url   any kind of URI
1039 * @return string        the URI with ? or # and everything after removed
1040 */
1041function stripQuery($url)
1042{
1043    return preg_replace('/[?#].*$/', '', $url);
1044}
1045
1046/**
1047 * Returns a fully qualified URL to the current script, including the query.
1048 *
1049 * @return string    a full url to the current script
1050 */
1051function absoluteMe()
1052{
1053    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
1054    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
1055}
1056
1057/**
1058 * Compares the current url with the referring url.
1059 *
1060 * @param  bool $exclude_query  Remove the query string first before comparing.
1061 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
1062 */
1063function refererIsMe($exclude_query=false)
1064{
1065    if ($exclude_query) {
1066        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
1067    } else {
1068        return (absoluteMe() == getenv('HTTP_REFERER'));
1069    }
1070}
1071
1072/**
1073 * Stub functions used when installation does not have
1074 * GNU gettext extension installed
1075 */
1076if (!extension_loaded('gettext')) {
1077    /**
1078    * Translates text
1079    *
1080    * @access public
1081    * @param string $text the text to be translated
1082    * @return string translated text
1083    */
1084    function gettext($text) {
1085        return $text;
1086    }
1087
1088    /**
1089    * Translates text
1090    *
1091    * @access public
1092    * @param string $text the text to be translated
1093    * @return string translated text
1094    */
1095    function _($text) {
1096        return $text;
1097    }
1098
1099    /**
1100    * Translates text by domain
1101    *
1102    * @access public
1103    * @param string $domain the language to translate the text into
1104    * @param string $text the text to be translated
1105    * @return string translated text
1106    */
1107    function dgettext($domain, $text) {
1108        return $text;
1109    }
1110
1111    /**
1112    * Translates text by domain and category
1113    *
1114    * @access public
1115    * @param string $domain the language to translate the text into
1116    * @param string $text the text to be translated
1117    * @param string $category the language dialect to use
1118    * @return string translated text
1119    */
1120    function dcgettext($domain, $text, $category) {
1121        return $text;
1122    }
1123
1124    /**
1125    * Binds the text domain
1126    *
1127    * @access public
1128    * @param string $domain the language to translate the text into
1129    * @param string
1130    * @return string translated text
1131    */
1132    function bindtextdomain($domain, $directory) {
1133        return $domain;
1134    }
1135
1136    /**
1137    * Sets the text domain
1138    *
1139    * @access public
1140    * @param string $domain the language to translate the text into
1141    * @return string translated text
1142    */
1143    function textdomain($domain) {
1144        return $domain;
1145    }
1146}
1147
1148?>
Note: See TracBrowser for help on using the repository browser.