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

Last change on this file since 601 was 601, checked in by anonymous, 7 years ago

Updated every instance of 'zero' date 0000-00-00 to use 1000-01-01 if mysql version >= 5.7.4

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