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 5274 2011-09-23 10:11:27Z 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 * Similar function as in_array() but case-insensitive
75 * @param mixed Needle value
76 * @param array Array to search in
77 * @return boolean True if found, False if not
79 function in_array_nocase($needle, $haystack)
81 $needle = mb_strtolower($needle);
82 foreach ($haystack as $value)
83 if ($needle===mb_strtolower($value))
91 * Find out if the string content means TRUE or FALSE
93 * @param string Input value
94 * @return boolean Imagine what!
96 function get_boolean($str)
98 $str = strtolower($str);
99 if (in_array($str, array('false', '0', 'no', 'off', 'nein', ''), TRUE))
107 * Parse a human readable string for a number of bytes
109 * @param string Input string
110 * @return float Number of bytes
112 function parse_bytes($str)
114 if (is_numeric($str))
115 return floatval($str);
117 if (preg_match('/([0-9\.]+)\s*([a-z]*)/i', $str, $regs))
119 $bytes = floatval($regs[1]);
120 switch (strtolower($regs[2]))
124 $bytes *= 1073741824;
137 return floatval($bytes);
141 * Create a human readable string for a number of bytes
143 * @param int Number of bytes
144 * @return string Byte string
146 function show_bytes($bytes)
148 if ($bytes >= 1073741824)
150 $gb = $bytes/1073741824;
151 $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
153 else if ($bytes >= 1048576)
155 $mb = $bytes/1048576;
156 $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
158 else if ($bytes >= 1024)
159 $str = sprintf("%d ", round($bytes/1024)) . rcube_label('KB');
161 $str = sprintf('%d ', $bytes) . rcube_label('B');
167 * Convert paths like ../xxx to an absolute path using a base url
169 * @param string Relative path
170 * @param string Base URL
171 * @return string Absolute URL
173 function make_absolute_url($path, $base_url)
175 $host_url = $base_url;
178 // check if path is an absolute URL
179 if (preg_match('/^[fhtps]+:\/\//', $path))
182 // cut base_url to the last directory
183 if (strrpos($base_url, '/')>7)
185 $host_url = substr($base_url, 0, strpos($base_url, '/', 7));
186 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
191 $abs_path = $host_url.$path;
194 // strip './' because its the same as ''
195 $path = preg_replace('/^\.\//', '', $path);
197 if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
198 foreach ($matches as $a_match)
200 if (strrpos($base_url, '/'))
201 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
203 $path = substr($path, 3);
206 $abs_path = $base_url.'/'.$path;
213 * Wrapper function for wordwrap
215 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
217 $para = explode($break, $string);
219 while (count($para)) {
220 $line = array_shift($para);
221 if ($line[0] == '>') {
222 $string .= $line.$break;
225 $list = explode(' ', $line);
227 while (count($list)) {
228 $line = array_shift($list);
229 $l = mb_strlen($line);
230 $newlen = $len + $l + ($len ? 1 : 0);
232 if ($newlen <= $width) {
233 $string .= ($len ? ' ' : '').$line;
240 $str = mb_substr($line, $start, $width);
241 $strlen = mb_strlen($str);
242 $string .= ($len ? $break : '').$str;
248 $string .= ($len ? $break : '').$line;
249 if (count($list)) $string .= $break;
253 $string .= $break.$line;
258 if (count($para)) $string .= $break;
264 * Read a specific HTTP request header
267 * @param string $name Header name
268 * @return mixed Header value or null if not available
270 function rc_request_header($name)
272 if (function_exists('getallheaders'))
274 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
275 $key = strtoupper($name);
279 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
280 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
288 * Make sure the string ends with a slash
290 function slashify($str)
292 return unslashify($str).'/';
297 * Remove slash at the end of the string
299 function unslashify($str)
301 return preg_replace('/\/$/', '', $str);
306 * Delete all files within a folder
308 * @param string Path to directory
309 * @return boolean True on success, False if directory was not found
311 function clear_directory($dir_path)
313 $dir = @opendir($dir_path);
314 if(!$dir) return FALSE;
316 while ($file = readdir($dir))
318 unlink("$dir_path/$file");
326 * Create a unix timestamp with a specified offset from now
328 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
329 * @param int Factor to multiply with the offset
330 * @return int Unix timestamp
332 function get_offset_time($offset_str, $factor=1)
334 if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
336 $amount = (int)$regs[1];
337 $unit = strtolower($regs[2]);
341 $amount = (int)$offset_str;
357 $ts += $amount * $factor;
365 * Truncate string if it is longer than the allowed length
366 * Replace the middle or the ending part of a string with a placeholder
368 * @param string Input string
369 * @param int Max. length
370 * @param string Replace removed chars with this
371 * @param bool Set to True if string should be truncated from the end
372 * @return string Abbreviated string
374 function abbreviate_string($str, $maxlength, $place_holder='...', $ending=false)
376 $length = mb_strlen($str);
378 if ($length > $maxlength)
381 return mb_substr($str, 0, $maxlength) . $place_holder;
383 $place_holder_length = mb_strlen($place_holder);
384 $first_part_length = floor(($maxlength - $place_holder_length)/2);
385 $second_starting_location = $length - $maxlength + $first_part_length + $place_holder_length;
386 $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location);
394 * A method to guess the mime_type of an attachment.
396 * @param string $path Path to the file.
397 * @param string $name File name (with suffix)
398 * @param string $failover Mime type supplied for failover.
399 * @param string $is_stream Set to True if $path contains file body
402 * @author Till Klampaeckel <till@php.net>
403 * @see http://de2.php.net/manual/en/ref.fileinfo.php
404 * @see http://de2.php.net/mime_content_type
406 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream', $is_stream=false)
409 $mime_magic = rcmail::get_instance()->config->get('mime_magic');
410 $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
411 $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
413 // use file name suffix with hard-coded mime-type map
414 if (is_array($mime_ext)) {
415 $mime_type = $mime_ext[$suffix];
417 // try fileinfo extension if available
418 if (!$mime_type && function_exists('finfo_open')) {
419 if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
421 $mime_type = finfo_buffer($finfo, $path);
423 $mime_type = finfo_file($finfo, $path);
427 // try PHP's mime_content_type
428 if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
429 $mime_type = @mime_content_type($path);
431 // fall back to user-submitted string
433 $mime_type = $failover;
436 // Sometimes (PHP-5.3?) content-type contains charset definition,
437 // Remove it (#1487122) also "charset=binary" is useless
438 $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
446 * Detect image type of the given binary data by checking magic numbers
448 * @param string Binary file content
449 * @return string Detected mime-type or jpeg as fallback
451 function rc_image_content_type($data)
454 if (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
455 else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
456 else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
457 // else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';
459 return 'image/' . $type;
464 * A method to guess encoding of a string.
466 * @param string $string String.
467 * @param string $failover Default result for failover.
471 function rc_detect_encoding($string, $failover='')
473 if (!function_exists('mb_detect_encoding')) {
477 // FIXME: the order is important, because sometimes
478 // iso string is detected as euc-jp and etc.
480 'UTF-8', 'SJIS', 'BIG5', 'GB2312',
481 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
482 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
483 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
484 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
485 'ISO-2022-KR', 'ISO-2022-JP'
488 $result = mb_detect_encoding($string, join(',', $enc));
490 return $result ? $result : $failover;
494 * Removes non-unicode characters from input
496 * @param mixed $input String or array.
499 function rc_utf8_clean($input)
501 // handle input of type array
502 if (is_array($input)) {
503 foreach ($input as $idx => $val)
504 $input[$idx] = rc_utf8_clean($val);
508 if (!is_string($input) || $input == '')
511 // iconv/mbstring are much faster (especially with long strings)
512 if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
515 if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
519 // '[\x00-\x7F]'. // UTF8-1
520 '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
521 '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
522 '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
523 '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
524 '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
525 '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
526 '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
527 '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
533 for ($i = 0, $len = strlen($input); $i < $len; $i++) {
539 $out .= preg_match($regexp, $seq) ? $seq : '';
542 // first (or second) byte of multibyte sequence
543 } else if ($ord >= 0xC0) {
544 if (strlen($seq)>1) {
545 $out .= preg_match($regexp, $seq) ? $seq : '';
547 } else if ($seq && ord($seq) < 0xC0) {
551 // next byte of multibyte sequence
558 $out .= preg_match($regexp, $seq) ? $seq : '';
565 * Convert a variable into a javascript object notation
567 * @param mixed Input value
568 * @return string Serialized JSON string
570 function json_serialize($input)
572 $input = rc_utf8_clean($input);
574 // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
575 // that's why we have @ here
576 return @json_encode($input);
581 * Explode quoted string
583 * @param string Delimiter expression string for preg_match()
584 * @param string Input string
586 function rcube_explode_quoted_string($delimiter, $string)
589 $strlen = strlen($string);
591 for ($q=$p=$i=0; $i < $strlen; $i++) {
592 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
593 $q = $q ? false : true;
595 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
596 $result[] = substr($string, $p, $i - $p);
601 $result[] = substr($string, $p);
607 * Get all keys from array (recursive)
609 * @param array Input array
612 function array_keys_recursive($array)
617 foreach ($array as $key => $child) {
619 foreach (array_keys_recursive($child) as $val)
627 * mbstring replacement functions
630 if (!extension_loaded('mbstring'))
632 function mb_strlen($str)
637 function mb_strtolower($str)
639 return strtolower($str);
642 function mb_strtoupper($str)
644 return strtoupper($str);
647 function mb_substr($str, $start, $len=null)
649 return substr($str, $start, $len);
652 function mb_strpos($haystack, $needle, $offset=0)
654 return strpos($haystack, $needle, $offset);
657 function mb_strrpos($haystack, $needle, $offset=0)
659 return strrpos($haystack, $needle, $offset);
664 * intl replacement functions
667 if (!function_exists('idn_to_utf8'))
669 function idn_to_utf8($domain, $flags=null)
671 static $idn, $loaded;
674 $idn = new Net_IDNA2();
678 if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
680 $domain = $idn->decode($domain);
682 catch (Exception $e) {
689 if (!function_exists('idn_to_ascii'))
691 function idn_to_ascii($domain, $flags=null)
693 static $idn, $loaded;
696 $idn = new Net_IDNA2();
700 if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
702 $domain = $idn->encode($domain);
704 catch (Exception $e) {