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

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

Minor fix

File size: 62.8 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[454]6 *
[362]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.
[454]13 *
[362]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.
[454]18 *
[362]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/**
[1]24 * Utilities.inc.php
25 */
26
27
28/**
29 * Print variable dump.
30 *
[479]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).
[613]33 * @param  bool     $dump_method   Dump method. See SC_DUMP_* constants.
[479]34 * @param  string   $file       Value of __FILE__.
35 * @param  string   $line       Value of __LINE__
[1]36 */
[613]37define('SC_DUMP_PRINT_R', 0);
38define('SC_DUMP_VAR_DUMP', 1);
39define('SC_DUMP_VAR_EXPORT', 2);
[743]40define('SC_DUMP_JSON', 3);
[613]41function dump($var, $display=false, $dump_method=SC_DUMP_PRINT_R, $file='', $line='')
[1]42{
[548]43    $app =& App::getInstance();
44
[665]45    if ($app->isCLI()) {
[477]46        echo "DUMP FROM: $file $line\n";
[454]47    } else {
[477]48        echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n";
[380]49    }
[613]50
51    switch ($dump_method) {
52    case SC_DUMP_PRINT_R:
53    default:
[479]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        }
[613]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;
[743]77
78    case SC_DUMP_JSON:
[744]79        echo json_encode($var, JSON_PRETTY_PRINT);
[743]80        break;
[1]81    }
[613]82
[665]83    if ($app->isCLI()) {
[380]84        echo "\n";
[454]85    } else {
[477]86        echo $display ? "\n</pre><br />\n" : "\n-->\n";
[380]87    }
[1]88}
89
[464]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        ?>
[518]105        <script type="text/javascript">
[464]106        /* <![CDATA[ */
[518]107        console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
[464]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*/
[331]123function getDump($var, $serialize=false)
[1]124{
[724]125    $app =& App::getInstance();
126
[1]127    ob_start();
128    print_r($var);
129    $d = ob_get_contents();
130    ob_end_clean();
[724]131    return $serialize ? preg_replace('/\s+/m' . $app->getParam('preg_u'), ' ', $d) : $d;
[1]132}
133
[652]134/*
135* Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts.
136* To output tab-style lists set $indent to "\t" and $depth to 0;
137* To output markdown-style lists set $indent to '- ' and $depth to 1;
138* Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php
139*
140* @param  array    $var        Variable to dump.
141* @param  string   $indent     A string to prepend indented lines.
142* @param  string   $depth      Starting depth of this iteration of recursion (set to 0 to have no initial indentation).
143* @return string               Pretty dump of $var.
144* @author   Quinn Comendant <quinn@strangecode.com>
145* @version 2.0
146*/
147function fancyDump($var, $indent='- ', $depth=1)
[1]148{
[724]149    $app =& App::getInstance();
150
[652]151    $indent_str = str_repeat($indent, $depth);
[1]152    $output = '';
153    if (is_array($var)) {
154        foreach ($var as $k=>$v) {
[247]155            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
[1]156            if (is_array($v)) {
[652]157                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
[1]158            } else {
[652]159                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
[1]160            }
161        }
162    } else {
[652]163        $output .= sprintf("%s%s\n", $indent_str, $var);
[1]164    }
[724]165    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);
[1]166}
167
168/**
[605]169 * @param string|mixed $value A string to UTF8-encode.
170 *
171 * @returns string|mixed The UTF8-encoded string, or the object passed in if
172 *    it wasn't a string.
173 */
174function conditionalUTF8Encode($value)
175{
176  if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
177    return utf8_encode($value);
178  } else {
179    return $value;
180  }
181}
182
183
184/**
[505]185 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
[1]186 *
[257]187 * @param  string $text             Text to clean.
[334]188 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
[485]189 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
190 * @return string                   HTML-safe text.
[1]191 */
[257]192function oTxt($text, $preserve_html=false)
[1]193{
[479]194    $app =& App::getInstance();
[136]195
[1]196    $search = array();
197    $replace = array();
198
199    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
[723]200    $search['retain_ampersand']     = '/&amp;/';
[1]201    $replace['retain_ampersand']    = '&';
202
203    if ($preserve_html) {
204        // Convert characters that must remain non-entities for displaying HTML.
[723]205        $search['retain_left_angle']       = '/&lt;/';
[1]206        $replace['retain_left_angle']      = '<';
[42]207
[723]208        $search['retain_right_angle']      = '/&gt;/';
[1]209        $replace['retain_right_angle']     = '>';
[42]210
[723]211        $search['retain_single_quote']     = '/&#039;/';
[1]212        $replace['retain_single_quote']    = "'";
[42]213
[723]214        $search['retain_double_quote']     = '/&quot;/';
[1]215        $replace['retain_double_quote']    = '"';
216    }
217
[334]218    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
[32]219    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
220    $replace['ampersand']       = '&amp;';
[1]221
[334]222    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
[1]223}
224
225/**
[334]226 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
[320]227 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
[1]228 *
[257]229 * @param  string   $text Text to clean.
[1]230 * @return string         Cleaned text.
231 */
[653]232function fancyTxt($text, $extra_search=null, $extra_replace=null)
[1]233{
[103]234    $search = array();
235    $replace = array();
236
[653]237    // "double quoted text"  →  “double quoted text”
238    $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;
239    $replace['_double_quotes']   = '“$1”';
[103]240
[653]241    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
242    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
243    $replace['_apostrophe']      = '’';
[103]244
[653]245    // 'single quoted text'  →  ‘single quoted text’
246    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
247    $replace['_single_quotes']   = '‘$1’';
[103]248
[653]249    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
250    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
251    $replace['_apostrophes']     = '’';
[103]252
[653]253    // double--hyphens  →  en — dashes
254    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
255    $replace['_em_dash']         = ' – ';
[103]256
[653]257    // ...  →  

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