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

Last change on this file since 807 was 807, checked in by anonymous, 3 months ago

Minor improvements. Add Validator::IPAddress() method.

File size: 69.7 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
27require_once dirname(__FILE__) . '/App.inc.php';
28
29/**
30 * Print variable dump.
31 *
32 * @param  mixed    $var            The variable to dump.
33 * @param  bool     $display        Print the dump in <pre> tags or hide it in html comments (non-CLI only).
34 * @param  const    $dump_method    Dump method. See SC_DUMP_* constants.
35 * @param  string   $file           Value of __FILE__.
36 * @param  string   $line           Value of __LINE__
37 */
38define('SC_DUMP_PRINT_R', 0);
39define('SC_DUMP_VAR_DUMP', 1);
40define('SC_DUMP_VAR_EXPORT', 2);
41define('SC_DUMP_JSON', 3);
42function dump($var, $display=false, $dump_method=SC_DUMP_JSON, $file='', $line='')
43{
44    $app =& App::getInstance();
45
46    if ($app->isCLI()) {
47        echo ('' != $file . $line) ? "DUMP FROM: $file $line\n" : "DUMP:\n";
48    } else {
49        echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n";
50    }
51
52    switch ($dump_method) {
53    case SC_DUMP_PRINT_R:
54    default:
55        // Print human-readable descriptions of invisible types.
56        if (null === $var) {
57            echo '(null)';
58        } else if (true === $var) {
59            echo '(bool: true)';
60        } else if (false === $var) {
61            echo '(bool: false)';
62        } else if (is_scalar($var) && '' === $var) {
63            echo '(empty string)';
64        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
65            echo '(only white space)';
66        } else {
67            print_r($var);
68        }
69        break;
70
71    case SC_DUMP_VAR_DUMP:
72        var_dump($var);
73        break;
74
75    case SC_DUMP_VAR_EXPORT:
76        var_export($var);
77        break;
78
79    case SC_DUMP_JSON:
80        echo json_encode($var, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
81        break;
82    }
83
84    if ($app->isCLI()) {
85        echo "\n";
86    } else {
87        echo $display ? "\n</pre><br />\n" : "\n-->\n";
88    }
89}
90
91/*
92* Log a PHP variable to javascript console. Relies on getDump(), below.
93*
94* @access   public
95* @param    mixed   $var      The variable to dump.
96* @param    string  $prefix   A short note to print before the output to make identifying output easier.
97* @param    string  $file     The value of __FILE__.
98* @param    string  $line     The value of __LINE__.
99* @return   null
100* @author   Quinn Comendant <quinn@strangecode.com>
101*/
102function jsDump($var, $prefix='jsDump', $file='-', $line='-')
103{
104    if (!empty($var)) {
105        ?>
106        <script type="text/javascript">
107        /* <![CDATA[ */
108        console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
109        /* ]]> */
110        </script>
111        <?php
112    }
113}
114
115/*
116* Return a string version of any variable, optionally serialized on one line.
117*
118* @access   public
119* @param    mixed   $var            The variable to dump.
120* @param    bool    $serialize      If true, remove line-endings. Useful for logging variables.
121* @param    const   $dump_method    Dump method. See SC_DUMP_* constants.
122* @return   string                  The dumped variable.
123* @author   Quinn Comendant <quinn@strangecode.com>
124*/
125function getDump($var, $serialize=false, $dump_method=SC_DUMP_JSON)
126{
127    $app =& App::getInstance();
128
129    switch ($dump_method) {
130    case SC_DUMP_PRINT_R:
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    default:
166        $json_flags = $serialize ? 0 : JSON_PRETTY_PRINT;
167        return json_encode($var, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | $json_flags);
168    }
169    return $serialize ? preg_replace('/\s+/m' . $app->getParam('preg_u'), ' ', $d) : $d;
170}
171
172/*
173* Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts.
174* To output tab-style lists set $indent to "\t" and $depth to 0;
175* To output markdown-style lists set $indent to '- ' and $depth to 1;
176* Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php
177*
178* @param  array    $var        Variable to dump.
179* @param  string   $indent     A string to prepend indented lines.
180* @param  string   $depth      Starting depth of this iteration of recursion (set to 0 to have no initial indentation).
181* @return string               Pretty dump of $var.
182* @author   Quinn Comendant <quinn@strangecode.com>
183* @version 2.0
184*/
185function fancyDump($var, $indent='- ', $depth=1)
186{
187    $app =& App::getInstance();
188
189    $indent = trim($indent, ' ') . ' ';
190
191    $indent_str = str_repeat($indent, $depth);
192    $output = '';
193    if (is_array($var)) {
194        foreach ($var as $k=>$v) {
195            $k = ucfirst(mb_strtolower(str_replace(['_', '  '], ' ', $k)));
196            if (is_array($v)) {
197                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
198            } else {
199                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
200            }
201        }
202    } else {
203        $output .= sprintf("%s%s\n", $indent_str, $var);
204    }
205
206    return preg_replace([
207        '/^[ \t]+$/' . $app->getParam('preg_u'),
208        '/\n\n+/' . $app->getParam('preg_u'),
209        sprintf('/^(?:%1$s( ))?(?:%1$s( ))?(?:%1$s( ))?(?:%1$s( ))?(?:%1$s( ))?(?:%1$s( ))?(?:%1$s( ))?(?:%1$s( ))?(%1$s )/m%2$s', preg_quote(trim($indent, ' '), '/'), $app->getParam('preg_u')),
210    ], [
211        '',
212        "\n",
213        '$1$1$2$2$3$3$4$4$5$5$6$6$7$7$8$8$9'
214    ], $output);
215}
216
217/**
218 * @param string|mixed $value A string to UTF8-encode.
219 *
220 * @returns string|mixed The UTF8-encoded string, or the object passed in if
221 *    it wasn't a string.
222 */
223function conditionalUTF8Encode($value)
224{
225  if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
226    return utf8_encode($value);
227  } else {
228    return $value;
229  }
230}
231
232
233/**
234 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
235 *
236 * @param  string $text             Text to clean.
237 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
238 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
239 * @return string                   HTML-safe text.
240 */
241function oTxt($text, $preserve_html=false)
242{
243    $app =& App::getInstance();
244
245    if ('' == $text) {
246        return '';
247    }
248
249    $search = array();
250    $replace = array();
251
252    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
253    $search['retain_ampersand']     = '/&amp;/';
254    $replace['retain_ampersand']    = '&';
255
256    if ($preserve_html) {
257        // Convert characters that must remain non-entities for displaying HTML.
258        $search['retain_left_angle']       = '/&lt;/';
259        $replace['retain_left_angle']      = '<';
260
261        $search['retain_right_angle']      = '/&gt;/';
262        $replace['retain_right_angle']     = '>';
263
264        $search['retain_single_quote']     = '/&#039;/';
265        $replace['retain_single_quote']    = "'";
266
267        $search['retain_double_quote']     = '/&quot;/';
268        $replace['retain_double_quote']    = '"';
269    }
270
271    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
272    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
273    $replace['ampersand']       = '&amp;';
274
275    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
276}
277
278/**
279 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
280 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
281 *
282 * @param  string   $text Text to clean.
283 * @return string         Cleaned text.
284 */
285function fancyTxt($text, $extra_search=null, $extra_replace=null)
286{
287    $search = array();
288    $replace = array();
289
290    // "double quoted text"  →  “double quoted text”
291    $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;
292    $replace['_double_quotes']   = '“$1”';
293
294    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
295    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
296    $replace['_apostrophe']      = '’';
297
298    // 'single quoted text'  →  ‘single quoted text’
299    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
300    $replace['_single_quotes']   = '‘$1’';
301
302    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
303    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
304    $replace['_apostrophes']     = '’';
305
306    // double--hyphens  →  en – dashes
307    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
308    $replace['_em_dash']         = ' – ';
309
310    // ...  →  

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