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

Last change on this file since 180 was 180, checked in by scdev, 18 years ago

Q - set limit to the length of logged messages. Added timeElapsed to Utilities.inc.php.

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