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

Last change on this file since 653 was 653, checked in by anonymous, 5 years ago

Update fancyTxt()

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

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