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
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[454]6 *
[362]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.
[454]13 *
[362]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.
[454]18 *
[362]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/**
[1]24 * Utilities.inc.php
25 */
26
27
28/**
29 * Print variable dump.
30 *
[479]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).
[613]33 * @param  bool     $dump_method   Dump method. See SC_DUMP_* constants.
[479]34 * @param  string   $file       Value of __FILE__.
35 * @param  string   $line       Value of __LINE__
[1]36 */
[613]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='')
[1]41{
[548]42    $app =& App::getInstance();
43
[665]44    if ($app->isCLI()) {
[477]45        echo "DUMP FROM: $file $line\n";
[454]46    } else {
[477]47        echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n";
[380]48    }
[613]49
50    switch ($dump_method) {
51    case SC_DUMP_PRINT_R:
52    default:
[479]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        }
[613]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;
[1]76    }
[613]77
[665]78    if ($app->isCLI()) {
[380]79        echo "\n";
[454]80    } else {
[477]81        echo $display ? "\n</pre><br />\n" : "\n-->\n";
[380]82    }
[1]83}
84
[464]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        ?>
[518]100        <script type="text/javascript">
[464]101        /* <![CDATA[ */
[518]102        console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
[464]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*/
[331]118function getDump($var, $serialize=false)
[1]119{
120    ob_start();
121    print_r($var);
122    $d = ob_get_contents();
123    ob_end_clean();
[696]124    return $serialize ? preg_replace('/\s+/mu', ' ', $d) : $d;
[1]125}
126
[652]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)
[1]141{
[652]142    $indent_str = str_repeat($indent, $depth);
[1]143    $output = '';
144    if (is_array($var)) {
145        foreach ($var as $k=>$v) {
[247]146            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
[1]147            if (is_array($v)) {
[652]148                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
[1]149            } else {
[652]150                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
[1]151            }
152        }
153    } else {
[652]154        $output .= sprintf("%s%s\n", $indent_str, $var);
[1]155    }
[696]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);
[1]157}
158
159/**
[605]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/**
[505]176 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
[1]177 *
[257]178 * @param  string $text             Text to clean.
[334]179 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
[485]180 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
181 * @return string                   HTML-safe text.
[1]182 */
[257]183function oTxt($text, $preserve_html=false)
[1]184{
[479]185    $app =& App::getInstance();
[136]186
[1]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.
[696]191    $search['retain_ampersand']     = '/&amp;/u';
[1]192    $replace['retain_ampersand']    = '&';
193
194    if ($preserve_html) {
195        // Convert characters that must remain non-entities for displaying HTML.
[696]196        $search['retain_left_angle']       = '/&lt;/u';
[1]197        $replace['retain_left_angle']      = '<';
[42]198
[696]199        $search['retain_right_angle']      = '/&gt;/u';
[1]200        $replace['retain_right_angle']     = '>';
[42]201
[696]202        $search['retain_single_quote']     = '/&#039;/u';
[1]203        $replace['retain_single_quote']    = "'";
[42]204
[696]205        $search['retain_double_quote']     = '/&quot;/u';
[1]206        $replace['retain_double_quote']    = '"';
207    }
208
[334]209    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
[32]210    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
211    $replace['ampersand']       = '&amp;';
[1]212
[334]213    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
[1]214}
215
216/**
[334]217 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
[320]218 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
[1]219 *
[257]220 * @param  string   $text Text to clean.
[1]221 * @return string         Cleaned text.
222 */
[653]223function fancyTxt($text, $extra_search=null, $extra_replace=null)
[1]224{
[103]225    $search = array();
226    $replace = array();
227
[653]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”';
[103]231
[653]232    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
233    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
234    $replace['_apostrophe']      = '’';
[103]235
[653]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’';
[103]239
[653]240    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
241    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
242    $replace['_apostrophes']     = '’';
[103]243
[653]244    // double--hyphens  →  en — dashes
245    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
246    $replace['_em_dash']         = ' – ';
[103]247
[653]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));
[1]259}
260
[505]261/*
262* Finds all URLs in text and hyperlinks them.
263*
264* @access   public
265* @param    string  $text   Text to search for URLs.
[541]266* @param    bool    $strict True to only include URLs starting with a scheme (http:// ftp:// im://), or false to include URLs starting with 'www.'.
[505]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>
[647]271* @version  2.2
[505]272* @since    22 Mar 2015 23:29:04
273*/
[541]274function hyperlinkTxt($text, $strict=false, $length=null, $delim='
')
[505]275{
[545]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
[541]279    // Capture the full URL into the first match and only the first X characters into the second match.
[647]280    // This will match URLs not preceded by " ' or = (URLs inside an attribute) or ` (Markdown quoted) or double-scheme (http://http://www.asdf.com)
[715]281    // https://stackoverflow.com/questions/1547899/which-characters-make-a-url-invalid/1547940#1547940
[541]282    $regex = '@
[647]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
[541]290            )
[647]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
[541]293        )
294        @Suxi
295    ';
296    $regex = sprintf($regex,
[545]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.)
[505]300    );
[541]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];
[545]306        $truncated_url = $m[2] . $m[3];
[541]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.
[545]310            // Remove http schemas, and any single trailing / to make the display URL.
[696]311            $display_url = preg_replace(['!^https?://!u', '!^([^/]+)/$!u'], ['', '$1'], $url);
[541]312            return sprintf('<a href="%s">%s</a>', oTxt($absolute_url), $display_url);
313        } else {
314            // Truncated URL.
[545]315            // Remove http schemas, and any single trailing / to make the display URL.
[696]316            $display_url = preg_replace(['!^https?://!u', '!^([^/]+)/$!u'], ['', '$1'], trim($truncated_url));
[541]317            return sprintf('<a href="%s">%s%s</a>', oTxt($absolute_url), $display_url, $delim);
318        }
319    }, $text);
[505]320}
321
[257]322/**
[334]323 * Applies a class to search terms to highlight them ala google results.
[257]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);
[454]333
[257]334    $search = array();
335    $replace = array();
[454]336
[257]337    foreach ($words as $w) {
[258]338        if ('' != trim($w)) {
[696]339            $search[] = '/\b(' . preg_quote($w) . ')\b/iu';
[258]340            $replace[] = '<span class="' . $class . '">$1</span>';
341        }
[257]342    }
[42]343
[258]344    return empty($replace) ? $text : preg_replace($search, $replace, $text);
[257]345}
346
[1]347/**
[334]348 * Generates a hexadecimal html color based on provided word.
[1]349 *
350 * @access public
351 * @param  string $text  A string for which to convert to color.
352 * @return string  A hexadecimal html color.
353 */
[534]354function getTextColor($text, $method=1, $n=0.87)
[1]355{
[235]356    $hash = md5($text);
357    $rgb = array(
[247]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),
[235]364    );
[1]365
366    switch ($method) {
[235]367    case 1 :
368    default :
[334]369        // Reduce all hex values slightly to avoid all white.
[696]370        array_walk($rgb, function (&$v) use ($n) {
371            $v = dechex(round(hexdec($v) * $n));
372        });
[235]373        break;
[696]374
[1]375    case 2 :
[235]376        foreach ($rgb as $i => $v) {
377            if (hexdec($v) > hexdec('c')) {
378                $rgb[$i] = dechex(hexdec('f') - hexdec($v));
379            }
[1]380        }
381        break;
382    }
383
[235]384    return join('', $rgb);
[1]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{
[255]397    $output = '';
[247]398    $num = mb_strlen($text);
[1]399    for ($i=0; $i<$num; $i++) {
400        $output .= sprintf('&#%03s', ord($text{$i}));
401    }
402    return $output;
403}
404
405/**
[84]406 * Encodes an email into a "user at domain dot com" format.
[9]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 */
[53]414function encodeEmail($email, $at=' at ', $dot=' dot ')
[9]415{
[696]416    $search = array('/@/u', '/\./u');
[9]417    $replace = array($at, $dot);
418    return preg_replace($search, $replace, $email);
419}
420
421/**
[454]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
".
[84]426 *
[454]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 *
[84]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'.
[454]434 * @return  string          Truncated output string.
[84]435 * @author  Quinn Comendant <quinn@strangecode.com>
436 * @since   29 Mar 2006 13:48:49
437 */
[454]438function truncate($str, $len=50, $where='end', $delim='
')
[84]439{
[454]440    $dlen = mb_strlen($delim);
441    if ($len <= $dlen || mb_strlen($str) <= $dlen) {
442        return substr($str, 0, $len);
[240]443    }
[454]444    $part1 = floor(($len - $dlen) / 2);
445    $part2 = ceil(($len - $dlen) / 2);
[531]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
[84]453    switch ($where) {
454    case 'start' :
[531]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);
[454]456
[84]457    case 'middle' :
[531]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);
[454]459
[84]460    case 'end' :
[454]461    default :
[531]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);
[84]463    }
464}
465
[340]466/*
467* A substitution for the missing mb_ucfirst function.
468*
469* @access   public
[414]470* @param    string  $string The string
471* @return   string          String with upper-cased first character.
[340]472* @author   Quinn Comendant <quinn@strangecode.com>
473* @version  1.0
474* @since    06 Dec 2008 17:04:01
475*/
[454]476if (!function_exists('mb_ucfirst')) {
[340]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
[414]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*/
[454]495if (!function_exists('mb_strtr')) {
[414]496    function mb_strtr($string, $from, $to)
497    {
498        return str_replace(mb_split('.', $from), mb_split('.', $to), $string);
499    }
500}
501
[474]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
[84]522/**
[338]523 * Return a human readable disk space measurement. Input value measured in bytes.
[1]524 *
[338]525 * @param       int    $size        Size in bytes.
[1]526 * @param       int    $unit        The maximum unit
527 * @param       int    $format      The return string format
528 * @author      Aidan Lister <aidan@php.net>
[362]529 * @author      Quinn Comendant <quinn@strangecode.com>
530 * @version     1.2.0
[1]531 */
[338]532function humanFileSize($size, $format='%01.2f %s', $max_unit=null, $multiplier=1024)
[1]533{
534    // Units
535    $units = array('B', 'KB', 'MB', 'GB', 'TB');
536    $ii = count($units) - 1;
[42]537
[1]538    // Max unit
[154]539    $max_unit = array_search((string) $max_unit, $units);
540    if ($max_unit === null || $max_unit === false) {
541        $max_unit = $ii;
[1]542    }
[42]543
[1]544    // Loop
545    $i = 0;
[338]546    while ($max_unit != $i && $size >= $multiplier && $i < $ii) {
547        $size /= $multiplier;
[1]548        $i++;
549    }
[42]550
[1]551    return sprintf($format, $size, $units[$i]);
552}
553
[180]554/*
[189]555* Returns a human readable amount of time for the given amount of seconds.
[454]556*
[180]557* 45 seconds
558* 12 minutes
559* 3.5 hours
560* 2 days
561* 1 week
562* 4 months
[454]563*
[180]564* Months are calculated using the real number of days in a year: 365.2422 / 12.
565*
566* @access   public
[189]567* @param    int $seconds Seconds of time.
[180]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*/
[189]575function humanTime($seconds, $max_unit=null, $format='%01.1f')
[180]576{
[202]577    // Units: array of seconds in the unit, singular and plural unit names.
[180]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")),
[362]587        'century' => array(3155692608, _("century"), _("centuries")),
[180]588    );
[454]589
[202]590    // Max unit to calculate.
[362]591    $max_unit = isset($units[$max_unit]) ? $max_unit : 'year';
[180]592
[189]593    $final_time = $seconds;
[363]594    $final_unit = 'second';
[180]595    foreach ($units as $k => $v) {
[363]596        if ($seconds >= $v[0]) {
[189]597            $final_time = $seconds / $v[0];
[363]598            $final_unit = $k;
[180]599        }
[363]600        if ($max_unit == $final_unit) {
601            break;
602        }
[180]603    }
[189]604    $final_time = sprintf($format, $final_time);
[454]605    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2]));
[180]606}
607
[722]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
[518]655/**
[722]656 * Converts a string of text into a safe file name by removing non-ASCII characters and non-word characters.
[518]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
[722]666    $file_name = preg_replace(['/[^a-zA-Z0-9()@._=+-]+/u', '/^_+|_+$/u'], ['_', ''], simplifyAccents($file_name));
[518]667    return mb_substr($file_name, 0, 250);
668}
669
[519]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
[487]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 != '') {
[718]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        }
[487]709    }
710
711    return (int)$val;
712}
713
[1]714/**
[334]715 * Tests the existence of a file anywhere in the include path.
[523]716 * Replaced by stream_resolve_include_path() in PHP 5 >= 5.3.2
[258]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();
[454]726
[258]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/**
[26]740 * Returns stats of a file from the include path.
741 *
742 * @param   string  $file   File in include path.
[258]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.
[26]745 * @author  Quinn Comendant <quinn@strangecode.com>
746 * @since   03 Dec 2005 14:23:26
747 */
[241]748function statIncludePath($file, $stat=null)
[26]749{
750    // Open file pointer read-only using include path.
751    if ($fp = fopen($file, 'r', true)) {
[258]752        // File opened successfully, get stats.
[26]753        $stats = fstat($fp);
754        fclose($fp);
755        // Return specified stats.
[241]756        return is_null($stat) ? $stats : $stats[$stat];
[26]757    } else {
758        return false;
759    }
760}
761
[330]762/*
763* Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5.
[400]764* It makes an exclusive lock on the file while writing.
[330]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{
[479]775    $app =& App::getInstance();
[330]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
[26]801/**
[1]802 * If $var is net set or null, set it to $default. Otherwise leave it alone.
[334]803 * Returns the final value of $var. Use to find a default value of one is not available.
[1]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.
[42]807 * @return mixed            The resulting value of $var.
[1]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
[334]823 * @param  array $delim    optional character that will also be escaped.
[1]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 *
[334]843 * @param  mixed $data        An array to transverse recursively, or a string
[1]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 */
[235]849function urlEncodeArray($data, $prefix='', $_return=true)
850{
[1]851    // Data is stored in static variable.
[590]852    static $args = array();
[42]853
[1]854    if (is_array($data)) {
855        foreach ($data as $key => $val) {
[334]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".
[1]858            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
859            // Enter recursion.
860            urlEncodeArray($val, $new_prefix, false);
861        }
862    } else {
[334]863        // We've come to the last dimension of the array, save the "array" and its value.
[1]864        $args[$prefix] = urlencode($data);
865    }
[42]866
[1]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 *
[580]879 * Todo: probably update to use the built-in http_build_query().
880 *
[334]881 * @param  mixed $data        An array to transverse recursively, or a string
[1]882 *                            to use directly to create url arguments.
[334]883 * @param  string $prefix     The name of the first dimension of the array.
[1]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 */
[235]887function urlEncodeArrayToString($data, $prefix='')
888{
[42]889
[1]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/**
[334]901 * Fills an array with the result from a multiple ereg search.
902 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
[1]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 {
[247]911        if (!mb_ereg($pattern, $string, $temp)) {
[1]912             continue;
913        }
914        $string = str_replace($temp[0], '', $string);
915        $results[] = $temp;
[247]916    } while (mb_ereg($pattern, $string, $temp));
[1]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,
[42]923 * used for printing the word "checked" in a checkbox form input.
[1]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,
[42]949 * otherwise prints nothing, used for printing the word "checked" in a
950 * select form input
[1]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/**
[111]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.
[1]978 *
[454]979 *
[111]980 * @param  array $in      Array to convert.
[1]981 * @return string         Comma list of array values.
982 */
[224]983function escapedList($in, $separator="', '")
[1]984{
[600]985    require_once dirname(__FILE__) . '/DB.inc.php';
[479]986    $db =& DB::getInstance();
[454]987
[111]988    if (is_array($in) && !empty($in)) {
[224]989        return join($separator, array_map(array($db, 'escapeString'), $in));
[111]990    } else {
[136]991        return $db->escapeString($in);
[1]992    }
993}
994
995/**
[111]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.
[1]999 *
1000 * @param  array $date     String date to convert.
[600]1001 * @param  array $format   Date format to pass to date(). Default produces MySQL datetime: YYYY-MM-DD hh:mm:ss
[1]1002 * @return string          SQL-safe date.
1003 */
1004function strToSQLDate($date, $format='Y-m-d H:i:s')
1005{
[600]1006    require_once dirname(__FILE__) . '/DB.inc.php';
1007    $db =& DB::getInstance();
1008
[601]1009    if ($db->isConnected() && mb_strpos($db->getParam('zero_date'), '-') !== false) {
[600]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
[601]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];
[600]1016    } else {
1017        $zero_y = '0000';
1018        $zero_m = '00';
1019        $zero_d = '00';
1020    }
[1]1021    // Translate the human string date into SQL-safe date format.
[600]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) {
[224]1023        // Return a string of zero time, formatted the same as $format.
1024        return strtr($format, array(
[600]1025            'Y' => $zero_y,
1026            'm' => $zero_m,
1027            'd' => $zero_d,
[224]1028            'H' => '00',
1029            'i' => '00',
1030            's' => '00',
1031        ));
[1]1032    } else {
[219]1033        return date($format, strtotime($date));
[1]1034    }
1035}
1036
1037/**
1038 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
[334]1039 * array, stripslashes is run on each value, recursively, and the stripped
[51]1040 * array is returned.
[1]1041 *
1042 * @param  mixed $var   The string or array to un-quote, if necessary.
1043 * @return mixed        $var, minus any magic quotes.
1044 */
[523]1045function dispelMagicQuotes($var, $always=false)
[1]1046{
1047    static $magic_quotes_gpc;
[42]1048
[1]1049    if (!isset($magic_quotes_gpc)) {
1050        $magic_quotes_gpc = get_magic_quotes_gpc();
1051    }
[42]1052
[523]1053    if ($always || $magic_quotes_gpc) {
[1]1054        if (!is_array($var)) {
1055            $var = stripslashes($var);
1056        } else {
1057            foreach ($var as $key=>$val) {
1058                if (is_array($val)) {
[523]1059                    $var[$key] = dispelMagicQuotes($val, $always);
[1]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 *
[701]1073 * @param string $key (optional) The name of a $_REQUEST key.
[1]1074 * @param string $default (optional) The value to return if the
1075 *                                   variable is not there.
[701]1076 * @return mixed      A cleaned GET or POST array if no key specified.
1077 * @return string     A cleaned form value if found, or $default.
[1]1078 */
[701]1079function getFormData($key=null, $default=null)
[1]1080{
[523]1081    $app =& App::getInstance();
1082
[718]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        }
[1]1095    }
[701]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;
[1]1112    } else {
1113        return $default;
1114    }
1115}
[523]1116
[701]1117function getPost($key=null, $default=null)
[1]1118{
[523]1119    $app =& App::getInstance();
1120
[701]1121    if (null === $key) {
[523]1122        return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
[1]1123    }
[701]1124    if (isset($_POST[$key])) {
1125        return dispelMagicQuotes($_POST[$key], $app->getParam('always_dispel_magicquotes'));
[1]1126    } else {
1127        return $default;
1128    }
1129}
[523]1130
[701]1131function getGet($key=null, $default=null)
[1]1132{
[523]1133    $app =& App::getInstance();
[701]1134
1135    if (null === $key) {
[523]1136        return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
[1]1137    }
[701]1138    if (isset($_GET[$key])) {
1139        return dispelMagicQuotes($_GET[$key], $app->getParam('always_dispel_magicquotes'));
[1]1140    } else {
1141        return $default;
1142    }
1143}
1144
[361]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{
[560]1158    switch (strtoupper(getenv('REQUEST_METHOD'))) {
1159    case 'POST':
[361]1160        $_POST[$key] = $val;
[560]1161        break;
1162
1163    case 'GET':
[361]1164        $_GET[$key] = $val;
[560]1165        break;
[361]1166    }
[718]1167
1168    $_REQUEST[$key] = $val;
[361]1169}
1170
[580]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{
[696]1184    return mb_substr(preg_replace('/[^\w]/u', '', base64_encode(hash('sha512', $string, true))), 0, $length);
[580]1185}
1186
[1]1187/**
1188 * Signs a value using md5 and a simple text key. In order for this
[502]1189 * function to be useful (i.e. secure) the salt must be kept secret, which
[1]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.
[159]1195 * @param   string  $salt   (Optional) A text key to use for computing the signature.
[282]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.
[1]1197 * @return  string  The original value with a signature appended.
1198 */
[282]1199function addSignature($val, $salt=null, $length=18)
[1]1200{
[159]1201    $app =& App::getInstance();
[454]1202
[159]1203    if ('' == trim($val)) {
[201]1204        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
[159]1205        return '';
[1]1206    }
[42]1207
[159]1208    if (!isset($salt)) {
1209        $salt = $app->getParam('signing_key');
[1]1210    }
[454]1211
[500]1212    switch ($app->getParam('signing_method')) {
1213    case 'sha512+base64':
[696]1214        return $val . '-' . mb_substr(preg_replace('/[^\w]/u', '', base64_encode(hash('sha512', $val . $salt, true))), 0, $length);
[500]1215
1216    case 'md5':
1217    default:
1218        return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
1219    }
[1]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{
[249]1231    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
1232        return '';
1233    }
[247]1234    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
[1]1235}
1236
1237/**
[500]1238 * Verifies a signature appended to a value by addSignature().
[1]1239 *
1240 * @access  public
1241 * @param   string  $signed_val A value with appended signature.
[159]1242 * @param   string  $salt       (Optional) A text key to use for computing the signature.
[502]1243 * @param   string  $length (Optional) The length of the added signature.
[1]1244 * @return  bool    True if the signature matches the var.
1245 */
[282]1246function verifySignature($signed_val, $salt=null, $length=18)
[1]1247{
1248    // Strip the value from the signed value.
[22]1249    $val = removeSignature($signed_val);
[1]1250    // If the signed value matches the original signed value we consider the value safe.
[532]1251    if ('' != $signed_val && $signed_val == addSignature($val, $salt, $length)) {
[1]1252        // Signature verified.
1253        return true;
1254    } else {
[500]1255        $app =& App::getInstance();
1256        $app->logMsg(sprintf('Failed signature (%s should be %s)', $signed_val, addSignature($val, $salt, $length)), LOG_DEBUG, __FILE__, __LINE__);
[1]1257        return false;
1258    }
1259}
1260
1261/**
1262 * Sends empty output to the browser and flushes the php buffer so the client
[42]1263 * will see data before the page is finished processing.
[1]1264 */
[235]1265function flushBuffer()
1266{
[1]1267    echo str_repeat('          ', 205);
1268    flush();
1269}
1270
1271/**
[667]1272 * A stub for apps that still use this function.
[1]1273 *
1274 * @access  public
[667]1275 * @return  void
[1]1276 */
1277function mailmanAddMember($email, $list, $send_welcome_message=false)
1278{
[479]1279    $app =& App::getInstance();
[667]1280    $app->logMsg(sprintf('mailmanAddMember called and ignored: %s, %s, %s', $email, $list, $send_welcome_message), LOG_WARNING, __FILE__, __LINE__);
[1]1281}
1282
1283/**
[667]1284 * A stub for apps that still use this function.
[1]1285 *
1286 * @access  public
[667]1287 * @return  void
[1]1288 */
1289function mailmanRemoveMember($email, $list, $send_user_ack=false)
1290{
[479]1291    $app =& App::getInstance();
[667]1292    $app->logMsg(sprintf('mailmanRemoveMember called and ignored: %s, %s, %s', $email, $list, $send_user_ack), LOG_WARNING, __FILE__, __LINE__);
[1]1293}
1294
[497]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)
[1]1312{
[497]1313    global $cfg;
1314
1315    if (!isset($_SERVER['REMOTE_ADDR'])) {
[507]1316        // In some cases this won't be set, e.g., CLI scripts.
1317        return null;
[497]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.
[706]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) {
[497]1330            // Loop through and if
1331            if (array_key_exists($key, $_SERVER)) {
1332                foreach (explode(',', $_SERVER[$key]) as $addr) {
[598]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);
[497]1335                    $addr = canonicalIPAddr(trim($addr));
[706]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)) {
[497]1337                        return $dolookup && '' != $addr ? gethostbyaddr($addr) : $addr;
1338                    }
1339                }
1340            }
[290]1341        }
[1]1342    }
[497]1343
1344    $addr = canonicalIPAddr(trim($_SERVER['REMOTE_ADDR']));
1345    return $dolookup && $addr ? gethostbyaddr($addr) : $addr;
[1]1346}
1347
[497]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{
[706]1361    if (!preg_match('/^([0-9a-f:]+|[0-9.])$/', $addr)) {
1362        // Definitely not an IPv6 or IPv4 address.
1363        return $addr;
1364    }
1365
[497]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
[1]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 */
[497]1392function ipInRange($addr, $networks)
[1]1393{
1394    if (!is_array($networks)) {
1395        $networks = array($networks);
1396    }
[42]1397
[497]1398    $addr_binary = sprintf('%032b', ip2long($addr));
[1]1399    foreach ($networks as $network) {
[715]1400        if (mb_strpos($network, '/') !== false) {
[1]1401            // IP is in CIDR notation.
[247]1402            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
[1]1403            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
[497]1404            if (mb_substr($addr_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
[1]1405               // IP address is within the specified IP range.
1406               return $network;
1407            }
1408        } else {
[497]1409            if ($addr === $network) {
[1]1410               // IP address exactly matches.
1411               return $network;
1412            }
1413        }
1414    }
[42]1415
[1]1416    return false;
1417}
1418
1419/**
[159]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])) {
[670]1432        if (!preg_match('!^https?://!i', $url)) {
[159]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 {
[670]1436            $urls[$url] = preg_match('!^https?://' . preg_quote(getenv('HTTP_HOST'), '!') . '!i', $url);
[159]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{
[696]1450    return preg_replace('/[?#].*$/u', '', $url);
[159]1451}
1452
1453/**
[690]1454 * Returns a fully qualified URL to the current script, including the query. If you don't need the scheme://, use REQUEST_URI instead.
[1]1455 *
1456 * @return string    a full url to the current script
1457 */
1458function absoluteMe()
1459{
[696]1460    $safe_http_host = preg_replace('/[^a-z\d.:-]/u', '', getenv('HTTP_HOST'));
[670]1461    return sprintf('%s://%s%s', (getenv('HTTPS') ? 'https' : 'http'), $safe_http_host, getenv('REQUEST_URI'));
[1]1462}
1463
1464/**
1465 * Compares the current url with the referring url.
1466 *
[159]1467 * @param  bool $exclude_query  Remove the query string first before comparing.
[334]1468 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
[1]1469 */
1470function refererIsMe($exclude_query=false)
1471{
[580]1472    $current_url = absoluteMe();
[598]1473    $referrer_url = getenv('HTTP_REFERER');
[580]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))) {
[696]1477        $current_url = preg_replace('@^https?://[^/]+@u', '', $current_url);
1478        $referrer_url = preg_replace('@^https?://[^/]+@u', '', $referrer_url);
[580]1479    }
1480
[1]1481    if ($exclude_query) {
[598]1482        return (stripQuery($current_url) == stripQuery($referrer_url));
[1]1483    } else {
[580]1484        $app =& App::getInstance();
[598]1485        $app->logMsg(sprintf('refererIsMe comparison: %s == %s', $current_url, $referrer_url), LOG_DEBUG, __FILE__, __LINE__);
1486        return ($current_url == $referrer_url);
[1]1487    }
1488}
[520]1489
1490/*
[591]1491* Returns true if the given URL resolves to a resource with a HTTP 2xx or 3xx header response.
[606]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.
[520]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>
[606]1500* @version  2.0
[520]1501* @since    02 May 2015 15:10:09
1502*/
1503function httpExists($url)
1504{
1505    $ch = curl_init($url);
[591]1506    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
[679]1507    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
[520]1508    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
[679]1509    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
[606]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");
[672]1511    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Don't pass through data to the browser.
[606]1512    curl_setopt($ch, CURLOPT_BUFFERSIZE, 128); // Frequent progress function calls.
1513    curl_setopt($ch, CURLOPT_NOPROGRESS, false); // Required to use CURLOPT_PROGRESSFUNCTION.
[607]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    }
[520]1528    curl_exec($ch);
[591]1529    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1530    return preg_match('/^[23]\d\d$/', $http_code);
[520]1531}
[704]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)) {
[705]1550        $app->logMsg(sprintf('JSON file "%s" not found in path "%s"', $filename, get_include_path()), LOG_ERR, __FILE__, __LINE__);
[704]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;
[706]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.
[707]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.
[706]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    }
[704]1640}
Note: See TracBrowser for help on using the repository browser.