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

Last change on this file since 793 was 793, checked in by anonymous, 14 months ago

Backport dump() function from trunk

File size: 68.5 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 *
[781]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  const    $dump_method    Dump method. See SC_DUMP_* constants.
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);
[743]40define('SC_DUMP_JSON', 3);
[793]41function dump($var, $display=false, $dump_method=SC_DUMP_JSON, $file='', $line='')
[1]42{
[548]43    $app =& App::getInstance();
44
[665]45    if ($app->isCLI()) {
[750]46        echo ('' != $file . $line) ? "DUMP FROM: $file $line\n" : "DUMP:\n";
[454]47    } else {
[477]48        echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n";
[380]49    }
[613]50
51    switch ($dump_method) {
52    case SC_DUMP_PRINT_R:
53    default:
[479]54        // Print human-readable descriptions of invisible types.
55        if (null === $var) {
56            echo '(null)';
57        } else if (true === $var) {
58            echo '(bool: true)';
59        } else if (false === $var) {
60            echo '(bool: false)';
61        } else if (is_scalar($var) && '' === $var) {
62            echo '(empty string)';
63        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
64            echo '(only white space)';
65        } else {
66            print_r($var);
67        }
[613]68        break;
69
70    case SC_DUMP_VAR_DUMP:
71        var_dump($var);
72        break;
73
74    case SC_DUMP_VAR_EXPORT:
75        var_export($var);
76        break;
[743]77
78    case SC_DUMP_JSON:
[793]79        echo json_encode($var, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
[743]80        break;
[1]81    }
[613]82
[665]83    if ($app->isCLI()) {
[380]84        echo "\n";
[454]85    } else {
[477]86        echo $display ? "\n</pre><br />\n" : "\n-->\n";
[380]87    }
[1]88}
89
[464]90/*
91* Log a PHP variable to javascript console. Relies on getDump(), below.
92*
93* @access   public
94* @param    mixed   $var      The variable to dump.
95* @param    string  $prefix   A short note to print before the output to make identifying output easier.
96* @param    string  $file     The value of __FILE__.
97* @param    string  $line     The value of __LINE__.
98* @return   null
99* @author   Quinn Comendant <quinn@strangecode.com>
100*/
101function jsDump($var, $prefix='jsDump', $file='-', $line='-')
102{
103    if (!empty($var)) {
104        ?>
[518]105        <script type="text/javascript">
[464]106        /* <![CDATA[ */
[518]107        console.log('<?php printf('%s: %s (on line %s of %s)', $prefix, str_replace("'", "\\'", getDump($var, true)), $line, $file); ?>');
[464]108        /* ]]> */
109        </script>
110        <?php
111    }
112}
113
114/*
115* Return a string version of any variable, optionally serialized on one line.
116*
117* @access   public
[781]118* @param    mixed   $var            The variable to dump.
119* @param    bool    $serialize      If true, remove line-endings. Useful for logging variables.
120* @param    const   $dump_method    Dump method. See SC_DUMP_* constants.
121* @return   string                  The dumped variable.
[464]122* @author   Quinn Comendant <quinn@strangecode.com>
123*/
[789]124function getDump($var, $serialize=false, $dump_method=SC_DUMP_JSON)
[1]125{
[724]126    $app =& App::getInstance();
127
[765]128    switch ($dump_method) {
129    case SC_DUMP_PRINT_R:
130        // Print human-readable descriptions of invisible types.
131        if (null === $var) {
132            $d = '(null)';
133        } else if (true === $var) {
134            $d = '(bool: true)';
135        } else if (false === $var) {
136            $d = '(bool: false)';
137        } else if (is_scalar($var) && '' === $var) {
138            $d = '(empty string)';
139        } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) {
140            $d = '(only white space)';
141        } else {
142            ob_start();
143            print_r($var);
144            $d = ob_get_contents();
145            ob_end_clean();
146        }
147        break;
148
149    case SC_DUMP_VAR_DUMP:
150        ob_start();
151        print_r($var);
152        var_dump($var);
153        ob_end_clean();
154        break;
155
156    case SC_DUMP_VAR_EXPORT:
157        ob_start();
158        print_r($var);
159        var_export($var);
160        ob_end_clean();
161        break;
162
163    case SC_DUMP_JSON:
[789]164    default:
[781]165        $json_flags = $serialize ? 0 : JSON_PRETTY_PRINT;
166        return json_encode($var, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | $json_flags);
[765]167    }
[724]168    return $serialize ? preg_replace('/\s+/m' . $app->getParam('preg_u'), ' ', $d) : $d;
[1]169}
170
[652]171/*
172* Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts.
173* To output tab-style lists set $indent to "\t" and $depth to 0;
174* To output markdown-style lists set $indent to '- ' and $depth to 1;
175* Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php
176*
177* @param  array    $var        Variable to dump.
178* @param  string   $indent     A string to prepend indented lines.
179* @param  string   $depth      Starting depth of this iteration of recursion (set to 0 to have no initial indentation).
180* @return string               Pretty dump of $var.
181* @author   Quinn Comendant <quinn@strangecode.com>
182* @version 2.0
183*/
184function fancyDump($var, $indent='- ', $depth=1)
[1]185{
[724]186    $app =& App::getInstance();
187
[652]188    $indent_str = str_repeat($indent, $depth);
[1]189    $output = '';
190    if (is_array($var)) {
191        foreach ($var as $k=>$v) {
[247]192            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
[1]193            if (is_array($v)) {
[652]194                $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1));
[1]195            } else {
[652]196                $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v);
[1]197            }
198        }
199    } else {
[652]200        $output .= sprintf("%s%s\n", $indent_str, $var);
[1]201    }
[724]202    return preg_replace(['/^[ \t]+$/' . $app->getParam('preg_u'), '/\n\n+/' . $app->getParam('preg_u'), '/^(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(\S )/m' . $app->getParam('preg_u')], ['', "\n", '$1$1$2$2$3$3$4$4$5$5$6$6$7$7$8$8$9'], $output);
[1]203}
204
205/**
[605]206 * @param string|mixed $value A string to UTF8-encode.
207 *
208 * @returns string|mixed The UTF8-encoded string, or the object passed in if
209 *    it wasn't a string.
210 */
211function conditionalUTF8Encode($value)
212{
213  if (is_string($value) && mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
214    return utf8_encode($value);
215  } else {
216    return $value;
217  }
218}
219
220
221/**
[505]222 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
[1]223 *
[257]224 * @param  string $text             Text to clean.
[334]225 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
[485]226 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
227 * @return string                   HTML-safe text.
[1]228 */
[257]229function oTxt($text, $preserve_html=false)
[1]230{
[479]231    $app =& App::getInstance();
[136]232
[785]233    if ('' == $text) {
234        return '';
235    }
236
[1]237    $search = array();
238    $replace = array();
239
240    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
[723]241    $search['retain_ampersand']     = '/&amp;/';
[1]242    $replace['retain_ampersand']    = '&';
243
244    if ($preserve_html) {
245        // Convert characters that must remain non-entities for displaying HTML.
[723]246        $search['retain_left_angle']       = '/&lt;/';
[1]247        $replace['retain_left_angle']      = '<';
[42]248
[723]249        $search['retain_right_angle']      = '/&gt;/';
[1]250        $replace['retain_right_angle']     = '>';
[42]251
[723]252        $search['retain_single_quote']     = '/&#039;/';
[1]253        $replace['retain_single_quote']    = "'";
[42]254
[723]255        $search['retain_double_quote']     = '/&quot;/';
[1]256        $replace['retain_double_quote']    = '"';
257    }
258
[334]259    // & becomes &amp;. Exclude any occurrence where the & is followed by a alphanum or unicode character.
[32]260    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
261    $replace['ampersand']       = '&amp;';
[1]262
[334]263    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
[1]264}
265
266/**
[334]267 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
[320]268 * TODO: Allow a string such as this to be passed: <a href="javascript:openPopup('/foo/bar.php')">Click here</a>
[1]269 *
[257]270 * @param  string   $text Text to clean.
[1]271 * @return string         Cleaned text.
272 */
[653]273function fancyTxt($text, $extra_search=null, $extra_replace=null)
[1]274{
[103]275    $search = array();
276    $replace = array();
277
[653]278    // "double quoted text"  →  “double quoted text”
279    $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;
280    $replace['_double_quotes']   = '“$1”';
[103]281
[653]282    // text's apostrophes  →  text’s apostrophes (except foot marks: 6'3")
283    $search['_apostrophe']       = '/(?<=[a-z])(?:\'|&#0?39;)(?=\w)/imsu';
284    $replace['_apostrophe']      = '’';
[103]285
[653]286    // 'single quoted text'  →  ‘single quoted text’
287    $search['_single_quotes']    = '/(?<=^|[^\w=(])(?:\'|&#0?39;|&lsquo;)([\w"][^\']+?)(?:\'|&#0?39;|&rsquo;)(?=[^)\w]|$)/imsu';
288    $replace['_single_quotes']   = '‘$1’';
[103]289
[653]290    // plural posessives' apostrophes  →  posessives’  (except foot marks: 6')
291    $search['_apostrophes']      = '/(?<=s)(?:\'|&#0?39;|&rsquo;)(?=\s)/imsu';
292    $replace['_apostrophes']     = '’';
[103]293
[774]294    // double--hyphens  →  en – dashes
[653]295    $search['_em_dash']          = '/(?<=[\w\s"\'”’)])--(?=[\w\s“”‘"\'(?])/imsu';
296    $replace['_em_dash']         = ' – ';
[103]297
[653]298    // ...  →  

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