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

Last change on this file since 255 was 255, checked in by jordan, 17 years ago

Bugs fixed via Jordan.

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