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

Last change on this file since 768 was 768, checked in by anonymous, 2 years ago

Minor improvements

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