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