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

Last change on this file since 742 was 742, checked in by anonymous, 3 years ago

Add urlMergeQuery() function

File size: 62.6 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    $array_args = urlEncodeArray($data, $prefix);
902    $url_args = '';
903    $delim = '';
904    foreach ($array_args as $key=>$val) {
905        $url_args .= $delim . $key . '=' . $val;
906        $delim = ini_get('arg_separator.output');
907    }
908    return $url_args;
909}
910
911/**
912 * Fills an array with the result from a multiple ereg search.
913 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
914 *
915 * @param  mixed $pattern   regular expression needle
916 * @param  mixed $string   haystack
917 * @return array    populated with each found result
918 */
919function eregAll($pattern, $string)
920{
921    do {
922        if (!mb_ereg($pattern, $string, $temp)) {
923             continue;
924        }
925        $string = str_replace($temp[0], '', $string);
926        $results[] = $temp;
927    } while (mb_ereg($pattern, $string, $temp));
928    return $results;
929}
930
931/**
932 * Prints the word "checked" if a variable is set, and optionally matches
933 * the desired value, otherwise prints nothing,
934 * used for printing the word "checked" in a checkbox form input.
935 *
936 * @param  mixed $var     the variable to compare
937 * @param  mixed $value   optional, what to compare with if a specific value is required.
938 */
939function frmChecked($var, $value=null)
940{
941    if (func_num_args() == 1 && $var) {
942        // 'Checked' if var is true.
943        echo ' checked="checked" ';
944    } else if (func_num_args() == 2 && $var == $value) {
945        // 'Checked' if var and value match.
946        echo ' checked="checked" ';
947    } else if (func_num_args() == 2 && is_array($var)) {
948        // 'Checked' if the value is in the key or the value of an array.
949        if (isset($var[$value])) {
950            echo ' checked="checked" ';
951        } else if (in_array($value, $var)) {
952            echo ' checked="checked" ';
953        }
954    }
955}
956
957/**
958 * prints the word "selected" if a variable is set, and optionally matches
959 * the desired value, otherwise prints nothing,
960 * otherwise prints nothing, used for printing the word "checked" in a
961 * select form input
962 *
963 * @param  mixed $var     the variable to compare
964 * @param  mixed $value   optional, what to compare with if a specific value is required.
965 */
966function frmSelected($var, $value=null)
967{
968    if (func_num_args() == 1 && $var) {
969        // 'selected' if var is true.
970        echo ' selected="selected" ';
971    } else if (func_num_args() == 2 && $var == $value) {
972        // 'selected' if var and value match.
973        echo ' selected="selected" ';
974    } else if (func_num_args() == 2 && is_array($var)) {
975        // 'selected' if the value is in the key or the value of an array.
976        if (isset($var[$value])) {
977            echo ' selected="selected" ';
978        } else if (in_array($value, $var)) {
979            echo ' selected="selected" ';
980        }
981    }
982}
983
984/**
985 * Adds slashes to values of an array and converts the array to a comma
986 * delimited list. If value provided is a string return the string
987 * escaped.  This is useful for putting values coming in from posted
988 * checkboxes into a SET column of a database.
989 *
990 *
991 * @param  array $in      Array to convert.
992 * @return string         Comma list of array values.
993 */
994function escapedList($in, $separator="', '")
995{
996    require_once dirname(__FILE__) . '/DB.inc.php';
997    $db =& DB::getInstance();
998
999    if (is_array($in) && !empty($in)) {
1000        return join($separator, array_map(array($db, 'escapeString'), $in));
1001    } else {
1002        return $db->escapeString($in);
1003    }
1004}
1005
1006/**
1007 * Converts a human string date into a SQL-safe date.  Dates nearing
1008 * infinity use the date 2038-01-01 so conversion to unix time format
1009 * remain within valid range.
1010 *
1011 * @param  array $date     String date to convert.
1012 * @param  array $format   Date format to pass to date(). Default produces MySQL datetime: YYYY-MM-DD hh:mm:ss
1013 * @return string          SQL-safe date.
1014 */
1015function strToSQLDate($date, $format='Y-m-d H:i:s')
1016{
1017    require_once dirname(__FILE__) . '/DB.inc.php';
1018    $db =& DB::getInstance();
1019
1020    if ($db->isConnected() && mb_strpos($db->getParam('zero_date'), '-') !== false) {
1021        // Mysql version >= 5.7.4 stopped allowing a "zero" date of 0000-00-00.
1022        // https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_date
1023        $zero_date_parts = explode('-', $db->getParam('zero_date'));
1024        $zero_y = $zero_date_parts[0];
1025        $zero_m = $zero_date_parts[1];
1026        $zero_d = $zero_date_parts[2];
1027    } else {
1028        $zero_y = '0000';
1029        $zero_m = '00';
1030        $zero_d = '00';
1031    }
1032    // Translate the human string date into SQL-safe date format.
1033    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) {
1034        // Return a string of zero time, formatted the same as $format.
1035        return strtr($format, array(
1036            'Y' => $zero_y,
1037            'm' => $zero_m,
1038            'd' => $zero_d,
1039            'H' => '00',
1040            'i' => '00',
1041            's' => '00',
1042        ));
1043    } else {
1044        return date($format, strtotime($date));
1045    }
1046}
1047
1048/**
1049 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
1050 * array, stripslashes is run on each value, recursively, and the stripped
1051 * array is returned.
1052 *
1053 * @param  mixed $var   The string or array to un-quote, if necessary.
1054 * @return mixed        $var, minus any magic quotes.
1055 */
1056function dispelMagicQuotes($var, $always=false)
1057{
1058    static $magic_quotes_gpc;
1059
1060    if (!isset($magic_quotes_gpc)) {
1061        $magic_quotes_gpc = version_compare(PHP_VERSION, '5.4.0', '<') ? get_magic_quotes_gpc() : false;
1062    }
1063
1064    if ($always || $magic_quotes_gpc) {
1065        if (!is_array($var)) {
1066            $var = stripslashes($var);
1067        } else {
1068            foreach ($var as $key=>$val) {
1069                if (is_array($val)) {
1070                    $var[$key] = dispelMagicQuotes($val, $always);
1071                } else {
1072                    $var[$key] = stripslashes($val);
1073                }
1074            }
1075        }
1076    }
1077    return $var;
1078}
1079
1080/**
1081 * Get a form variable from GET or POST data, stripped of magic
1082 * quotes if necessary.
1083 *
1084 * @param string $key (optional) The name of a $_REQUEST key.
1085 * @param string $default (optional) The value to return if the
1086 *                                   variable is not there.
1087 * @return mixed      A cleaned GET or POST array if no key specified.
1088 * @return string     A cleaned form value if found, or $default.
1089 */
1090function getFormData($key=null, $default=null)
1091{
1092    $app =& App::getInstance();
1093
1094    if (null === $key) {
1095        // Return entire array.
1096        switch (strtoupper(getenv('REQUEST_METHOD'))) {
1097        case 'POST':
1098            return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
1099
1100        case 'GET':
1101            return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
1102
1103        default:
1104            return dispelMagicQuotes($_REQUEST, $app->getParam('always_dispel_magicquotes'));
1105        }
1106    }
1107
1108    if (isset($_REQUEST[$key])) {
1109        // $key is found in the flat array of REQUEST.
1110        return dispelMagicQuotes($_REQUEST[$key], $app->getParam('always_dispel_magicquotes'));
1111    } else if (mb_strpos($key, '[') !== false && isset($_REQUEST[strtok($key, '[')]) && preg_match_all('/\[([a-z0-9._~-]+)\]/', $key, $matches)) {
1112        // $key is formatted with sub-keys, e.g., getFormData('foo[bar][baz]') and top level key (`foo`) exists in REQUEST.
1113        // Extract these as sub-keys and access REQUEST as a multi-dimensional array, e.g., $_REQUEST[foo][bar][baz].
1114        $leaf = $_REQUEST[strtok($key, '[')];
1115        foreach ($matches[1] as $subkey) {
1116            if (is_array($leaf) && isset($leaf[$subkey])) {
1117                $leaf = $leaf[$subkey];
1118            } else {
1119                $leaf = null;
1120            }
1121        }
1122        return $leaf;
1123    } else {
1124        return $default;
1125    }
1126}
1127
1128function getPost($key=null, $default=null)
1129{
1130    $app =& App::getInstance();
1131
1132    if (null === $key) {
1133        return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
1134    }
1135    if (isset($_POST[$key])) {
1136        return dispelMagicQuotes($_POST[$key], $app->getParam('always_dispel_magicquotes'));
1137    } else {
1138        return $default;
1139    }
1140}
1141
1142function getGet($key=null, $default=null)
1143{
1144    $app =& App::getInstance();
1145
1146    if (null === $key) {
1147        return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
1148    }
1149    if (isset($_GET[$key])) {
1150        return dispelMagicQuotes($_GET[$key], $app->getParam('always_dispel_magicquotes'));
1151    } else {
1152        return $default;
1153    }
1154}
1155
1156/*
1157* Sets a $_GET or $_POST variable.
1158*
1159* @access   public
1160* @param    string  $key    The key of the request array to set.
1161* @param    mixed   $val    The value to save in the request array.
1162* @return   void
1163* @author   Quinn Comendant <quinn@strangecode.com>
1164* @version  1.0
1165* @since    01 Nov 2009 12:25:29
1166*/
1167function putFormData($key, $val)
1168{
1169    switch (strtoupper(getenv('REQUEST_METHOD'))) {
1170    case 'POST':
1171        $_POST[$key] = $val;
1172        break;
1173
1174    case 'GET':
1175        $_GET[$key] = $val;
1176        break;
1177    }
1178
1179    $_REQUEST[$key] = $val;
1180}
1181
1182/*
1183* Generates a base-65-encoded sha512 hash of $string truncated to $length.
1184*
1185* @access   public
1186* @param    string  $string Input string to hash.
1187* @param    int     $length Length of output hash string.
1188* @return   string          String of hash.
1189* @author   Quinn Comendant <quinn@strangecode.com>
1190* @version  1.0
1191* @since    03 Apr 2016 19:48:49
1192*/
1193function hash64($string, $length=18)
1194{
1195    $app =& App::getInstance();
1196
1197    return mb_substr(preg_replace('/[^\w]/' . $app->getParam('preg_u'), '', base64_encode(hash('sha512', $string, true))), 0, $length);
1198}
1199
1200/**
1201 * Signs a value using md5 and a simple text key. In order for this
1202 * function to be useful (i.e. secure) the salt must be kept secret, which
1203 * means keeping it as safe as database credentials. Putting it into an
1204 * environment variable set in httpd.conf is a good place.
1205 *
1206 * @access  public
1207 * @param   string  $val    The string to sign.
1208 * @param   string  $salt   (Optional) A text key to use for computing the signature.
1209 * @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.
1210 * @return  string  The original value with a signature appended.
1211 */
1212function addSignature($val, $salt=null, $length=18)
1213{
1214    $app =& App::getInstance();
1215
1216    if ('' == trim($val)) {
1217        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
1218        return '';
1219    }
1220
1221    if (!isset($salt)) {
1222        $salt = $app->getParam('signing_key');
1223    }
1224
1225    switch ($app->getParam('signing_method')) {
1226    case 'sha512+base64':
1227        return $val . '-' . mb_substr(preg_replace('/[^\w]/' . $app->getParam('preg_u'), '', base64_encode(hash('sha512', $val . $salt, true))), 0, $length);
1228
1229    case 'md5':
1230    default:
1231        return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
1232    }
1233}
1234
1235/**
1236 * Strips off the signature appended by addSignature().
1237 *
1238 * @access  public
1239 * @param   string  $signed_val     The string to sign.
1240 * @return  string  The original value with a signature removed.
1241 */
1242function removeSignature($signed_val)
1243{
1244    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
1245        return '';
1246    }
1247    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
1248}
1249
1250/**
1251 * Verifies a signature appended to a value by addSignature().
1252 *
1253 * @access  public
1254 * @param   string  $signed_val A value with appended signature.
1255 * @param   string  $salt       (Optional) A text key to use for computing the signature.
1256 * @param   string  $length (Optional) The length of the added signature.
1257 * @return  bool    True if the signature matches the var.
1258 */
1259function verifySignature($signed_val, $salt=null, $length=18)
1260{
1261    // Strip the value from the signed value.
1262    $val = removeSignature($signed_val);
1263    // If the signed value matches the original signed value we consider the value safe.
1264    if ('' != $signed_val && $signed_val == addSignature($val, $salt, $length)) {
1265        // Signature verified.
1266        return true;
1267    } else {
1268        $app =& App::getInstance();
1269        $app->logMsg(sprintf('Failed signature (%s should be %s)', $signed_val, addSignature($val, $salt, $length)), LOG_DEBUG, __FILE__, __LINE__);
1270        return false;
1271    }
1272}
1273
1274/**
1275 * Sends empty output to the browser and flushes the php buffer so the client
1276 * will see data before the page is finished processing.
1277 */
1278function flushBuffer()
1279{
1280    echo str_repeat('          ', 205);
1281    flush();
1282}
1283
1284/**
1285 * A stub for apps that still use this function.
1286 *
1287 * @access  public
1288 * @return  void
1289 */
1290function mailmanAddMember($email, $list, $send_welcome_message=false)
1291{
1292    $app =& App::getInstance();
1293    $app->logMsg(sprintf('mailmanAddMember called and ignored: %s, %s, %s', $email, $list, $send_welcome_message), LOG_WARNING, __FILE__, __LINE__);
1294}
1295
1296/**
1297 * A stub for apps that still use this function.
1298 *
1299 * @access  public
1300 * @return  void
1301 */
1302function mailmanRemoveMember($email, $list, $send_user_ack=false)
1303{
1304    $app =& App::getInstance();
1305    $app->logMsg(sprintf('mailmanRemoveMember called and ignored: %s, %s, %s', $email, $list, $send_user_ack), LOG_WARNING, __FILE__, __LINE__);
1306}
1307
1308/*
1309* Returns the remote IP address, taking into consideration proxy servers.
1310*
1311* If strict checking is enabled, we will only trust REMOTE_ADDR or an HTTP header
1312* value if REMOTE_ADDR is a trusted proxy (configured as an array in $cfg['trusted_proxies']).
1313*
1314* @access   public
1315* @param    bool $dolookup            Resolve to IP to a hostname?
1316* @param    bool $trust_all_proxies   Should we trust any IP address set in HTTP_* variables? Set to FALSE for secure usage.
1317* @return   mixed Canonicalized IP address (or a corresponding hostname if $dolookup is true), or false if no IP was found.
1318* @author   Alix Axel <http://stackoverflow.com/a/2031935/277303>
1319* @author   Corey Ballou <http://blackbe.lt/advanced-method-to-obtain-the-client-ip-in-php/>
1320* @author   Quinn Comendant <quinn@strangecode.com>
1321* @version  1.0
1322* @since    12 Sep 2014 19:07:46
1323*/
1324function getRemoteAddr($dolookup=false, $trust_all_proxies=true)
1325{
1326    global $cfg;
1327
1328    if (!isset($_SERVER['REMOTE_ADDR'])) {
1329        // In some cases this won't be set, e.g., CLI scripts.
1330        return null;
1331    }
1332
1333    // Use an HTTP header value only if $trust_all_proxies is true or when REMOTE_ADDR is in our $cfg['trusted_proxies'] array.
1334    // $cfg['trusted_proxies'] is an array of proxy server addresses we expect to see in REMOTE_ADDR.
1335    if ($trust_all_proxies || isset($cfg['trusted_proxies']) && is_array($cfg['trusted_proxies']) && in_array($_SERVER['REMOTE_ADDR'], $cfg['trusted_proxies'], true)) {
1336        // Then it's probably safe to use an IP address value set in an HTTP header.
1337        // Loop through possible IP address headers from those most likely to contain the correct value first.
1338        // HTTP_CLIENT_IP: set by Apache Module mod_remoteip
1339        // HTTP_REAL_IP: set by Nginx Module ngx_http_realip_module
1340        // HTTP_CF_CONNECTING_IP: set by Cloudflare proxy
1341        // HTTP_X_FORWARDED_FOR: defacto standard for web proxies
1342        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) {
1343            // Loop through and if
1344            if (array_key_exists($key, $_SERVER)) {
1345                foreach (explode(',', $_SERVER[$key]) as $addr) {
1346                    // Strip non-address data to avoid "PHP Warning:  inet_pton(): Unrecognized address for=189.211.197.173 in ./Utilities.inc.php on line 1293"
1347                    $addr = preg_replace('/[^=]=/', '', $addr);
1348                    $addr = canonicalIPAddr(trim($addr));
1349                    if (false !== filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 | FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
1350                        return $dolookup && '' != $addr ? gethostbyaddr($addr) : $addr;
1351                    }
1352                }
1353            }
1354        }
1355    }
1356
1357    $addr = canonicalIPAddr(trim($_SERVER['REMOTE_ADDR']));
1358    return $dolookup && $addr ? gethostbyaddr($addr) : $addr;
1359}
1360
1361/*
1362* Converts an ipv4 IP address in hexadecimal form into canonical form (i.e., it removes the prefix).
1363*
1364* @access   public
1365* @param    string  $addr   IP address.
1366* @return   string          Canonical IP address.
1367* @author   Sander Steffann <http://stackoverflow.com/a/12436099/277303>
1368* @author   Quinn Comendant <quinn@strangecode.com>
1369* @version  1.0
1370* @since    15 Sep 2012
1371*/
1372function canonicalIPAddr($addr)
1373{
1374    if (!preg_match('/^([0-9a-f:]+|[0-9.])$/', $addr)) {
1375        // Definitely not an IPv6 or IPv4 address.
1376        return $addr;
1377    }
1378
1379    // Known prefix
1380    $v4mapped_prefix_bin = pack('H*', '00000000000000000000ffff');
1381
1382    // Parse
1383    $addr_bin = inet_pton($addr);
1384
1385    // Check prefix
1386    if (substr($addr_bin, 0, strlen($v4mapped_prefix_bin)) == $v4mapped_prefix_bin) {
1387        // Strip prefix
1388        $addr_bin = substr($addr_bin, strlen($v4mapped_prefix_bin));
1389    }
1390
1391    // Convert back to printable address in canonical form
1392    return inet_ntop($addr_bin);
1393}
1394
1395/**
1396 * Tests whether a given IP address can be found in an array of IP address networks.
1397 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
1398 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
1399 *
1400 * @access  public
1401 * @param   string  IP address to search for.
1402 * @param   array   Array of networks to search within.
1403 * @return  mixed   Returns the network that matched on success, false on failure.
1404 */
1405function ipInRange($addr, $networks)
1406{
1407    if (!is_array($networks)) {
1408        $networks = array($networks);
1409    }
1410
1411    $addr_binary = sprintf('%032b', ip2long($addr));
1412    foreach ($networks as $network) {
1413        if (mb_strpos($network, '/') !== false) {
1414            // IP is in CIDR notation.
1415            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
1416            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
1417            if (mb_substr($addr_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
1418               // IP address is within the specified IP range.
1419               return $network;
1420            }
1421        } else {
1422            if ($addr === $network) {
1423               // IP address exactly matches.
1424               return $network;
1425            }
1426        }
1427    }
1428
1429    return false;
1430}
1431
1432/**
1433 * If the given $url is on the same web site, return true. This can be used to
1434 * prevent from sending sensitive info in a get query (like the SID) to another
1435 * domain.
1436 *
1437 * @param  string $url    the URI to test.
1438 * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another.
1439 */
1440function isMyDomain($url)
1441{
1442    static $urls = array();
1443
1444    if (!isset($urls[$url])) {
1445        if (!preg_match('!^https?://!i', $url)) {
1446            // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg").
1447            $urls[$url] = true;
1448        } else {
1449            $urls[$url] = preg_match('!^https?://' . preg_quote(getenv('HTTP_HOST'), '!') . '!i', $url);
1450        }
1451    }
1452    return $urls[$url];
1453}
1454
1455/**
1456 * Takes a URL and returns it without the query or anchor portion
1457 *
1458 * @param  string $url   any kind of URI
1459 * @return string        the URI with ? or # and everything after removed
1460 */
1461function stripQuery($url)
1462{
1463    $app =& App::getInstance();
1464
1465    return preg_replace('/[?#].*$/' . $app->getParam('preg_u'), '', $url);
1466}
1467
1468/*
1469* Merge query arguments into a URL.
1470* Usage:
1471* Add ?lang=it or replace an existing ?lang= argument:
1472* $url = urlMerge('https://example.com/?lang=en', ['lang' => 'it']).
1473*
1474* @access   public
1475* @param    string  $url        Original URL.
1476* @param    array   $new_args   New/modified query arguments.
1477* @return   string              Modified URL.
1478* @author   Quinn Comendant <quinn@strangecode.com>
1479* @since    20 Feb 2021 21:21:53
1480*/
1481function urlMergeQuery($url, Array $new_args)
1482{
1483    $u = parse_url($url);
1484    if (isset($u['query']) && '' != $u['query']) {
1485        parse_str($u['query'], $args);
1486    } else {
1487        $args = [];
1488    }
1489    $u['query'] = http_build_query(array_merge($args, $new_args));
1490    return sprintf('%s%s%s%s%s',
1491        (isset($u['scheme'])    && '' != $u['scheme']   ? $u['scheme'] . '://' : ''),
1492        (isset($u['host'])      && '' != $u['host']     ? $u['host']           : ''),
1493        (isset($u['path'])      && '' != $u['path']     ? $u['path']           : '/'),
1494        (isset($u['query'])     && '' != $u['query']    ? '?' . $u['query']    : ''),
1495        (isset($u['fragment'])  && '' != $u['fragment'] ? '#' . $u['fragment'] : '')
1496    );
1497}
1498
1499/**
1500 * Returns a fully qualified URL to the current script, including the query. If you don't need the scheme://, use REQUEST_URI instead.
1501 *
1502 * @return string    a full url to the current script
1503 */
1504function absoluteMe()
1505{
1506    $app =& App::getInstance();
1507
1508    $safe_http_host = preg_replace('/[^a-z\d.:-]/' . $app->getParam('preg_u'), '', getenv('HTTP_HOST'));
1509    return sprintf('%s://%s%s', (getenv('HTTPS') ? 'https' : 'http'), $safe_http_host, getenv('REQUEST_URI'));
1510}
1511
1512/**
1513 * Compares the current url with the referring url.
1514 *
1515 * @param  bool $exclude_query  Remove the query string first before comparing.
1516 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
1517 */
1518function refererIsMe($exclude_query=false)
1519{
1520    $current_url = absoluteMe();
1521    $referrer_url = getenv('HTTP_REFERER');
1522
1523    // If one of the hostnames is an IP address, compare only the path of both.
1524    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))) {
1525        $current_url = preg_replace('@^https?://[^/]+@u', '', $current_url);
1526        $referrer_url = preg_replace('@^https?://[^/]+@u', '', $referrer_url);
1527    }
1528
1529    if ($exclude_query) {
1530        return (stripQuery($current_url) == stripQuery($referrer_url));
1531    } else {
1532        $app =& App::getInstance();
1533        $app->logMsg(sprintf('refererIsMe comparison: %s == %s', $current_url, $referrer_url), LOG_DEBUG, __FILE__, __LINE__);
1534        return ($current_url == $referrer_url);
1535    }
1536}
1537
1538/*
1539* Returns true if the given URL resolves to a resource with a HTTP 2xx or 3xx header response.
1540* The download will abort if it retrieves >= 10KB of data to avoid downloading large files.
1541* We couldn't use CURLOPT_NOBODY (a HEAD request) because some services don't behave without a GET request (ahem, BBC).
1542* This function may not be very portable, if the server doesn't support CURLOPT_PROGRESSFUNCTION.
1543*
1544* @access   public
1545* @param    string  $url    URL to a file.
1546* @return   bool            True if the resource exists, false otherwise.
1547* @author   Quinn Comendant <quinn@strangecode.com>
1548* @version  2.0
1549* @since    02 May 2015 15:10:09
1550*/
1551function httpExists($url, $timeout=5)
1552{
1553    $ch = curl_init($url);
1554    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1555    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1556    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1557    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
1558    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");
1559    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Don't pass through data to the browser.
1560    curl_setopt($ch, CURLOPT_BUFFERSIZE, 128); // Frequent progress function calls.
1561    curl_setopt($ch, CURLOPT_NOPROGRESS, false); // Required to use CURLOPT_PROGRESSFUNCTION.
1562    // Function arguments for CURLOPT_PROGRESSFUNCTION changed with php 5.5.0.
1563    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
1564        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($ch, $dltot, $dlcur, $ultot, $ulcur){
1565            // Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error
1566            // 10KB should be enough to catch a few 302 redirect headers and get to the actual content.
1567            return ($dlcur > 10*1024) ? 1 : 0;
1568        });
1569    } else {
1570        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($dltot, $dlcur, $ultot, $ulcur){
1571            // Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error
1572            // 10KB should be enough to catch a few 302 redirect headers and get to the actual content.
1573            return ($dlcur > 10*1024) ? 1 : 0;
1574        });
1575    }
1576    curl_exec($ch);
1577    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1578    return preg_match('/^[23]\d\d$/', $http_code);
1579}
1580
1581/*
1582* Get a HTTP response header.
1583*
1584* @access   public
1585* @param    string  $url    URL to hit.
1586* @param    string  $key    Name of the header to return.
1587* @param    array   $valid_response_codes   Array of acceptable HTTP return codes.
1588* @return   string  Value of the http header.
1589* @author   Quinn Comendant <quinn@strangecode.com>
1590* @since    28 Oct 2020 20:00:36
1591*/
1592function getHttpHeader($url, $key, Array $valid_response_codes=[200])
1593{
1594    $headers = @get_headers($url, 1);
1595
1596    if ($headers && preg_match(sprintf('/\b(%s)\b/', join('|', $valid_response_codes)), $headers[0])) {
1597        $headers = array_change_key_case($headers, CASE_LOWER);
1598        $key = strtolower($key);
1599        if (isset($headers[$key])) {
1600            return $headers[$key];
1601        }
1602    }
1603
1604    return false;
1605}
1606
1607/*
1608* Load JSON data from a file and return it as an array (as specified by the json_decode options passed below.)
1609*
1610* @access   public
1611* @param    string  $filename   Name of the file to load. Just exist in the include path.
1612* @param    bool    $assoc      When TRUE, returned objects will be converted into associative arrays.
1613* @param    int     $depth      Recursion depth.
1614* @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.
1615* @return   array               Array of data from the file, or null if there was a problem.
1616* @author   Quinn Comendant <quinn@strangecode.com>
1617* @since    09 Oct 2019 21:32:47
1618*/
1619function jsonDecodeFile($filename, $assoc=true, $depth=512, $options=0)
1620{
1621    $app =& App::getInstance();
1622
1623    if (false === $resolved_filename = stream_resolve_include_path($filename)) {
1624        $app->logMsg(sprintf('JSON file "%s" not found in path "%s"', $filename, get_include_path()), LOG_ERR, __FILE__, __LINE__);
1625        return null;
1626    }
1627
1628    if (!is_readable($resolved_filename)) {
1629        $app->logMsg(sprintf('JSON file is unreadable: %s', $resolved_filename), LOG_ERR, __FILE__, __LINE__);
1630        return null;
1631    }
1632
1633    if (null === $data = json_decode(file_get_contents($resolved_filename), $assoc, $depth, $options)) {
1634        $app->logMsg(sprintf('JSON is unparsable: %s', $resolved_filename), LOG_ERR, __FILE__, __LINE__);
1635        return null;
1636    }
1637
1638    return $data;
1639}
1640
1641/*
1642* Get IP address status from IP Intelligence. https://getipintel.net/free-proxy-vpn-tor-detection-api/#expected_output
1643*
1644* @access   public
1645* @param    string  $ip         IP address to check.
1646* @param    float   $threshold  Return true if the IP score is above this threshold (0-1).
1647* @param    string  $email      Requester email address.
1648* @return   boolean             True if the IP address appears to be a robot, proxy, or VPN.
1649*                               False if the IP address is a residential or business IP address, or the API failed to return a valid response.
1650* @author   Quinn Comendant <quinn@strangecode.com>
1651* @since    26 Oct 2019 15:39:17
1652*/
1653function IPIntelligenceBadIP($ip, $threshold=0.95, $email='hello@strangecode.com')
1654{
1655    $app =& App::getInstance();
1656
1657    $ch = curl_init(sprintf('http://check.getipintel.net/check.php?ip=%s&contact=%s', urlencode($ip), urlencode($email)));
1658    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
1659    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1660    $response = curl_exec($ch);
1661    $errorno = curl_errno($ch);
1662    $error = curl_error($ch);
1663    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1664    curl_close($ch);
1665
1666    if ($errorno == CURLE_OPERATION_TIMEOUTED) {
1667        $http_code = 408;
1668    }
1669
1670    switch ($http_code) {
1671    case 200:
1672    case 400:
1673        // Check response value, below.
1674        break;
1675
1676    case 408:
1677        $app->logMsg(sprintf('IP Intelligence timeout', null), LOG_WARNING, __FILE__, __LINE__);
1678        return false;
1679    case 429:
1680        $app->logMsg(sprintf('IP Intelligence number of allowed queries exceeded (rate limit 15 requests/minute)', null), LOG_WARNING, __FILE__, __LINE__);
1681        return false;
1682    default:
1683        $app->logMsg(sprintf('IP Intelligence unexpected response (%s): %s: %s', $http_code, $error, $response), LOG_ERR, __FILE__, __LINE__);
1684        return false;
1685    }
1686
1687    switch ($response) {
1688    case -1:
1689        $app->logMsg('IP Intelligence: Invalid no input', LOG_WARNING, __FILE__, __LINE__);
1690        return false;
1691    case -2:
1692        $app->logMsg('IP Intelligence: Invalid IP address', LOG_WARNING, __FILE__, __LINE__);
1693        return false;
1694    case -3:
1695        $app->logMsg('IP Intelligence: Unroutable or private address', LOG_WARNING, __FILE__, __LINE__);
1696        return false;
1697    case -4:
1698        $app->logMsg('IP Intelligence: Unable to reach database', LOG_WARNING, __FILE__, __LINE__);
1699        return false;
1700    case -5:
1701        $app->logMsg('IP Intelligence: Banned: no permission or invalid email address', LOG_WARNING, __FILE__, __LINE__);
1702        return false;
1703    case -6:
1704        $app->logMsg('IP Intelligence: Invalid contact information', LOG_WARNING, __FILE__, __LINE__);
1705        return false;
1706    default:
1707        if (!is_numeric($response) || $response < 0 || $response >= $threshold) {
1708            $app->logMsg(sprintf('IP Intelligence: Bad IP (%s): %s', $response, $ip), LOG_NOTICE, __FILE__, __LINE__);
1709            return true;
1710        }
1711        $app->logMsg(sprintf('IP Intelligence: Good IP (%s): %s', $response, $ip), LOG_NOTICE, __FILE__, __LINE__);
1712        return false;
1713    }
1714}
1715
1716/*
1717* Test if a string is valid json.
1718* https://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php
1719*
1720* @access   public
1721* @param    string  $str  The string to test.
1722* @return   boolean       True if the string is valid json.
1723* @author   Quinn Comendant <quinn@strangecode.com>
1724* @since    06 Dec 2020 18:41:51
1725*/
1726function isJSON($str)
1727{
1728    json_decode($str);
1729    return (json_last_error() === JSON_ERROR_NONE);
1730}
Note: See TracBrowser for help on using the repository browser.