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

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

Add App::unsetCookie(). Quench some PHP 8 depreciation notices.

File size: 66.9 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  const    $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);
40define('SC_DUMP_JSON', 3);
41function dump($var, $display=false, $dump_method=SC_DUMP_PRINT_R, $file='', $line='')
42{
43    $app =& App::getInstance();
44
45    if ($app->isCLI()) {
46        echo ('' != $file . $line) ? "DUMP FROM: $file $line\n" : "DUMP:\n";
47    } else {
48        echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n";
49    }
50
51    switch ($dump_method) {
52    case SC_DUMP_PRINT_R:
53    default:
54        // Print human-readable descriptions of invisible types.
55        if (null === $var) {
56            echo '(null)';
57        } else if (true === $var) {
58            echo '(bool: true)';
59        } else if (false === $var) {
60            echo '(bool: false)';
61        } else if (is_scalar($var) && '' === $var) {
62            echo '(empty string)';
63        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
64            echo '(only white space)';
65        } else {
66            print_r($var);
67        }
68        break;
69
70    case SC_DUMP_VAR_DUMP:
71        var_dump($var);
72        break;
73
74    case SC_DUMP_VAR_EXPORT:
75        var_export($var);
76        break;
77
78    case SC_DUMP_JSON:
79        echo json_encode($var, JSON_PRETTY_PRINT);
80        break;
81    }
82
83    if ($app->isCLI()) {
84        echo "\n";
85    } else {
86        echo $display ? "\n</pre><br />\n" : "\n-->\n";
87    }
88}
89
90/*
91* Log a PHP variable to javascript console. Relies on getDump(), below.
92*
93* @access   public
94* @param    mixed   $var      The variable to dump.
95* @param    string  $prefix   A short note to print before the output to make identifying output easier.
96* @param    string  $file     The value of __FILE__.
97* @param    string  $line     The value of __LINE__.
98* @return   null
99* @author   Quinn Comendant <quinn@strangecode.com>
100*/
101function jsDump($var, $prefix='jsDump', $file='-', $line='-')
102{
103    if (!empty($var)) {
104        ?>
105        <script type="text/javascript">
106        /* <![CDATA[ */
107        console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
108        /* ]]> */
109        </script>
110        <?php
111    }
112}
113
114/*
115* Return a string version of any variable, optionally serialized on one line.
116*
117* @access   public
118* @param    mixed   $var            The variable to dump.
119* @param    bool    $serialize      If true, remove line-endings. Useful for logging variables.
120* @param    const   $dump_method    Dump method. See SC_DUMP_* constants.
121* @return   string                  The dumped variable.
122* @author   Quinn Comendant <quinn@strangecode.com>
123*/
124function getDump($var, $serialize=false, $dump_method=SC_DUMP_PRINT_R)
125{
126    $app =& App::getInstance();
127
128    switch ($dump_method) {
129    case SC_DUMP_PRINT_R:
130    default:
131        // Print human-readable descriptions of invisible types.
132        if (null === $var) {
133            $d = '(null)';
134        } else if (true === $var) {
135            $d = '(bool: true)';
136        } else if (false === $var) {
137            $d = '(bool: false)';
138        } else if (is_scalar($var) && '' === $var) {
139            $d = '(empty string)';
140        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
141            $d = '(only white space)';
142        } else {
143            ob_start();
144            print_r($var);
145            $d = ob_get_contents();
146            ob_end_clean();
147        }
148        break;
149
150    case SC_DUMP_VAR_DUMP:
151        ob_start();
152        print_r($var);
153        var_dump($var);
154        ob_end_clean();
155        break;
156
157    case SC_DUMP_VAR_EXPORT:
158        ob_start();
159        print_r($var);
160        var_export($var);
161        ob_end_clean();
162        break;
163
164    case SC_DUMP_JSON:
165        $json_flags = $serialize ? 0 : JSON_PRETTY_PRINT;
166        return json_encode($var, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | $json_flags);
167    }
168    return $serialize ? preg_replace('/\s+/m' . $app->getParam('preg_u'), ' ', $d) : $d;
169}
170
171/*
172* Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts.
173* To output tab-style lists set $indent to "\t" and $depth to 0;
174* To output markdown-style lists set $indent to '- ' and $depth to 1;
175* Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php
176*
177* @param  array    $var        Variable to dump.
178* @param  string   $indent     A string to prepend indented lines.
179* @param  string   $depth      Starting depth of this iteration of recursion (set to 0 to have no initial indentation).
180* @return string               Pretty dump of $var.
181* @author   Quinn Comendant <quinn@strangecode.com>
182* @version 2.0
183*/
184function fancyDump($var, $indent='- ', $depth=1)
185{
186    $app =& App::getInstance();
187
188    $indent_str = str_repeat($indent, $depth);
189    $output = '';
190    if (is_array($var)) {
191        foreach ($var as $k=>$v) {
192            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
193            if (is_array($v)) {
194                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
195            } else {
196                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
197            }
198        }
199    } else {
200        $output .= sprintf("%s%s\n", $indent_str, $var);
201    }
202    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);
203}
204
205/**
206 * @param string|mixed $value A string to UTF8-encode.
207 *
208 * @returns string|mixed The UTF8-encoded string, or the object passed in if
209 *    it wasn't a string.
210 */
211function conditionalUTF8Encode($value)
212{
213  if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
214    return utf8_encode($value);
215  } else {
216    return $value;
217  }
218}
219
220
221/**
222 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
223 *
224 * @param  string $text             Text to clean.
225 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
226 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
227 * @return string                   HTML-safe text.
228 */
229function oTxt($text, $preserve_html=false)
230{
231    $app =& App::getInstance();
232
233    if ('' == $text) {
234        return '';
235    }
236
237    $search = array();
238    $replace = array();
239
240    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
241    $search['retain_ampersand']     = '/&amp;/';
242    $replace['retain_ampersand']    = '&';
243
244    if ($preserve_html) {
245        // Convert characters that must remain non-entities for displaying HTML.
246        $search['retain_left_angle']       = '/&lt;/';
247        $replace['retain_left_angle']      = '<';
248
249        $search['retain_right_angle']      = '/&gt;/';
250        $replace['retain_right_angle']     = '>';
251
252        $search['retain_single_quote']     = '/&#039;/';
253        $replace['retain_single_quote']    = "'";
254
255        $search['retain_double_quote']     = '/&quot;/';
256        $replace['retain_double_quote']    = '"';
257    }
258
259    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
260    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
261    $replace['ampersand']       = '&amp;';
262
263    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
264}
265
266/**
267 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
268 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
269 *
270 * @param  string   $text Text to clean.
271 * @return string         Cleaned text.
272 */
273function fancyTxt($text, $extra_search=null, $extra_replace=null)
274{
275    $search = array();
276    $replace = array();
277
278    // "double quoted text"  →  “double quoted text”
279    $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;
280    $replace['_double_quotes']   = '“$1”';
281
282    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
283    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
284    $replace['_apostrophe']      = '’';
285
286    // 'single quoted text'  →  ‘single quoted text’
287    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
288    $replace['_single_quotes']   = '‘$1’';
289
290    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
291    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
292    $replace['_apostrophes']     = '’';
293
294    // double--hyphens  →  en – dashes
295    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
296    $replace['_em_dash']         = ' – ';
297
298    // ...  →  

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