source: branches/1.1dev/lib/Utilities.inc.php @ 569

Last change on this file since 569 was 423, checked in by anonymous, 11 years ago

Backporting fixes to v1.1

File size: 24.5 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 *
31 * @return string Dump of var.
32 */
33function getDump($var)
34{
35    ob_start();
36    print_r($var);
37    $d = ob_get_contents();
38    ob_end_clean();
39    return $d;
40}
41
42/**
43 * Return dump as cleaned text. Useful for dumping data into emails.
44 *
45 * @param  mixed $var      Variable to dump.
46 *
47 * @return string Dump of var.
48 */
49function fancyDump($var, $indent='')
50{
51    $output = '';
52    if (is_array($var)) {
53        foreach ($var as $k=>$v) {
54            $k = ucfirst(strtolower(str_replace(array('_', '  '), ' ', $k)));
55            if (is_array($v)) {
56                $output .= sprintf("\n%s%s: %s\n", $indent, $k, fancyDump($v, $indent . $indent));
57            } else {
58                $output .= sprintf("%s%s: %s\n", $indent, $k, $v);
59            }
60        }
61    } else {
62        $output .= sprintf("%s%s\n", $indent, $var);
63    }
64    return $output;
65}
66
67/**
68 * Returns text with appropriate html translations.
69 *
70 * @param  string $txt              Text to clean.
71 * @param  bool   $preserve_html    If set to true, oTxt will not translage <, >, ", or '
72 *                                  characters into HTML entities. This allows HTML to pass
73 *                                  through unmunged.
74 *
75 * @return string                   Cleaned text.
76 */
77function oTxt($txt, $preserve_html=false)
78{
79    global $CFG;
80
81    $search = array();
82    $replace = array();
83
84    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
85    $search['retain_ampersand']     = '/&amp;/';
86    $replace['retain_ampersand']    = '&';
87
88    if ($preserve_html) {
89        // Convert characters that must remain non-entities for displaying HTML.
90        $search['retain_left_angle']       = '/&lt;/';
91        $replace['retain_left_angle']      = '<';
92       
93        $search['retain_right_angle']      = '/&gt;/';
94        $replace['retain_right_angle']     = '>';
95       
96        $search['retain_single_quote']     = '/&#039;/';
97        $replace['retain_single_quote']    = "'";
98       
99        $search['retain_double_quote']     = '/&quot;/';
100        $replace['retain_double_quote']    = '"';
101    }
102
103    // & becomes &amp;
104    $search['ampersand']        = '/&((?![\w\d#]{1,10};))/';
105    $replace['ampersand']       = '&amp;\\1';
106
107    return preg_replace($search, $replace, htmlentities($txt, ENT_QUOTES, $CFG->character_set));
108}
109
110/**
111 * Returns text with stylistic modifications.
112 *
113 * @param  string   $txt  Text to clean.
114 *
115 * @return string         Cleaned text.
116 */
117function fancyTxt($txt)
118{
119    $search = array();
120    $replace = array();
121
122    // "double quoted text"  becomes  &ldquo;double quoted text&rdquo;
123    $search['double_quotes']    = '/(^|[^\w=])(?:"|&quot;|&#34;|&#x22;|&ldquo;)([^"]+?)(?:"|&quot;|&#34;|&#x22;|&rdquo;)([^\w]|$)/'; // " is the same as &quot; and &#34; and &#x22;
124    $replace['double_quotes']   = '\\1&ldquo;\\2&rdquo;\\3';
125
126    // text's apostrophes  become  text&rsquo;s apostrophes
127    $search['apostrophe']       = '/(\w)(?:\'|&#39;)(\w)/';
128    $replace['apostrophe']      = '\\1&rsquo;\\2';
129
130    // "single quoted text"  becomes  &lsquo;single quoted text&rsquo;
131    $search['single_quotes']    = '/(^|[^\w=])(?:\'|&#39;|&lsquo;)([^\']+?)(?:\'|&#39;|&rsquo;)([^\w]|$)/';
132    $replace['single_quotes']   = '\\1&lsquo;\\2&rsquo;\\3';
133   
134    // em--dashes  become em&mdash;dashes
135    $search['em_dash']          = '/(\s*[^!<-])--([^>-]\s*)/';
136    $replace['em_dash']         = '\\1&mdash;\\2';
137   
138    // & becomes &amp;
139    $search['ampersand']        = '/&((?![\w\d#]{1,10};))/';
140    $replace['ampersand']       = '&amp;\\1';
141
142    return preg_replace($search, $replace, $txt);
143}
144
145/**
146 * Turns "a really long string" into "a rea...string"
147 *
148 * @access  public
149 * @param   string  $str    Input string
150 * @param   int     $len    Maximum string length.
151 * @param   string  $where  Where to cut the string. One of: 'start', 'middle', or 'end'.
152 * @return  string          Truncated output string
153 * @author  Quinn Comendant <quinn@strangecode.com>
154 * @since   29 Mar 2006 13:48:49
155 */
156function truncate($str, $len, $where='end', $delim='
')
157{
158    if ($len <= 3 || mb_strlen($str) <= 3) {
159        return '';
160    }
161    $part1 = floor(($len - 3) / 2);
162    $part2 = ceil(($len - 3) / 2);
163    switch ($where) {
164    case 'start' :
165        return preg_replace(array(sprintf('/^.{4,}(.{%s})$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array($delim . '$1', $delim), $str);
166        break;
167    default :
168    case 'middle' :
169        return preg_replace(array(sprintf('/^(.{%s}).{4,}(.{%s})$/sU', $part1, $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim . '$2', $delim), $str);
170        break;   
171    case 'end' :
172        return preg_replace(array(sprintf('/^(.{%s}).{4,}$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim, $delim), $str);
173        break;
174    }
175}
176   
177/**
178 * Generates a hexadecimal html color based on provided word.
179 *
180 * @access public
181 *
182 * @param  string $text  A string for which to convert to color.
183 *
184 * @return string  A hexadecimal html color.
185 */
186function getTextColor($text, $method=1)
187{
188    $hash = md5($text);
189    $rgb = array(
190        substr($hash, 0, 1),
191        substr($hash, 1, 1),
192        substr($hash, 2, 1),
193        substr($hash, 3, 1),
194        substr($hash, 4, 1),
195        substr($hash, 5, 1),
196    );
197
198    switch ($method) {
199    case 1 :
200    default :
201        // Reduce all hex values slighly to avoid all white.
202        array_walk($rgb, create_function('&$v', '$v = dechex(round(hexdec($v) * 0.87));'));
203        break;
204    case 2 :
205        foreach ($rgb as $i => $v) {
206            if (hexdec($v) > hexdec('c')) {
207                $rgb[$i] = dechex(hexdec('f') - hexdec($v));
208            }
209        }
210        break;
211    }
212
213    return join('', $rgb);
214}
215
216/**
217 * Encodes a string into unicode values 128-255.
218 * Useful for hiding an email address from spambots.
219 *
220 * @access  public
221 *
222 * @param   string   $text   A line of text to encode.
223 *
224 * @return  string   Encoded text.
225 */
226function encodeAscii($text)
227{
228    $ouput = '';
229    $num = strlen($text);
230    for ($i=0; $i<$num; $i++) {
231        $output .= sprintf('&#%03s', ord($text{$i}));
232    }
233    return $output;
234}
235
236/**
237 * Encodes an email into a user (at) domain (dot) com format.
238 *
239 * @access  public
240 * @param   string   $email   An email to encode.
241 * @param   string   $at      Replaces the @.
242 * @param   string   $dot     Replaces the ..
243 * @return  string   Encoded email.
244 */
245function encodeEmail($email, $at=' at ', $dot=' dot ')
246{
247    $search = array('/@/', '/\./');
248    $replace = array($at, $dot);
249    return preg_replace($search, $replace, $email);
250}
251
252/**
253 * Return a human readable filesize.
254 *
255 * @param       int    $size        Size
256 * @param       int    $unit        The maximum unit
257 * @param       int    $format      The return string format
258 * @author      Aidan Lister <aidan@php.net>
259 * @version     1.1.0
260 */
261function humanFileSize($size, $unit=null, $format='%01.2f %s')
262{
263    // Units
264    $units = array('B', 'KB', 'MB', 'GB', 'TB');
265    $ii = count($units) - 1;
266 
267    // Max unit
268    $unit = array_search((string) $unit, $units);
269    if ($unit === null || $unit === false) {
270        $unit = $ii;
271    }
272 
273    // Loop
274    $i = 0;
275    while ($unit != $i && $size >= 1024 && $i < $ii) {
276        $size /= 1024;
277        $i++;
278    }
279 
280    return sprintf($format, $size, $units[$i]);
281}
282
283/**
284 * If $var is net set or null, set it to $default. Otherwise leave it alone.
285 * Returns the final value of $var. Use to find a default value of one is not avilable.
286 *
287 * @param  mixed $var       The variable that is being set.
288 * @param  mixed $default   What to set it to if $val is not currently set.
289 * @return mixed            The resulting value of $var.
290 */
291function setDefault(&$var, $default='')
292{
293    if (!isset($var)) {
294        $var = $default;
295    }
296    return $var;
297}
298
299/**
300 * Like preg_quote() except for arrays, it takes an array of strings and puts
301 * a backslash in front of every character that is part of the regular
302 * expression syntax.
303 *
304 * @param  array $array    input array
305 * @param  array $delim    optional character that will also be excaped.
306 *
307 * @return array    an array with the same values as $array1 but shuffled
308 */
309function pregQuoteArray($array, $delim='/')
310{
311    if (!empty($array)) {
312        if (is_array($array)) {
313            foreach ($array as $key=>$val) {
314                $quoted_array[$key] = preg_quote($val, $delim);
315            }
316            return $quoted_array;
317        } else {
318            return preg_quote($array, $delim);
319        }
320    }
321}
322
323/**
324 * Converts a PHP Array into encoded URL arguments and return them as an array.
325 *
326 * @param  mixed $data        An array to transverse recursively, or a string
327 *                            to use directly to create url arguments.
328 * @param  string $prefix     The name of the first dimension of the array.
329 *                            If not specified, the first keys of the array will be used.
330 *
331 * @return array              URL with array elements as URL key=value arguments.
332 */
333function urlEncodeArray($data, $prefix='', $_return=true) {
334   
335    // Data is stored in static variable.
336    static $args;
337   
338    if (is_array($data)) {
339        foreach ($data as $key => $val) {
340            // If the prefix is empty, use the $key as the name of the first dimension of the "array".
341            // ...otherwise, append the key as a new dimension of the "array".
342            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
343            // Enter recursion.
344            urlEncodeArray($val, $new_prefix, false);
345        }
346    } else {
347        // We've come to the last dimension of the array, save the "array" and it's value.
348        $args[$prefix] = urlencode($data);
349    }
350   
351    if ($_return) {
352        // This is not a recursive execution. All recursion is complete.
353        // Reset static var and return the result.
354        $ret = $args;
355        $args = array();
356        return is_array($ret) ? $ret : array();
357    }
358}
359
360/**
361 * Converts a PHP Array into encoded URL arguments and return them in a string.
362 *
363 * @param  mixed $data        An array to transverse recursively, or a string
364 *                            to use directly to create url arguments.
365 * @param  string $prefix     The name of the first dimension of the array.
366 *                            If not specified, the first keys of the array will be used.
367 *
368 * @return string url         A string ready to append to a url.
369 */
370function urlEncodeArrayToString($data, $prefix='') {
371   
372    $array_args = urlEncodeArray($data, $prefix);
373    $url_args = '';
374    $delim = '';
375    foreach ($array_args as $key=>$val) {
376        $url_args .= $delim . $key . '=' . $val;
377        $delim = ini_get('arg_separator.output');
378    }
379    return $url_args;
380}
381
382/**
383 * An alternative to "shuffle()" that actually works.
384 *
385 * @param  array $array1   input array
386 * @param  array $array2   argument used internally through recursion
387 *
388 * @return array    an array with the same values as $array1 but shuffled
389 */
390function arrayRand(&$array1, $array2 = array())
391{
392    if (!sizeof($array1)) {
393        return array();
394    }
395   
396    srand((double) microtime() * 10000000);
397    $rand = array_rand($array1);
398   
399    $array2[] = $array1[$rand];
400    unset ($array1[$rand]);
401   
402    return $array2 + arrayRand($array1, $array2);
403}
404
405/**
406 * Fills an arrray with the result from a multiple ereg search.
407 * Curtesy of Bruno - rbronosky@mac.com - 10-May-2001
408 * Blame him for the funky do...while loop.
409 *
410 * @param  mixed $pattern   regular expression needle
411 * @param  mixed $string   haystack
412 *
413 * @return array    populated with each found result
414 */
415function eregAll($pattern, $string)
416{
417    do {
418        if (!ereg($pattern, $string, $temp)) {
419             continue;
420        }
421        $string = str_replace($temp[0], '', $string);
422        $results[] = $temp;
423    } while (ereg($pattern, $string, $temp));
424    return $results;
425}
426
427/**
428 * Prints the word "checked" if a variable is set, and optionally matches
429 * the desired value, otherwise prints nothing,
430 * used for printing the word "checked" in a checkbox form input.
431 *
432 * @param  mixed $var     the variable to compare
433 * @param  mixed $value   optional, what to compare with if a specific value is required.
434 */
435function frmChecked($var, $value=null)
436{
437    if (func_num_args() == 1 && $var) {
438        // 'Checked' if var is true.
439        echo ' checked="checked" ';
440    } else if (func_num_args() == 2 && $var == $value) {
441        // 'Checked' if var and value match.
442        echo ' checked="checked" ';
443    } else if (func_num_args() == 2 && is_array($var)) {
444        // 'Checked' if the value is in the key or the value of an array.
445        if (isset($var[$value])) {
446            echo ' checked="checked" ';
447        } else if (in_array($value, $var)) {
448            echo ' checked="checked" ';
449        }
450    }
451}
452
453/**
454 * prints the word "selected" if a variable is set, and optionally matches
455 * the desired value, otherwise prints nothing,
456 * otherwise prints nothing, used for printing the word "checked" in a
457 * select form input
458 *
459 * @param  mixed $var     the variable to compare
460 * @param  mixed $value   optional, what to compare with if a specific value is required.
461 */
462function frmSelected($var, $value=null)
463{
464    if (func_num_args() == 1 && $var) {
465        // 'selected' if var is true.
466        echo ' selected="selected" ';
467    } else if (func_num_args() == 2 && $var == $value) {
468        // 'selected' if var and value match.
469        echo ' selected="selected" ';
470    } else if (func_num_args() == 2 && is_array($var)) {
471        // 'selected' if the value is in the key or the value of an array.
472        if (isset($var[$value])) {
473            echo ' selected="selected" ';
474        } else if (in_array($value, $var)) {
475            echo ' selected="selected" ';
476        }
477    }
478}
479
480/**
481 * Adds slashes to values of an array and converts the array to a
482 * comma delimited list. If value provided is not an array or is empty
483 * return nothing. This is useful for putting values coming in from
484 * posted checkboxes into a SET column of a database.
485 *
486 * @param  array $array   Array to convert.
487 * @return string         Comma list of array values.
488 */
489function dbArrayToList($array)
490{
491    if (is_array($array) && !empty($array)) {
492        return join(',', array_map('mysql_real_escape_string', array_keys($array)));
493    }
494}
495
496/**
497 * Converts a human string date into a SQL-safe date.
498 * Dates nearing infinity use the date 2038-01-01 so conversion to unix time
499 * format remain within valid range.
500 *
501 * @param  array $date     String date to convert.
502 * @param  array $format   Date format to pass to date().
503 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
504 *
505 * @return string          SQL-safe date.
506 */
507function strToSQLDate($date, $format='Y-m-d H:i:s')
508{
509    // Translate the human string date into SQL-safe date format.
510    if (empty($date) || '0000-00-00' == $date || strtotime($date) === -1) {
511        $sql_date = '0000-00-00';
512    } else {
513        $sql_date = date($format, strtotime($date));
514    }
515   
516    return $sql_date;
517}
518
519/**
520 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
521 * array, stripslashes is run on each value, recursively, and the stripped
522 * array is returned
523 *
524 * @param  mixed $var   The string or array to un-quote, if necessary.
525 * @return mixed        $var, minus any magic quotes.
526 */
527function dispelMagicQuotes($var)
528{
529    static $magic_quotes_gpc;
530   
531    if (!isset($magic_quotes_gpc)) {
532        $magic_quotes_gpc = get_magic_quotes_gpc();
533    }
534   
535    if ($magic_quotes_gpc) {
536        if (!is_array($var)) {
537            $var = stripslashes($var);
538        } else {
539            foreach ($var as $key=>$val) {
540                if (is_array($val)) {
541                    $var[$key] = dispelMagicQuotes($val);
542                } else {
543                    $var[$key] = stripslashes($val);
544                }
545            }
546        }
547    }
548    return $var;
549}
550
551/**
552 * Get a form variable from GET or POST data, stripped of magic
553 * quotes if necessary.
554 *
555 * @param string $var (optional) The name of the form variable to look for.
556 * @param string $default (optional) The value to return if the
557 *                                   variable is not there.
558 *
559 * @return mixed      A cleaned GET or POST if no $var specified.
560 * @return string     A cleaned form $var if found, or $default.
561 */
562function getFormData($var=null, $default=null)
563{
564    if ('POST' == $_SERVER['REQUEST_METHOD'] && is_null($var)) {
565        return dispelMagicQuotes($_POST);
566    } else if ('GET' == $_SERVER['REQUEST_METHOD'] && is_null($var)) {
567        return dispelMagicQuotes($_GET);
568    }
569    if (isset($_POST[$var])) {
570        return dispelMagicQuotes($_POST[$var]);
571    } else if (isset($_GET[$var])) {
572        return dispelMagicQuotes($_GET[$var]);
573    } else {
574        return $default;
575    }
576}
577function getPost($var=null, $default=null)
578{
579    if (is_null($var)) {
580        return dispelMagicQuotes($_POST);
581    }
582    if (isset($_POST[$var])) {
583        return dispelMagicQuotes($_POST[$var]);
584    } else {
585        return $default;
586    }
587}
588function getGet($var=null, $default=null)
589{
590    if (is_null($var)) {
591        return dispelMagicQuotes($_GET);
592    }
593    if (isset($_GET[$var])) {
594        return dispelMagicQuotes($_GET[$var]);
595    } else {
596        return $default;
597    }
598}
599
600/**
601 * Signs a value using md5 and a simple text key. In order for this
602 * function to be useful (i.e. secure) the key must be kept secret, which
603 * means keeping it as safe as database credentials. Putting it into an
604 * environment variable set in httpd.conf is a good place.
605 *
606 * @access  public
607 *
608 * @param   string  $val    The string to sign.
609 * @param   string  $key    (Optional) A text key to use for computing the signature.
610 *
611 * @return  string  The original value with a signature appended.
612 */
613function addSignature($val, $key=null)
614{
615    global $CFG;
616   
617    if ('' == $val) {
618        logMsg(sprintf('Adding signature to empty string.', null), LOG_NOTICE, __FILE__, __LINE__);
619    }
620   
621    if (!isset($key)) {
622        $key = $CFG->signing_key;
623    }
624
625    return $val . '-' . substr(md5($val . $key), 0, 18);
626}
627
628/**
629 * Strips off the signature appended by addSignature().
630 *
631 * @access  public
632 *
633 * @param   string  $signed_val     The string to sign.
634 *
635 * @return  string  The original value with a signature removed.
636 */
637function removeSignature($signed_val)
638{
639    return substr($signed_val, 0, strrpos($signed_val, '-'));
640}
641
642
643/**
644 * Verifies a signature appened to a value by addSignature().
645 *
646 * @access  public
647 *
648 * @param   string  $signed_val A value with appended signature.
649 * @param   string  $key        (Optional) A text key to use for computing the signature.
650 *
651 * @return  bool    True if the signature matches the var.
652 */
653function verifySignature($signed_val, $key=null)
654{
655    // Strip the value from the signed value.
656    $val = substr($signed_val, 0, strrpos($signed_val, '-'));
657    // If the signed value matches the original signed value we consider the value safe.
658    if ($signed_val == addSignature($val, $key)) {
659        // Signature verified.
660        return true;
661    } else {
662        return false;
663    }
664}
665
666/**
667 * Stub functions used when installation does not have
668 * GNU gettext extension installed
669 */
670if (!extension_loaded('gettext')) {
671    /**
672    * Translates text
673    *
674    * @access public
675    * @param string $text the text to be translated
676    * @return string translated text
677    */
678    function gettext($text) {
679        return $text;
680    }
681   
682    /**
683    * Translates text
684    *
685    * @access public
686    * @param string $text the text to be translated
687    * @return string translated text
688    */
689    function _($text) {
690        return $text;
691    }
692   
693    /**
694    * Translates text by domain
695    *
696    * @access public
697    * @param string $domain the language to translate the text into
698    * @param string $text the text to be translated
699    * @return string translated text
700    */
701    function dgettext($domain, $text) {
702        return $text;
703    }
704   
705    /**
706    * Translates text by domain and category
707    *
708    * @access public
709    * @param string $domain the language to translate the text into
710    * @param string $text the text to be translated
711    * @param string $category the language dialect to use
712    * @return string translated text
713    */
714    function dcgettext($domain, $text, $category) {
715        return $text;
716    }
717   
718    /**
719    * Binds the text domain
720    *
721    * @access public
722    * @param string $domain the language to translate the text into
723    * @param string
724    * @return string translated text
725    */
726    function bindtextdomain($domain, $directory) {
727        return $domain;
728    }
729   
730    /**
731    * Sets the text domain
732    *
733    * @access public
734    * @param string $domain the language to translate the text into
735    * @return string translated text
736    */
737    function textdomain($domain) {
738        return $domain;
739    }
740}
741
742/**
743 * Sends empty output to the browser and flushes the php buffer so the client
744 * will see data before the page is finished processing.
745 */
746function flushBuffer() {
747    echo str_repeat('          ', 205);
748    flush();
749}
750
751/**
752 * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
753 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
754 *
755 * @access  public
756 *
757 * @param   string  $email     Email address to add.
758 * @param   string  $list      Name of list to add to.
759 * @param   bool    $send_welcome_message   True to send welcome message to subscriber.
760 *
761 * @return  bool    True on success, false on failure.
762 */
763function mailmanAddMember($email, $list, $send_welcome_message=false)
764{
765   $add_members = '/usr/lib/mailman/bin/add_members';
766    if (true || is_executable($add_members) && is_readable($add_members)) {
767        $welcome_msg = $send_welcome_message ? 'y' : 'n';
768        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);
769        $stdout = is_array($stdout) ? getDump($stdout) : $stdout;
770        if (0 == $return_code) {
771            logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
772            return true;
773        } else {
774            logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
775            return false;
776        }
777    } else {
778        logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
779        return false;
780    }
781}
782
783/**
784 * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
785 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
786 *
787 * @access  public
788 *
789 * @param   string  $email     Email address to add.
790 * @param   string  $list      Name of list to add to.
791 * @param   bool    $send_user_ack   True to send goodbye message to subscriber.
792 *
793 * @return  bool    True on success, false on failure.
794 */
795function mailmanRemoveMember($email, $list, $send_user_ack=false)
796{
797    $remove_members = '/usr/lib/mailman/bin/remove_members';
798    if (true || is_executable($remove_members) && is_readable($remove_members)) {
799        $userack = $send_user_ack ? '' : '--nouserack';
800        exec(sprintf('/usr/bin/sudo %s %s --noadminack %s %s', escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
801        $stdout = is_array($stdout) ? getDump($stdout) : $stdout;
802        if (0 == $return_code) {
803            logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email, $stdout), LOG_INFO, __FILE__, __LINE__);
804            return true;
805        } else {
806            logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
807            return false;
808        }
809    } else {
810        logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
811        return false;
812    }
813}
814
815
816
817?>
Note: See TracBrowser for help on using the repository browser.