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