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

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

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