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

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

Added a GPL license info header to all source files. Updated license to GPL v3.

File size: 36.7 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    $last_unit = 'second';
382    foreach ($units as $k => $v) {
383        if ($max_unit != $k && $seconds >= $v[0]) {
384            $final_time = $seconds / $v[0];
385            $last_unit = $k;
386        }
387    }
388    $final_time = sprintf($format, $final_time);
389    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$last_unit][1] : $units[$last_unit][2]));   
390}
391
392/**
393 * Tests the existence of a file anywhere in the include path.
394 *
395 * @param   string  $file   File in include path.
396 * @return  mixed           False if file not found, the path of the file if it is found.
397 * @author  Quinn Comendant <quinn@strangecode.com>
398 * @since   03 Dec 2005 14:23:26
399 */
400function fileExistsIncludePath($file)
401{
402    $app =& App::getInstance();
403   
404    foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) {
405        $fullpath = $path . DIRECTORY_SEPARATOR . $file;
406        if (file_exists($fullpath)) {
407            $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__);
408            return $fullpath;
409        } else {
410            $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__);
411            return false;
412        }
413    }
414}
415
416/**
417 * Returns stats of a file from the include path.
418 *
419 * @param   string  $file   File in include path.
420 * @param   mixed   $stat   Which statistic to return (or null to return all).
421 * @return  mixed           Value of requested key from fstat(), or false on error.
422 * @author  Quinn Comendant <quinn@strangecode.com>
423 * @since   03 Dec 2005 14:23:26
424 */
425function statIncludePath($file, $stat=null)
426{
427    // Open file pointer read-only using include path.
428    if ($fp = fopen($file, 'r', true)) {
429        // File opened successfully, get stats.
430        $stats = fstat($fp);
431        fclose($fp);
432        // Return specified stats.
433        return is_null($stat) ? $stats : $stats[$stat];
434    } else {
435        return false;
436    }
437}
438
439/*
440* Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5.
441*
442* @access   public
443* @param    string  $filename   Path to file.
444* @param    string  $content    Data to write into file.
445* @return   bool                Success or failure.
446* @author   Quinn Comendant <quinn@strangecode.com>
447* @since    11 Apr 2006 22:48:30
448*/
449function filePutContents($filename, $content)
450{
451    $app =& App::getInstance();
452
453    // Open file for writing and truncate to zero length.
454    if ($fp = fopen($filename, 'w')) {
455        if (flock($fp, LOCK_EX)) {
456            if (!fwrite($fp, $content, mb_strlen($content))) {
457                $app->logMsg(sprintf('Failed writing to file: %s', $filename), LOG_ERR, __FILE__, __LINE__);
458                fclose($fp);
459                return false;
460            }
461            flock($fp, LOCK_UN);
462        } else {
463            $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
464            fclose($fp);
465            return false;
466        }
467        fclose($fp);
468        // Success!
469        $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
470        return true;
471    } else {
472        $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
473        return false;
474    }
475}
476
477
478/**
479 * If $var is net set or null, set it to $default. Otherwise leave it alone.
480 * Returns the final value of $var. Use to find a default value of one is not available.
481 *
482 * @param  mixed $var       The variable that is being set.
483 * @param  mixed $default   What to set it to if $val is not currently set.
484 * @return mixed            The resulting value of $var.
485 */
486function setDefault(&$var, $default='')
487{
488    if (!isset($var)) {
489        $var = $default;
490    }
491    return $var;
492}
493
494/**
495 * Like preg_quote() except for arrays, it takes an array of strings and puts
496 * a backslash in front of every character that is part of the regular
497 * expression syntax.
498 *
499 * @param  array $array    input array
500 * @param  array $delim    optional character that will also be escaped.
501 * @return array    an array with the same values as $array1 but shuffled
502 */
503function pregQuoteArray($array, $delim='/')
504{
505    if (!empty($array)) {
506        if (is_array($array)) {
507            foreach ($array as $key=>$val) {
508                $quoted_array[$key] = preg_quote($val, $delim);
509            }
510            return $quoted_array;
511        } else {
512            return preg_quote($array, $delim);
513        }
514    }
515}
516
517/**
518 * Converts a PHP Array into encoded URL arguments and return them as an array.
519 *
520 * @param  mixed $data        An array to transverse recursively, or a string
521 *                            to use directly to create url arguments.
522 * @param  string $prefix     The name of the first dimension of the array.
523 *                            If not specified, the first keys of the array will be used.
524 * @return array              URL with array elements as URL key=value arguments.
525 */
526function urlEncodeArray($data, $prefix='', $_return=true)
527{
528
529    // Data is stored in static variable.
530    static $args;
531
532    if (is_array($data)) {
533        foreach ($data as $key => $val) {
534            // If the prefix is empty, use the $key as the name of the first dimension of the "array".
535            // ...otherwise, append the key as a new dimension of the "array".
536            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
537            // Enter recursion.
538            urlEncodeArray($val, $new_prefix, false);
539        }
540    } else {
541        // We've come to the last dimension of the array, save the "array" and its value.
542        $args[$prefix] = urlencode($data);
543    }
544
545    if ($_return) {
546        // This is not a recursive execution. All recursion is complete.
547        // Reset static var and return the result.
548        $ret = $args;
549        $args = array();
550        return is_array($ret) ? $ret : array();
551    }
552}
553
554/**
555 * Converts a PHP Array into encoded URL arguments and return them in a string.
556 *
557 * @param  mixed $data        An array to transverse recursively, or a string
558 *                            to use directly to create url arguments.
559 * @param  string $prefix     The name of the first dimension of the array.
560 *                            If not specified, the first keys of the array will be used.
561 * @return string url         A string ready to append to a url.
562 */
563function urlEncodeArrayToString($data, $prefix='')
564{
565
566    $array_args = urlEncodeArray($data, $prefix);
567    $url_args = '';
568    $delim = '';
569    foreach ($array_args as $key=>$val) {
570        $url_args .= $delim . $key . '=' . $val;
571        $delim = ini_get('arg_separator.output');
572    }
573    return $url_args;
574}
575
576/**
577 * Fills an array with the result from a multiple ereg search.
578 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
579 *
580 * @param  mixed $pattern   regular expression needle
581 * @param  mixed $string   haystack
582 * @return array    populated with each found result
583 */
584function eregAll($pattern, $string)
585{
586    do {
587        if (!mb_ereg($pattern, $string, $temp)) {
588             continue;
589        }
590        $string = str_replace($temp[0], '', $string);
591        $results[] = $temp;
592    } while (mb_ereg($pattern, $string, $temp));
593    return $results;
594}
595
596/**
597 * Prints the word "checked" if a variable is set, and optionally matches
598 * the desired value, otherwise prints nothing,
599 * used for printing the word "checked" in a checkbox form input.
600 *
601 * @param  mixed $var     the variable to compare
602 * @param  mixed $value   optional, what to compare with if a specific value is required.
603 */
604function frmChecked($var, $value=null)
605{
606    if (func_num_args() == 1 && $var) {
607        // 'Checked' if var is true.
608        echo ' checked="checked" ';
609    } else if (func_num_args() == 2 && $var == $value) {
610        // 'Checked' if var and value match.
611        echo ' checked="checked" ';
612    } else if (func_num_args() == 2 && is_array($var)) {
613        // 'Checked' if the value is in the key or the value of an array.
614        if (isset($var[$value])) {
615            echo ' checked="checked" ';
616        } else if (in_array($value, $var)) {
617            echo ' checked="checked" ';
618        }
619    }
620}
621
622/**
623 * prints the word "selected" if a variable is set, and optionally matches
624 * the desired value, otherwise prints nothing,
625 * otherwise prints nothing, used for printing the word "checked" in a
626 * select form input
627 *
628 * @param  mixed $var     the variable to compare
629 * @param  mixed $value   optional, what to compare with if a specific value is required.
630 */
631function frmSelected($var, $value=null)
632{
633    if (func_num_args() == 1 && $var) {
634        // 'selected' if var is true.
635        echo ' selected="selected" ';
636    } else if (func_num_args() == 2 && $var == $value) {
637        // 'selected' if var and value match.
638        echo ' selected="selected" ';
639    } else if (func_num_args() == 2 && is_array($var)) {
640        // 'selected' if the value is in the key or the value of an array.
641        if (isset($var[$value])) {
642            echo ' selected="selected" ';
643        } else if (in_array($value, $var)) {
644            echo ' selected="selected" ';
645        }
646    }
647}
648
649/**
650 * Adds slashes to values of an array and converts the array to a comma
651 * delimited list. If value provided is a string return the string
652 * escaped.  This is useful for putting values coming in from posted
653 * checkboxes into a SET column of a database.
654 *
655 *
656 * @param  array $in      Array to convert.
657 * @return string         Comma list of array values.
658 */
659function escapedList($in, $separator="', '")
660{
661    $db =& DB::getInstance();
662   
663    if (is_array($in) && !empty($in)) {
664        return join($separator, array_map(array($db, 'escapeString'), $in));
665    } else {
666        return $db->escapeString($in);
667    }
668}
669
670/**
671 * Converts a human string date into a SQL-safe date.  Dates nearing
672 * infinity use the date 2038-01-01 so conversion to unix time format
673 * remain within valid range.
674 *
675 * @param  array $date     String date to convert.
676 * @param  array $format   Date format to pass to date().
677 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
678 * @return string          SQL-safe date.
679 */
680function strToSQLDate($date, $format='Y-m-d H:i:s')
681{
682    // Translate the human string date into SQL-safe date format.
683    if (empty($date) || mb_strpos($date, '0000-00-00') !== false || strtotime($date) === -1 || strtotime($date) === false) {
684        // Return a string of zero time, formatted the same as $format.
685        return strtr($format, array(
686            'Y' => '0000',
687            'm' => '00',
688            'd' => '00',
689            'H' => '00',
690            'i' => '00',
691            's' => '00',
692        ));
693    } else {
694        return date($format, strtotime($date));
695    }
696}
697
698/**
699 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
700 * array, stripslashes is run on each value, recursively, and the stripped
701 * array is returned.
702 *
703 * @param  mixed $var   The string or array to un-quote, if necessary.
704 * @return mixed        $var, minus any magic quotes.
705 */
706function dispelMagicQuotes($var)
707{
708    static $magic_quotes_gpc;
709
710    if (!isset($magic_quotes_gpc)) {
711        $magic_quotes_gpc = get_magic_quotes_gpc();
712    }
713
714    if ($magic_quotes_gpc) {
715        if (!is_array($var)) {
716            $var = stripslashes($var);
717        } else {
718            foreach ($var as $key=>$val) {
719                if (is_array($val)) {
720                    $var[$key] = dispelMagicQuotes($val);
721                } else {
722                    $var[$key] = stripslashes($val);
723                }
724            }
725        }
726    }
727    return $var;
728}
729
730/**
731 * Get a form variable from GET or POST data, stripped of magic
732 * quotes if necessary.
733 *
734 * @param string $var (optional) The name of the form variable to look for.
735 * @param string $default (optional) The value to return if the
736 *                                   variable is not there.
737 * @return mixed      A cleaned GET or POST if no $var specified.
738 * @return string     A cleaned form $var if found, or $default.
739 */
740function getFormData($var=null, $default=null)
741{
742    if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) {
743        return dispelMagicQuotes($_POST);
744    } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) {
745        return dispelMagicQuotes($_GET);
746    }
747    if (isset($_POST[$var])) {
748        return dispelMagicQuotes($_POST[$var]);
749    } else if (isset($_GET[$var])) {
750        return dispelMagicQuotes($_GET[$var]);
751    } else {
752        return $default;
753    }
754}
755function getPost($var=null, $default=null)
756{
757    if (is_null($var)) {
758        return dispelMagicQuotes($_POST);
759    }
760    if (isset($_POST[$var])) {
761        return dispelMagicQuotes($_POST[$var]);
762    } else {
763        return $default;
764    }
765}
766function getGet($var=null, $default=null)
767{
768    if (is_null($var)) {
769        return dispelMagicQuotes($_GET);
770    }
771    if (isset($_GET[$var])) {
772        return dispelMagicQuotes($_GET[$var]);
773    } else {
774        return $default;
775    }
776}
777
778/*
779* Sets a $_GET or $_POST variable.
780*
781* @access   public
782* @param    string  $key    The key of the request array to set.
783* @param    mixed   $val    The value to save in the request array.
784* @return   void
785* @author   Quinn Comendant <quinn@strangecode.com>
786* @version  1.0
787* @since    01 Nov 2009 12:25:29
788*/
789function putFormData($key, $val)
790{
791    if ('POST' == getenv('REQUEST_METHOD')) {
792        $_POST[$key] = $val;
793    } else if ('GET' == getenv('REQUEST_METHOD')) {
794        $_GET[$key] = $val;
795    }
796}
797
798/**
799 * Signs a value using md5 and a simple text key. In order for this
800 * function to be useful (i.e. secure) the key must be kept secret, which
801 * means keeping it as safe as database credentials. Putting it into an
802 * environment variable set in httpd.conf is a good place.
803 *
804 * @access  public
805 * @param   string  $val    The string to sign.
806 * @param   string  $salt   (Optional) A text key to use for computing the signature.
807 * @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.
808 * @return  string  The original value with a signature appended.
809 */
810function addSignature($val, $salt=null, $length=18)
811{
812    $app =& App::getInstance();
813   
814    if ('' == trim($val)) {
815        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
816        return '';
817    }
818
819    if (!isset($salt)) {
820        $salt = $app->getParam('signing_key');
821    }
822
823    return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
824}
825
826/**
827 * Strips off the signature appended by addSignature().
828 *
829 * @access  public
830 * @param   string  $signed_val     The string to sign.
831 * @return  string  The original value with a signature removed.
832 */
833function removeSignature($signed_val)
834{
835    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
836        return '';
837    }
838    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
839}
840
841
842/**
843 * Verifies a signature appened to a value by addSignature().
844 *
845 * @access  public
846 * @param   string  $signed_val A value with appended signature.
847 * @param   string  $salt       (Optional) A text key to use for computing the signature.
848 * @return  bool    True if the signature matches the var.
849 */
850function verifySignature($signed_val, $salt=null, $length=18)
851{
852    // All comparisons are done using lower-case strings.
853    $signed_val = mb_strtolower($signed_val);
854    // Strip the value from the signed value.
855    $val = removeSignature($signed_val);
856    // If the signed value matches the original signed value we consider the value safe.
857    if ($signed_val == addSignature($val, $salt, $length)) {
858        // Signature verified.
859        return true;
860    } else {
861        return false;
862    }
863}
864
865/**
866 * Sends empty output to the browser and flushes the php buffer so the client
867 * will see data before the page is finished processing.
868 */
869function flushBuffer()
870{
871    echo str_repeat('          ', 205);
872    flush();
873}
874
875/**
876 * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
877 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
878 *
879 * @access  public
880 * @param   string  $email     Email address to add.
881 * @param   string  $list      Name of list to add to.
882 * @param   bool    $send_welcome_message   True to send welcome message to subscriber.
883 * @return  bool    True on success, false on failure.
884 */
885function mailmanAddMember($email, $list, $send_welcome_message=false)
886{
887    $app =& App::getInstance();
888   
889    $add_members = '/usr/lib/mailman/bin/add_members';
890    /// FIXME: checking of executable is disabled.
891    if (true || is_executable($add_members) && is_readable($add_members)) {
892        $welcome_msg = $send_welcome_message ? 'y' : 'n';
893        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);
894        if (0 == $return_code) {
895            $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
896            return true;
897        } else {
898            $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
899            return false;
900        }
901    } else {
902        $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
903        return false;
904    }
905}
906
907/**
908 * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
909 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
910 *
911 * @access  public
912 * @param   string  $email     Email address to add.
913 * @param   string  $list      Name of list to add to.
914 * @param   bool    $send_user_ack   True to send goodbye message to subscriber.
915 * @return  bool    True on success, false on failure.
916 */
917function mailmanRemoveMember($email, $list, $send_user_ack=false)
918{
919    $app =& App::getInstance();
920   
921    $remove_members = '/usr/lib/mailman/bin/remove_members';
922    /// FIXME: checking of executable is disabled.
923    if (true || is_executable($remove_members) && is_readable($remove_members)) {
924        $userack = $send_user_ack ? '' : '--nouserack';
925        exec(sprintf("/usr/bin/sudo %s %s --noadminack '%s' '%s'", escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
926        if (0 == $return_code) {
927            $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
928            return true;
929        } else {
930            $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
931            return false;
932        }
933    } else {
934        $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
935        return false;
936    }
937}
938
939/**
940 * Returns the remote IP address, taking into consideration proxy servers.
941 *
942 * @param  bool $dolookup   If true we resolve to IP to a host name,
943 *                          if false we don't.
944 * @return string    IP address if $dolookup is false or no arg
945 *                   Hostname if $dolookup is true
946 */
947function getRemoteAddr($dolookup=false)
948{
949    $ip = getenv('HTTP_CLIENT_IP');
950    if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) {
951        $ip = getenv('HTTP_X_FORWARDED_FOR');
952        if (mb_strpos($ip, ',') !== false) {
953            // If HTTP_X_FORWARDED_FOR returns a comma-delimited list of IPs then return the first one (assuming the first is the original).
954            $ips = explode(',', $ip, 2);
955            $ip = $ips[0];
956        }
957        if (in_array($ip, array('', 'unknown', 'localhost', '127.0.0.1'))) {
958            $ip = getenv('REMOTE_ADDR');
959        }
960    }
961    return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip;
962}
963
964/**
965 * Tests whether a given IP address can be found in an array of IP address networks.
966 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
967 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
968 *
969 * @access  public
970 * @param   string  IP address to search for.
971 * @param   array   Array of networks to search within.
972 * @return  mixed   Returns the network that matched on success, false on failure.
973 */
974function ipInRange($ip, $networks)
975{
976    if (!is_array($networks)) {
977        $networks = array($networks);
978    }
979
980    $ip_binary = sprintf('%032b', ip2long($ip));
981    foreach ($networks as $network) {
982        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) {
983            // IP is in CIDR notation.
984            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
985            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
986            if (mb_substr($ip_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
987               // IP address is within the specified IP range.
988               return $network;
989            }
990        } else {
991            if ($ip === $network) {
992               // IP address exactly matches.
993               return $network;
994            }
995        }
996    }
997
998    return false;
999}
1000
1001/**
1002 * If the given $url is on the same web site, return true. This can be used to
1003 * prevent from sending sensitive info in a get query (like the SID) to another
1004 * domain.
1005 *
1006 * @param  string $url    the URI to test.
1007 * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another.
1008 */
1009function isMyDomain($url)
1010{
1011    static $urls = array();
1012
1013    if (!isset($urls[$url])) {
1014        if (!preg_match('|https?://[\w.]+/|', $url)) {
1015            // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg").
1016            $urls[$url] = true;
1017        } else {
1018            $urls[$url] = preg_match('|https?://[\w.]*' . preg_quote(getenv('HTTP_HOST'), '|') . '|i', $url);
1019        }
1020    }
1021    return $urls[$url];
1022}
1023
1024/**
1025 * Takes a URL and returns it without the query or anchor portion
1026 *
1027 * @param  string $url   any kind of URI
1028 * @return string        the URI with ? or # and everything after removed
1029 */
1030function stripQuery($url)
1031{
1032    return preg_replace('/[?#].*$/', '', $url);
1033}
1034
1035/**
1036 * Returns a fully qualified URL to the current script, including the query.
1037 *
1038 * @return string    a full url to the current script
1039 */
1040function absoluteMe()
1041{
1042    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
1043    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
1044}
1045
1046/**
1047 * Compares the current url with the referring url.
1048 *
1049 * @param  bool $exclude_query  Remove the query string first before comparing.
1050 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
1051 */
1052function refererIsMe($exclude_query=false)
1053{
1054    if ($exclude_query) {
1055        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
1056    } else {
1057        return (absoluteMe() == getenv('HTTP_REFERER'));
1058    }
1059}
1060
1061/**
1062 * Stub functions used when installation does not have
1063 * GNU gettext extension installed
1064 */
1065if (!extension_loaded('gettext')) {
1066    /**
1067    * Translates text
1068    *
1069    * @access public
1070    * @param string $text the text to be translated
1071    * @return string translated text
1072    */
1073    function gettext($text) {
1074        return $text;
1075    }
1076
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 _($text) {
1085        return $text;
1086    }
1087
1088    /**
1089    * Translates text by domain
1090    *
1091    * @access public
1092    * @param string $domain the language to translate the text into
1093    * @param string $text the text to be translated
1094    * @return string translated text
1095    */
1096    function dgettext($domain, $text) {
1097        return $text;
1098    }
1099
1100    /**
1101    * Translates text by domain and category
1102    *
1103    * @access public
1104    * @param string $domain the language to translate the text into
1105    * @param string $text the text to be translated
1106    * @param string $category the language dialect to use
1107    * @return string translated text
1108    */
1109    function dcgettext($domain, $text, $category) {
1110        return $text;
1111    }
1112
1113    /**
1114    * Binds the text domain
1115    *
1116    * @access public
1117    * @param string $domain the language to translate the text into
1118    * @param string
1119    * @return string translated text
1120    */
1121    function bindtextdomain($domain, $directory) {
1122        return $domain;
1123    }
1124
1125    /**
1126    * Sets the text domain
1127    *
1128    * @access public
1129    * @param string $domain the language to translate the text into
1130    * @return string translated text
1131    */
1132    function textdomain($domain) {
1133        return $domain;
1134    }
1135}
1136
1137
1138
1139?>
Note: See TracBrowser for help on using the repository browser.