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