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

Last change on this file since 781 was 781, checked in by anonymous, 15 months ago

Improve pretty json output

File size: 66.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  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    $search = array();
234    $replace = array();
235
236    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
237    $search['retain_ampersand']     = '/&amp;/';
238    $replace['retain_ampersand']    = '&';
239
240    if ($preserve_html) {
241        // Convert characters that must remain non-entities for displaying HTML.
242        $search['retain_left_angle']       = '/&lt;/';
243        $replace['retain_left_angle']      = '<';
244
245        $search['retain_right_angle']      = '/&gt;/';
246        $replace['retain_right_angle']     = '>';
247
248        $search['retain_single_quote']     = '/&#039;/';
249        $replace['retain_single_quote']    = "'";
250
251        $search['retain_double_quote']     = '/&quot;/';
252        $replace['retain_double_quote']    = '"';
253    }
254
255    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
256    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
257    $replace['ampersand']       = '&amp;';
258
259    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
260}
261
262/**
263 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
264 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
265 *
266 * @param  string   $text Text to clean.
267 * @return string         Cleaned text.
268 */
269function fancyTxt($text, $extra_search=null, $extra_replace=null)
270{
271    $search = array();
272    $replace = array();
273
274    // "double quoted text"  →  “double quoted text”
275    $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;
276    $replace['_double_quotes']   = '“$1”';
277
278    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
279    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
280    $replace['_apostrophe']      = '’';
281
282    // 'single quoted text'  →  ‘single quoted text’
283    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
284    $replace['_single_quotes']   = '‘$1’';
285
286    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
287    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
288    $replace['_apostrophes']     = '’';
289
290    // double--hyphens  →  en – dashes
291    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
292    $replace['_em_dash']         = ' – ';
293
294    // ...  →  

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