source: tags/2.0.2/lib/Utilities.inc.php @ 480

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

Removed an errant 's'.

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