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 5770 2012-01-13 11:23:17Z 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 * Wrapper function for wordwrap
169 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
171 $para = explode($break, $string);
173 while (count($para)) {
174 $line = array_shift($para);
175 if ($line[0] == '>') {
176 $string .= $line.$break;
179 $list = explode(' ', $line);
181 while (count($list)) {
182 $line = array_shift($list);
183 $l = mb_strlen($line);
184 $newlen = $len + $l + ($len ? 1 : 0);
186 if ($newlen <= $width) {
187 $string .= ($len ? ' ' : '').$line;
194 $str = mb_substr($line, $start, $width);
195 $strlen = mb_strlen($str);
196 $string .= ($len ? $break : '').$str;
202 $string .= ($len ? $break : '').$line;
203 if (count($list)) $string .= $break;
207 $string .= $break.$line;
212 if (count($para)) $string .= $break;
218 * Read a specific HTTP request header
221 * @param string $name Header name
222 * @return mixed Header value or null if not available
224 function rc_request_header($name)
226 if (function_exists('getallheaders'))
228 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
229 $key = strtoupper($name);
233 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
234 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
242 * Make sure the string ends with a slash
244 function slashify($str)
246 return unslashify($str).'/';
251 * Remove slash at the end of the string
253 function unslashify($str)
255 return preg_replace('/\/$/', '', $str);
260 * Delete all files within a folder
262 * @param string Path to directory
263 * @return boolean True on success, False if directory was not found
265 function clear_directory($dir_path)
267 $dir = @opendir($dir_path);
268 if(!$dir) return FALSE;
270 while ($file = readdir($dir))
272 unlink("$dir_path/$file");
280 * Create a unix timestamp with a specified offset from now
282 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
283 * @param int Factor to multiply with the offset
284 * @return int Unix timestamp
286 function get_offset_time($offset_str, $factor=1)
288 if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
290 $amount = (int)$regs[1];
291 $unit = strtolower($regs[2]);
295 $amount = (int)$offset_str;
311 $ts += $amount * $factor;
319 * Truncate string if it is longer than the allowed length
320 * Replace the middle or the ending part of a string with a placeholder
322 * @param string Input string
323 * @param int Max. length
324 * @param string Replace removed chars with this
325 * @param bool Set to True if string should be truncated from the end
326 * @return string Abbreviated string
328 function abbreviate_string($str, $maxlength, $place_holder='...', $ending=false)
330 $length = mb_strlen($str);
332 if ($length > $maxlength)
335 return mb_substr($str, 0, $maxlength) . $place_holder;
337 $place_holder_length = mb_strlen($place_holder);
338 $first_part_length = floor(($maxlength - $place_holder_length)/2);
339 $second_starting_location = $length - $maxlength + $first_part_length + $place_holder_length;
340 $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location);
348 * A method to guess the mime_type of an attachment.
350 * @param string $path Path to the file.
351 * @param string $name File name (with suffix)
352 * @param string $failover Mime type supplied for failover.
353 * @param string $is_stream Set to True if $path contains file body
356 * @author Till Klampaeckel <till@php.net>
357 * @see http://de2.php.net/manual/en/ref.fileinfo.php
358 * @see http://de2.php.net/mime_content_type
360 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream', $is_stream=false)
363 $mime_magic = rcmail::get_instance()->config->get('mime_magic');
364 $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
366 // use file name suffix with hard-coded mime-type map
367 if (is_array($mime_ext) && $name) {
368 if ($suffix = substr($name, strrpos($name, '.')+1)) {
369 $mime_type = $mime_ext[strtolower($suffix)];
373 // try fileinfo extension if available
374 if (!$mime_type && function_exists('finfo_open')) {
375 if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
377 $mime_type = finfo_buffer($finfo, $path);
379 $mime_type = finfo_file($finfo, $path);
384 // try PHP's mime_content_type
385 if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
386 $mime_type = @mime_content_type($path);
389 // fall back to user-submitted string
391 $mime_type = $failover;
394 // Sometimes (PHP-5.3?) content-type contains charset definition,
395 // Remove it (#1487122) also "charset=binary" is useless
396 $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
404 * Detect image type of the given binary data by checking magic numbers
406 * @param string Binary file content
407 * @return string Detected mime-type or jpeg as fallback
409 function rc_image_content_type($data)
412 if (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
413 else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
414 else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
415 // else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';
417 return 'image/' . $type;
422 * A method to guess encoding of a string.
424 * @param string $string String.
425 * @param string $failover Default result for failover.
429 function rc_detect_encoding($string, $failover='')
431 if (!function_exists('mb_detect_encoding')) {
435 // FIXME: the order is important, because sometimes
436 // iso string is detected as euc-jp and etc.
438 'UTF-8', 'SJIS', 'BIG5', 'GB2312',
439 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
440 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
441 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
442 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
443 'ISO-2022-KR', 'ISO-2022-JP'
446 $result = mb_detect_encoding($string, join(',', $enc));
448 return $result ? $result : $failover;
452 * Removes non-unicode characters from input
454 * @param mixed $input String or array.
457 function rc_utf8_clean($input)
459 // handle input of type array
460 if (is_array($input)) {
461 foreach ($input as $idx => $val)
462 $input[$idx] = rc_utf8_clean($val);
466 if (!is_string($input) || $input == '')
469 // iconv/mbstring are much faster (especially with long strings)
470 if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
473 if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
477 // '[\x00-\x7F]'. // UTF8-1
478 '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
479 '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
480 '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
481 '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
482 '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
483 '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
484 '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
485 '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
491 for ($i = 0, $len = strlen($input); $i < $len; $i++) {
497 $out .= preg_match($regexp, $seq) ? $seq : '';
500 // first (or second) byte of multibyte sequence
501 } else if ($ord >= 0xC0) {
502 if (strlen($seq)>1) {
503 $out .= preg_match($regexp, $seq) ? $seq : '';
505 } else if ($seq && ord($seq) < 0xC0) {
509 // next byte of multibyte sequence
516 $out .= preg_match($regexp, $seq) ? $seq : '';
523 * Convert a variable into a javascript object notation
525 * @param mixed Input value
526 * @return string Serialized JSON string
528 function json_serialize($input)
530 $input = rc_utf8_clean($input);
532 // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
533 // that's why we have @ here
534 return @json_encode($input);
539 * Explode quoted string
541 * @param string Delimiter expression string for preg_match()
542 * @param string Input string
544 function rcube_explode_quoted_string($delimiter, $string)
547 $strlen = strlen($string);
549 for ($q=$p=$i=0; $i < $strlen; $i++) {
550 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
551 $q = $q ? false : true;
553 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
554 $result[] = substr($string, $p, $i - $p);
559 $result[] = substr($string, $p);
565 * Get all keys from array (recursive)
567 * @param array Input array
570 function array_keys_recursive($array)
575 foreach ($array as $key => $child) {
577 foreach (array_keys_recursive($child) as $val)
585 * mbstring replacement functions
588 if (!extension_loaded('mbstring'))
590 function mb_strlen($str)
595 function mb_strtolower($str)
597 return strtolower($str);
600 function mb_strtoupper($str)
602 return strtoupper($str);
605 function mb_substr($str, $start, $len=null)
607 return substr($str, $start, $len);
610 function mb_strpos($haystack, $needle, $offset=0)
612 return strpos($haystack, $needle, $offset);
615 function mb_strrpos($haystack, $needle, $offset=0)
617 return strrpos($haystack, $needle, $offset);
622 * intl replacement functions
625 if (!function_exists('idn_to_utf8'))
627 function idn_to_utf8($domain, $flags=null)
629 static $idn, $loaded;
632 $idn = new Net_IDNA2();
636 if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
638 $domain = $idn->decode($domain);
640 catch (Exception $e) {
647 if (!function_exists('idn_to_ascii'))
649 function idn_to_ascii($domain, $flags=null)
651 static $idn, $loaded;
654 $idn = new Net_IDNA2();
658 if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
660 $domain = $idn->encode($domain);
662 catch (Exception $e) {