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

Last change on this file since 363 was 363, checked in by quinn, 15 years ago

Fixed a bug in the humanTime() function.

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