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