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

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