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

Last change on this file since 792 was 792, checked in by anonymous, 14 months ago

Backport dump() function from trunk

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