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

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

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