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

Last change on this file since 547 was 547, checked in by anonymous, 9 years ago

Moved CLI flag to ->cli which can be forced off for tests

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