source: trunk/lib/Utilities.inc.php @ 734

Last change on this file since 734 was 729, checked in by anonymous, 4 years ago
File size: 60.1 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * Utilities.inc.php
25 */
26
27
28/**
29 * Print variable dump.
30 *
31 * @param  mixed    $var        The variable to dump.
32 * @param  bool     $display    Print the dump in <pre> tags or hide it in html comments (non-CLI only).
33 * @param  bool     $dump_method   Dump method. See SC_DUMP_* constants.
34 * @param  string   $file       Value of __FILE__.
35 * @param  string   $line       Value of __LINE__
36 */
37define('SC_DUMP_PRINT_R', 0);
38define('SC_DUMP_VAR_DUMP', 1);
39define('SC_DUMP_VAR_EXPORT', 2);
40function dump($var, $display=false, $dump_method=SC_DUMP_PRINT_R, $file='', $line='')
41{
42    $app =& App::getInstance();
43
44    if ($app->isCLI()) {
45        echo "DUMP FROM: $file $line\n";
46    } else {
47        echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n";
48    }
49
50    switch ($dump_method) {
51    case SC_DUMP_PRINT_R:
52    default:
53        // Print human-readable descriptions of invisible types.
54        if (null === $var) {
55            echo '(null)';
56        } else if (true === $var) {
57            echo '(bool: true)';
58        } else if (false === $var) {
59            echo '(bool: false)';
60        } else if (is_scalar($var) && '' === $var) {
61            echo '(empty string)';
62        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
63            echo '(only white space)';
64        } else {
65            print_r($var);
66        }
67        break;
68
69    case SC_DUMP_VAR_DUMP:
70        var_dump($var);
71        break;
72
73    case SC_DUMP_VAR_EXPORT:
74        var_export($var);
75        break;
76    }
77
78    if ($app->isCLI()) {
79        echo "\n";
80    } else {
81        echo $display ? "\n</pre><br />\n" : "\n-->\n";
82    }
83}
84
85/*
86* Log a PHP variable to javascript console. Relies on getDump(), below.
87*
88* @access   public
89* @param    mixed   $var      The variable to dump.
90* @param    string  $prefix   A short note to print before the output to make identifying output easier.
91* @param    string  $file     The value of __FILE__.
92* @param    string  $line     The value of __LINE__.
93* @return   null
94* @author   Quinn Comendant <quinn@strangecode.com>
95*/
96function jsDump($var, $prefix='jsDump', $file='-', $line='-')
97{
98    if (!empty($var)) {
99        ?>
100        <script type="text/javascript">
101        /* <![CDATA[ */
102        console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
103        /* ]]> */
104        </script>
105        <?php
106    }
107}
108
109/*
110* Return a string version of any variable, optionally serialized on one line.
111*
112* @access   public
113* @param    mixed   $var        The variable to dump.
114* @param    bool    $serialize  If true, remove line-endings. Useful for logging variables.
115* @return   string              The dumped variable.
116* @author   Quinn Comendant <quinn@strangecode.com>
117*/
118function getDump($var, $serialize=false)
119{
120    $app =& App::getInstance();
121
122    ob_start();
123    print_r($var);
124    $d = ob_get_contents();
125    ob_end_clean();
126    return $serialize ? preg_replace('/\s+/m' . $app->getParam('preg_u'), ' ', $d) : $d;
127}
128
129/*
130* Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts.
131* To output tab-style lists set $indent to "\t" and $depth to 0;
132* To output markdown-style lists set $indent to '- ' and $depth to 1;
133* Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php
134*
135* @param  array    $var        Variable to dump.
136* @param  string   $indent     A string to prepend indented lines.
137* @param  string   $depth      Starting depth of this iteration of recursion (set to 0 to have no initial indentation).
138* @return string               Pretty dump of $var.
139* @author   Quinn Comendant <quinn@strangecode.com>
140* @version 2.0
141*/
142function fancyDump($var, $indent='- ', $depth=1)
143{
144    $app =& App::getInstance();
145
146    $indent_str = str_repeat($indent, $depth);
147    $output = '';
148    if (is_array($var)) {
149        foreach ($var as $k=>$v) {
150            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
151            if (is_array($v)) {
152                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
153            } else {
154                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
155            }
156        }
157    } else {
158        $output .= sprintf("%s%s\n", $indent_str, $var);
159    }
160    return preg_replace(['/^[ \t]+$/' . $app->getParam('preg_u'), '/\n\n+/' . $app->getParam('preg_u'), '/^(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(\S )/m' . $app->getParam('preg_u')], ['', "\n", '$1$1$2$2$3$3$4$4$5$5$6$6$7$7$8$8$9'], $output);
161}
162
163/**
164 * @param string|mixed $value A string to UTF8-encode.
165 *
166 * @returns string|mixed The UTF8-encoded string, or the object passed in if
167 *    it wasn't a string.
168 */
169function conditionalUTF8Encode($value)
170{
171  if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
172    return utf8_encode($value);
173  } else {
174    return $value;
175  }
176}
177
178
179/**
180 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
181 *
182 * @param  string $text             Text to clean.
183 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
184 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
185 * @return string                   HTML-safe text.
186 */
187function oTxt($text, $preserve_html=false)
188{
189    $app =& App::getInstance();
190
191    $search = array();
192    $replace = array();
193
194    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
195    $search['retain_ampersand']     = '/&amp;/';
196    $replace['retain_ampersand']    = '&';
197
198    if ($preserve_html) {
199        // Convert characters that must remain non-entities for displaying HTML.
200        $search['retain_left_angle']       = '/&lt;/';
201        $replace['retain_left_angle']      = '<';
202
203        $search['retain_right_angle']      = '/&gt;/';
204        $replace['retain_right_angle']     = '>';
205
206        $search['retain_single_quote']     = '/&#039;/';
207        $replace['retain_single_quote']    = "'";
208
209        $search['retain_double_quote']     = '/&quot;/';
210        $replace['retain_double_quote']    = '"';
211    }
212
213    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
214    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
215    $replace['ampersand']       = '&amp;';
216
217    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
218}
219
220/**
221 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
222 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
223 *
224 * @param  string   $text Text to clean.
225 * @return string         Cleaned text.
226 */
227function fancyTxt($text, $extra_search=null, $extra_replace=null)
228{
229    $search = array();
230    $replace = array();
231
232    // "double quoted text"  →  “double quoted text”
233    $search['_double_quotes']    = '/(?<=^|[^\w=(])(?:"|&quot;|&#0?34;|&#x22;|&ldquo;)([\w\'.
(—–-][^"]*?)(?:"|&quot;|&#0?34;|&#x22;|&rdquo;)(?=[^)\w]|$)/imsu'; // " is the same as &quot; and &#34; and &#034; and &#x22;
234    $replace['_double_quotes']   = '“$1”';
235
236    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
237    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
238    $replace['_apostrophe']      = '’';
239
240    // 'single quoted text'  →  ‘single quoted text’
241    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
242    $replace['_single_quotes']   = '‘$1’';
243
244    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
245    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
246    $replace['_apostrophes']     = '’';
247
248    // double--hyphens  →  en — dashes
249    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
250    $replace['_em_dash']         = ' – ';
251
252    // ...  →  

253    $search['_elipsis']          = '/(?<=^|[^.])\.\.\.(?=[^.]|$)/imsu';
254    $replace['_elipsis']         = '
';
255
256    if (is_array($extra_search) && is_array($extra_replace) && sizeof($extra_search) == sizeof($extra_replace)) {
257        // Append additional search replacements.
258        $search = array_merge($search, $extra_search);
259        $replace = array_merge($replace, $extra_replace);
260    }
261
262    return trim(preg_replace($search, $replace, $text));
263}
264
265/*
266* Finds all URLs in text and hyperlinks them.
267*
268* @access   public
269* @param    string  $text   Text to search for URLs.
270* @param    bool    $strict True to only include URLs starting with a scheme (http:// ftp:// im://), or false to include URLs starting with 'www.'.
271* @param    mixed   $length Number of characters to truncate URL, or NULL to disable truncating.
272* @param    string  $delim  Delimiter to append, indicate truncation.
273* @return   string          Same input text, but URLs hyperlinked.
274* @author   Quinn Comendant <quinn@strangecode.com>
275* @version  2.2
276* @since    22 Mar 2015 23:29:04
277*/
278function hyperlinkTxt($text, $strict=false, $length=null, $delim='
')
279{
280    // A list of schemes we allow at the beginning of a URL.
281    $schemes = 'mailto:|tel:|skype:|callto:|facetime:|bitcoin:|geo:|magnet:\?|sip:|sms:|xmpp:|view-source:(?:https?://)?|[\w-]{2,}://';
282
283    // Capture the full URL into the first match and only the first X characters into the second match.
284    // This will match URLs not preceded by " ' or = (URLs inside an attribute) or ` (Markdown quoted) or double-scheme (http://http://www.asdf.com)
285    // https://stackoverflow.com/questions/1547899/which-characters-make-a-url-invalid/1547940#1547940
286    $regex = '@
287        \b                                 # Start with a word-boundary.
288        (?<!"|\'|=|>|`|\]\(|\[\d\] |[:/]/) # Negative look-behind to exclude URLs already in <a> tag, <tags>beween</tags>, `Markdown quoted`, [Markdown](link), [1] www.markdown.footnotes, and avoid broken:/ and doubled://schemes://
289        (                                  # Begin match 1
290            (                              # Begin match 2
291                (?:%s)                     # URL starts with known scheme or www. if strict = false
292                [^\s/$.?#]+                # Any domain-valid characters
293                [^\s"`<>]{1,%s}            # Match 2 is limited to a maximum of LENGTH valid URL characters
294            )
295            [^\s"`<>]*                     # Match 1 continues with any further valid URL characters
296            ([^\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
297        )
298        @Suxi
299    ';
300    $regex = sprintf($regex,
301        ($strict ? $schemes : $schemes . '|www\.'), // Strict=false adds "www." to the list of allowed start-of-URL.
302        ($length ? $length : ''),
303        ($strict ? '' : '?!.,:;)\'-') // Strict=false excludes some "URL-valid" characters from the last character of URL. (Hyphen must remain last character in this class.)
304    );
305
306    // Use a callback function to decide when to append the delim.
307    // Also encode special chars with oTxt().
308    return preg_replace_callback($regex, function ($m) use ($length, $delim) {
309        $url = $m[1];
310        $truncated_url = $m[2] . $m[3];
311        $absolute_url = preg_replace('!^www\.!', 'http://www.', $url);
312        if (is_null($length) || $url == $truncated_url) {
313            // If not truncating, or URL was not truncated.
314            // Remove http schemas, and any single trailing / to make the display URL.
315            $display_url = preg_replace(['!^https?://!u', '!^([^/]+)/$!u'], ['', '$1'], $url);
316            return sprintf('<a href="%s">%s</a>', oTxt($absolute_url), $display_url);
317        } else {
318            // Truncated URL.
319            // Remove http schemas, and any single trailing / to make the display URL.
320            $display_url = preg_replace(['!^https?://!u', '!^([^/]+)/$!u'], ['', '$1'], trim($truncated_url));
321            return sprintf('<a href="%s">%s%s</a>', oTxt($absolute_url), $display_url, $delim);
322        }
323    }, $text);
324}
325
326/**
327 * Applies a class to search terms to highlight them ala google results.
328 *
329 * @param  string   $text   Input text to search.
330 * @param  string   $search String of word(s) that will be highlighted.
331 * @param  string   $class  CSS class to apply.
332 * @return string           Text with searched words wrapped in <span>.
333 */
334function highlightWords($text, $search, $class='sc-highlightwords')
335{
336    $app =& App::getInstance();
337
338    $words = preg_split('/[^\w]/', $search, -1, PREG_SPLIT_NO_EMPTY);
339
340    $search = array();
341    $replace = array();
342
343    foreach ($words as $w) {
344        if ('' != trim($w)) {
345            $search[] = '/\b(' . preg_quote($w) . ')\b/i' . $app->getParam('preg_u');
346            $replace[] = '<span class="' . $class . '">$1</span>';
347        }
348    }
349
350    return empty($replace) ? $text : preg_replace($search, $replace, $text);
351}
352
353/**
354 * Generates a hexadecimal html color based on provided word.
355 *
356 * @access public
357 * @param  string $text  A string for which to convert to color.
358 * @return string  A hexadecimal html color.
359 */
360function getTextColor($text, $method=1, $n=0.87)
361{
362    $hash = md5($text);
363    $rgb = array(
364        mb_substr($hash, 0, 1),
365        mb_substr($hash, 1, 1),
366        mb_substr($hash, 2, 1),
367        mb_substr($hash, 3, 1),
368        mb_substr($hash, 4, 1),
369        mb_substr($hash, 5, 1),
370    );
371
372    switch ($method) {
373    case 1 :
374    default :
375        // Reduce all hex values slightly to avoid all white.
376        array_walk($rgb, function (&$v) use ($n) {
377            $v = dechex(round(hexdec($v) * $n));
378        });
379        break;
380
381    case 2 :
382        foreach ($rgb as $i => $v) {
383            if (hexdec($v) > hexdec('c')) {
384                $rgb[$i] = dechex(hexdec('f') - hexdec($v));
385            }
386        }
387        break;
388    }
389
390    return join('', $rgb);
391}
392
393/**
394 * Encodes a string into unicode values 128-255.
395 * Useful for hiding an email address from spambots.
396 *
397 * @access  public
398 * @param   string   $text   A line of text to encode.
399 * @return  string   Encoded text.
400 */
401function encodeAscii($text)
402{
403    $output = '';
404    $num = mb_strlen($text);
405    for ($i=0; $i<$num; $i++) {
406        $output .= sprintf('&#%03s', ord($text[$i]));
407    }
408    return $output;
409}
410
411/**
412 * Encodes an email into a "user at domain dot com" format.
413 *
414 * @access  public
415 * @param   string   $email   An email to encode.
416 * @param   string   $at      Replaces the @.
417 * @param   string   $dot     Replaces the ..
418 * @return  string   Encoded email.
419 */
420function encodeEmail($email, $at=' at ', $dot=' dot ')
421{
422    $app =& App::getInstance();
423
424    $search = array('/@/' . $app->getParam('preg_u'), '/\./' . $app->getParam('preg_u'));
425    $replace = array($at, $dot);
426    return preg_replace($search, $replace, $email);
427}
428
429/**
430 * Truncates "a really long string" into a string of specified length
431 * at the beginning: "
long string"
432 * at the middle: "a rea
string"
433 * or at the end: "a really
".
434 *
435 * The regular expressions below first match and replace the string to the specified length and position,
436 * and secondly they remove any whitespace from around the delimiter (to avoid "this 
 " from happening).
437 *
438 * @access  public
439 * @param   string  $str    Input string
440 * @param   int     $len    Maximum string length.
441 * @param   string  $where  Where to cut the string. One of: 'start', 'middle', or 'end'.
442 * @return  string          Truncated output string.
443 * @author  Quinn Comendant <quinn@strangecode.com>
444 * @since   29 Mar 2006 13:48:49
445 */
446function truncate($str, $len=50, $where='end', $delim='
')
447{
448    $app =& App::getInstance();
449
450    $dlen = mb_strlen($delim);
451    if ($len <= $dlen || mb_strlen($str) <= $dlen) {
452        return substr($str, 0, $len);
453    }
454    $part1 = floor(($len - $dlen) / 2);
455    $part2 = ceil(($len - $dlen) / 2);
456
457    if ($len > ini_get('pcre.backtrack_limit')) {
458        $app =& App::getInstance();
459        $app->logMsg(sprintf('Asked to truncate string len of %s > pcre.backtrack_limit of %s', $len, ini_get('pcre.backtrack_limit')), LOG_DEBUG, __FILE__, __LINE__);
460        ini_set('pcre.backtrack_limit', $len);
461    }
462
463    switch ($where) {
464    case 'start' :
465        return preg_replace(array(sprintf('/^.{%s,}(.{%s})$/s' . $app->getParam('preg_u'), $dlen + 1, $part1 + $part2), sprintf('/\s*%s{%s,}\s*/s' . $app->getParam('preg_u'), preg_quote($delim), $dlen)), array($delim . '$1', $delim), $str);
466
467    case 'middle' :
468        return preg_replace(array(sprintf('/^(.{%s}).{%s,}(.{%s})$/s' . $app->getParam('preg_u'), $part1, $dlen + 1, $part2), sprintf('/\s*%s{%s,}\s*/s' . $app->getParam('preg_u'), preg_quote($delim), $dlen)), array('$1' . $delim . '$2', $delim), $str);
469
470    case 'end' :
471    default :
472        return preg_replace(array(sprintf('/^(.{%s}).{%s,}$/s' . $app->getParam('preg_u'), $part1 + $part2, $dlen + 1), sprintf('/\s*%s{%s,}\s*/s' . $app->getParam('preg_u'), preg_quote($delim), $dlen)), array('$1' . $delim, $delim), $str);
473    }
474}
475
476/*
477* A substitution for the missing mb_ucfirst function.
478*
479* @access   public
480* @param    string  $string The string
481* @return   string          String with upper-cased first character.
482* @author   Quinn Comendant <quinn@strangecode.com>
483* @version  1.0
484* @since    06 Dec 2008 17:04:01
485*/
486if (!function_exists('mb_ucfirst')) {
487    function mb_ucfirst($string)
488    {
489        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1, mb_strlen($string));
490    }
491}
492
493/*
494* A substitution for the missing mb_strtr function.
495*
496* @access   public
497* @param    string  $string The string
498* @param    string  $from   String of characters to translate from
499* @param    string  $to     String of characters to translate to
500* @return   string          String with translated characters.
501* @author   Quinn Comendant <quinn@strangecode.com>
502* @version  1.0
503* @since    20 Jan 2013 12:33:26
504*/
505if (!function_exists('mb_strtr')) {
506    function mb_strtr($string, $from, $to)
507    {
508        return str_replace(mb_split('.', $from), mb_split('.', $to), $string);
509    }
510}
511
512/*
513* A substitution for the missing mb_str_pad function.
514*
515* @access   public
516* @param    string  $input      The string that receives padding.
517* @param    string  $pad_length Total length of resultant string.
518* @param    string  $pad_string The string to use for padding
519* @param    string  $pad_type   Flags STR_PAD_RIGHT or STR_PAD_LEFT or STR_PAD_BOTH
520* @return   string          String with translated characters.
521* @author   Quinn Comendant <quinn@strangecode.com>
522* @version  1.0
523* @since    20 Jan 2013 12:33:26
524*/
525if (!function_exists('mb_str_pad')) {
526    function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
527        $diff = strlen($input) - mb_strlen($input);
528        return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
529    }
530}
531
532/**
533 * Return a human readable disk space measurement. Input value measured in bytes.
534 *
535 * @param       int    $size        Size in bytes.
536 * @param       int    $unit        The maximum unit
537 * @param       int    $format      The return string format
538 * @author      Aidan Lister <aidan@php.net>
539 * @author      Quinn Comendant <quinn@strangecode.com>
540 * @version     1.2.0
541 */
542function humanFileSize($size, $format='%01.2f %s', $max_unit=null, $multiplier=1024)
543{
544    // Units
545    $units = array('B', 'KB', 'MB', 'GB', 'TB');
546    $ii = count($units) - 1;
547
548    // Max unit
549    $max_unit = array_search((string) $max_unit, $units);
550    if ($max_unit === null || $max_unit === false) {
551        $max_unit = $ii;
552    }
553
554    // Loop
555    $i = 0;
556    while ($max_unit != $i && $size >= $multiplier && $i < $ii) {
557        $size /= $multiplier;
558        $i++;
559    }
560
561    return sprintf($format, $size, $units[$i]);
562}
563
564/*
565* Returns a human readable amount of time for the given amount of seconds.
566*
567* 45 seconds
568* 12 minutes
569* 3.5 hours
570* 2 days
571* 1 week
572* 4 months
573*
574* Months are calculated using the real number of days in a year: 365.2422 / 12.
575*
576* @access   public
577* @param    int $seconds Seconds of time.
578* @param    string $max_unit Key value from the $units array.
579* @param    string $format Sprintf formatting string.
580* @return   string Value of units elapsed.
581* @author   Quinn Comendant <quinn@strangecode.com>
582* @version  1.0
583* @since    23 Jun 2006 12:15:19
584*/
585function humanTime($seconds, $max_unit=null, $format='%01.1f')
586{
587    // Units: array of seconds in the unit, singular and plural unit names.
588    $units = array(
589        'second' => array(1, _("second"), _("seconds")),
590        'minute' => array(60, _("minute"), _("minutes")),
591        'hour' => array(3600, _("hour"), _("hours")),
592        'day' => array(86400, _("day"), _("days")),
593        'week' => array(604800, _("week"), _("weeks")),
594        'month' => array(2629743.84, _("month"), _("months")),
595        'year' => array(31556926.08, _("year"), _("years")),
596        'decade' => array(315569260.8, _("decade"), _("decades")),
597        'century' => array(3155692608, _("century"), _("centuries")),
598    );
599
600    // Max unit to calculate.
601    $max_unit = isset($units[$max_unit]) ? $max_unit : 'year';
602
603    $final_time = $seconds;
604    $final_unit = 'second';
605    foreach ($units as $k => $v) {
606        if ($seconds >= $v[0]) {
607            $final_time = $seconds / $v[0];
608            $final_unit = $k;
609        }
610        if ($max_unit == $final_unit) {
611            break;
612        }
613    }
614    $final_time = sprintf($format, $final_time);
615    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2]));
616}
617
618/*
619* Converts strange characters into ASCII using a htmlentities hack. If a character does not have a specific rule, it will remain as its entity name, e.g., `5¢` becomes `5&cent;` which becomes `5cent`.
620*
621* @access   public
622* @param    string  $str    Input string of text containing accents.
623* @return   string          String with accented characters converted to ASCII equivalents.
624* @author   Quinn Comendant <quinn@strangecode.com>
625* @since    30 Apr 2020 21:29:16
626*/
627function simplifyAccents($str)
628{
629    $app =& App::getInstance();
630
631    return preg_replace([
632        '/&amp;(?=[\w\d#]{1,10};)/i' . $app->getParam('preg_u'),
633        '/&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml|caron);/i' . $app->getParam('preg_u'),
634        '/&(?:ndash|mdash|horbar);/i' . $app->getParam('preg_u'),
635        '/&(?:nbsp);/i' . $app->getParam('preg_u'),
636        '/&(?:bdquo|ldquo|ldquor|lsquo|lsquor|rdquo|rdquor|rsquo|rsquor|sbquo|lsaquo|rsaquo);/i' . $app->getParam('preg_u'),
637        '/&(?:amp);/i' . $app->getParam('preg_u'), // This replacement must come after matching all other entities.
638        '/[&;]+/' . $app->getParam('preg_u'),
639    ], [
640        '&',
641        '$1',
642        '-',
643        ' ',
644        '',
645        'and',
646        '',
647    ], htmlentities($str, ENT_NOQUOTES | ENT_IGNORE, $app->getParam('character_set')));
648}
649
650/*
651* Converts a string into a URL-safe slug, removing spaces and non word characters.
652*
653* @access   public
654* @param    string  $str    String to convert.
655* @return   string          URL-safe slug.
656* @author   Quinn Comendant <quinn@strangecode.com>
657* @version  1.0
658* @since    18 Aug 2014 12:54:29
659*/
660function URLSlug($str)
661{
662    $app =& App::getInstance();
663
664    return strtolower(urlencode(preg_replace(['/[-\s–—.:;?!@#=+_\/\\\]+|(?:&nbsp;|&#160;|&ndash;|&#8211;|&mdash;|&#8212;|%c2%a0|%e2%80%93|%e2%80%9)+/' . $app->getParam('preg_u'), '/-+/' . $app->getParam('preg_u'), '/[^\w-]+/' . $app->getParam('preg_u'), '/^-+|-+$/' . $app->getParam('preg_u')], ['-', '-', '', ''], simplifyAccents($str))));
665}
666
667/**
668 * Converts a string of text into a safe file name by removing non-ASCII characters and non-word characters.
669 *
670 * @access  public
671 * @param   string  $file_name  A name of a file.
672 * @return  string              The same name, but cleaned.
673 */
674function cleanFileName($file_name)
675{
676    $app =& App::getInstance();
677
678    $file_name = preg_replace(['/[^a-zA-Z0-9()@._=+-]+/' . $app->getParam('preg_u'), '/^_+|_+$/' . $app->getParam('preg_u')], ['_', ''], simplifyAccents($file_name));
679    return mb_substr($file_name, 0, 250);
680}
681
682/**
683 * Returns the extension of a file name, or an empty string if none exists.
684 *
685 * @access  public
686 * @param   string  $file_name  A name of a file, with extension after a dot.
687 * @return  string              The value found after the dot
688 */
689function getFilenameExtension($file_name)
690{
691    preg_match('/.*?\.(\w+)$/i', trim($file_name), $ext);
692    return isset($ext[1]) ? $ext[1] : '';
693}
694
695/*
696* Convert a php.ini value (8M, 512K, etc), into integer value of bytes.
697*
698* @access   public
699* @param    string  $val    Value from php config, e.g., upload_max_filesize.
700* @return   int             Value converted to bytes as an integer.
701* @author   Quinn Comendant <quinn@strangecode.com>
702* @version  1.0
703* @since    20 Aug 2014 14:32:41
704*/
705function phpIniGetBytes($val)
706{
707    $val = trim(ini_get($val));
708    if ($val != '') {
709        $unit = strtolower($val[mb_strlen($val) - 1]);
710        $val = preg_replace('/\D/', '', $val);
711
712        switch ($unit) {
713            // No `break`, so these multiplications are cumulative.
714            case 'g':
715                $val *= 1024;
716            case 'm':
717                $val *= 1024;
718            case 'k':
719                $val *= 1024;
720        }
721    }
722
723    return (int)$val;
724}
725
726/**
727 * Tests the existence of a file anywhere in the include path.
728 * Replaced by stream_resolve_include_path() in PHP 5 >= 5.3.2
729 *
730 * @param   string  $file   File in include path.
731 * @return  mixed           False if file not found, the path of the file if it is found.
732 * @author  Quinn Comendant <quinn@strangecode.com>
733 * @since   03 Dec 2005 14:23:26
734 */
735function fileExistsIncludePath($file)
736{
737    $app =& App::getInstance();
738
739    foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) {
740        $fullpath = $path . DIRECTORY_SEPARATOR . $file;
741        if (file_exists($fullpath)) {
742            $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__);
743            return $fullpath;
744        } else {
745            $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__);
746            return false;
747        }
748    }
749}
750
751/**
752 * Returns stats of a file from the include path.
753 *
754 * @param   string  $file   File in include path.
755 * @param   mixed   $stat   Which statistic to return (or null to return all).
756 * @return  mixed           Value of requested key from fstat(), or false on error.
757 * @author  Quinn Comendant <quinn@strangecode.com>
758 * @since   03 Dec 2005 14:23:26
759 */
760function statIncludePath($file, $stat=null)
761{
762    // Open file pointer read-only using include path.
763    if ($fp = fopen($file, 'r', true)) {
764        // File opened successfully, get stats.
765        $stats = fstat($fp);
766        fclose($fp);
767        // Return specified stats.
768        return is_null($stat) ? $stats : $stats[$stat];
769    } else {
770        return false;
771    }
772}
773
774/*
775* Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5.
776* It makes an exclusive lock on the file while writing.
777*
778* @access   public
779* @param    string  $filename   Path to file.
780* @param    string  $content    Data to write into file.
781* @return   bool                Success or failure.
782* @author   Quinn Comendant <quinn@strangecode.com>
783* @since    11 Apr 2006 22:48:30
784*/
785function filePutContents($filename, $content)
786{
787    $app =& App::getInstance();
788
789    // Open file for writing and truncate to zero length.
790    if ($fp = fopen($filename, 'w')) {
791        if (flock($fp, LOCK_EX)) {
792            if (!fwrite($fp, $content, mb_strlen($content))) {
793                $app->logMsg(sprintf('Failed writing to file: %s', $filename), LOG_ERR, __FILE__, __LINE__);
794                fclose($fp);
795                return false;
796            }
797            flock($fp, LOCK_UN);
798        } else {
799            $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
800            fclose($fp);
801            return false;
802        }
803        fclose($fp);
804        // Success!
805        $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
806        return true;
807    } else {
808        $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
809        return false;
810    }
811}
812
813/**
814 * If $var is net set or null, set it to $default. Otherwise leave it alone.
815 * Returns the final value of $var. Use to find a default value of one is not available.
816 *
817 * @param  mixed $var       The variable that is being set.
818 * @param  mixed $default   What to set it to if $val is not currently set.
819 * @return mixed            The resulting value of $var.
820 */
821function setDefault(&$var, $default='')
822{
823    if (!isset($var)) {
824        $var = $default;
825    }
826    return $var;
827}
828
829/**
830 * Like preg_quote() except for arrays, it takes an array of strings and puts
831 * a backslash in front of every character that is part of the regular
832 * expression syntax.
833 *
834 * @param  array $array    input array
835 * @param  array $delim    optional character that will also be escaped.
836 * @return array    an array with the same values as $array1 but shuffled
837 */
838function pregQuoteArray($array, $delim='/')
839{
840    if (!empty($array)) {
841        if (is_array($array)) {
842            foreach ($array as $key=>$val) {
843                $quoted_array[$key] = preg_quote($val, $delim);
844            }
845            return $quoted_array;
846        } else {
847            return preg_quote($array, $delim);
848        }
849    }
850}
851
852/**
853 * Converts a PHP Array into encoded URL arguments and return them as an array.
854 *
855 * @param  mixed $data        An array to transverse recursively, or a string
856 *                            to use directly to create url arguments.
857 * @param  string $prefix     The name of the first dimension of the array.
858 *                            If not specified, the first keys of the array will be used.
859 * @return array              URL with array elements as URL key=value arguments.
860 */
861function urlEncodeArray($data, $prefix='', $_return=true)
862{
863    // Data is stored in static variable.
864    static $args = array();
865
866    if (is_array($data)) {
867        foreach ($data as $key => $val) {
868            // If the prefix is empty, use the $key as the name of the first dimension of the "array".
869            // ...otherwise, append the key as a new dimension of the "array".
870            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
871            // Enter recursion.
872            urlEncodeArray($val, $new_prefix, false);
873        }
874    } else {
875        // We've come to the last dimension of the array, save the "array" and its value.
876        $args[$prefix] = urlencode($data);
877    }
878
879    if ($_return) {
880        // This is not a recursive execution. All recursion is complete.
881        // Reset static var and return the result.
882        $ret = $args;
883        $args = array();
884        return is_array($ret) ? $ret : array();
885    }
886}
887
888/**
889 * Converts a PHP Array into encoded URL arguments and return them in a string.
890 *
891 * Todo: probably update to use the built-in http_build_query().
892 *
893 * @param  mixed $data        An array to transverse recursively, or a string
894 *                            to use directly to create url arguments.
895 * @param  string $prefix     The name of the first dimension of the array.
896 *                            If not specified, the first keys of the array will be used.
897 * @return string url         A string ready to append to a url.
898 */
899function urlEncodeArrayToString($data, $prefix='')
900{
901
902    $array_args = urlEncodeArray($data, $prefix);
903    $url_args = '';
904    $delim = '';
905    foreach ($array_args as $key=>$val) {
906        $url_args .= $delim . $key . '=' . $val;
907        $delim = ini_get('arg_separator.output');
908    }
909    return $url_args;
910}
911
912/**
913 * Fills an array with the result from a multiple ereg search.
914 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
915 *
916 * @param  mixed $pattern   regular expression needle
917 * @param  mixed $string   haystack
918 * @return array    populated with each found result
919 */
920function eregAll($pattern, $string)
921{
922    do {
923        if (!mb_ereg($pattern, $string, $temp)) {
924             continue;
925        }
926        $string = str_replace($temp[0], '', $string);
927        $results[] = $temp;
928    } while (mb_ereg($pattern, $string, $temp));
929    return $results;
930}
931
932/**
933 * Prints the word "checked" if a variable is set, and optionally matches
934 * the desired value, otherwise prints nothing,
935 * used for printing the word "checked" in a checkbox form input.
936 *
937 * @param  mixed $var     the variable to compare
938 * @param  mixed $value   optional, what to compare with if a specific value is required.
939 */
940function frmChecked($var, $value=null)
941{
942    if (func_num_args() == 1 && $var) {
943        // 'Checked' if var is true.
944        echo ' checked="checked" ';
945    } else if (func_num_args() == 2 && $var == $value) {
946        // 'Checked' if var and value match.
947        echo ' checked="checked" ';
948    } else if (func_num_args() == 2 && is_array($var)) {
949        // 'Checked' if the value is in the key or the value of an array.
950        if (isset($var[$value])) {
951            echo ' checked="checked" ';
952        } else if (in_array($value, $var)) {
953            echo ' checked="checked" ';
954        }
955    }
956}
957
958/**
959 * prints the word "selected" if a variable is set, and optionally matches
960 * the desired value, otherwise prints nothing,
961 * otherwise prints nothing, used for printing the word "checked" in a
962 * select form input
963 *
964 * @param  mixed $var     the variable to compare
965 * @param  mixed $value   optional, what to compare with if a specific value is required.
966 */
967function frmSelected($var, $value=null)
968{
969    if (func_num_args() == 1 && $var) {
970        // 'selected' if var is true.
971        echo ' selected="selected" ';
972    } else if (func_num_args() == 2 && $var == $value) {
973        // 'selected' if var and value match.
974        echo ' selected="selected" ';
975    } else if (func_num_args() == 2 && is_array($var)) {
976        // 'selected' if the value is in the key or the value of an array.
977        if (isset($var[$value])) {
978            echo ' selected="selected" ';
979        } else if (in_array($value, $var)) {
980            echo ' selected="selected" ';
981        }
982    }
983}
984
985/**
986 * Adds slashes to values of an array and converts the array to a comma
987 * delimited list. If value provided is a string return the string
988 * escaped.  This is useful for putting values coming in from posted
989 * checkboxes into a SET column of a database.
990 *
991 *
992 * @param  array $in      Array to convert.
993 * @return string         Comma list of array values.
994 */
995function escapedList($in, $separator="', '")
996{
997    require_once dirname(__FILE__) . '/DB.inc.php';
998    $db =& DB::getInstance();
999
1000    if (is_array($in) && !empty($in)) {
1001        return join($separator, array_map(array($db, 'escapeString'), $in));
1002    } else {
1003        return $db->escapeString($in);
1004    }
1005}
1006
1007/**
1008 * Converts a human string date into a SQL-safe date.  Dates nearing
1009 * infinity use the date 2038-01-01 so conversion to unix time format
1010 * remain within valid range.
1011 *
1012 * @param  array $date     String date to convert.
1013 * @param  array $format   Date format to pass to date(). Default produces MySQL datetime: YYYY-MM-DD hh:mm:ss
1014 * @return string          SQL-safe date.
1015 */
1016function strToSQLDate($date, $format='Y-m-d H:i:s')
1017{
1018    require_once dirname(__FILE__) . '/DB.inc.php';
1019    $db =& DB::getInstance();
1020
1021    if ($db->isConnected() && mb_strpos($db->getParam('zero_date'), '-') !== false) {
1022        // Mysql version >= 5.7.4 stopped allowing a "zero" date of 0000-00-00.
1023        // https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_date
1024        $zero_date_parts = explode('-', $db->getParam('zero_date'));
1025        $zero_y = $zero_date_parts[0];
1026        $zero_m = $zero_date_parts[1];
1027        $zero_d = $zero_date_parts[2];
1028    } else {
1029        $zero_y = '0000';
1030        $zero_m = '00';
1031        $zero_d = '00';
1032    }
1033    // Translate the human string date into SQL-safe date format.
1034    if (empty($date) || mb_strpos($date, sprintf('%s-%s-%s', $zero_y, $zero_m, $zero_d)) !== false || strtotime($date) === -1 || strtotime($date) === false || strtotime($date) === null) {
1035        // Return a string of zero time, formatted the same as $format.
1036        return strtr($format, array(
1037            'Y' => $zero_y,
1038            'm' => $zero_m,
1039            'd' => $zero_d,
1040            'H' => '00',
1041            'i' => '00',
1042            's' => '00',
1043        ));
1044    } else {
1045        return date($format, strtotime($date));
1046    }
1047}
1048
1049/**
1050 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
1051 * array, stripslashes is run on each value, recursively, and the stripped
1052 * array is returned.
1053 *
1054 * @param  mixed $var   The string or array to un-quote, if necessary.
1055 * @return mixed        $var, minus any magic quotes.
1056 */
1057function dispelMagicQuotes($var, $always=false)
1058{
1059    static $magic_quotes_gpc;
1060
1061    if (!isset($magic_quotes_gpc)) {
1062        $magic_quotes_gpc = get_magic_quotes_gpc();
1063    }
1064
1065    if ($always || $magic_quotes_gpc) {
1066        if (!is_array($var)) {
1067            $var = stripslashes($var);
1068        } else {
1069            foreach ($var as $key=>$val) {
1070                if (is_array($val)) {
1071                    $var[$key] = dispelMagicQuotes($val, $always);
1072                } else {
1073                    $var[$key] = stripslashes($val);
1074                }
1075            }
1076        }
1077    }
1078    return $var;
1079}
1080
1081/**
1082 * Get a form variable from GET or POST data, stripped of magic
1083 * quotes if necessary.
1084 *
1085 * @param string $key (optional) The name of a $_REQUEST key.
1086 * @param string $default (optional) The value to return if the
1087 *                                   variable is not there.
1088 * @return mixed      A cleaned GET or POST array if no key specified.
1089 * @return string     A cleaned form value if found, or $default.
1090 */
1091function getFormData($key=null, $default=null)
1092{
1093    $app =& App::getInstance();
1094
1095    if (null === $key) {
1096        // Return entire array.
1097        switch (strtoupper(getenv('REQUEST_METHOD'))) {
1098        case 'POST':
1099            return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
1100
1101        case 'GET':
1102            return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
1103
1104        default:
1105            return dispelMagicQuotes($_REQUEST, $app->getParam('always_dispel_magicquotes'));
1106        }
1107    }
1108
1109    if (isset($_REQUEST[$key])) {
1110        // $key is found in the flat array of REQUEST.
1111        return dispelMagicQuotes($_REQUEST[$key], $app->getParam('always_dispel_magicquotes'));
1112    } else if (mb_strpos($key, '[') !== false && isset($_REQUEST[strtok($key, '[')]) && preg_match_all('/\[([a-z0-9._~-]+)\]/', $key, $matches)) {
1113        // $key is formatted with sub-keys, e.g., getFormData('foo[bar][baz]') and top level key (`foo`) exists in REQUEST.
1114        // Extract these as sub-keys and access REQUEST as a multi-dimensional array, e.g., $_REQUEST[foo][bar][baz].
1115        $leaf = $_REQUEST[strtok($key, '[')];
1116        foreach ($matches[1] as $subkey) {
1117            if (is_array($leaf) && isset($leaf[$subkey])) {
1118                $leaf = $leaf[$subkey];
1119            } else {
1120                $leaf = null;
1121            }
1122        }
1123        return $leaf;
1124    } else {
1125        return $default;
1126    }
1127}
1128
1129function getPost($key=null, $default=null)
1130{
1131    $app =& App::getInstance();
1132
1133    if (null === $key) {
1134        return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
1135    }
1136    if (isset($_POST[$key])) {
1137        return dispelMagicQuotes($_POST[$key], $app->getParam('always_dispel_magicquotes'));
1138    } else {
1139        return $default;
1140    }
1141}
1142
1143function getGet($key=null, $default=null)
1144{
1145    $app =& App::getInstance();
1146
1147    if (null === $key) {
1148        return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
1149    }
1150    if (isset($_GET[$key])) {
1151        return dispelMagicQuotes($_GET[$key], $app->getParam('always_dispel_magicquotes'));
1152    } else {
1153        return $default;
1154    }
1155}
1156
1157/*
1158* Sets a $_GET or $_POST variable.
1159*
1160* @access   public
1161* @param    string  $key    The key of the request array to set.
1162* @param    mixed   $val    The value to save in the request array.
1163* @return   void
1164* @author   Quinn Comendant <quinn@strangecode.com>
1165* @version  1.0
1166* @since    01 Nov 2009 12:25:29
1167*/
1168function putFormData($key, $val)
1169{
1170    switch (strtoupper(getenv('REQUEST_METHOD'))) {
1171    case 'POST':
1172        $_POST[$key] = $val;
1173        break;
1174
1175    case 'GET':
1176        $_GET[$key] = $val;
1177        break;
1178    }
1179
1180    $_REQUEST[$key] = $val;
1181}
1182
1183/*
1184* Generates a base-65-encoded sha512 hash of $string truncated to $length.
1185*
1186* @access   public
1187* @param    string  $string Input string to hash.
1188* @param    int     $length Length of output hash string.
1189* @return   string          String of hash.
1190* @author   Quinn Comendant <quinn@strangecode.com>
1191* @version  1.0
1192* @since    03 Apr 2016 19:48:49
1193*/
1194function hash64($string, $length=18)
1195{
1196    $app =& App::getInstance();
1197
1198    return mb_substr(preg_replace('/[^\w]/' . $app->getParam('preg_u'), '', base64_encode(hash('sha512', $string, true))), 0, $length);
1199}
1200
1201/**
1202 * Signs a value using md5 and a simple text key. In order for this
1203 * function to be useful (i.e. secure) the salt must be kept secret, which
1204 * means keeping it as safe as database credentials. Putting it into an
1205 * environment variable set in httpd.conf is a good place.
1206 *
1207 * @access  public
1208 * @param   string  $val    The string to sign.
1209 * @param   string  $salt   (Optional) A text key to use for computing the signature.
1210 * @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.
1211 * @return  string  The original value with a signature appended.
1212 */
1213function addSignature($val, $salt=null, $length=18)
1214{
1215    $app =& App::getInstance();
1216
1217    if ('' == trim($val)) {
1218        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
1219        return '';
1220    }
1221
1222    if (!isset($salt)) {
1223        $salt = $app->getParam('signing_key');
1224    }
1225
1226    switch ($app->getParam('signing_method')) {
1227    case 'sha512+base64':
1228        return $val . '-' . mb_substr(preg_replace('/[^\w]/' . $app->getParam('preg_u'), '', base64_encode(hash('sha512', $val . $salt, true))), 0, $length);
1229
1230    case 'md5':
1231    default:
1232        return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
1233    }
1234}
1235
1236/**
1237 * Strips off the signature appended by addSignature().
1238 *
1239 * @access  public
1240 * @param   string  $signed_val     The string to sign.
1241 * @return  string  The original value with a signature removed.
1242 */
1243function removeSignature($signed_val)
1244{
1245    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
1246        return '';
1247    }
1248    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
1249}
1250
1251/**
1252 * Verifies a signature appended to a value by addSignature().
1253 *
1254 * @access  public
1255 * @param   string  $signed_val A value with appended signature.
1256 * @param   string  $salt       (Optional) A text key to use for computing the signature.
1257 * @param   string  $length (Optional) The length of the added signature.
1258 * @return  bool    True if the signature matches the var.
1259 */
1260function verifySignature($signed_val, $salt=null, $length=18)
1261{
1262    // Strip the value from the signed value.
1263    $val = removeSignature($signed_val);
1264    // If the signed value matches the original signed value we consider the value safe.
1265    if ('' != $signed_val && $signed_val == addSignature($val, $salt, $length)) {
1266        // Signature verified.
1267        return true;
1268    } else {
1269        $app =& App::getInstance();
1270        $app->logMsg(sprintf('Failed signature (%s should be %s)', $signed_val, addSignature($val, $salt, $length)), LOG_DEBUG, __FILE__, __LINE__);
1271        return false;
1272    }
1273}
1274
1275/**
1276 * Sends empty output to the browser and flushes the php buffer so the client
1277 * will see data before the page is finished processing.
1278 */
1279function flushBuffer()
1280{
1281    echo str_repeat('          ', 205);
1282    flush();
1283}
1284
1285/**
1286 * A stub for apps that still use this function.
1287 *
1288 * @access  public
1289 * @return  void
1290 */
1291function mailmanAddMember($email, $list, $send_welcome_message=false)
1292{
1293    $app =& App::getInstance();
1294    $app->logMsg(sprintf('mailmanAddMember called and ignored: %s, %s, %s', $email, $list, $send_welcome_message), LOG_WARNING, __FILE__, __LINE__);
1295}
1296
1297/**
1298 * A stub for apps that still use this function.
1299 *
1300 * @access  public
1301 * @return  void
1302 */
1303function mailmanRemoveMember($email, $list, $send_user_ack=false)
1304{
1305    $app =& App::getInstance();
1306    $app->logMsg(sprintf('mailmanRemoveMember called and ignored: %s, %s, %s', $email, $list, $send_user_ack), LOG_WARNING, __FILE__, __LINE__);
1307}
1308
1309/*
1310* Returns the remote IP address, taking into consideration proxy servers.
1311*
1312* If strict checking is enabled, we will only trust REMOTE_ADDR or an HTTP header
1313* value if REMOTE_ADDR is a trusted proxy (configured as an array in $cfg['trusted_proxies']).
1314*
1315* @access   public
1316* @param    bool $dolookup            Resolve to IP to a hostname?
1317* @param    bool $trust_all_proxies   Should we trust any IP address set in HTTP_* variables? Set to FALSE for secure usage.
1318* @return   mixed Canonicalized IP address (or a corresponding hostname if $dolookup is true), or false if no IP was found.
1319* @author   Alix Axel <http://stackoverflow.com/a/2031935/277303>
1320* @author   Corey Ballou <http://blackbe.lt/advanced-method-to-obtain-the-client-ip-in-php/>
1321* @author   Quinn Comendant <quinn@strangecode.com>
1322* @version  1.0
1323* @since    12 Sep 2014 19:07:46
1324*/
1325function getRemoteAddr($dolookup=false, $trust_all_proxies=true)
1326{
1327    global $cfg;
1328
1329    if (!isset($_SERVER['REMOTE_ADDR'])) {
1330        // In some cases this won't be set, e.g., CLI scripts.
1331        return null;
1332    }
1333
1334    // Use an HTTP header value only if $trust_all_proxies is true or when REMOTE_ADDR is in our $cfg['trusted_proxies'] array.
1335    // $cfg['trusted_proxies'] is an array of proxy server addresses we expect to see in REMOTE_ADDR.
1336    if ($trust_all_proxies || isset($cfg['trusted_proxies']) && is_array($cfg['trusted_proxies']) && in_array($_SERVER['REMOTE_ADDR'], $cfg['trusted_proxies'], true)) {
1337        // Then it's probably safe to use an IP address value set in an HTTP header.
1338        // Loop through possible IP address headers from those most likely to contain the correct value first.
1339        // HTTP_CLIENT_IP: set by Apache Module mod_remoteip
1340        // HTTP_REAL_IP: set by Nginx Module ngx_http_realip_module
1341        // HTTP_CF_CONNECTING_IP: set by Cloudflare proxy
1342        // HTTP_X_FORWARDED_FOR: defacto standard for web proxies
1343        foreach (array('HTTP_CLIENT_IP', 'HTTP_REAL_IP', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED') as $key) {
1344            // Loop through and if
1345            if (array_key_exists($key, $_SERVER)) {
1346                foreach (explode(',', $_SERVER[$key]) as $addr) {
1347                    // Strip non-address data to avoid "PHP Warning:  inet_pton(): Unrecognized address for=189.211.197.173 in ./Utilities.inc.php on line 1293"
1348                    $addr = preg_replace('/[^=]=/', '', $addr);
1349                    $addr = canonicalIPAddr(trim($addr));
1350                    if (false !== filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 | FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
1351                        return $dolookup && '' != $addr ? gethostbyaddr($addr) : $addr;
1352                    }
1353                }
1354            }
1355        }
1356    }
1357
1358    $addr = canonicalIPAddr(trim($_SERVER['REMOTE_ADDR']));
1359    return $dolookup && $addr ? gethostbyaddr($addr) : $addr;
1360}
1361
1362/*
1363* Converts an ipv4 IP address in hexadecimal form into canonical form (i.e., it removes the prefix).
1364*
1365* @access   public
1366* @param    string  $addr   IP address.
1367* @return   string          Canonical IP address.
1368* @author   Sander Steffann <http://stackoverflow.com/a/12436099/277303>
1369* @author   Quinn Comendant <quinn@strangecode.com>
1370* @version  1.0
1371* @since    15 Sep 2012
1372*/
1373function canonicalIPAddr($addr)
1374{
1375    if (!preg_match('/^([0-9a-f:]+|[0-9.])$/', $addr)) {
1376        // Definitely not an IPv6 or IPv4 address.
1377        return $addr;
1378    }
1379
1380    // Known prefix
1381    $v4mapped_prefix_bin = pack('H*', '00000000000000000000ffff');
1382
1383    // Parse
1384    $addr_bin = inet_pton($addr);
1385
1386    // Check prefix
1387    if (substr($addr_bin, 0, strlen($v4mapped_prefix_bin)) == $v4mapped_prefix_bin) {
1388        // Strip prefix
1389        $addr_bin = substr($addr_bin, strlen($v4mapped_prefix_bin));
1390    }
1391
1392    // Convert back to printable address in canonical form
1393    return inet_ntop($addr_bin);
1394}
1395
1396/**
1397 * Tests whether a given IP address can be found in an array of IP address networks.
1398 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
1399 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
1400 *
1401 * @access  public
1402 * @param   string  IP address to search for.
1403 * @param   array   Array of networks to search within.
1404 * @return  mixed   Returns the network that matched on success, false on failure.
1405 */
1406function ipInRange($addr, $networks)
1407{
1408    if (!is_array($networks)) {
1409        $networks = array($networks);
1410    }
1411
1412    $addr_binary = sprintf('%032b', ip2long($addr));
1413    foreach ($networks as $network) {
1414        if (mb_strpos($network, '/') !== false) {
1415            // IP is in CIDR notation.
1416            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
1417            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
1418            if (mb_substr($addr_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
1419               // IP address is within the specified IP range.
1420               return $network;
1421            }
1422        } else {
1423            if ($addr === $network) {
1424               // IP address exactly matches.
1425               return $network;
1426            }
1427        }
1428    }
1429
1430    return false;
1431}
1432
1433/**
1434 * If the given $url is on the same web site, return true. This can be used to
1435 * prevent from sending sensitive info in a get query (like the SID) to another
1436 * domain.
1437 *
1438 * @param  string $url    the URI to test.
1439 * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another.
1440 */
1441function isMyDomain($url)
1442{
1443    static $urls = array();
1444
1445    if (!isset($urls[$url])) {
1446        if (!preg_match('!^https?://!i', $url)) {
1447            // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg").
1448            $urls[$url] = true;
1449        } else {
1450            $urls[$url] = preg_match('!^https?://' . preg_quote(getenv('HTTP_HOST'), '!') . '!i', $url);
1451        }
1452    }
1453    return $urls[$url];
1454}
1455
1456/**
1457 * Takes a URL and returns it without the query or anchor portion
1458 *
1459 * @param  string $url   any kind of URI
1460 * @return string        the URI with ? or # and everything after removed
1461 */
1462function stripQuery($url)
1463{
1464    $app =& App::getInstance();
1465
1466    return preg_replace('/[?#].*$/' . $app->getParam('preg_u'), '', $url);
1467}
1468
1469/**
1470 * Returns a fully qualified URL to the current script, including the query. If you don't need the scheme://, use REQUEST_URI instead.
1471 *
1472 * @return string    a full url to the current script
1473 */
1474function absoluteMe()
1475{
1476    $app =& App::getInstance();
1477
1478    $safe_http_host = preg_replace('/[^a-z\d.:-]/' . $app->getParam('preg_u'), '', getenv('HTTP_HOST'));
1479    return sprintf('%s://%s%s', (getenv('HTTPS') ? 'https' : 'http'), $safe_http_host, getenv('REQUEST_URI'));
1480}
1481
1482/**
1483 * Compares the current url with the referring url.
1484 *
1485 * @param  bool $exclude_query  Remove the query string first before comparing.
1486 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
1487 */
1488function refererIsMe($exclude_query=false)
1489{
1490    $current_url = absoluteMe();
1491    $referrer_url = getenv('HTTP_REFERER');
1492
1493    // If one of the hostnames is an IP address, compare only the path of both.
1494    if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', parse_url($current_url, PHP_URL_HOST)) || preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', parse_url($referrer_url, PHP_URL_HOST))) {
1495        $current_url = preg_replace('@^https?://[^/]+@u', '', $current_url);
1496        $referrer_url = preg_replace('@^https?://[^/]+@u', '', $referrer_url);
1497    }
1498
1499    if ($exclude_query) {
1500        return (stripQuery($current_url) == stripQuery($referrer_url));
1501    } else {
1502        $app =& App::getInstance();
1503        $app->logMsg(sprintf('refererIsMe comparison: %s == %s', $current_url, $referrer_url), LOG_DEBUG, __FILE__, __LINE__);
1504        return ($current_url == $referrer_url);
1505    }
1506}
1507
1508/*
1509* Returns true if the given URL resolves to a resource with a HTTP 2xx or 3xx header response.
1510* The download will abort if it retrieves >= 10KB of data to avoid downloading large files.
1511* We couldn't use CURLOPT_NOBODY (a HEAD request) because some services don't behave without a GET request (ahem, BBC).
1512* This function may not be very portable, if the server doesn't support CURLOPT_PROGRESSFUNCTION.
1513*
1514* @access   public
1515* @param    string  $url    URL to a file.
1516* @return   bool            True if the resource exists, false otherwise.
1517* @author   Quinn Comendant <quinn@strangecode.com>
1518* @version  2.0
1519* @since    02 May 2015 15:10:09
1520*/
1521function httpExists($url)
1522{
1523    $ch = curl_init($url);
1524    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
1525    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1526    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1527    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
1528    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
1529    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Don't pass through data to the browser.
1530    curl_setopt($ch, CURLOPT_BUFFERSIZE, 128); // Frequent progress function calls.
1531    curl_setopt($ch, CURLOPT_NOPROGRESS, false); // Required to use CURLOPT_PROGRESSFUNCTION.
1532    // Function arguments for CURLOPT_PROGRESSFUNCTION changed with php 5.5.0.
1533    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
1534        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($ch, $dltot, $dlcur, $ultot, $ulcur){
1535            // Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error
1536            // 10KB should be enough to catch a few 302 redirect headers and get to the actual content.
1537            return ($dlcur > 10*1024) ? 1 : 0;
1538        });
1539    } else {
1540        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($dltot, $dlcur, $ultot, $ulcur){
1541            // Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error
1542            // 10KB should be enough to catch a few 302 redirect headers and get to the actual content.
1543            return ($dlcur > 10*1024) ? 1 : 0;
1544        });
1545    }
1546    curl_exec($ch);
1547    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1548    return preg_match('/^[23]\d\d$/', $http_code);
1549}
1550
1551/*
1552* Load JSON data from a file and return it as an array (as specified by the json_decode options passed below.)
1553*
1554* @access   public
1555* @param    string  $filename   Name of the file to load. Just exist in the include path.
1556* @param    bool    $assoc      When TRUE, returned objects will be converted into associative arrays.
1557* @param    int     $depth      Recursion depth.
1558* @param    const   $options    Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR.
1559* @return   array               Array of data from the file, or null if there was a problem.
1560* @author   Quinn Comendant <quinn@strangecode.com>
1561* @since    09 Oct 2019 21:32:47
1562*/
1563function jsonDecodeFile($filename, $assoc=true, $depth=512, $options=0)
1564{
1565    $app =& App::getInstance();
1566
1567    if (false === $resolved_filename = stream_resolve_include_path($filename)) {
1568        $app->logMsg(sprintf('JSON file "%s" not found in path "%s"', $filename, get_include_path()), LOG_ERR, __FILE__, __LINE__);
1569        return null;
1570    }
1571
1572    if (!is_readable($resolved_filename)) {
1573        $app->logMsg(sprintf('JSON file is unreadable: %s', $resolved_filename), LOG_ERR, __FILE__, __LINE__);
1574        return null;
1575    }
1576
1577    if (null === $data = json_decode(file_get_contents($resolved_filename), $assoc, $depth, $options)) {
1578        $app->logMsg(sprintf('JSON is unparsable: %s', $resolved_filename), LOG_ERR, __FILE__, __LINE__);
1579        return null;
1580    }
1581
1582    return $data;
1583}
1584
1585/*
1586* Get IP address status from IP Intelligence. https://getipintel.net/free-proxy-vpn-tor-detection-api/#expected_output
1587*
1588* @access   public
1589* @param    string  $ip         IP address to check.
1590* @param    float   $threshold  Return true if the IP score is above this threshold (0-1).
1591* @param    string  $email      Requester email address.
1592* @return   boolean             True if the IP address appears to be a robot, proxy, or VPN.
1593*                               False if the IP address is a residential or business IP address, or the API failed to return a valid response.
1594* @author   Quinn Comendant <quinn@strangecode.com>
1595* @since    26 Oct 2019 15:39:17
1596*/
1597function IPIntelligenceBadIP($ip, $threshold=0.95, $email='hello@strangecode.com')
1598{
1599    $app =& App::getInstance();
1600
1601    $ch = curl_init(sprintf('http://check.getipintel.net/check.php?ip=%s&contact=%s', urlencode($ip), urlencode($email)));
1602    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
1603    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1604    $response = curl_exec($ch);
1605    $errorno = curl_errno($ch);
1606    $error = curl_error($ch);
1607    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1608    curl_close($ch);
1609
1610    if ($errorno == CURLE_OPERATION_TIMEOUTED) {
1611        $http_code = 408;
1612    }
1613
1614    switch ($http_code) {
1615    case 200:
1616    case 400:
1617        // Check response value, below.
1618        break;
1619
1620    case 408:
1621        $app->logMsg(sprintf('IP Intelligence timeout', null), LOG_WARNING, __FILE__, __LINE__);
1622        return false;
1623    case 429:
1624        $app->logMsg(sprintf('IP Intelligence number of allowed queries exceeded (rate limit 15 requests/minute)', null), LOG_WARNING, __FILE__, __LINE__);
1625        return false;
1626    default:
1627        $app->logMsg(sprintf('IP Intelligence unexpected response (%s): %s: %s', $http_code, $error, $response), LOG_ERR, __FILE__, __LINE__);
1628        return false;
1629    }
1630
1631    switch ($response) {
1632    case -1:
1633        $app->logMsg('IP Intelligence: Invalid no input', LOG_WARNING, __FILE__, __LINE__);
1634        return false;
1635    case -2:
1636        $app->logMsg('IP Intelligence: Invalid IP address', LOG_WARNING, __FILE__, __LINE__);
1637        return false;
1638    case -3:
1639        $app->logMsg('IP Intelligence: Unroutable or private address', LOG_WARNING, __FILE__, __LINE__);
1640        return false;
1641    case -4:
1642        $app->logMsg('IP Intelligence: Unable to reach database', LOG_WARNING, __FILE__, __LINE__);
1643        return false;
1644    case -5:
1645        $app->logMsg('IP Intelligence: Banned: no permission or invalid email address', LOG_WARNING, __FILE__, __LINE__);
1646        return false;
1647    case -6:
1648        $app->logMsg('IP Intelligence: Invalid contact information', LOG_WARNING, __FILE__, __LINE__);
1649        return false;
1650    default:
1651        if (!is_numeric($response) || $response < 0 || $response >= $threshold) {
1652            $app->logMsg(sprintf('IP Intelligence: Bad IP (%s): %s', $response, $ip), LOG_NOTICE, __FILE__, __LINE__);
1653            return true;
1654        }
1655        $app->logMsg(sprintf('IP Intelligence: Good IP (%s): %s', $response, $ip), LOG_NOTICE, __FILE__, __LINE__);
1656        return false;
1657    }
1658}
Note: See TracBrowser for help on using the repository browser.