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

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

Q - fixed bug in truncate() for lines < 3 chars.

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