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

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

Minor

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