4 +-----------------------------------------------------------------------+
7 | This file is part of the Roundcube PHP suite |
8 | Copyright (C) 2005-2007, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | Shared functions and classes used in PHP projects |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: rcube_shared.inc 4710 2011-04-29 08:17:42Z alec $
24 * Roundcube shared functions
31 * Send HTTP headers to prevent caching this page
33 function send_nocacheing_headers()
40 header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
41 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
42 // Request browser to disable DNS prefetching (CVE-2010-0464)
43 header("X-DNS-Prefetch-Control: off");
45 // We need to set the following headers to make downloads work using IE in HTTPS mode.
46 if ($OUTPUT->browser->ie && rcube_https_check()) {
47 header('Pragma: private');
48 header("Cache-Control: private, must-revalidate");
50 header("Cache-Control: private, no-cache, must-revalidate, post-check=0, pre-check=0");
51 header("Pragma: no-cache");
57 * Send header with expire date 30 days in future
59 * @param int Expiration time in seconds
61 function send_future_expire_header($offset=2600000)
66 header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
67 header("Cache-Control: max-age=$offset");
73 * Check request for If-Modified-Since and send an according response.
74 * This will terminate the current script if headers match the given values
76 * @param int Modified date as unix timestamp
77 * @param string Etag value for caching
79 function send_modified_header($mdate, $etag=null, $skip_check=false)
85 $etag = $etag ? "\"$etag\"" : null;
89 if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
93 $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
97 header("HTTP/1.x 304 Not Modified");
99 header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
101 header("Cache-Control: private, must-revalidate, max-age=0");
106 header("Etag: $etag");
117 * Similar function as in_array() but case-insensitive
119 * @param mixed Needle value
120 * @param array Array to search in
121 * @return boolean True if found, False if not
123 function in_array_nocase($needle, $haystack)
125 $needle = mb_strtolower($needle);
126 foreach ($haystack as $value)
127 if ($needle===mb_strtolower($value))
135 * Find out if the string content means TRUE or FALSE
137 * @param string Input value
138 * @return boolean Imagine what!
140 function get_boolean($str)
142 $str = strtolower($str);
143 if (in_array($str, array('false', '0', 'no', 'off', 'nein', ''), TRUE))
151 * Parse a human readable string for a number of bytes
153 * @param string Input string
154 * @return float Number of bytes
156 function parse_bytes($str)
158 if (is_numeric($str))
159 return floatval($str);
161 if (preg_match('/([0-9\.]+)\s*([a-z]*)/i', $str, $regs))
163 $bytes = floatval($regs[1]);
164 switch (strtolower($regs[2]))
168 $bytes *= 1073741824;
181 return floatval($bytes);
185 * Create a human readable string for a number of bytes
187 * @param int Number of bytes
188 * @return string Byte string
190 function show_bytes($bytes)
192 if ($bytes >= 1073741824)
194 $gb = $bytes/1073741824;
195 $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
197 else if ($bytes >= 1048576)
199 $mb = $bytes/1048576;
200 $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
202 else if ($bytes >= 1024)
203 $str = sprintf("%d ", round($bytes/1024)) . rcube_label('KB');
205 $str = sprintf('%d ', $bytes) . rcube_label('B');
211 * Convert paths like ../xxx to an absolute path using a base url
213 * @param string Relative path
214 * @param string Base URL
215 * @return string Absolute URL
217 function make_absolute_url($path, $base_url)
219 $host_url = $base_url;
222 // check if path is an absolute URL
223 if (preg_match('/^[fhtps]+:\/\//', $path))
226 // cut base_url to the last directory
227 if (strrpos($base_url, '/')>7)
229 $host_url = substr($base_url, 0, strpos($base_url, '/', 7));
230 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
235 $abs_path = $host_url.$path;
238 // strip './' because its the same as ''
239 $path = preg_replace('/^\.\//', '', $path);
241 if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
242 foreach ($matches as $a_match)
244 if (strrpos($base_url, '/'))
245 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
247 $path = substr($path, 3);
250 $abs_path = $base_url.'/'.$path;
257 * Wrapper function for wordwrap
259 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
261 $para = explode($break, $string);
263 while (count($para)) {
264 $line = array_shift($para);
265 if ($line[0] == '>') {
266 $string .= $line.$break;
269 $list = explode(' ', $line);
271 while (count($list)) {
272 $line = array_shift($list);
273 $l = mb_strlen($line);
274 $newlen = $len + $l + ($len ? 1 : 0);
276 if ($newlen <= $width) {
277 $string .= ($len ? ' ' : '').$line;
284 $str = mb_substr($line, $start, $width);
285 $strlen = mb_strlen($str);
286 $string .= ($len ? $break : '').$str;
292 $string .= ($len ? $break : '').$line;
293 if (count($list)) $string .= $break;
297 $string .= $break.$line;
302 if (count($para)) $string .= $break;
308 * Read a specific HTTP request header
311 * @param string $name Header name
312 * @return mixed Header value or null if not available
314 function rc_request_header($name)
316 if (function_exists('getallheaders'))
318 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
319 $key = strtoupper($name);
323 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
324 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
332 * Make sure the string ends with a slash
334 function slashify($str)
336 return unslashify($str).'/';
341 * Remove slash at the end of the string
343 function unslashify($str)
345 return preg_replace('/\/$/', '', $str);
350 * Delete all files within a folder
352 * @param string Path to directory
353 * @return boolean True on success, False if directory was not found
355 function clear_directory($dir_path)
357 $dir = @opendir($dir_path);
358 if(!$dir) return FALSE;
360 while ($file = readdir($dir))
362 unlink("$dir_path/$file");
370 * Create a unix timestamp with a specified offset from now
372 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
373 * @param int Factor to multiply with the offset
374 * @return int Unix timestamp
376 function get_offset_time($offset_str, $factor=1)
378 if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
380 $amount = (int)$regs[1];
381 $unit = strtolower($regs[2]);
385 $amount = (int)$offset_str;
401 $ts += $amount * $factor;
409 * Truncate string if it is longer than the allowed length
410 * Replace the middle or the ending part of a string with a placeholder
412 * @param string Input string
413 * @param int Max. length
414 * @param string Replace removed chars with this
415 * @param bool Set to True if string should be truncated from the end
416 * @return string Abbreviated string
418 function abbreviate_string($str, $maxlength, $place_holder='...', $ending=false)
420 $length = mb_strlen($str);
422 if ($length > $maxlength)
425 return mb_substr($str, 0, $maxlength) . $place_holder;
427 $place_holder_length = mb_strlen($place_holder);
428 $first_part_length = floor(($maxlength - $place_holder_length)/2);
429 $second_starting_location = $length - $maxlength + $first_part_length + $place_holder_length;
430 $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location);
437 * A method to guess the mime_type of an attachment.
439 * @param string $path Path to the file.
440 * @param string $name File name (with suffix)
441 * @param string $failover Mime type supplied for failover.
442 * @param string $is_stream Set to True if $path contains file body
445 * @author Till Klampaeckel <till@php.net>
446 * @see http://de2.php.net/manual/en/ref.fileinfo.php
447 * @see http://de2.php.net/mime_content_type
449 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream', $is_stream=false)
452 $mime_magic = rcmail::get_instance()->config->get('mime_magic');
453 $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
454 $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
456 // use file name suffix with hard-coded mime-type map
457 if (is_array($mime_ext)) {
458 $mime_type = $mime_ext[$suffix];
460 // try fileinfo extension if available
461 if (!$mime_type && function_exists('finfo_open')) {
462 if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
464 $mime_type = finfo_buffer($finfo, $path);
466 $mime_type = finfo_file($finfo, $path);
470 // try PHP's mime_content_type
471 if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
472 $mime_type = @mime_content_type($path);
474 // fall back to user-submitted string
476 $mime_type = $failover;
479 // Sometimes (PHP-5.3?) content-type contains charset definition,
480 // Remove it (#1487122) also "charset=binary" is useless
481 $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
489 * Detect image type of the given binary data by checking magic numbers
491 * @param string Binary file content
492 * @return string Detected mime-type or jpeg as fallback
494 function rc_image_content_type($data)
497 if (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
498 else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
499 else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
500 // else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';
502 return 'image/' . $type;
507 * A method to guess encoding of a string.
509 * @param string $string String.
510 * @param string $failover Default result for failover.
514 function rc_detect_encoding($string, $failover='')
516 if (!function_exists('mb_detect_encoding')) {
520 // FIXME: the order is important, because sometimes
521 // iso string is detected as euc-jp and etc.
523 'UTF-8', 'SJIS', 'BIG5', 'GB2312',
524 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
525 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
526 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
527 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
528 'ISO-2022-KR', 'ISO-2022-JP'
531 $result = mb_detect_encoding($string, join(',', $enc));
533 return $result ? $result : $failover;
537 * Removes non-unicode characters from input
539 * @param mixed $input String or array.
542 function rc_utf8_clean($input)
544 // handle input of type array
545 if (is_array($input)) {
546 foreach ($input as $idx => $val)
547 $input[$idx] = rc_utf8_clean($val);
551 if (!is_string($input) || $input == '')
554 // iconv/mbstring are much faster (especially with long strings)
555 if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
558 if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
562 // '[\x00-\x7F]'. // UTF8-1
563 '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
564 '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
565 '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
566 '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
567 '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
568 '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
569 '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
570 '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
576 for ($i = 0, $len = strlen($input); $i < $len; $i++) {
582 $out .= preg_match($regexp, $seq) ? $seq : '';
585 // first (or second) byte of multibyte sequence
586 } else if ($ord >= 0xC0) {
587 if (strlen($seq)>1) {
588 $out .= preg_match($regexp, $seq) ? $seq : '';
590 } else if ($seq && ord($seq) < 0xC0) {
594 // next byte of multibyte sequence
601 $out .= preg_match($regexp, $seq) ? $seq : '';
608 * Convert a variable into a javascript object notation
610 * @param mixed Input value
611 * @return string Serialized JSON string
613 function json_serialize($input)
615 $input = rc_utf8_clean($input);
617 // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
618 // that's why we have @ here
619 return @json_encode($input);
624 * Explode quoted string
626 * @param string Delimiter expression string for preg_match()
627 * @param string Input string
629 function rcube_explode_quoted_string($delimiter, $string)
632 $strlen = strlen($string);
634 for ($q=$p=$i=0; $i < $strlen; $i++) {
635 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
636 $q = $q ? false : true;
638 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
639 $result[] = substr($string, $p, $i - $p);
644 $result[] = substr($string, $p);
650 * Get all keys from array (recursive)
652 * @param array Input array
655 function array_keys_recursive($array)
660 foreach ($array as $key => $child) {
662 foreach (array_keys_recursive($child) as $val)
670 * mbstring replacement functions
673 if (!extension_loaded('mbstring'))
675 function mb_strlen($str)
680 function mb_strtolower($str)
682 return strtolower($str);
685 function mb_strtoupper($str)
687 return strtoupper($str);
690 function mb_substr($str, $start, $len=null)
692 return substr($str, $start, $len);
695 function mb_strpos($haystack, $needle, $offset=0)
697 return strpos($haystack, $needle, $offset);
700 function mb_strrpos($haystack, $needle, $offset=0)
702 return strrpos($haystack, $needle, $offset);
707 * intl replacement functions
710 if (!function_exists('idn_to_utf8'))
712 function idn_to_utf8($domain, $flags=null)
714 static $idn, $loaded;
717 $idn = new Net_IDNA2();
721 if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
723 $domain = $idn->decode($domain);
725 catch (Exception $e) {
732 if (!function_exists('idn_to_ascii'))
734 function idn_to_ascii($domain, $flags=null)
736 static $idn, $loaded;
739 $idn = new Net_IDNA2();
743 if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
745 $domain = $idn->encode($domain);
747 catch (Exception $e) {