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

Last change on this file since 782 was 760, checked in by anonymous, 2 years ago

Add humanTime() function

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