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