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

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

Improve getDump()

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

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