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

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

Q - fixed bug in 1.1dev

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