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