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

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