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

Last change on this file since 773 was 773, checked in by anonymous, 22 months ago

Accept separator argument for cleanFileName()

File size: 66.3 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * Utilities.inc.php
25 */
26
27
28/**
29 * Print variable dump.
30 *
31 * @param  mixed    $var        The variable to dump.
32 * @param  bool     $display    Print the dump in <pre> tags or hide it in html comments (non-CLI only).
33 * @param  bool     $dump_method   Dump method. See SC_DUMP_* constants.
34 * @param  string   $file       Value of __FILE__.
35 * @param  string   $line       Value of __LINE__
36 */
37define('SC_DUMP_PRINT_R', 0);
38define('SC_DUMP_VAR_DUMP', 1);
39define('SC_DUMP_VAR_EXPORT', 2);
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* @return   string              The dumped variable.
121* @author   Quinn Comendant <quinn@strangecode.com>
122*/
123function getDump($var, $serialize=false, $dump_method=SC_DUMP_PRINT_R)
124{
125    $app =& App::getInstance();
126
127    switch ($dump_method) {
128    case SC_DUMP_PRINT_R:
129    default:
130        // Print human-readable descriptions of invisible types.
131        if (null === $var) {
132            $d = '(null)';
133        } else if (true === $var) {
134            $d = '(bool: true)';
135        } else if (false === $var) {
136            $d = '(bool: false)';
137        } else if (is_scalar($var) && '' === $var) {
138            $d = '(empty string)';
139        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
140            $d = '(only white space)';
141        } else {
142            ob_start();
143            print_r($var);
144            $d = ob_get_contents();
145            ob_end_clean();
146        }
147        break;
148
149    case SC_DUMP_VAR_DUMP:
150        ob_start();
151        print_r($var);
152        var_dump($var);
153        ob_end_clean();
154        break;
155
156    case SC_DUMP_VAR_EXPORT:
157        ob_start();
158        print_r($var);
159        var_export($var);
160        ob_end_clean();
161        break;
162
163    case SC_DUMP_JSON:
164        $d = json_encode($var, JSON_PRETTY_PRINT);
165        break;
166    }
167    return $serialize ? preg_replace('/\s+/m' . $app->getParam('preg_u'), ' ', $d) : $d;
168}
169
170/*
171* Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts.
172* To output tab-style lists set $indent to "\t" and $depth to 0;
173* To output markdown-style lists set $indent to '- ' and $depth to 1;
174* Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php
175*
176* @param  array    $var        Variable to dump.
177* @param  string   $indent     A string to prepend indented lines.
178* @param  string   $depth      Starting depth of this iteration of recursion (set to 0 to have no initial indentation).
179* @return string               Pretty dump of $var.
180* @author   Quinn Comendant <quinn@strangecode.com>
181* @version 2.0
182*/
183function fancyDump($var, $indent='- ', $depth=1)
184{
185    $app =& App::getInstance();
186
187    $indent_str = str_repeat($indent, $depth);
188    $output = '';
189    if (is_array($var)) {
190        foreach ($var as $k=>$v) {
191            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
192            if (is_array($v)) {
193                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
194            } else {
195                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
196            }
197        }
198    } else {
199        $output .= sprintf("%s%s\n", $indent_str, $var);
200    }
201    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);
202}
203
204/**
205 * @param string|mixed $value A string to UTF8-encode.
206 *
207 * @returns string|mixed The UTF8-encoded string, or the object passed in if
208 *    it wasn't a string.
209 */
210function conditionalUTF8Encode($value)
211{
212  if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
213    return utf8_encode($value);
214  } else {
215    return $value;
216  }
217}
218
219
220/**
221 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
222 *
223 * @param  string $text             Text to clean.
224 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
225 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
226 * @return string                   HTML-safe text.
227 */
228function oTxt($text, $preserve_html=false)
229{
230    $app =& App::getInstance();
231
232    $search = array();
233    $replace = array();
234
235    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
236    $search['retain_ampersand']     = '/&amp;/';
237    $replace['retain_ampersand']    = '&';
238
239    if ($preserve_html) {
240        // Convert characters that must remain non-entities for displaying HTML.
241        $search['retain_left_angle']       = '/&lt;/';
242        $replace['retain_left_angle']      = '<';
243
244        $search['retain_right_angle']      = '/&gt;/';
245        $replace['retain_right_angle']     = '>';
246
247        $search['retain_single_quote']     = '/&#039;/';
248        $replace['retain_single_quote']    = "'";
249
250        $search['retain_double_quote']     = '/&quot;/';
251        $replace['retain_double_quote']    = '"';
252    }
253
254    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
255    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
256    $replace['ampersand']       = '&amp;';
257
258    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
259}
260
261/**
262 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
263 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
264 *
265 * @param  string   $text Text to clean.
266 * @return string         Cleaned text.
267 */
268function fancyTxt($text, $extra_search=null, $extra_replace=null)
269{
270    $search = array();
271    $replace = array();
272
273    // "double quoted text"  →  “double quoted text”
274    $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;
275    $replace['_double_quotes']   = '“$1”';
276
277    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
278    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
279    $replace['_apostrophe']      = '’';
280
281    // 'single quoted text'  →  ‘single quoted text’
282    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
283    $replace['_single_quotes']   = '‘$1’';
284
285    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
286    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
287    $replace['_apostrophes']     = '’';
288
289    // double--hyphens  →  en — dashes
290    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
291    $replace['_em_dash']         = ' – ';
292
293    // ...  →  

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