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

Last change on this file since 331 was 331, checked in by quinn, 16 years ago

Truncating output from getDump when used for logging.

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