[1] | 1 | <?php |
---|
| 2 | /** |
---|
| 3 | * Utilities.inc.php |
---|
| 4 | * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information |
---|
| 5 | */ |
---|
| 6 | |
---|
| 7 | |
---|
| 8 | /** |
---|
| 9 | * Print variable dump. |
---|
| 10 | * |
---|
[649] | 11 | * @param mixed $var The variable to dump. |
---|
| 12 | * @param bool $display Print the dump in <pre> tags or hide it in html comments (non-CLI only). |
---|
| 13 | * @param bool $dump_method Dump method. See SC_DUMP_* constants. |
---|
| 14 | * @param string $file Value of __FILE__. |
---|
| 15 | * @param string $line Value of __LINE__ |
---|
[1] | 16 | */ |
---|
[649] | 17 | define('SC_DUMP_PRINT_R', 0); |
---|
| 18 | define('SC_DUMP_VAR_DUMP', 1); |
---|
| 19 | define('SC_DUMP_VAR_EXPORT', 2); |
---|
| 20 | function dump($var, $display=false, $dump_method=SC_DUMP_PRINT_R, $file='', $line='') |
---|
[1] | 21 | { |
---|
[649] | 22 | if ('cli' === php_sapi_name() || defined('_CLI')) { |
---|
| 23 | echo "DUMP FROM: $file $line\n"; |
---|
| 24 | } else { |
---|
| 25 | echo $display ? "\n<br />DUMP <strong>$file $line</strong><br /><pre>\n" : "\n<!-- DUMP $file $line\n"; |
---|
| 26 | } |
---|
| 27 | |
---|
| 28 | switch ($dump_method) { |
---|
| 29 | case SC_DUMP_PRINT_R: |
---|
| 30 | default: |
---|
| 31 | // Print human-readable descriptions of invisible types. |
---|
| 32 | if (null === $var) { |
---|
| 33 | echo '(null)'; |
---|
| 34 | } else if (true === $var) { |
---|
| 35 | echo '(bool: true)'; |
---|
| 36 | } else if (false === $var) { |
---|
| 37 | echo '(bool: false)'; |
---|
| 38 | } else if (is_scalar($var) && '' === $var) { |
---|
| 39 | echo '(empty string)'; |
---|
| 40 | } else if (is_scalar($var) && preg_match('/^\s+$/', $var)) { |
---|
| 41 | echo '(only white space)'; |
---|
| 42 | } else { |
---|
| 43 | print_r($var); |
---|
| 44 | } |
---|
| 45 | break; |
---|
| 46 | |
---|
| 47 | case SC_DUMP_VAR_DUMP: |
---|
[1] | 48 | var_dump($var); |
---|
[649] | 49 | break; |
---|
| 50 | |
---|
| 51 | case SC_DUMP_VAR_EXPORT: |
---|
| 52 | var_export($var); |
---|
| 53 | break; |
---|
| 54 | } |
---|
| 55 | |
---|
| 56 | if ('cli' === php_sapi_name() || defined('_CLI')) { |
---|
| 57 | echo "\n"; |
---|
[1] | 58 | } else { |
---|
[649] | 59 | echo $display ? "\n</pre><br />\n" : "\n-->\n"; |
---|
[1] | 60 | } |
---|
| 61 | } |
---|
| 62 | |
---|
| 63 | /** |
---|
| 64 | * Return dump as variable. |
---|
| 65 | * |
---|
| 66 | * @param mixed $var Variable to dump. |
---|
| 67 | * |
---|
| 68 | * @return string Dump of var. |
---|
| 69 | */ |
---|
| 70 | function getDump($var) |
---|
| 71 | { |
---|
| 72 | ob_start(); |
---|
| 73 | print_r($var); |
---|
| 74 | $d = ob_get_contents(); |
---|
| 75 | ob_end_clean(); |
---|
| 76 | return $d; |
---|
| 77 | } |
---|
| 78 | |
---|
[651] | 79 | /* |
---|
| 80 | * Return dump as cleaned text. Useful for dumping data into emails or output from CLI scripts. |
---|
| 81 | * To output tab-style lists set $indent to "\t" and $depth to 0; |
---|
| 82 | * To output markdown-style lists set $indent to '- ' and $depth to 1; |
---|
| 83 | * Also see yaml_emit() https://secure.php.net/manual/en/function.yaml-emit.php |
---|
| 84 | * |
---|
| 85 | * @param array $var Variable to dump. |
---|
| 86 | * @param string $indent A string to prepend indented lines. |
---|
| 87 | * @param string $depth Starting depth of this iteration of recursion (set to 0 to have no initial indentation). |
---|
| 88 | * @return string Pretty dump of $var. |
---|
| 89 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 90 | * @version 2.0 |
---|
| 91 | */ |
---|
| 92 | function fancyDump($var, $indent='- ', $depth=1) |
---|
[1] | 93 | { |
---|
[651] | 94 | $indent_str = str_repeat($indent, $depth); |
---|
[1] | 95 | $output = ''; |
---|
| 96 | if (is_array($var)) { |
---|
| 97 | foreach ($var as $k=>$v) { |
---|
[649] | 98 | $k = ucfirst(mb_strtolower(str_replace(array('_', ' '), ' ', $k))); |
---|
[1] | 99 | if (is_array($v)) { |
---|
[651] | 100 | $output .= sprintf("\n%s%s:\n%s\n", $indent_str, $k, fancyDump($v, $indent, $depth+1)); |
---|
[1] | 101 | } else { |
---|
[651] | 102 | $output .= sprintf("%s%s: %s\n", $indent_str, $k, $v); |
---|
[1] | 103 | } |
---|
| 104 | } |
---|
| 105 | } else { |
---|
[651] | 106 | $output .= sprintf("%s%s\n", $indent_str, $var); |
---|
[1] | 107 | } |
---|
[651] | 108 | return preg_replace(['/^[ \t]+$/', '/\n\n+/', '/^(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(?:\S( ))?(\S )/m'], ['', "\n", '$1$1$2$2$3$3$4$4$5$5$6$6$7$7$8$8$9'], $output); |
---|
[1] | 109 | } |
---|
| 110 | |
---|
| 111 | /** |
---|
[646] | 112 | * Returns text with appropriate html translations. |
---|
[1] | 113 | * |
---|
| 114 | * @param string $txt Text to clean. |
---|
[646] | 115 | * @param bool $preserve_html If set to true, oTxt will not translage <, >, ", or ' |
---|
[1] | 116 | * characters into HTML entities. This allows HTML to pass |
---|
| 117 | * through unmunged. |
---|
| 118 | * |
---|
| 119 | * @return string Cleaned text. |
---|
| 120 | */ |
---|
| 121 | function oTxt($txt, $preserve_html=false) |
---|
| 122 | { |
---|
| 123 | global $CFG; |
---|
| 124 | |
---|
| 125 | $search = array(); |
---|
| 126 | $replace = array(); |
---|
| 127 | |
---|
| 128 | // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities. |
---|
| 129 | $search['retain_ampersand'] = '/&/'; |
---|
| 130 | $replace['retain_ampersand'] = '&'; |
---|
| 131 | |
---|
| 132 | if ($preserve_html) { |
---|
| 133 | // Convert characters that must remain non-entities for displaying HTML. |
---|
| 134 | $search['retain_left_angle'] = '/</'; |
---|
| 135 | $replace['retain_left_angle'] = '<'; |
---|
[646] | 136 | |
---|
[1] | 137 | $search['retain_right_angle'] = '/>/'; |
---|
| 138 | $replace['retain_right_angle'] = '>'; |
---|
[646] | 139 | |
---|
[1] | 140 | $search['retain_single_quote'] = '/'/'; |
---|
| 141 | $replace['retain_single_quote'] = "'"; |
---|
[646] | 142 | |
---|
[1] | 143 | $search['retain_double_quote'] = '/"/'; |
---|
| 144 | $replace['retain_double_quote'] = '"'; |
---|
| 145 | } |
---|
| 146 | |
---|
| 147 | // & becomes & |
---|
| 148 | $search['ampersand'] = '/&((?![\w\d#]{1,10};))/'; |
---|
| 149 | $replace['ampersand'] = '&\\1'; |
---|
| 150 | |
---|
| 151 | return preg_replace($search, $replace, htmlentities($txt, ENT_QUOTES, $CFG->character_set)); |
---|
| 152 | } |
---|
| 153 | |
---|
| 154 | /** |
---|
[646] | 155 | * Returns text with stylistic modifications. |
---|
[1] | 156 | * |
---|
| 157 | * @param string $txt Text to clean. |
---|
| 158 | * |
---|
| 159 | * @return string Cleaned text. |
---|
| 160 | */ |
---|
| 161 | function fancyTxt($txt) |
---|
| 162 | { |
---|
| 163 | $search = array(); |
---|
| 164 | $replace = array(); |
---|
| 165 | |
---|
| 166 | // "double quoted text" becomes “double quoted text” |
---|
| 167 | $search['double_quotes'] = '/(^|[^\w=])(?:"|"|"|"|“)([^"]+?)(?:"|"|"|"|”)([^\w]|$)/'; // " is the same as " and " and " |
---|
| 168 | $replace['double_quotes'] = '\\1“\\2”\\3'; |
---|
| 169 | |
---|
| 170 | // text's apostrophes become text’s apostrophes |
---|
| 171 | $search['apostrophe'] = '/(\w)(?:\'|')(\w)/'; |
---|
| 172 | $replace['apostrophe'] = '\\1’\\2'; |
---|
| 173 | |
---|
| 174 | // "single quoted text" becomes ‘single quoted text’ |
---|
| 175 | $search['single_quotes'] = '/(^|[^\w=])(?:\'|'|‘)([^\']+?)(?:\'|'|’)([^\w]|$)/'; |
---|
| 176 | $replace['single_quotes'] = '\\1‘\\2’\\3'; |
---|
[646] | 177 | |
---|
[1] | 178 | // em--dashes become em—dashes |
---|
| 179 | $search['em_dash'] = '/(\s*[^!<-])--([^>-]\s*)/'; |
---|
| 180 | $replace['em_dash'] = '\\1—\\2'; |
---|
[646] | 181 | |
---|
[1] | 182 | // & becomes & |
---|
| 183 | $search['ampersand'] = '/&((?![\w\d#]{1,10};))/'; |
---|
| 184 | $replace['ampersand'] = '&\\1'; |
---|
| 185 | |
---|
| 186 | return preg_replace($search, $replace, $txt); |
---|
| 187 | } |
---|
| 188 | |
---|
[646] | 189 | /* |
---|
| 190 | * Finds all URLs in text and hyperlinks them. |
---|
| 191 | * |
---|
| 192 | * @access public |
---|
| 193 | * @param string $text Text to search for URLs. |
---|
| 194 | * @param bool $strict True to only include URLs starting with a scheme (http:// ftp:// im://), or false to include URLs starting with 'www.'. |
---|
| 195 | * @param mixed $length Number of characters to truncate URL, or NULL to disable truncating. |
---|
| 196 | * @param string $delim Delimiter to append, indicate truncation. |
---|
| 197 | * @return string Same input text, but URLs hyperlinked. |
---|
| 198 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 199 | * @version 2.1 |
---|
| 200 | * @since 22 Mar 2015 23:29:04 |
---|
| 201 | */ |
---|
| 202 | function hyperlinkTxt($text, $strict=false, $length=null, $delim='âŠ') |
---|
| 203 | { |
---|
| 204 | // A list of schemes we allow at the beginning of a URL. |
---|
| 205 | $schemes = 'mailto:|tel:|skype:|callto:|facetime:|bitcoin:|geo:|magnet:\?|sip:|sms:|xmpp:|view-source:(?:https?://)?|[\w-]{2,}://'; |
---|
| 206 | |
---|
| 207 | // Capture the full URL into the first match and only the first X characters into the second match. |
---|
| 208 | // This will match URLs not preceded by " ' or = (URLs inside an attribute) or ` (Markdown quoted) or double-scheme (http://http://www.asdf.com) |
---|
| 209 | // Valid URL characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;= |
---|
| 210 | $regex = '@ |
---|
| 211 | \b # Start with a word-boundary. |
---|
| 212 | (?<!"|\'|=|>|`|\]\(|[:/]/) # Negative look-behind to exclude URLs already in <a> tag, <tags>beween</tags>, `Markdown quoted`, [Markdown](link), and avoid broken:/ and doubled://schemes:// |
---|
| 213 | ( # Begin match 1 |
---|
| 214 | ( # Begin match 2 |
---|
| 215 | (?:%s) # URL starts with known scheme or www. if strict = false |
---|
| 216 | [^\s/$.?#]+ # Any domain-valid characters |
---|
| 217 | [^\s"`<>]{1,%s} # Match 2 is limited to a maximum of LENGTH valid URL characters |
---|
| 218 | ) |
---|
| 219 | [^\s"`<>]* # Match 1 continues with any further valid URL characters |
---|
| 220 | ([^\P{Any}\sâŠ<>«»"ââ%s]) # Final character not a space or common end-of-sentence punctuation (.,:;?!, etc). Using double negation set, see http://stackoverflow.com/a/4786560/277303 |
---|
| 221 | ) |
---|
| 222 | @Suxi |
---|
| 223 | '; |
---|
| 224 | $regex = sprintf($regex, |
---|
| 225 | ($strict ? $schemes : $schemes . '|www\.'), // Strict=false adds "www." to the list of allowed start-of-URL. |
---|
| 226 | ($length ? $length : ''), |
---|
| 227 | ($strict ? '' : '?!.,:;)\'-') // Strict=false excludes some "URL-valid" characters from the last character of URL. (Hyphen must remain last character in this class.) |
---|
| 228 | ); |
---|
| 229 | |
---|
| 230 | // Use a callback function to decide when to append the delim. |
---|
| 231 | // Also encode special chars with oTxt(). |
---|
| 232 | return preg_replace_callback($regex, function ($m) use ($length, $delim) { |
---|
| 233 | $url = $m[1]; |
---|
| 234 | $truncated_url = $m[2] . $m[3]; |
---|
| 235 | $absolute_url = preg_replace('!^www\.!', 'http://www.', $url); |
---|
| 236 | if (is_null($length) || $url == $truncated_url) { |
---|
| 237 | // If not truncating, or URL was not truncated. |
---|
| 238 | // Remove http schemas, and any single trailing / to make the display URL. |
---|
| 239 | $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], $url); |
---|
| 240 | return sprintf('<a href="%s">%s</a>', oTxt($absolute_url), $display_url); |
---|
| 241 | } else { |
---|
| 242 | // Truncated URL. |
---|
| 243 | // Remove http schemas, and any single trailing / to make the display URL. |
---|
| 244 | $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], trim($truncated_url)); |
---|
| 245 | return sprintf('<a href="%s">%s%s</a>', oTxt($absolute_url), $display_url, $delim); |
---|
| 246 | } |
---|
| 247 | }, $text); |
---|
| 248 | } |
---|
| 249 | |
---|
[77] | 250 | /** |
---|
| 251 | * Turns "a really long string" into "a rea...string" |
---|
| 252 | * |
---|
| 253 | * @access public |
---|
| 254 | * @param string $str Input string |
---|
| 255 | * @param int $len Maximum string length. |
---|
| 256 | * @param string $where Where to cut the string. One of: 'start', 'middle', or 'end'. |
---|
| 257 | * @return string Truncated output string |
---|
| 258 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 259 | * @since 29 Mar 2006 13:48:49 |
---|
| 260 | */ |
---|
[649] | 261 | function truncate($str, $len=50, $where='end', $delim='âŠ') |
---|
[77] | 262 | { |
---|
[649] | 263 | $dlen = mb_strlen($delim); |
---|
| 264 | if ($len <= $dlen || mb_strlen($str) <= $dlen) { |
---|
| 265 | return substr($str, 0, $len); |
---|
[423] | 266 | } |
---|
[649] | 267 | $part1 = floor(($len - $dlen) / 2); |
---|
| 268 | $part2 = ceil(($len - $dlen) / 2); |
---|
| 269 | |
---|
| 270 | if ($len > ini_get('pcre.backtrack_limit')) { |
---|
| 271 | logMsg(sprintf('Asked to truncate string len of %s > pcre.backtrack_limit of %s', $len, ini_get('pcre.backtrack_limit')), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 272 | ini_set('pcre.backtrack_limit', $len); |
---|
| 273 | } |
---|
| 274 | |
---|
[77] | 275 | switch ($where) { |
---|
| 276 | case 'start' : |
---|
[649] | 277 | 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); |
---|
| 278 | |
---|
[77] | 279 | case 'middle' : |
---|
[649] | 280 | 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); |
---|
| 281 | |
---|
[77] | 282 | case 'end' : |
---|
[649] | 283 | default : |
---|
| 284 | 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); |
---|
[77] | 285 | } |
---|
| 286 | } |
---|
[646] | 287 | |
---|
[1] | 288 | /** |
---|
[265] | 289 | * Generates a hexadecimal html color based on provided word. |
---|
[1] | 290 | * |
---|
| 291 | * @access public |
---|
| 292 | * |
---|
| 293 | * @param string $text A string for which to convert to color. |
---|
| 294 | * |
---|
| 295 | * @return string A hexadecimal html color. |
---|
| 296 | */ |
---|
| 297 | function getTextColor($text, $method=1) |
---|
| 298 | { |
---|
[265] | 299 | $hash = md5($text); |
---|
| 300 | $rgb = array( |
---|
| 301 | substr($hash, 0, 1), |
---|
| 302 | substr($hash, 1, 1), |
---|
| 303 | substr($hash, 2, 1), |
---|
| 304 | substr($hash, 3, 1), |
---|
| 305 | substr($hash, 4, 1), |
---|
| 306 | substr($hash, 5, 1), |
---|
| 307 | ); |
---|
[1] | 308 | |
---|
| 309 | switch ($method) { |
---|
[265] | 310 | case 1 : |
---|
| 311 | default : |
---|
| 312 | // Reduce all hex values slighly to avoid all white. |
---|
| 313 | array_walk($rgb, create_function('&$v', '$v = dechex(round(hexdec($v) * 0.87));')); |
---|
| 314 | break; |
---|
[1] | 315 | case 2 : |
---|
[265] | 316 | foreach ($rgb as $i => $v) { |
---|
| 317 | if (hexdec($v) > hexdec('c')) { |
---|
| 318 | $rgb[$i] = dechex(hexdec('f') - hexdec($v)); |
---|
| 319 | } |
---|
[1] | 320 | } |
---|
| 321 | break; |
---|
| 322 | } |
---|
| 323 | |
---|
[265] | 324 | return join('', $rgb); |
---|
[1] | 325 | } |
---|
| 326 | |
---|
| 327 | /** |
---|
| 328 | * Encodes a string into unicode values 128-255. |
---|
| 329 | * Useful for hiding an email address from spambots. |
---|
| 330 | * |
---|
| 331 | * @access public |
---|
| 332 | * |
---|
| 333 | * @param string $text A line of text to encode. |
---|
| 334 | * |
---|
| 335 | * @return string Encoded text. |
---|
| 336 | */ |
---|
| 337 | function encodeAscii($text) |
---|
| 338 | { |
---|
| 339 | $ouput = ''; |
---|
| 340 | $num = strlen($text); |
---|
| 341 | for ($i=0; $i<$num; $i++) { |
---|
[753] | 342 | $output .= sprintf('&#%03s', ord($text[$i])); |
---|
[1] | 343 | } |
---|
| 344 | return $output; |
---|
| 345 | } |
---|
| 346 | |
---|
| 347 | /** |
---|
[30] | 348 | * Encodes an email into a user (at) domain (dot) com format. |
---|
| 349 | * |
---|
| 350 | * @access public |
---|
| 351 | * @param string $email An email to encode. |
---|
| 352 | * @param string $at Replaces the @. |
---|
| 353 | * @param string $dot Replaces the .. |
---|
| 354 | * @return string Encoded email. |
---|
| 355 | */ |
---|
[140] | 356 | function encodeEmail($email, $at=' at ', $dot=' dot ') |
---|
[30] | 357 | { |
---|
| 358 | $search = array('/@/', '/\./'); |
---|
| 359 | $replace = array($at, $dot); |
---|
| 360 | return preg_replace($search, $replace, $email); |
---|
| 361 | } |
---|
| 362 | |
---|
[678] | 363 | /* |
---|
| 364 | * Converts a string into a URL-safe slug, removing spaces and non word characters. |
---|
| 365 | * |
---|
| 366 | * @access public |
---|
| 367 | * @param string $str String to convert. |
---|
| 368 | * @return string URL-safe slug. |
---|
| 369 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 370 | * @version 1.0 |
---|
| 371 | * @since 18 Aug 2014 12:54:29 |
---|
| 372 | */ |
---|
| 373 | function URLSlug($str) |
---|
| 374 | { |
---|
| 375 | $slug = preg_replace(array('/\W+/u', '/^-+|-+$/'), array('-', ''), $str); |
---|
| 376 | $slug = strtolower($slug); |
---|
| 377 | return $slug; |
---|
| 378 | } |
---|
| 379 | |
---|
[30] | 380 | /** |
---|
[1] | 381 | * Return a human readable filesize. |
---|
| 382 | * |
---|
| 383 | * @param int $size Size |
---|
| 384 | * @param int $unit The maximum unit |
---|
| 385 | * @param int $format The return string format |
---|
| 386 | * @author Aidan Lister <aidan@php.net> |
---|
| 387 | * @version 1.1.0 |
---|
| 388 | */ |
---|
| 389 | function humanFileSize($size, $unit=null, $format='%01.2f %s') |
---|
| 390 | { |
---|
| 391 | // Units |
---|
| 392 | $units = array('B', 'KB', 'MB', 'GB', 'TB'); |
---|
| 393 | $ii = count($units) - 1; |
---|
[646] | 394 | |
---|
[1] | 395 | // Max unit |
---|
| 396 | $unit = array_search((string) $unit, $units); |
---|
| 397 | if ($unit === null || $unit === false) { |
---|
| 398 | $unit = $ii; |
---|
| 399 | } |
---|
[646] | 400 | |
---|
[1] | 401 | // Loop |
---|
| 402 | $i = 0; |
---|
| 403 | while ($unit != $i && $size >= 1024 && $i < $ii) { |
---|
| 404 | $size /= 1024; |
---|
| 405 | $i++; |
---|
| 406 | } |
---|
[646] | 407 | |
---|
[1] | 408 | return sprintf($format, $size, $units[$i]); |
---|
| 409 | } |
---|
| 410 | |
---|
| 411 | /** |
---|
| 412 | * If $var is net set or null, set it to $default. Otherwise leave it alone. |
---|
| 413 | * Returns the final value of $var. Use to find a default value of one is not avilable. |
---|
| 414 | * |
---|
| 415 | * @param mixed $var The variable that is being set. |
---|
| 416 | * @param mixed $default What to set it to if $val is not currently set. |
---|
[646] | 417 | * @return mixed The resulting value of $var. |
---|
[1] | 418 | */ |
---|
| 419 | function setDefault(&$var, $default='') |
---|
| 420 | { |
---|
| 421 | if (!isset($var)) { |
---|
| 422 | $var = $default; |
---|
| 423 | } |
---|
| 424 | return $var; |
---|
| 425 | } |
---|
| 426 | |
---|
| 427 | /** |
---|
| 428 | * Like preg_quote() except for arrays, it takes an array of strings and puts |
---|
| 429 | * a backslash in front of every character that is part of the regular |
---|
| 430 | * expression syntax. |
---|
| 431 | * |
---|
| 432 | * @param array $array input array |
---|
| 433 | * @param array $delim optional character that will also be excaped. |
---|
| 434 | * |
---|
| 435 | * @return array an array with the same values as $array1 but shuffled |
---|
| 436 | */ |
---|
| 437 | function pregQuoteArray($array, $delim='/') |
---|
| 438 | { |
---|
| 439 | if (!empty($array)) { |
---|
| 440 | if (is_array($array)) { |
---|
| 441 | foreach ($array as $key=>$val) { |
---|
| 442 | $quoted_array[$key] = preg_quote($val, $delim); |
---|
| 443 | } |
---|
| 444 | return $quoted_array; |
---|
| 445 | } else { |
---|
| 446 | return preg_quote($array, $delim); |
---|
| 447 | } |
---|
| 448 | } |
---|
| 449 | } |
---|
| 450 | |
---|
| 451 | /** |
---|
| 452 | * Converts a PHP Array into encoded URL arguments and return them as an array. |
---|
| 453 | * |
---|
[401] | 454 | * @param mixed $data An array to transverse recursively, or a string |
---|
[1] | 455 | * to use directly to create url arguments. |
---|
| 456 | * @param string $prefix The name of the first dimension of the array. |
---|
| 457 | * If not specified, the first keys of the array will be used. |
---|
| 458 | * |
---|
| 459 | * @return array URL with array elements as URL key=value arguments. |
---|
| 460 | */ |
---|
| 461 | function urlEncodeArray($data, $prefix='', $_return=true) { |
---|
[646] | 462 | |
---|
[1] | 463 | // Data is stored in static variable. |
---|
| 464 | static $args; |
---|
[646] | 465 | |
---|
[1] | 466 | if (is_array($data)) { |
---|
| 467 | foreach ($data as $key => $val) { |
---|
[401] | 468 | // If the prefix is empty, use the $key as the name of the first dimension of the "array". |
---|
| 469 | // ...otherwise, append the key as a new dimension of the "array". |
---|
[1] | 470 | $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']'; |
---|
| 471 | // Enter recursion. |
---|
| 472 | urlEncodeArray($val, $new_prefix, false); |
---|
| 473 | } |
---|
| 474 | } else { |
---|
[401] | 475 | // We've come to the last dimension of the array, save the "array" and it's value. |
---|
[1] | 476 | $args[$prefix] = urlencode($data); |
---|
| 477 | } |
---|
[646] | 478 | |
---|
[1] | 479 | if ($_return) { |
---|
| 480 | // This is not a recursive execution. All recursion is complete. |
---|
| 481 | // Reset static var and return the result. |
---|
| 482 | $ret = $args; |
---|
| 483 | $args = array(); |
---|
| 484 | return is_array($ret) ? $ret : array(); |
---|
| 485 | } |
---|
| 486 | } |
---|
| 487 | |
---|
| 488 | /** |
---|
| 489 | * Converts a PHP Array into encoded URL arguments and return them in a string. |
---|
| 490 | * |
---|
[401] | 491 | * @param mixed $data An array to transverse recursively, or a string |
---|
[1] | 492 | * to use directly to create url arguments. |
---|
[401] | 493 | * @param string $prefix The name of the first dimension of the array. |
---|
[1] | 494 | * If not specified, the first keys of the array will be used. |
---|
| 495 | * |
---|
| 496 | * @return string url A string ready to append to a url. |
---|
| 497 | */ |
---|
| 498 | function urlEncodeArrayToString($data, $prefix='') { |
---|
[646] | 499 | |
---|
[1] | 500 | $array_args = urlEncodeArray($data, $prefix); |
---|
| 501 | $url_args = ''; |
---|
| 502 | $delim = ''; |
---|
| 503 | foreach ($array_args as $key=>$val) { |
---|
| 504 | $url_args .= $delim . $key . '=' . $val; |
---|
| 505 | $delim = ini_get('arg_separator.output'); |
---|
| 506 | } |
---|
| 507 | return $url_args; |
---|
| 508 | } |
---|
| 509 | |
---|
| 510 | /** |
---|
[646] | 511 | * An alternative to "shuffle()" that actually works. |
---|
[1] | 512 | * |
---|
| 513 | * @param array $array1 input array |
---|
| 514 | * @param array $array2 argument used internally through recursion |
---|
| 515 | * |
---|
| 516 | * @return array an array with the same values as $array1 but shuffled |
---|
| 517 | */ |
---|
| 518 | function arrayRand(&$array1, $array2 = array()) |
---|
| 519 | { |
---|
| 520 | if (!sizeof($array1)) { |
---|
| 521 | return array(); |
---|
| 522 | } |
---|
[646] | 523 | |
---|
[1] | 524 | srand((double) microtime() * 10000000); |
---|
| 525 | $rand = array_rand($array1); |
---|
[646] | 526 | |
---|
[1] | 527 | $array2[] = $array1[$rand]; |
---|
| 528 | unset ($array1[$rand]); |
---|
[646] | 529 | |
---|
[1] | 530 | return $array2 + arrayRand($array1, $array2); |
---|
| 531 | } |
---|
| 532 | |
---|
| 533 | /** |
---|
| 534 | * Fills an arrray with the result from a multiple ereg search. |
---|
| 535 | * Curtesy of Bruno - rbronosky@mac.com - 10-May-2001 |
---|
| 536 | * Blame him for the funky do...while loop. |
---|
| 537 | * |
---|
| 538 | * @param mixed $pattern regular expression needle |
---|
| 539 | * @param mixed $string haystack |
---|
| 540 | * |
---|
| 541 | * @return array populated with each found result |
---|
| 542 | */ |
---|
| 543 | function eregAll($pattern, $string) |
---|
| 544 | { |
---|
| 545 | do { |
---|
| 546 | if (!ereg($pattern, $string, $temp)) { |
---|
| 547 | continue; |
---|
| 548 | } |
---|
| 549 | $string = str_replace($temp[0], '', $string); |
---|
| 550 | $results[] = $temp; |
---|
| 551 | } while (ereg($pattern, $string, $temp)); |
---|
| 552 | return $results; |
---|
| 553 | } |
---|
| 554 | |
---|
| 555 | /** |
---|
| 556 | * Prints the word "checked" if a variable is set, and optionally matches |
---|
| 557 | * the desired value, otherwise prints nothing, |
---|
[646] | 558 | * used for printing the word "checked" in a checkbox form input. |
---|
[1] | 559 | * |
---|
| 560 | * @param mixed $var the variable to compare |
---|
| 561 | * @param mixed $value optional, what to compare with if a specific value is required. |
---|
| 562 | */ |
---|
| 563 | function frmChecked($var, $value=null) |
---|
| 564 | { |
---|
| 565 | if (func_num_args() == 1 && $var) { |
---|
| 566 | // 'Checked' if var is true. |
---|
| 567 | echo ' checked="checked" '; |
---|
| 568 | } else if (func_num_args() == 2 && $var == $value) { |
---|
| 569 | // 'Checked' if var and value match. |
---|
| 570 | echo ' checked="checked" '; |
---|
| 571 | } else if (func_num_args() == 2 && is_array($var)) { |
---|
| 572 | // 'Checked' if the value is in the key or the value of an array. |
---|
| 573 | if (isset($var[$value])) { |
---|
| 574 | echo ' checked="checked" '; |
---|
| 575 | } else if (in_array($value, $var)) { |
---|
| 576 | echo ' checked="checked" '; |
---|
| 577 | } |
---|
| 578 | } |
---|
| 579 | } |
---|
| 580 | |
---|
| 581 | /** |
---|
| 582 | * prints the word "selected" if a variable is set, and optionally matches |
---|
| 583 | * the desired value, otherwise prints nothing, |
---|
[646] | 584 | * otherwise prints nothing, used for printing the word "checked" in a |
---|
| 585 | * select form input |
---|
[1] | 586 | * |
---|
| 587 | * @param mixed $var the variable to compare |
---|
| 588 | * @param mixed $value optional, what to compare with if a specific value is required. |
---|
| 589 | */ |
---|
| 590 | function frmSelected($var, $value=null) |
---|
| 591 | { |
---|
| 592 | if (func_num_args() == 1 && $var) { |
---|
| 593 | // 'selected' if var is true. |
---|
| 594 | echo ' selected="selected" '; |
---|
| 595 | } else if (func_num_args() == 2 && $var == $value) { |
---|
| 596 | // 'selected' if var and value match. |
---|
| 597 | echo ' selected="selected" '; |
---|
| 598 | } else if (func_num_args() == 2 && is_array($var)) { |
---|
| 599 | // 'selected' if the value is in the key or the value of an array. |
---|
| 600 | if (isset($var[$value])) { |
---|
| 601 | echo ' selected="selected" '; |
---|
| 602 | } else if (in_array($value, $var)) { |
---|
| 603 | echo ' selected="selected" '; |
---|
| 604 | } |
---|
| 605 | } |
---|
| 606 | } |
---|
| 607 | |
---|
| 608 | /** |
---|
| 609 | * Adds slashes to values of an array and converts the array to a |
---|
| 610 | * comma delimited list. If value provided is not an array or is empty |
---|
| 611 | * return nothing. This is useful for putting values coming in from |
---|
| 612 | * posted checkboxes into a SET column of a database. |
---|
| 613 | * |
---|
| 614 | * @param array $array Array to convert. |
---|
| 615 | * @return string Comma list of array values. |
---|
| 616 | */ |
---|
| 617 | function dbArrayToList($array) |
---|
| 618 | { |
---|
| 619 | if (is_array($array) && !empty($array)) { |
---|
[82] | 620 | return join(',', array_map('mysql_real_escape_string', array_keys($array))); |
---|
[1] | 621 | } |
---|
| 622 | } |
---|
| 623 | |
---|
| 624 | /** |
---|
| 625 | * Converts a human string date into a SQL-safe date. |
---|
| 626 | * Dates nearing infinity use the date 2038-01-01 so conversion to unix time |
---|
| 627 | * format remain within valid range. |
---|
| 628 | * |
---|
| 629 | * @param array $date String date to convert. |
---|
[646] | 630 | * @param array $format Date format to pass to date(). |
---|
[1] | 631 | * Default produces MySQL datetime: 0000-00-00 00:00:00. |
---|
| 632 | * |
---|
| 633 | * @return string SQL-safe date. |
---|
| 634 | */ |
---|
| 635 | function strToSQLDate($date, $format='Y-m-d H:i:s') |
---|
| 636 | { |
---|
| 637 | // Translate the human string date into SQL-safe date format. |
---|
| 638 | if (empty($date) || '0000-00-00' == $date || strtotime($date) === -1) { |
---|
| 639 | $sql_date = '0000-00-00'; |
---|
| 640 | } else { |
---|
| 641 | $sql_date = date($format, strtotime($date)); |
---|
| 642 | } |
---|
[646] | 643 | |
---|
[1] | 644 | return $sql_date; |
---|
| 645 | } |
---|
| 646 | |
---|
| 647 | /** |
---|
| 648 | * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an |
---|
[401] | 649 | * array, stripslashes is run on each value, recursively, and the stripped |
---|
[1] | 650 | * array is returned |
---|
| 651 | * |
---|
| 652 | * @param mixed $var The string or array to un-quote, if necessary. |
---|
| 653 | * @return mixed $var, minus any magic quotes. |
---|
| 654 | */ |
---|
| 655 | function dispelMagicQuotes($var) |
---|
| 656 | { |
---|
| 657 | static $magic_quotes_gpc; |
---|
[646] | 658 | |
---|
[1] | 659 | if (!isset($magic_quotes_gpc)) { |
---|
| 660 | $magic_quotes_gpc = get_magic_quotes_gpc(); |
---|
| 661 | } |
---|
[646] | 662 | |
---|
[1] | 663 | if ($magic_quotes_gpc) { |
---|
| 664 | if (!is_array($var)) { |
---|
| 665 | $var = stripslashes($var); |
---|
| 666 | } else { |
---|
| 667 | foreach ($var as $key=>$val) { |
---|
| 668 | if (is_array($val)) { |
---|
| 669 | $var[$key] = dispelMagicQuotes($val); |
---|
| 670 | } else { |
---|
| 671 | $var[$key] = stripslashes($val); |
---|
| 672 | } |
---|
| 673 | } |
---|
| 674 | } |
---|
| 675 | } |
---|
| 676 | return $var; |
---|
| 677 | } |
---|
| 678 | |
---|
| 679 | /** |
---|
| 680 | * Get a form variable from GET or POST data, stripped of magic |
---|
| 681 | * quotes if necessary. |
---|
| 682 | * |
---|
| 683 | * @param string $var (optional) The name of the form variable to look for. |
---|
| 684 | * @param string $default (optional) The value to return if the |
---|
| 685 | * variable is not there. |
---|
| 686 | * |
---|
| 687 | * @return mixed A cleaned GET or POST if no $var specified. |
---|
| 688 | * @return string A cleaned form $var if found, or $default. |
---|
| 689 | */ |
---|
| 690 | function getFormData($var=null, $default=null) |
---|
| 691 | { |
---|
| 692 | if ('POST' == $_SERVER['REQUEST_METHOD'] && is_null($var)) { |
---|
| 693 | return dispelMagicQuotes($_POST); |
---|
| 694 | } else if ('GET' == $_SERVER['REQUEST_METHOD'] && is_null($var)) { |
---|
| 695 | return dispelMagicQuotes($_GET); |
---|
| 696 | } |
---|
| 697 | if (isset($_POST[$var])) { |
---|
| 698 | return dispelMagicQuotes($_POST[$var]); |
---|
| 699 | } else if (isset($_GET[$var])) { |
---|
| 700 | return dispelMagicQuotes($_GET[$var]); |
---|
| 701 | } else { |
---|
| 702 | return $default; |
---|
| 703 | } |
---|
| 704 | } |
---|
| 705 | function getPost($var=null, $default=null) |
---|
| 706 | { |
---|
| 707 | if (is_null($var)) { |
---|
| 708 | return dispelMagicQuotes($_POST); |
---|
| 709 | } |
---|
| 710 | if (isset($_POST[$var])) { |
---|
| 711 | return dispelMagicQuotes($_POST[$var]); |
---|
| 712 | } else { |
---|
| 713 | return $default; |
---|
| 714 | } |
---|
| 715 | } |
---|
| 716 | function getGet($var=null, $default=null) |
---|
| 717 | { |
---|
| 718 | if (is_null($var)) { |
---|
| 719 | return dispelMagicQuotes($_GET); |
---|
| 720 | } |
---|
| 721 | if (isset($_GET[$var])) { |
---|
| 722 | return dispelMagicQuotes($_GET[$var]); |
---|
| 723 | } else { |
---|
| 724 | return $default; |
---|
| 725 | } |
---|
| 726 | } |
---|
| 727 | |
---|
[754] | 728 | /* |
---|
| 729 | * Generates a base-65-encoded sha512 hash of $string truncated to $length. |
---|
| 730 | * |
---|
| 731 | * @access public |
---|
| 732 | * @param string $string Input string to hash. |
---|
| 733 | * @param int $length Length of output hash string. |
---|
| 734 | * @return string String of hash. |
---|
| 735 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 736 | * @version 1.0 |
---|
| 737 | * @since 03 Apr 2016 19:48:49 |
---|
| 738 | */ |
---|
| 739 | function hash64($string, $length=18) |
---|
| 740 | { |
---|
[756] | 741 | return mb_substr(preg_replace('/[^\w]/', '', base64_encode(hash('sha512', $string, true))), 0, $length); |
---|
[754] | 742 | } |
---|
| 743 | |
---|
[1] | 744 | /** |
---|
| 745 | * Signs a value using md5 and a simple text key. In order for this |
---|
[756] | 746 | * function to be useful (i.e. secure) the salt must be kept secret, which |
---|
[1] | 747 | * means keeping it as safe as database credentials. Putting it into an |
---|
| 748 | * environment variable set in httpd.conf is a good place. |
---|
| 749 | * |
---|
| 750 | * @access public |
---|
| 751 | * @param string $val The string to sign. |
---|
[756] | 752 | * @param string $salt (Optional) A text key to use for computing the signature. |
---|
| 753 | * @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] | 754 | * @return string The original value with a signature appended. |
---|
| 755 | */ |
---|
[756] | 756 | function addSignature($val, $salt=null, $length=18) |
---|
[1] | 757 | { |
---|
[756] | 758 | if ('' == trim($val)) { |
---|
| 759 | logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__); |
---|
| 760 | return ''; |
---|
[1] | 761 | } |
---|
[646] | 762 | |
---|
[756] | 763 | if (!isset($salt)) { |
---|
| 764 | global $CFG; |
---|
| 765 | $salt = $CFG->signing_key; |
---|
[1] | 766 | } |
---|
| 767 | |
---|
[756] | 768 | return $val . '-' . mb_substr(preg_replace('/[^\w]/', '', base64_encode(hash('sha512', $val . $salt, true))), 0, $length); |
---|
[1] | 769 | } |
---|
| 770 | |
---|
| 771 | /** |
---|
| 772 | * Strips off the signature appended by addSignature(). |
---|
| 773 | * |
---|
| 774 | * @access public |
---|
| 775 | * @param string $signed_val The string to sign. |
---|
| 776 | * @return string The original value with a signature removed. |
---|
| 777 | */ |
---|
| 778 | function removeSignature($signed_val) |
---|
| 779 | { |
---|
[756] | 780 | if (empty($signed_val) || mb_strpos($signed_val, '-') === false) { |
---|
| 781 | return ''; |
---|
| 782 | } |
---|
| 783 | return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-')); |
---|
[1] | 784 | } |
---|
| 785 | |
---|
| 786 | /** |
---|
[756] | 787 | * Verifies a signature appended to a value by addSignature(). |
---|
[1] | 788 | * |
---|
| 789 | * @access public |
---|
| 790 | * @param string $signed_val A value with appended signature. |
---|
[756] | 791 | * @param string $salt (Optional) A text key to use for computing the signature. |
---|
| 792 | * @param string $length (Optional) The length of the added signature. |
---|
[1] | 793 | * @return bool True if the signature matches the var. |
---|
| 794 | */ |
---|
[756] | 795 | function verifySignature($signed_val, $salt=null, $length=18) |
---|
[1] | 796 | { |
---|
| 797 | // Strip the value from the signed value. |
---|
[756] | 798 | $val = removeSignature($signed_val); |
---|
[1] | 799 | // If the signed value matches the original signed value we consider the value safe. |
---|
[756] | 800 | if ('' != $signed_val && $signed_val == addSignature($val, $salt, $length)) { |
---|
[1] | 801 | // Signature verified. |
---|
[756] | 802 | return true; |
---|
[1] | 803 | } else { |
---|
[756] | 804 | logMsg(sprintf('Failed signature (%s should be %s)', $signed_val, addSignature($val, $salt, $length)), LOG_DEBUG, __FILE__, __LINE__); |
---|
[1] | 805 | return false; |
---|
| 806 | } |
---|
| 807 | } |
---|
| 808 | |
---|
| 809 | /** |
---|
| 810 | * Sends empty output to the browser and flushes the php buffer so the client |
---|
[646] | 811 | * will see data before the page is finished processing. |
---|
[1] | 812 | */ |
---|
| 813 | function flushBuffer() { |
---|
| 814 | echo str_repeat(' ', 205); |
---|
| 815 | flush(); |
---|
| 816 | } |
---|
| 817 | |
---|
| 818 | /** |
---|
[749] | 819 | * A stub for apps that still use this function. |
---|
[1] | 820 | * |
---|
| 821 | * @access public |
---|
[749] | 822 | * @return void |
---|
[1] | 823 | */ |
---|
| 824 | function mailmanAddMember($email, $list, $send_welcome_message=false) |
---|
| 825 | { |
---|
[749] | 826 | logMsg(sprintf('mailmanAddMember called and ignored: %s, %s, %s', $email, $list, $send_welcome_message), LOG_WARNING, __FILE__, __LINE__); |
---|
[1] | 827 | } |
---|
| 828 | |
---|
| 829 | /** |
---|
[749] | 830 | * A stub for apps that still use this function. |
---|
[1] | 831 | * |
---|
| 832 | * @access public |
---|
[749] | 833 | * @return void |
---|
[1] | 834 | */ |
---|
| 835 | function mailmanRemoveMember($email, $list, $send_user_ack=false) |
---|
| 836 | { |
---|
[749] | 837 | logMsg(sprintf('mailmanRemoveMember called and ignored: %s, %s, %s', $email, $list, $send_user_ack), LOG_WARNING, __FILE__, __LINE__); |
---|
[1] | 838 | } |
---|
| 839 | |
---|