0
|
1 <?php
|
|
2
|
|
3 /**
|
|
4 +-----------------------------------------------------------------------+
|
|
5 | This file is part of the Roundcube Webmail client |
|
|
6 | Copyright (C) 2008-2012, The Roundcube Dev Team |
|
|
7 | Copyright (C) 2011-2012, Kolab Systems AG |
|
|
8 | |
|
|
9 | Licensed under the GNU General Public License version 3 or |
|
|
10 | any later version with exceptions for skins & plugins. |
|
|
11 | See the README file for a full license statement. |
|
|
12 | |
|
|
13 | PURPOSE: |
|
|
14 | Utility class providing common functions |
|
|
15 +-----------------------------------------------------------------------+
|
|
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
|
|
17 | Author: Aleksander Machniak <alec@alec.pl> |
|
|
18 +-----------------------------------------------------------------------+
|
|
19 */
|
|
20
|
|
21 /**
|
|
22 * Utility class providing common functions
|
|
23 *
|
|
24 * @package Framework
|
|
25 * @subpackage Utils
|
|
26 */
|
|
27 class rcube_utils
|
|
28 {
|
|
29 // define constants for input reading
|
|
30 const INPUT_GET = 1;
|
|
31 const INPUT_POST = 2;
|
|
32 const INPUT_COOKIE = 4;
|
|
33 const INPUT_GP = 3; // GET + POST
|
|
34 const INPUT_GPC = 7; // GET + POST + COOKIE
|
|
35
|
|
36
|
|
37 /**
|
|
38 * Helper method to set a cookie with the current path and host settings
|
|
39 *
|
|
40 * @param string Cookie name
|
|
41 * @param string Cookie value
|
|
42 * @param string Expiration time
|
|
43 */
|
|
44 public static function setcookie($name, $value, $exp = 0)
|
|
45 {
|
|
46 if (headers_sent()) {
|
|
47 return;
|
|
48 }
|
|
49
|
|
50 $cookie = session_get_cookie_params();
|
|
51 $secure = $cookie['secure'] || self::https_check();
|
|
52
|
|
53 setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'], $secure, true);
|
|
54 }
|
|
55
|
|
56 /**
|
|
57 * E-mail address validation.
|
|
58 *
|
|
59 * @param string $email Email address
|
|
60 * @param boolean $dns_check True to check dns
|
|
61 *
|
|
62 * @return boolean True on success, False if address is invalid
|
|
63 */
|
|
64 public static function check_email($email, $dns_check=true)
|
|
65 {
|
|
66 // Check for invalid characters
|
|
67 if (preg_match('/[\x00-\x1F\x7F-\xFF]/', $email)) {
|
|
68 return false;
|
|
69 }
|
|
70
|
|
71 // Check for length limit specified by RFC 5321 (#1486453)
|
|
72 if (strlen($email) > 254) {
|
|
73 return false;
|
|
74 }
|
|
75
|
|
76 $email_array = explode('@', $email);
|
|
77
|
|
78 // Check that there's one @ symbol
|
|
79 if (count($email_array) < 2) {
|
|
80 return false;
|
|
81 }
|
|
82
|
|
83 $domain_part = array_pop($email_array);
|
|
84 $local_part = implode('@', $email_array);
|
|
85
|
|
86 // from PEAR::Validate
|
|
87 $regexp = '&^(?:
|
|
88 ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")| #1 quoted name
|
|
89 ([-\w!\#\$%\&\'*+~/^`|{}=]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}=]+)*)) #2 OR dot-atom (RFC5322)
|
|
90 $&xi';
|
|
91
|
|
92 if (!preg_match($regexp, $local_part)) {
|
|
93 return false;
|
|
94 }
|
|
95
|
|
96 // Validate domain part
|
|
97 if (preg_match('/^\[((IPv6:[0-9a-f:.]+)|([0-9.]+))\]$/i', $domain_part, $matches)) {
|
|
98 return self::check_ip(preg_replace('/^IPv6:/i', '', $matches[1])); // valid IPv4 or IPv6 address
|
|
99 }
|
|
100 else {
|
|
101 // If not an IP address
|
|
102 $domain_array = explode('.', $domain_part);
|
|
103 // Not enough parts to be a valid domain
|
|
104 if (count($domain_array) < 2) {
|
|
105 return false;
|
|
106 }
|
|
107
|
|
108 foreach ($domain_array as $part) {
|
|
109 if (!preg_match('/^((xn--)?([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/', $part)) {
|
|
110 return false;
|
|
111 }
|
|
112 }
|
|
113
|
|
114 // last domain part
|
|
115 $last_part = array_pop($domain_array);
|
|
116 if (strpos($last_part, 'xn--') !== 0 && preg_match('/[^a-zA-Z]/', $last_part)) {
|
|
117 return false;
|
|
118 }
|
|
119
|
|
120 $rcube = rcube::get_instance();
|
|
121
|
|
122 if (!$dns_check || !$rcube->config->get('email_dns_check')) {
|
|
123 return true;
|
|
124 }
|
|
125
|
|
126 // find MX record(s)
|
|
127 if (!function_exists('getmxrr') || getmxrr($domain_part, $mx_records)) {
|
|
128 return true;
|
|
129 }
|
|
130
|
|
131 // find any DNS record
|
|
132 if (!function_exists('checkdnsrr') || checkdnsrr($domain_part, 'ANY')) {
|
|
133 return true;
|
|
134 }
|
|
135 }
|
|
136
|
|
137 return false;
|
|
138 }
|
|
139
|
|
140 /**
|
|
141 * Validates IPv4 or IPv6 address
|
|
142 *
|
|
143 * @param string $ip IP address in v4 or v6 format
|
|
144 *
|
|
145 * @return bool True if the address is valid
|
|
146 */
|
|
147 public static function check_ip($ip)
|
|
148 {
|
|
149 return filter_var($ip, FILTER_VALIDATE_IP) !== false;
|
|
150 }
|
|
151
|
|
152 /**
|
|
153 * Check whether the HTTP referer matches the current request
|
|
154 *
|
|
155 * @return boolean True if referer is the same host+path, false if not
|
|
156 */
|
|
157 public static function check_referer()
|
|
158 {
|
|
159 $uri = parse_url($_SERVER['REQUEST_URI']);
|
|
160 $referer = parse_url(self::request_header('Referer'));
|
|
161
|
|
162 return $referer['host'] == self::request_header('Host') && $referer['path'] == $uri['path'];
|
|
163 }
|
|
164
|
|
165 /**
|
|
166 * Replacing specials characters to a specific encoding type
|
|
167 *
|
|
168 * @param string Input string
|
|
169 * @param string Encoding type: text|html|xml|js|url
|
|
170 * @param string Replace mode for tags: show|remove|strict
|
|
171 * @param boolean Convert newlines
|
|
172 *
|
|
173 * @return string The quoted string
|
|
174 */
|
|
175 public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
|
|
176 {
|
|
177 static $html_encode_arr = false;
|
|
178 static $js_rep_table = false;
|
|
179 static $xml_rep_table = false;
|
|
180
|
|
181 if (!is_string($str)) {
|
|
182 $str = strval($str);
|
|
183 }
|
|
184
|
|
185 // encode for HTML output
|
|
186 if ($enctype == 'html') {
|
|
187 if (!$html_encode_arr) {
|
|
188 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
|
|
189 unset($html_encode_arr['?']);
|
|
190 }
|
|
191
|
|
192 $encode_arr = $html_encode_arr;
|
|
193
|
|
194 if ($mode == 'remove') {
|
|
195 $str = strip_tags($str);
|
|
196 }
|
|
197 else if ($mode != 'strict') {
|
|
198 // don't replace quotes and html tags
|
|
199 $ltpos = strpos($str, '<');
|
|
200 if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
|
|
201 unset($encode_arr['"']);
|
|
202 unset($encode_arr['<']);
|
|
203 unset($encode_arr['>']);
|
|
204 unset($encode_arr['&']);
|
|
205 }
|
|
206 }
|
|
207
|
|
208 $out = strtr($str, $encode_arr);
|
|
209
|
|
210 return $newlines ? nl2br($out) : $out;
|
|
211 }
|
|
212
|
|
213 // if the replace tables for XML and JS are not yet defined
|
|
214 if ($js_rep_table === false) {
|
|
215 $js_rep_table = $xml_rep_table = array();
|
|
216 $xml_rep_table['&'] = '&';
|
|
217
|
|
218 // can be increased to support more charsets
|
|
219 for ($c=160; $c<256; $c++) {
|
|
220 $xml_rep_table[chr($c)] = "&#$c;";
|
|
221 }
|
|
222
|
|
223 $xml_rep_table['"'] = '"';
|
|
224 $js_rep_table['"'] = '\\"';
|
|
225 $js_rep_table["'"] = "\\'";
|
|
226 $js_rep_table["\\"] = "\\\\";
|
|
227 // Unicode line and paragraph separators (#1486310)
|
|
228 $js_rep_table[chr(hexdec('E2')).chr(hexdec('80')).chr(hexdec('A8'))] = '
';
|
|
229 $js_rep_table[chr(hexdec('E2')).chr(hexdec('80')).chr(hexdec('A9'))] = '
';
|
|
230 }
|
|
231
|
|
232 // encode for javascript use
|
|
233 if ($enctype == 'js') {
|
|
234 return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
|
|
235 }
|
|
236
|
|
237 // encode for plaintext
|
|
238 if ($enctype == 'text') {
|
|
239 return str_replace("\r\n", "\n", $mode == 'remove' ? strip_tags($str) : $str);
|
|
240 }
|
|
241
|
|
242 if ($enctype == 'url') {
|
|
243 return rawurlencode($str);
|
|
244 }
|
|
245
|
|
246 // encode for XML
|
|
247 if ($enctype == 'xml') {
|
|
248 return strtr($str, $xml_rep_table);
|
|
249 }
|
|
250
|
|
251 // no encoding given -> return original string
|
|
252 return $str;
|
|
253 }
|
|
254
|
|
255 /**
|
|
256 * Read input value and convert it for internal use
|
|
257 * Performs stripslashes() and charset conversion if necessary
|
|
258 *
|
|
259 * @param string Field name to read
|
|
260 * @param int Source to get value from (see self::INPUT_*)
|
|
261 * @param boolean Allow HTML tags in field value
|
|
262 * @param string Charset to convert into
|
|
263 *
|
|
264 * @return string Field value or NULL if not available
|
|
265 */
|
|
266 public static function get_input_value($fname, $source, $allow_html = false, $charset = null)
|
|
267 {
|
|
268 $value = null;
|
|
269
|
|
270 if (($source & self::INPUT_GET) && isset($_GET[$fname])) {
|
|
271 $value = $_GET[$fname];
|
|
272 }
|
|
273
|
|
274 if (($source & self::INPUT_POST) && isset($_POST[$fname])) {
|
|
275 $value = $_POST[$fname];
|
|
276 }
|
|
277
|
|
278 if (($source & self::INPUT_COOKIE) && isset($_COOKIE[$fname])) {
|
|
279 $value = $_COOKIE[$fname];
|
|
280 }
|
|
281
|
|
282 return self::parse_input_value($value, $allow_html, $charset);
|
|
283 }
|
|
284
|
|
285 /**
|
|
286 * Parse/validate input value. See self::get_input_value()
|
|
287 * Performs stripslashes() and charset conversion if necessary
|
|
288 *
|
|
289 * @param string Input value
|
|
290 * @param boolean Allow HTML tags in field value
|
|
291 * @param string Charset to convert into
|
|
292 *
|
|
293 * @return string Parsed value
|
|
294 */
|
|
295 public static function parse_input_value($value, $allow_html = false, $charset = null)
|
|
296 {
|
|
297 global $OUTPUT;
|
|
298
|
|
299 if (empty($value)) {
|
|
300 return $value;
|
|
301 }
|
|
302
|
|
303 if (is_array($value)) {
|
|
304 foreach ($value as $idx => $val) {
|
|
305 $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
|
|
306 }
|
|
307 return $value;
|
|
308 }
|
|
309
|
|
310 // remove HTML tags if not allowed
|
|
311 if (!$allow_html) {
|
|
312 $value = strip_tags($value);
|
|
313 }
|
|
314
|
|
315 $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
|
|
316
|
|
317 // remove invalid characters (#1488124)
|
|
318 if ($output_charset == 'UTF-8') {
|
|
319 $value = rcube_charset::clean($value);
|
|
320 }
|
|
321
|
|
322 // convert to internal charset
|
|
323 if ($charset && $output_charset) {
|
|
324 $value = rcube_charset::convert($value, $output_charset, $charset);
|
|
325 }
|
|
326
|
|
327 return $value;
|
|
328 }
|
|
329
|
|
330 /**
|
|
331 * Convert array of request parameters (prefixed with _)
|
|
332 * to a regular array with non-prefixed keys.
|
|
333 *
|
|
334 * @param int $mode Source to get value from (GPC)
|
|
335 * @param string $ignore PCRE expression to skip parameters by name
|
|
336 * @param boolean $allow_html Allow HTML tags in field value
|
|
337 *
|
|
338 * @return array Hash array with all request parameters
|
|
339 */
|
|
340 public static function request2param($mode = null, $ignore = 'task|action', $allow_html = false)
|
|
341 {
|
|
342 $out = array();
|
|
343 $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
|
|
344
|
|
345 foreach (array_keys($src) as $key) {
|
|
346 $fname = $key[0] == '_' ? substr($key, 1) : $key;
|
|
347 if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
|
|
348 $out[$fname] = self::get_input_value($key, $mode, $allow_html);
|
|
349 }
|
|
350 }
|
|
351
|
|
352 return $out;
|
|
353 }
|
|
354
|
|
355 /**
|
|
356 * Convert the given string into a valid HTML identifier
|
|
357 * Same functionality as done in app.js with rcube_webmail.html_identifier()
|
|
358 */
|
|
359 public static function html_identifier($str, $encode=false)
|
|
360 {
|
|
361 if ($encode) {
|
|
362 return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
|
|
363 }
|
|
364 else {
|
|
365 return asciiwords($str, true, '_');
|
|
366 }
|
|
367 }
|
|
368
|
|
369 /**
|
|
370 * Replace all css definitions with #container [def]
|
|
371 * and remove css-inlined scripting, make position style safe
|
|
372 *
|
|
373 * @param string CSS source code
|
|
374 * @param string Container ID to use as prefix
|
|
375 * @param bool Allow remote content
|
|
376 *
|
|
377 * @return string Modified CSS source
|
|
378 */
|
|
379 public static function mod_css_styles($source, $container_id, $allow_remote = false)
|
|
380 {
|
|
381 $last_pos = 0;
|
|
382 $replacements = new rcube_string_replacer;
|
|
383
|
|
384 // ignore the whole block if evil styles are detected
|
|
385 $source = self::xss_entity_decode($source);
|
|
386 $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
|
|
387 $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\((?!data:image)' : '');
|
|
388
|
|
389 if (preg_match("/$evilexpr/i", $stripped)) {
|
|
390 return '/* evil! */';
|
|
391 }
|
|
392
|
|
393 $strict_url_regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
|
|
394
|
|
395 // cut out all contents between { and }
|
|
396 while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
|
|
397 $nested = strpos($source, '{', $pos+1);
|
|
398 if ($nested && $nested < $pos2) // when dealing with nested blocks (e.g. @media), take the inner one
|
|
399 $pos = $nested;
|
|
400 $length = $pos2 - $pos - 1;
|
|
401 $styles = substr($source, $pos+1, $length);
|
|
402
|
|
403 // Convert position:fixed to position:absolute (#5264)
|
|
404 $styles = preg_replace('/position:[\s\r\n]*fixed/i', 'position: absolute', $styles);
|
|
405
|
|
406 // check every line of a style block...
|
|
407 if ($allow_remote) {
|
|
408 $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
|
|
409
|
|
410 for ($i=0, $len=count($a_styles); $i < $len; $i++) {
|
|
411 $line = $a_styles[$i];
|
|
412 $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
|
|
413
|
|
414 // allow data:image uri, join with continuation
|
|
415 if (stripos($stripped, 'url(data:image')) {
|
|
416 $a_styles[$i] .= ';' . $a_styles[$i+1];
|
|
417 unset($a_styles[$i+1]);
|
|
418 }
|
|
419 // allow strict url() values only
|
|
420 else if (stripos($stripped, 'url(') && !preg_match($strict_url_regexp, $line)) {
|
|
421 $a_styles = array('/* evil! */');
|
|
422 break;
|
|
423 }
|
|
424 }
|
|
425
|
|
426 $styles = join(";\n", $a_styles);
|
|
427 }
|
|
428
|
|
429 $key = $replacements->add($styles);
|
|
430 $repl = $replacements->get_replacement($key);
|
|
431 $source = substr_replace($source, $repl, $pos+1, $length);
|
|
432 $last_pos = $pos2 - ($length - strlen($repl));
|
|
433 }
|
|
434
|
|
435 // remove html comments and add #container to each tag selector.
|
|
436 // also replace body definition because we also stripped off the <body> tag
|
|
437 $source = preg_replace(
|
|
438 array(
|
|
439 '/(^\s*<\!--)|(-->\s*$)/m',
|
|
440 // (?!##str) below is to not match with ##str_replacement_0##
|
|
441 // from rcube_string_replacer used above, this is needed for
|
|
442 // cases like @media { body { position: fixed; } } (#5811)
|
|
443 '/(^\s*|,\s*|\}\s*|\{\s*)((?!##str)[a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
|
|
444 '/'.preg_quote($container_id, '/').'\s+body/i',
|
|
445 ),
|
|
446 array(
|
|
447 '',
|
|
448 "\\1#$container_id \\2",
|
|
449 $container_id,
|
|
450 ),
|
|
451 $source);
|
|
452
|
|
453 // put block contents back in
|
|
454 $source = $replacements->resolve($source);
|
|
455
|
|
456 return $source;
|
|
457 }
|
|
458
|
|
459 /**
|
|
460 * Generate CSS classes from mimetype and filename extension
|
|
461 *
|
|
462 * @param string $mimetype Mimetype
|
|
463 * @param string $filename Filename
|
|
464 *
|
|
465 * @return string CSS classes separated by space
|
|
466 */
|
|
467 public static function file2class($mimetype, $filename)
|
|
468 {
|
|
469 $mimetype = strtolower($mimetype);
|
|
470 $filename = strtolower($filename);
|
|
471
|
|
472 list($primary, $secondary) = explode('/', $mimetype);
|
|
473
|
|
474 $classes = array($primary ?: 'unknown');
|
|
475
|
|
476 if ($secondary) {
|
|
477 $classes[] = $secondary;
|
|
478 }
|
|
479
|
|
480 if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
|
|
481 if (!in_array($m[1], $classes)) {
|
|
482 $classes[] = $m[1];
|
|
483 }
|
|
484 }
|
|
485
|
|
486 return join(" ", $classes);
|
|
487 }
|
|
488
|
|
489 /**
|
|
490 * Decode escaped entities used by known XSS exploits.
|
|
491 * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
|
|
492 *
|
|
493 * @param string CSS content to decode
|
|
494 *
|
|
495 * @return string Decoded string
|
|
496 */
|
|
497 public static function xss_entity_decode($content)
|
|
498 {
|
|
499 $callback = function($matches) { return chr(hexdec($matches[1])); };
|
|
500
|
|
501 $out = html_entity_decode(html_entity_decode($content));
|
|
502 $out = trim(preg_replace('/(^<!--|-->$)/', '', trim($out)));
|
|
503 $out = preg_replace_callback('/\\\([0-9a-f]{4})/i', $callback, $out);
|
|
504 $out = preg_replace('#/\*.*\*/#Ums', '', $out);
|
|
505 $out = strip_tags($out);
|
|
506
|
|
507 return $out;
|
|
508 }
|
|
509
|
|
510 /**
|
|
511 * Check if we can process not exceeding memory_limit
|
|
512 *
|
|
513 * @param integer Required amount of memory
|
|
514 *
|
|
515 * @return boolean True if memory won't be exceeded, False otherwise
|
|
516 */
|
|
517 public static function mem_check($need)
|
|
518 {
|
|
519 $mem_limit = parse_bytes(ini_get('memory_limit'));
|
|
520 $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
|
|
521
|
|
522 return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
|
|
523 }
|
|
524
|
|
525 /**
|
|
526 * Check if working in SSL mode
|
|
527 *
|
|
528 * @param integer $port HTTPS port number
|
|
529 * @param boolean $use_https Enables 'use_https' option checking
|
|
530 *
|
|
531 * @return boolean
|
|
532 */
|
|
533 public static function https_check($port=null, $use_https=true)
|
|
534 {
|
|
535 if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
|
|
536 return true;
|
|
537 }
|
|
538 if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
|
|
539 && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
|
|
540 && in_array($_SERVER['REMOTE_ADDR'], rcube::get_instance()->config->get('proxy_whitelist', array()))
|
|
541 ) {
|
|
542 return true;
|
|
543 }
|
|
544 if ($port && $_SERVER['SERVER_PORT'] == $port) {
|
|
545 return true;
|
|
546 }
|
|
547 if ($use_https && rcube::get_instance()->config->get('use_https')) {
|
|
548 return true;
|
|
549 }
|
|
550
|
|
551 return false;
|
|
552 }
|
|
553
|
|
554 /**
|
|
555 * Replaces hostname variables.
|
|
556 *
|
|
557 * @param string $name Hostname
|
|
558 * @param string $host Optional IMAP hostname
|
|
559 *
|
|
560 * @return string Hostname
|
|
561 */
|
|
562 public static function parse_host($name, $host = '')
|
|
563 {
|
|
564 if (!is_string($name)) {
|
|
565 return $name;
|
|
566 }
|
|
567
|
|
568 // %n - host
|
|
569 $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
|
|
570 // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
|
|
571 $t = preg_replace('/^[^\.]+\./', '', $n);
|
|
572 // %d - domain name without first part
|
|
573 $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
|
|
574 // %h - IMAP host
|
|
575 $h = $_SESSION['storage_host'] ?: $host;
|
|
576 // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
|
|
577 $z = preg_replace('/^[^\.]+\./', '', $h);
|
|
578 // %s - domain name after the '@' from e-mail address provided at login screen.
|
|
579 // Returns FALSE if an invalid email is provided
|
|
580 if (strpos($name, '%s') !== false) {
|
|
581 $user_email = self::get_input_value('_user', self::INPUT_POST);
|
|
582 $user_email = self::idn_convert($user_email, true);
|
|
583 $matches = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
|
|
584 if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
|
|
585 return false;
|
|
586 }
|
|
587 }
|
|
588
|
|
589 return str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
|
|
590 }
|
|
591
|
|
592 /**
|
|
593 * Returns remote IP address and forwarded addresses if found
|
|
594 *
|
|
595 * @return string Remote IP address(es)
|
|
596 */
|
|
597 public static function remote_ip()
|
|
598 {
|
|
599 $address = $_SERVER['REMOTE_ADDR'];
|
|
600
|
|
601 // append the NGINX X-Real-IP header, if set
|
|
602 if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
|
|
603 $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
|
|
604 }
|
|
605
|
|
606 // append the X-Forwarded-For header, if set
|
|
607 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
|
|
608 $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
|
|
609 }
|
|
610
|
|
611 if (!empty($remote_ip)) {
|
|
612 $address .= '(' . implode(',', $remote_ip) . ')';
|
|
613 }
|
|
614
|
|
615 return $address;
|
|
616 }
|
|
617
|
|
618 /**
|
|
619 * Returns the real remote IP address
|
|
620 *
|
|
621 * @return string Remote IP address
|
|
622 */
|
|
623 public static function remote_addr()
|
|
624 {
|
|
625 // Check if any of the headers are set first to improve performance
|
|
626 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_X_REAL_IP'])) {
|
|
627 $proxy_whitelist = rcube::get_instance()->config->get('proxy_whitelist', array());
|
|
628 if (in_array($_SERVER['REMOTE_ADDR'], $proxy_whitelist)) {
|
|
629 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
|
|
630 foreach (array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $forwarded_ip) {
|
|
631 if (!in_array($forwarded_ip, $proxy_whitelist)) {
|
|
632 return $forwarded_ip;
|
|
633 }
|
|
634 }
|
|
635 }
|
|
636
|
|
637 if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
|
|
638 return $_SERVER['HTTP_X_REAL_IP'];
|
|
639 }
|
|
640 }
|
|
641 }
|
|
642
|
|
643 if (!empty($_SERVER['REMOTE_ADDR'])) {
|
|
644 return $_SERVER['REMOTE_ADDR'];
|
|
645 }
|
|
646
|
|
647 return '';
|
|
648 }
|
|
649
|
|
650 /**
|
|
651 * Read a specific HTTP request header.
|
|
652 *
|
|
653 * @param string $name Header name
|
|
654 *
|
|
655 * @return mixed Header value or null if not available
|
|
656 */
|
|
657 public static function request_header($name)
|
|
658 {
|
|
659 if (function_exists('getallheaders')) {
|
|
660 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
|
|
661 $key = strtoupper($name);
|
|
662 }
|
|
663 else {
|
|
664 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
|
|
665 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
|
|
666 }
|
|
667
|
|
668 return $hdrs[$key];
|
|
669 }
|
|
670
|
|
671 /**
|
|
672 * Explode quoted string
|
|
673 *
|
|
674 * @param string Delimiter expression string for preg_match()
|
|
675 * @param string Input string
|
|
676 *
|
|
677 * @return array String items
|
|
678 */
|
|
679 public static function explode_quoted_string($delimiter, $string)
|
|
680 {
|
|
681 $result = array();
|
|
682 $strlen = strlen($string);
|
|
683
|
|
684 for ($q=$p=$i=0; $i < $strlen; $i++) {
|
|
685 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
|
|
686 $q = $q ? false : true;
|
|
687 }
|
|
688 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
|
|
689 $result[] = substr($string, $p, $i - $p);
|
|
690 $p = $i + 1;
|
|
691 }
|
|
692 }
|
|
693
|
|
694 $result[] = (string) substr($string, $p);
|
|
695
|
|
696 return $result;
|
|
697 }
|
|
698
|
|
699 /**
|
|
700 * Improved equivalent to strtotime()
|
|
701 *
|
|
702 * @param string $date Date string
|
|
703 * @param DateTimeZone $timezone Timezone to use for DateTime object
|
|
704 *
|
|
705 * @return int Unix timestamp
|
|
706 */
|
|
707 public static function strtotime($date, $timezone = null)
|
|
708 {
|
|
709 $date = self::clean_datestr($date);
|
|
710 $tzname = $timezone ? ' ' . $timezone->getName() : '';
|
|
711
|
|
712 // unix timestamp
|
|
713 if (is_numeric($date)) {
|
|
714 return (int) $date;
|
|
715 }
|
|
716
|
|
717 // if date parsing fails, we have a date in non-rfc format.
|
|
718 // remove token from the end and try again
|
|
719 while ((($ts = @strtotime($date . $tzname)) === false) || ($ts < 0)) {
|
|
720 $d = explode(' ', $date);
|
|
721 array_pop($d);
|
|
722 if (!$d) {
|
|
723 break;
|
|
724 }
|
|
725 $date = implode(' ', $d);
|
|
726 }
|
|
727
|
|
728 return (int) $ts;
|
|
729 }
|
|
730
|
|
731 /**
|
|
732 * Date parsing function that turns the given value into a DateTime object
|
|
733 *
|
|
734 * @param string $date Date string
|
|
735 * @param DateTimeZone $timezone Timezone to use for DateTime object
|
|
736 *
|
|
737 * @return DateTime instance or false on failure
|
|
738 */
|
|
739 public static function anytodatetime($date, $timezone = null)
|
|
740 {
|
|
741 if ($date instanceof DateTime) {
|
|
742 return $date;
|
|
743 }
|
|
744
|
|
745 $dt = false;
|
|
746 $date = self::clean_datestr($date);
|
|
747
|
|
748 // try to parse string with DateTime first
|
|
749 if (!empty($date)) {
|
|
750 try {
|
|
751 $dt = $timezone ? new DateTime($date, $timezone) : new DateTime($date);
|
|
752 }
|
|
753 catch (Exception $e) {
|
|
754 // ignore
|
|
755 }
|
|
756 }
|
|
757
|
|
758 // try our advanced strtotime() method
|
|
759 if (!$dt && ($timestamp = self::strtotime($date, $timezone))) {
|
|
760 try {
|
|
761 $dt = new DateTime("@".$timestamp);
|
|
762 if ($timezone) {
|
|
763 $dt->setTimezone($timezone);
|
|
764 }
|
|
765 }
|
|
766 catch (Exception $e) {
|
|
767 // ignore
|
|
768 }
|
|
769 }
|
|
770
|
|
771 return $dt;
|
|
772 }
|
|
773
|
|
774 /**
|
|
775 * Clean up date string for strtotime() input
|
|
776 *
|
|
777 * @param string $date Date string
|
|
778 *
|
|
779 * @return string Date string
|
|
780 */
|
|
781 public static function clean_datestr($date)
|
|
782 {
|
|
783 $date = trim($date);
|
|
784
|
|
785 // check for MS Outlook vCard date format YYYYMMDD
|
|
786 if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
|
|
787 return sprintf('%04d-%02d-%02d 00:00:00', intval($m[1]), intval($m[2]), intval($m[3]));
|
|
788 }
|
|
789
|
|
790 // Clean malformed data
|
|
791 $date = preg_replace(
|
|
792 array(
|
|
793 '/GMT\s*([+-][0-9]+)/', // support non-standard "GMTXXXX" literal
|
|
794 '/[^a-z0-9\x20\x09:+-\/]/i', // remove any invalid characters
|
|
795 '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i', // remove weekday names
|
|
796 ),
|
|
797 array(
|
|
798 '\\1',
|
|
799 '',
|
|
800 '',
|
|
801 ), $date);
|
|
802
|
|
803 $date = trim($date);
|
|
804
|
|
805 // try to fix dd/mm vs. mm/dd discrepancy, we can't do more here
|
|
806 if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})(\s.*)?$/', $date, $m)) {
|
|
807 $mdy = $m[2] > 12 && $m[1] <= 12;
|
|
808 $day = $mdy ? $m[2] : $m[1];
|
|
809 $month = $mdy ? $m[1] : $m[2];
|
|
810 $date = sprintf('%04d-%02d-%02d%s', $m[3], $month, $day, $m[4] ?: ' 00:00:00');
|
|
811 }
|
|
812 // I've found that YYYY.MM.DD is recognized wrong, so here's a fix
|
|
813 else if (preg_match('/^(\d{4})\.(\d{1,2})\.(\d{1,2})(\s.*)?$/', $date, $m)) {
|
|
814 $date = sprintf('%04d-%02d-%02d%s', $m[1], $m[2], $m[3], $m[4] ?: ' 00:00:00');
|
|
815 }
|
|
816
|
|
817 return $date;
|
|
818 }
|
|
819
|
|
820 /**
|
|
821 * Turns the given date-only string in defined format into YYYY-MM-DD format.
|
|
822 *
|
|
823 * Supported formats: 'Y/m/d', 'Y.m.d', 'd-m-Y', 'd/m/Y', 'd.m.Y', 'j.n.Y'
|
|
824 *
|
|
825 * @param string $date Date string
|
|
826 * @param string $format Input date format
|
|
827 *
|
|
828 * @return strin Date string in YYYY-MM-DD format, or the original string
|
|
829 * if format is not supported
|
|
830 */
|
|
831 public static function format_datestr($date, $format)
|
|
832 {
|
|
833 $format_items = preg_split('/[.-\/\\\\]/', $format);
|
|
834 $date_items = preg_split('/[.-\/\\\\]/', $date);
|
|
835 $iso_format = '%04d-%02d-%02d';
|
|
836
|
|
837 if (count($format_items) == 3 && count($date_items) == 3) {
|
|
838 if ($format_items[0] == 'Y') {
|
|
839 $date = sprintf($iso_format, $date_items[0], $date_items[1], $date_items[2]);
|
|
840 }
|
|
841 else if (strpos('dj', $format_items[0]) !== false) {
|
|
842 $date = sprintf($iso_format, $date_items[2], $date_items[1], $date_items[0]);
|
|
843 }
|
|
844 else if (strpos('mn', $format_items[0]) !== false) {
|
|
845 $date = sprintf($iso_format, $date_items[2], $date_items[0], $date_items[1]);
|
|
846 }
|
|
847 }
|
|
848
|
|
849 return $date;
|
|
850 }
|
|
851
|
|
852 /*
|
|
853 * Idn_to_ascii wrapper.
|
|
854 * Intl/Idn modules version of this function doesn't work with e-mail address
|
|
855 */
|
|
856 public static function idn_to_ascii($str)
|
|
857 {
|
|
858 return self::idn_convert($str, true);
|
|
859 }
|
|
860
|
|
861 /*
|
|
862 * Idn_to_ascii wrapper.
|
|
863 * Intl/Idn modules version of this function doesn't work with e-mail address
|
|
864 */
|
|
865 public static function idn_to_utf8($str)
|
|
866 {
|
|
867 return self::idn_convert($str, false);
|
|
868 }
|
|
869
|
|
870 public static function idn_convert($input, $is_utf = false)
|
|
871 {
|
|
872 if ($at = strpos($input, '@')) {
|
|
873 $user = substr($input, 0, $at);
|
|
874 $domain = substr($input, $at+1);
|
|
875 }
|
|
876 else {
|
|
877 $domain = $input;
|
|
878 }
|
|
879
|
|
880 $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
|
|
881
|
|
882 if ($domain === false) {
|
|
883 return '';
|
|
884 }
|
|
885
|
|
886 return $at ? $user . '@' . $domain : $domain;
|
|
887 }
|
|
888
|
|
889 /**
|
|
890 * Split the given string into word tokens
|
|
891 *
|
|
892 * @param string Input to tokenize
|
|
893 * @param integer Minimum length of a single token
|
|
894 * @return array List of tokens
|
|
895 */
|
|
896 public static function tokenize_string($str, $minlen = 2)
|
|
897 {
|
|
898 $expr = array('/[\s;,"\'\/+-]+/ui', '/(\d)[-.\s]+(\d)/u');
|
|
899 $repl = array(' ', '\\1\\2');
|
|
900
|
|
901 if ($minlen > 1) {
|
|
902 $minlen--;
|
|
903 $expr[] = "/(^|\s+)\w{1,$minlen}(\s+|$)/u";
|
|
904 $repl[] = ' ';
|
|
905 }
|
|
906
|
|
907 return array_filter(explode(" ", preg_replace($expr, $repl, $str)));
|
|
908 }
|
|
909
|
|
910 /**
|
|
911 * Normalize the given string for fulltext search.
|
|
912 * Currently only optimized for ISO-8859-1 and ISO-8859-2 characters; to be extended
|
|
913 *
|
|
914 * @param string Input string (UTF-8)
|
|
915 * @param boolean True to return list of words as array
|
|
916 * @param integer Minimum length of tokens
|
|
917 *
|
|
918 * @return mixed Normalized string or a list of normalized tokens
|
|
919 */
|
|
920 public static function normalize_string($str, $as_array = false, $minlen = 2)
|
|
921 {
|
|
922 // replace 4-byte unicode characters with '?' character,
|
|
923 // these are not supported in default utf-8 charset on mysql,
|
|
924 // the chance we'd need them in searching is very low
|
|
925 $str = preg_replace('/('
|
|
926 . '\xF0[\x90-\xBF][\x80-\xBF]{2}'
|
|
927 . '|[\xF1-\xF3][\x80-\xBF]{3}'
|
|
928 . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'
|
|
929 . ')/', '?', $str);
|
|
930
|
|
931 // split by words
|
|
932 $arr = self::tokenize_string($str, $minlen);
|
|
933
|
|
934 // detect character set
|
|
935 if (utf8_encode(utf8_decode($str)) == $str) {
|
|
936 // ISO-8859-1 (or ASCII)
|
|
937 preg_match_all('/./u', 'äâàåáãæçéêëèïîìíñöôòøõóüûùúýÿ', $keys);
|
|
938 preg_match_all('/./', 'aaaaaaaceeeeiiiinoooooouuuuyy', $values);
|
|
939
|
|
940 $mapping = array_combine($keys[0], $values[0]);
|
|
941 $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
|
|
942 }
|
|
943 else if (rcube_charset::convert(rcube_charset::convert($str, 'UTF-8', 'ISO-8859-2'), 'ISO-8859-2', 'UTF-8') == $str) {
|
|
944 // ISO-8859-2
|
|
945 preg_match_all('/./u', 'ąáâäćçčéęëěíîłľĺńňóôöŕřśšşťţůúűüźžżý', $keys);
|
|
946 preg_match_all('/./', 'aaaaccceeeeiilllnnooorrsssttuuuuzzzy', $values);
|
|
947
|
|
948 $mapping = array_combine($keys[0], $values[0]);
|
|
949 $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
|
|
950 }
|
|
951
|
|
952 foreach ($arr as $i => $part) {
|
|
953 $part = mb_strtolower($part);
|
|
954
|
|
955 if (!empty($mapping)) {
|
|
956 $part = strtr($part, $mapping);
|
|
957 }
|
|
958
|
|
959 $arr[$i] = $part;
|
|
960 }
|
|
961
|
|
962 return $as_array ? $arr : join(" ", $arr);
|
|
963 }
|
|
964
|
|
965 /**
|
|
966 * Compare two strings for matching words (order not relevant)
|
|
967 *
|
|
968 * @param string Haystack
|
|
969 * @param string Needle
|
|
970 *
|
|
971 * @return boolean True if match, False otherwise
|
|
972 */
|
|
973 public static function words_match($haystack, $needle)
|
|
974 {
|
|
975 $a_needle = self::tokenize_string($needle, 1);
|
|
976 $_haystack = join(" ", self::tokenize_string($haystack, 1));
|
|
977 $valid = strlen($_haystack) > 0;
|
|
978 $hits = 0;
|
|
979
|
|
980 foreach ($a_needle as $w) {
|
|
981 if ($valid) {
|
|
982 if (stripos($_haystack, $w) !== false) {
|
|
983 $hits++;
|
|
984 }
|
|
985 }
|
|
986 else if (stripos($haystack, $w) !== false) {
|
|
987 $hits++;
|
|
988 }
|
|
989 }
|
|
990
|
|
991 return $hits >= count($a_needle);
|
|
992 }
|
|
993
|
|
994 /**
|
|
995 * Parse commandline arguments into a hash array
|
|
996 *
|
|
997 * @param array $aliases Argument alias names
|
|
998 *
|
|
999 * @return array Argument values hash
|
|
1000 */
|
|
1001 public static function get_opt($aliases = array())
|
|
1002 {
|
|
1003 $args = array();
|
|
1004 $bool = array();
|
|
1005
|
|
1006 // find boolean (no value) options
|
|
1007 foreach ($aliases as $key => $alias) {
|
|
1008 if ($pos = strpos($alias, ':')) {
|
|
1009 $aliases[$key] = substr($alias, 0, $pos);
|
|
1010 $bool[] = $key;
|
|
1011 $bool[] = $aliases[$key];
|
|
1012 }
|
|
1013 }
|
|
1014
|
|
1015 for ($i=1; $i < count($_SERVER['argv']); $i++) {
|
|
1016 $arg = $_SERVER['argv'][$i];
|
|
1017 $value = true;
|
|
1018 $key = null;
|
|
1019
|
|
1020 if ($arg[0] == '-') {
|
|
1021 $key = preg_replace('/^-+/', '', $arg);
|
|
1022 $sp = strpos($arg, '=');
|
|
1023
|
|
1024 if ($sp > 0) {
|
|
1025 $key = substr($key, 0, $sp - 2);
|
|
1026 $value = substr($arg, $sp+1);
|
|
1027 }
|
|
1028 else if (in_array($key, $bool)) {
|
|
1029 $value = true;
|
|
1030 }
|
|
1031 else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
|
|
1032 $value = $_SERVER['argv'][++$i];
|
|
1033 }
|
|
1034
|
|
1035 $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
|
|
1036 }
|
|
1037 else {
|
|
1038 $args[] = $arg;
|
|
1039 }
|
|
1040
|
|
1041 if ($alias = $aliases[$key]) {
|
|
1042 $args[$alias] = $args[$key];
|
|
1043 }
|
|
1044 }
|
|
1045
|
|
1046 return $args;
|
|
1047 }
|
|
1048
|
|
1049 /**
|
|
1050 * Safe password prompt for command line
|
|
1051 * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
|
|
1052 *
|
|
1053 * @return string Password
|
|
1054 */
|
|
1055 public static function prompt_silent($prompt = "Password:")
|
|
1056 {
|
|
1057 if (preg_match('/^win/i', PHP_OS)) {
|
|
1058 $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
|
|
1059 $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
|
|
1060 file_put_contents($vbscript, $vbcontent);
|
|
1061
|
|
1062 $command = "cscript //nologo " . escapeshellarg($vbscript);
|
|
1063 $password = rtrim(shell_exec($command));
|
|
1064 unlink($vbscript);
|
|
1065
|
|
1066 return $password;
|
|
1067 }
|
|
1068 else {
|
|
1069 $command = "/usr/bin/env bash -c 'echo OK'";
|
|
1070 if (rtrim(shell_exec($command)) !== 'OK') {
|
|
1071 echo $prompt;
|
|
1072 $pass = trim(fgets(STDIN));
|
|
1073 echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
|
|
1074 return $pass;
|
|
1075 }
|
|
1076
|
|
1077 $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
|
|
1078 $password = rtrim(shell_exec($command));
|
|
1079 echo "\n";
|
|
1080 return $password;
|
|
1081 }
|
|
1082 }
|
|
1083
|
|
1084 /**
|
|
1085 * Find out if the string content means true or false
|
|
1086 *
|
|
1087 * @param string $str Input value
|
|
1088 *
|
|
1089 * @return boolean Boolean value
|
|
1090 */
|
|
1091 public static function get_boolean($str)
|
|
1092 {
|
|
1093 $str = strtolower($str);
|
|
1094
|
|
1095 return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
|
|
1096 }
|
|
1097
|
|
1098 /**
|
|
1099 * OS-dependent absolute path detection
|
|
1100 */
|
|
1101 public static function is_absolute_path($path)
|
|
1102 {
|
|
1103 if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
|
|
1104 return (bool) preg_match('!^[a-z]:[\\\\/]!i', $path);
|
|
1105 }
|
|
1106 else {
|
|
1107 return $path[0] == '/';
|
|
1108 }
|
|
1109 }
|
|
1110
|
|
1111 /**
|
|
1112 * Resolve relative URL
|
|
1113 *
|
|
1114 * @param string $url Relative URL
|
|
1115 *
|
|
1116 * @return string Absolute URL
|
|
1117 */
|
|
1118 public static function resolve_url($url)
|
|
1119 {
|
|
1120 // prepend protocol://hostname:port
|
|
1121 if (!preg_match('|^https?://|', $url)) {
|
|
1122 $schema = 'http';
|
|
1123 $default_port = 80;
|
|
1124
|
|
1125 if (self::https_check()) {
|
|
1126 $schema = 'https';
|
|
1127 $default_port = 443;
|
|
1128 }
|
|
1129
|
|
1130 $prefix = $schema . '://' . preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']);
|
|
1131 if ($_SERVER['SERVER_PORT'] != $default_port) {
|
|
1132 $prefix .= ':' . $_SERVER['SERVER_PORT'];
|
|
1133 }
|
|
1134
|
|
1135 $url = $prefix . ($url[0] == '/' ? '' : '/') . $url;
|
|
1136 }
|
|
1137
|
|
1138 return $url;
|
|
1139 }
|
|
1140
|
|
1141 /**
|
|
1142 * Generate a random string
|
|
1143 *
|
|
1144 * @param int $length String length
|
|
1145 * @param bool $raw Return RAW data instead of ascii
|
|
1146 *
|
|
1147 * @return string The generated random string
|
|
1148 */
|
|
1149 public static function random_bytes($length, $raw = false)
|
|
1150 {
|
|
1151 $hextab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
1152 $tabsize = strlen($hextab);
|
|
1153
|
|
1154 // Use PHP7 true random generator
|
|
1155 if ($raw && function_exists('random_bytes')) {
|
|
1156 return random_bytes($length);
|
|
1157 }
|
|
1158
|
|
1159 if (!$raw && function_exists('random_int')) {
|
|
1160 $result = '';
|
|
1161 while ($length-- > 0) {
|
|
1162 $result .= $hextab[random_int(0, $tabsize - 1)];
|
|
1163 }
|
|
1164
|
|
1165 return $result;
|
|
1166 }
|
|
1167
|
|
1168 $random = openssl_random_pseudo_bytes($length);
|
|
1169
|
|
1170 if ($random === false && $length > 0) {
|
|
1171 throw new Exception("Failed to get random bytes");
|
|
1172 }
|
|
1173
|
|
1174 if (!$raw) {
|
|
1175 for ($x = 0; $x < $length; $x++) {
|
|
1176 $random[$x] = $hextab[ord($random[$x]) % $tabsize];
|
|
1177 }
|
|
1178 }
|
|
1179
|
|
1180 return $random;
|
|
1181 }
|
|
1182
|
|
1183 /**
|
|
1184 * Convert binary data into readable form (containing a-zA-Z0-9 characters)
|
|
1185 *
|
|
1186 * @param string $input Binary input
|
|
1187 *
|
|
1188 * @return string Readable output (Base62)
|
|
1189 * @deprecated since 1.3.1
|
|
1190 */
|
|
1191 public static function bin2ascii($input)
|
|
1192 {
|
|
1193 $hextab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
1194 $result = '';
|
|
1195
|
|
1196 for ($x = 0; $x < strlen($input); $x++) {
|
|
1197 $result .= $hextab[ord($input[$x]) % 62];
|
|
1198 }
|
|
1199
|
|
1200 return $result;
|
|
1201 }
|
|
1202
|
|
1203 /**
|
|
1204 * Format current date according to specified format.
|
|
1205 * This method supports microseconds (u).
|
|
1206 *
|
|
1207 * @param string $format Date format (default: 'd-M-Y H:i:s O')
|
|
1208 *
|
|
1209 * @return string Formatted date
|
|
1210 */
|
|
1211 public static function date_format($format = null)
|
|
1212 {
|
|
1213 if (empty($format)) {
|
|
1214 $format = 'd-M-Y H:i:s O';
|
|
1215 }
|
|
1216
|
|
1217 if (strpos($format, 'u') !== false) {
|
|
1218 $dt = number_format(microtime(true), 6, '.', '');
|
|
1219 $dt .= '.' . date_default_timezone_get();
|
|
1220
|
|
1221 if ($date = date_create_from_format('U.u.e', $dt)) {
|
|
1222 return $date->format($format);
|
|
1223 }
|
|
1224 }
|
|
1225
|
|
1226 return date($format);
|
|
1227 }
|
|
1228
|
|
1229 /**
|
|
1230 * Parses socket options and returns options for specified hostname.
|
|
1231 *
|
|
1232 * @param array &$options Configured socket options
|
|
1233 * @param string $host Hostname
|
|
1234 */
|
|
1235 public static function parse_socket_options(&$options, $host = null)
|
|
1236 {
|
|
1237 if (empty($host) || empty($options)) {
|
|
1238 return $options;
|
|
1239 }
|
|
1240
|
|
1241 // get rid of schema and port from the hostname
|
|
1242 $host_url = parse_url($host);
|
|
1243 if (isset($host_url['host'])) {
|
|
1244 $host = $host_url['host'];
|
|
1245 }
|
|
1246
|
|
1247 // find per-host options
|
|
1248 if (array_key_exists($host, $options)) {
|
|
1249 $options = $options[$host];
|
|
1250 }
|
|
1251 }
|
|
1252
|
|
1253 /**
|
|
1254 * Get maximum upload size
|
|
1255 *
|
|
1256 * @return int Maximum size in bytes
|
|
1257 */
|
|
1258 public static function max_upload_size()
|
|
1259 {
|
|
1260 // find max filesize value
|
|
1261 $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
|
|
1262 $max_postsize = parse_bytes(ini_get('post_max_size'));
|
|
1263
|
|
1264 if ($max_postsize && $max_postsize < $max_filesize) {
|
|
1265 $max_filesize = $max_postsize;
|
|
1266 }
|
|
1267
|
|
1268 return $max_filesize;
|
|
1269 }
|
|
1270 }
|