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

Last change on this file since 718 was 718, checked in by anonymous, 4 years ago

Minor fixes

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

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