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

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

Refactor URLSlug() and cleanFileName(). Add simplifyAccents().

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

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