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

Last change on this file since 652 was 652, checked in by anonymous, 6 years ago

Update fancyDump

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