4 +-----------------------------------------------------------------------+
7 | This file is part of the RoundCube PHP suite |
8 | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
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 3063 2009-10-27 09:43:39Z alec $
24 * RoundCube shared functions
31 * Send HTTP headers to prevent caching this page
33 function send_nocacheing_headers()
38 header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
39 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
40 header("Cache-Control: private, must-revalidate, post-check=0, pre-check=0");
41 header("Pragma: no-cache");
43 // We need to set the following headers to make downloads work using IE in HTTPS mode.
44 if (rcube_https_check()) {
46 header('Cache-Control: ');
52 * Send header with expire date 30 days in future
54 * @param int Expiration time in seconds
56 function send_future_expire_header($offset=2600000)
61 header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
62 header("Cache-Control: max-age=$offset");
68 * Check request for If-Modified-Since and send an according response.
69 * This will terminate the current script if headers match the given values
71 * @param int Modified date as unix timestamp
72 * @param string Etag value for caching
74 function send_modified_header($mdate, $etag=null, $skip_check=false)
80 $etag = $etag ? "\"$etag\"" : null;
84 if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
88 $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
92 header("HTTP/1.x 304 Not Modified");
94 header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
96 header("Cache-Control: max-age=0");
101 header("Etag: $etag");
112 * Returns whether an $str is a reserved word for any of the version of Javascript or ECMAScript
113 * @param str String to check
114 * @return boolean True if $str is a reserver word, False if not
116 function is_js_reserved_word($str)
118 return in_array($str, array(
119 // ECMASript ver 4 reserved words
120 'as','break','case','catch','class','const','continue',
121 'default','delete','do','else','export','extends','false','finally','for','function',
122 'if','import','in','instanceof','is','namespace','new','null','package','private',
123 'public','return','super','switch','this','throw','true','try','typeof','use','var',
124 'void','while','with',
125 // ECMAScript ver 4 future reserved words
126 'abstract','debugger','enum','goto','implements','interface','native','protected',
127 'synchronized','throws','transient','volatile',
128 // special meaning in some contexts
130 // were reserved in ECMAScript ver 3
131 'boolean','byte','char','double','final','float','int','long','short','static'
137 * Convert a variable into a javascript object notation
139 * @param mixed Input value
140 * @return string Serialized JSON string
142 function json_serialize($var)
145 $var = get_object_vars($var);
154 $keys_arr = array_keys($var);
155 $is_assoc = $have_numeric = 0;
157 for ($i=0; $i<sizeof($keys_arr); ++$i)
159 if (is_numeric($keys_arr[$i]))
161 if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
163 if ($is_assoc && $have_numeric)
167 $brackets = $is_assoc ? '{}' : '[]';
170 foreach ($var as $key => $value)
172 // enclose key with quotes if it is not variable-name conform
173 if (!preg_match('/^[_a-zA-Z]{1}[_a-zA-Z0-9]*$/', $key) || is_js_reserved_word($key))
176 $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
179 return $brackets{0} . implode(',', $pairs) . $brackets{1};
182 else if (!is_string($var) && strval(intval($var)) === strval($var))
184 else if (is_bool($var))
185 return $var ? '1' : '0';
187 return "'".JQ($var)."'";
192 * Function to convert an array to a javascript array
193 * Actually an alias function for json_serialize()
196 function array2js($arr, $type='')
198 return json_serialize($arr);
203 * Similar function as in_array() but case-insensitive
205 * @param mixed Needle value
206 * @param array Array to search in
207 * @return boolean True if found, False if not
209 function in_array_nocase($needle, $haystack)
211 $needle = mb_strtolower($needle);
212 foreach ($haystack as $value)
213 if ($needle===mb_strtolower($value))
221 * Find out if the string content means TRUE or FALSE
223 * @param string Input value
224 * @return boolean Imagine what!
226 function get_boolean($str)
228 $str = strtolower($str);
229 if (in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
237 * Parse a human readable string for a number of bytes
239 * @param string Input string
240 * @return float Number of bytes
242 function parse_bytes($str)
244 if (is_numeric($str))
245 return floatval($str);
247 if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
249 $bytes = floatval($regs[1]);
250 switch (strtolower($regs[2]))
253 $bytes *= 1073741824;
264 return floatval($bytes);
268 * Create a human readable string for a number of bytes
270 * @param int Number of bytes
271 * @return string Byte string
273 function show_bytes($bytes)
275 if ($bytes > 1073741824)
277 $gb = $bytes/1073741824;
278 $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
280 else if ($bytes > 1048576)
282 $mb = $bytes/1048576;
283 $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
285 else if ($bytes > 1024)
286 $str = sprintf("%d ", round($bytes/1024)) . rcube_label('KB');
288 $str = sprintf('%d ', $bytes) . rcube_label('B');
295 * Convert paths like ../xxx to an absolute path using a base url
297 * @param string Relative path
298 * @param string Base URL
299 * @return string Absolute URL
301 function make_absolute_url($path, $base_url)
303 $host_url = $base_url;
306 // check if path is an absolute URL
307 if (preg_match('/^[fhtps]+:\/\//', $path))
310 // cut base_url to the last directory
311 if (strrpos($base_url, '/')>7)
313 $host_url = substr($base_url, 0, strpos($base_url, '/'));
314 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
319 $abs_path = $host_url.$path;
322 // strip './' because its the same as ''
323 $path = preg_replace('/^\.\//', '', $path);
325 if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
326 foreach ($matches as $a_match)
328 if (strrpos($base_url, '/'))
329 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
331 $path = substr($path, 3);
334 $abs_path = $base_url.'/'.$path;
341 * Wrapper function for wordwrap
343 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
345 $para = explode($break, $string);
347 while (count($para)) {
348 $list = explode(' ', array_shift($para));
350 while (count($list)) {
351 $line = array_shift($list);
352 $l = mb_strlen($line);
353 $newlen = $len + $l + ($len ? 1 : 0);
355 if ($newlen <= $width) {
356 $string .= ($len ? ' ' : '').$line;
363 $str = mb_substr($line, $start, $width);
364 $strlen = mb_strlen($str);
365 $string .= ($len ? $break : '').$str;
371 $string .= ($len ? $break : '').$line;
372 if (count($list)) $string .= $break;
376 $string .= $break.$line;
381 if (count($para)) $string .= $break;
387 * Read a specific HTTP request header
390 * @param string $name Header name
391 * @return mixed Header value or null if not available
393 function rc_request_header($name)
395 if (function_exists('getallheaders'))
397 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
398 $key = strtoupper($name);
402 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
403 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
411 * Make sure the string ends with a slash
413 function slashify($str)
415 return unslashify($str).'/';
420 * Remove slash at the end of the string
422 function unslashify($str)
424 return preg_replace('/\/$/', '', $str);
429 * Delete all files within a folder
431 * @param string Path to directory
432 * @return boolean True on success, False if directory was not found
434 function clear_directory($dir_path)
436 $dir = @opendir($dir_path);
437 if(!$dir) return FALSE;
439 while ($file = readdir($dir))
441 unlink("$dir_path/$file");
449 * Create a unix timestamp with a specified offset from now
451 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
452 * @param int Factor to multiply with the offset
453 * @return int Unix timestamp
455 function get_offset_time($offset_str, $factor=1)
457 if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
459 $amount = (int)$regs[1];
460 $unit = strtolower($regs[2]);
464 $amount = (int)$offset_str;
480 $ts += $amount * $factor;
488 * Replace the middle part of a string with ...
489 * if it is longer than the allowed length
491 * @param string Input string
492 * @param int Max. length
493 * @param string Replace removed chars with this
494 * @return string Abbreviated string
496 function abbreviate_string($str, $maxlength, $place_holder='...')
498 $length = mb_strlen($str);
499 $first_part_length = floor($maxlength/2) - mb_strlen($place_holder);
501 if ($length > $maxlength)
503 $second_starting_location = $length - $maxlength + $first_part_length + 1;
504 $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location, $length);
511 * A method to guess the mime_type of an attachment.
513 * @param string $path Path to the file.
514 * @param string $name File name (with suffix)
515 * @param string $failover Mime type supplied for failover.
518 * @author Till Klampaeckel <till@php.net>
519 * @see http://de2.php.net/manual/en/ref.fileinfo.php
520 * @see http://de2.php.net/mime_content_type
522 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream')
525 $mime_magic = rcmail::get_instance()->config->get('mime_magic');
526 $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
527 $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
529 // use file name suffix with hard-coded mime-type map
530 if (is_array($mime_ext)) {
531 $mime_type = $mime_ext[$suffix];
533 // try fileinfo extension if available
535 if (!extension_loaded('fileinfo')) {
536 @dl('fileinfo.' . PHP_SHLIB_SUFFIX);
538 if (function_exists('finfo_open')) {
539 if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
540 $mime_type = finfo_file($finfo, $path);
545 // try PHP's mime_content_type
546 if (!$mime_type && function_exists('mime_content_type')) {
547 $mime_type = mime_content_type($path);
549 // fall back to user-submitted string
551 $mime_type = $failover;
558 * A method to guess encoding of a string.
560 * @param string $string String.
561 * @param string $failover Default result for failover.
565 function rc_detect_encoding($string, $failover='')
567 if (!function_exists('mb_detect_encoding')) {
571 // FIXME: the order is important, because sometimes
572 // iso string is detected as euc-jp and etc.
574 'UTF-8', 'SJIS', 'BIG5', 'GB2312',
575 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
576 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
577 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
578 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
579 'ISO-2022-KR', 'ISO-2022-JP'
582 $result = mb_detect_encoding($string, join(',', $enc));
584 return $result ? $result : $failover;
588 * Removes non-unicode characters from input
590 * @param mixed $input String or array.
593 function rc_utf8_clean($input)
595 // handle input of type array
596 if (is_array($input)) {
597 foreach ($input as $idx => $val)
598 $input[$idx] = rc_utf8_clean($val);
602 if (!is_string($input) || $input == '')
605 // iconv/mbstring are much faster (especially with long strings)
606 if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF8', 'UTF8')))
609 if (function_exists('iconv') && ($res = iconv('UTF8', 'UTF8//IGNORE', $input)))
613 // '[\x00-\x7F]'. // UTF8-1
614 '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
615 '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
616 '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
617 '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
618 '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
619 '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
620 '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
621 '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
627 for ($i = 0, $len = strlen($input)-1; $i < $len; $i++) {
633 $out .= preg_match($regexp, $seq) ? $seq : '';
636 // first (or second) byte of multibyte sequence
637 } else if ($ord >= 0xC0) {
638 if (strlen($seq)>1) {
639 $out .= preg_match($regexp, $seq) ? $seq : '';
641 } else if ($seq && ord($seq) < 0xC0) {
645 // next byte of multibyte sequence
652 $out .= preg_match($regexp, $seq) ? $seq : '';
658 * Explode quoted string
660 * @param string Delimiter expression string for preg_match()
661 * @param string Input string
663 function rcube_explode_quoted_string($delimiter, $string)
666 $strlen = strlen($string);
668 for ($q=$p=$i=0; $i < $strlen; $i++) {
669 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
670 $q = $q ? false : true;
672 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
673 $result[] = substr($string, $p, $i - $p);
678 $result[] = substr($string, $p);
684 * mbstring replacement functions
687 if (!extension_loaded('mbstring'))
689 function mb_strlen($str)
694 function mb_strtolower($str)
696 return strtolower($str);
699 function mb_strtoupper($str)
701 return strtoupper($str);
704 function mb_substr($str, $start, $len=null)
706 return substr($str, $start, $len);
709 function mb_strpos($haystack, $needle, $offset=0)
711 return strpos($haystack, $needle, $offset);
714 function mb_strrpos($haystack, $needle, $offset=0)
716 return strrpos($haystack, $needle, $offset);