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

Last change on this file since 646 was 646, checked in by anonymous, 6 years ago

Add hyperlinkTxt function

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