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

Last change on this file since 257 was 257, checked in by quinn, 17 years ago

Added a function to highlight words matching a search query highlightWords().

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