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

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

Backport dump() function from trunk

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