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