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 5715 2012-01-05 10:28:24Z 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');
365 $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
367 // use file name suffix with hard-coded mime-type map
368 if (is_array($mime_ext)) {
369 $mime_type = $mime_ext[$suffix];
371 // try fileinfo extension if available
372 if (!$mime_type && function_exists('finfo_open')) {
373 if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
375 $mime_type = finfo_buffer($finfo, $path);
377 $mime_type = finfo_file($finfo, $path);
381 // try PHP's mime_content_type
382 if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
383 $mime_type = @mime_content_type($path);
385 // fall back to user-submitted string
387 $mime_type = $failover;
390 // Sometimes (PHP-5.3?) content-type contains charset definition,
391 // Remove it (#1487122) also "charset=binary" is useless
392 $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
400 * Detect image type of the given binary data by checking magic numbers
402 * @param string Binary file content
403 * @return string Detected mime-type or jpeg as fallback
405 function rc_image_content_type($data)
408 if (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
409 else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
410 else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
411 // else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';
413 return 'image/' . $type;
418 * A method to guess encoding of a string.
420 * @param string $string String.
421 * @param string $failover Default result for failover.
425 function rc_detect_encoding($string, $failover='')
427 if (!function_exists('mb_detect_encoding')) {
431 // FIXME: the order is important, because sometimes
432 // iso string is detected as euc-jp and etc.
434 'UTF-8', 'SJIS', 'BIG5', 'GB2312',
435 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
436 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
437 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
438 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
439 'ISO-2022-KR', 'ISO-2022-JP'
442 $result = mb_detect_encoding($string, join(',', $enc));
444 return $result ? $result : $failover;
448 * Removes non-unicode characters from input
450 * @param mixed $input String or array.
453 function rc_utf8_clean($input)
455 // handle input of type array
456 if (is_array($input)) {
457 foreach ($input as $idx => $val)
458 $input[$idx] = rc_utf8_clean($val);
462 if (!is_string($input) || $input == '')
465 // iconv/mbstring are much faster (especially with long strings)
466 if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
469 if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
473 // '[\x00-\x7F]'. // UTF8-1
474 '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
475 '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
476 '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
477 '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
478 '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
479 '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
480 '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
481 '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
487 for ($i = 0, $len = strlen($input); $i < $len; $i++) {
493 $out .= preg_match($regexp, $seq) ? $seq : '';
496 // first (or second) byte of multibyte sequence
497 } else if ($ord >= 0xC0) {
498 if (strlen($seq)>1) {
499 $out .= preg_match($regexp, $seq) ? $seq : '';
501 } else if ($seq && ord($seq) < 0xC0) {
505 // next byte of multibyte sequence
512 $out .= preg_match($regexp, $seq) ? $seq : '';
519 * Convert a variable into a javascript object notation
521 * @param mixed Input value
522 * @return string Serialized JSON string
524 function json_serialize($input)
526 $input = rc_utf8_clean($input);
528 // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
529 // that's why we have @ here
530 return @json_encode($input);
535 * Explode quoted string
537 * @param string Delimiter expression string for preg_match()
538 * @param string Input string
540 function rcube_explode_quoted_string($delimiter, $string)
543 $strlen = strlen($string);
545 for ($q=$p=$i=0; $i < $strlen; $i++) {
546 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
547 $q = $q ? false : true;
549 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
550 $result[] = substr($string, $p, $i - $p);
555 $result[] = substr($string, $p);
561 * Get all keys from array (recursive)
563 * @param array Input array
566 function array_keys_recursive($array)
571 foreach ($array as $key => $child) {
573 foreach (array_keys_recursive($child) as $val)
581 * mbstring replacement functions
584 if (!extension_loaded('mbstring'))
586 function mb_strlen($str)
591 function mb_strtolower($str)
593 return strtolower($str);
596 function mb_strtoupper($str)
598 return strtoupper($str);
601 function mb_substr($str, $start, $len=null)
603 return substr($str, $start, $len);
606 function mb_strpos($haystack, $needle, $offset=0)
608 return strpos($haystack, $needle, $offset);
611 function mb_strrpos($haystack, $needle, $offset=0)
613 return strrpos($haystack, $needle, $offset);
618 * intl replacement functions
621 if (!function_exists('idn_to_utf8'))
623 function idn_to_utf8($domain, $flags=null)
625 static $idn, $loaded;
628 $idn = new Net_IDNA2();
632 if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
634 $domain = $idn->decode($domain);
636 catch (Exception $e) {
643 if (!function_exists('idn_to_ascii'))
645 function idn_to_ascii($domain, $flags=null)
647 static $idn, $loaded;
650 $idn = new Net_IDNA2();
654 if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
656 $domain = $idn->encode($domain);
658 catch (Exception $e) {