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