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 1490 2008-06-07 18:48:59Z alec $
24 * RoundCube shared functions
31 * Provide details about the client's browser
33 * @return array Key-value pairs of browser properties
35 function rcube_browser()
37 $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
40 $bw['win'] = stristr($HTTP_USER_AGENT, 'win');
41 $bw['mac'] = stristr($HTTP_USER_AGENT, 'mac');
42 $bw['linux'] = stristr($HTTP_USER_AGENT, 'linux');
43 $bw['unix'] = stristr($HTTP_USER_AGENT, 'unix');
45 $bw['ns4'] = stristr($HTTP_USER_AGENT, 'mozilla/4') && !stristr($HTTP_USER_AGENT, 'msie');
46 $bw['ns'] = ($bw['ns4'] || stristr($HTTP_USER_AGENT, 'netscape'));
47 $bw['ie'] = stristr($HTTP_USER_AGENT, 'msie');
48 $bw['mz'] = stristr($HTTP_USER_AGENT, 'mozilla/5');
49 $bw['opera'] = stristr($HTTP_USER_AGENT, 'opera');
50 $bw['safari'] = stristr($HTTP_USER_AGENT, 'safari');
54 $test = eregi("mozilla\/([0-9\.]+)", $HTTP_USER_AGENT, $regs);
55 $bw['ver'] = $test ? (float)$regs[1] : 0;
59 $test = ereg("rv:([0-9\.]+)", $HTTP_USER_AGENT, $regs);
60 $bw['ver'] = $test ? (float)$regs[1] : 0;
64 $test = eregi("msie ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
65 $bw['ver'] = $test ? (float)$regs[1] : 0;
69 $test = eregi("opera ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
70 $bw['ver'] = $test ? (float)$regs[1] : 0;
73 if(eregi(" ([a-z]{2})-([a-z]{2})", $HTTP_USER_AGENT, $regs))
74 $bw['lang'] = $regs[1];
78 $bw['dom'] = ($bw['mz'] || $bw['safari'] || ($bw['ie'] && $bw['ver']>=5) || ($bw['opera'] && $bw['ver']>=7));
79 $bw['pngalpha'] = $bw['mz'] || $bw['safari'] || ($bw['ie'] && $bw['ver']>=5.5) ||
80 ($bw['ie'] && $bw['ver']>=5 && $bw['mac']) || ($bw['opera'] && $bw['ver']>=7) ? TRUE : FALSE;
87 * Send HTTP headers to prevent caching this page
89 function send_nocacheing_headers()
94 header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
95 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
96 header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
97 header("Pragma: no-cache");
102 * Send header with expire date 30 days in future
104 * @param int Expiration time in seconds
106 function send_future_expire_header($offset=2600000)
111 header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
112 header("Cache-Control: max-age=$offset");
118 * Check request for If-Modified-Since and send an according response.
119 * This will terminate the current script if headers match the given values
121 * @param int Modified date as unix timestamp
122 * @param string Etag value for caching
124 function send_modified_header($mdate, $etag=null, $skip_check=false)
130 $etag = $etag ? "\"$etag\"" : null;
134 if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
138 $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
142 header("HTTP/1.x 304 Not Modified");
144 header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
146 header("Cache-Control: max-age=0");
151 header("Etag: $etag");
162 * Convert a variable into a javascript object notation
164 * @param mixed Input value
165 * @return string Serialized JSON string
167 function json_serialize($var)
170 $var = get_object_vars($var);
179 $keys_arr = array_keys($var);
180 $is_assoc = $have_numeric = 0;
182 for ($i=0; $i<sizeof($keys_arr); ++$i)
184 if (is_numeric($keys_arr[$i]))
186 if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
188 if ($is_assoc && $have_numeric)
192 $brackets = $is_assoc ? '{}' : '[]';
195 foreach ($var as $key => $value)
197 // enclose key with quotes if it is not variable-name conform
198 if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) /* || is_js_reserved_word($key) */)
201 $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
204 return $brackets{0} . implode(',', $pairs) . $brackets{1};
207 else if (is_numeric($var) && strval(intval($var)) === strval($var))
209 else if (is_bool($var))
210 return $var ? '1' : '0';
212 return "'".JQ($var)."'";
217 * Function to convert an array to a javascript array
218 * Actually an alias function for json_serialize()
221 function array2js($arr, $type='')
223 return json_serialize($arr);
228 * Similar function as in_array() but case-insensitive
230 * @param mixed Needle value
231 * @param array Array to search in
232 * @return boolean True if found, False if not
234 function in_array_nocase($needle, $haystack)
236 foreach ($haystack as $value)
237 if (strtolower($needle)===strtolower($value))
245 * Find out if the string content means TRUE or FALSE
247 * @param string Input value
248 * @return boolean Imagine what!
250 function get_boolean($str)
252 $str = strtolower($str);
253 if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
261 * Parse a human readable string for a number of bytes
263 * @param string Input string
264 * @return int Number of bytes
266 function parse_bytes($str)
268 if (is_numeric($str))
271 if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
273 $bytes = floatval($regs[1]);
274 switch (strtolower($regs[2]))
277 $bytes *= 1073741824;
288 return intval($bytes);
292 * Create a human readable string for a number of bytes
294 * @param int Number of bytes
295 * @return string Byte string
297 function show_bytes($bytes)
299 if ($bytes > 1073741824)
301 $gb = $bytes/1073741824;
302 $str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
304 else if ($bytes > 1048576)
306 $mb = $bytes/1048576;
307 $str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
309 else if ($bytes > 1024)
310 $str = sprintf("%d KB", round($bytes/1024));
312 $str = sprintf('%d B', $bytes);
319 * Convert paths like ../xxx to an absolute path using a base url
321 * @param string Relative path
322 * @param string Base URL
323 * @return string Absolute URL
325 function make_absolute_url($path, $base_url)
327 $host_url = $base_url;
330 // check if path is an absolute URL
331 if (preg_match('/^[fhtps]+:\/\//', $path))
334 // cut base_url to the last directory
335 if (strpos($base_url, '/')>7)
337 $host_url = substr($base_url, 0, strpos($base_url, '/'));
338 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
343 $abs_path = $host_url.$path;
346 // strip './' because its the same as ''
347 $path = preg_replace('/^\.\//', '', $path);
349 if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
350 foreach ($matches as $a_match)
352 if (strrpos($base_url, '/'))
353 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
355 $path = substr($path, 3);
358 $abs_path = $base_url.'/'.$path;
366 * Wrapper function for strlen
368 function rc_strlen($str)
370 if (function_exists('mb_strlen'))
371 return mb_strlen($str);
377 * Wrapper function for strtolower
379 function rc_strtolower($str)
381 if (function_exists('mb_strtolower'))
382 return mb_strtolower($str);
384 return strtolower($str);
388 * Wrapper function for substr
390 function rc_substr($str, $start, $len=null)
392 if (function_exists('mb_substr'))
393 return mb_substr($str, $start, $len);
395 return substr($str, $start, $len);
399 * Wrapper function for strpos
401 function rc_strpos($haystack, $needle, $offset=0)
403 if (function_exists('mb_strpos'))
404 return mb_strpos($haystack, $needle, $offset);
406 return strpos($haystack, $needle, $offset);
410 * Wrapper function for strrpos
412 function rc_strrpos($haystack, $needle, $offset=0)
414 if (function_exists('mb_strrpos'))
415 return mb_strrpos($haystack, $needle, $offset);
417 return strrpos($haystack, $needle, $offset);
422 * Read a specific HTTP request header
425 * @param string $name Header name
426 * @return mixed Header value or null if not available
428 function rc_request_header($name)
430 if (function_exists('getallheaders'))
432 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
433 $key = strtoupper($name);
437 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
438 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
446 * Replace the middle part of a string with ...
447 * if it is longer than the allowed length
449 * @param string Input string
450 * @param int Max. length
451 * @param string Replace removed chars with this
452 * @return string Abbreviated string
454 function abbreviate_string($str, $maxlength, $place_holder='...')
456 $length = rc_strlen($str);
457 $first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
459 if ($length > $maxlength)
461 $second_starting_location = $length - $maxlength + $first_part_length + 1;
462 $str = rc_substr($str, 0, $first_part_length) . $place_holder . rc_substr($str, $second_starting_location, $length);
470 * Make sure the string ends with a slash
472 function slashify($str)
474 return unslashify($str).'/';
479 * Remove slash at the end of the string
481 function unslashify($str)
483 return preg_replace('/\/$/', '', $str);
488 * Delete all files within a folder
490 * @param string Path to directory
491 * @return boolean True on success, False if directory was not found
493 function clear_directory($dir_path)
495 $dir = @opendir($dir_path);
496 if(!$dir) return FALSE;
498 while ($file = readdir($dir))
500 unlink("$dir_path/$file");
508 * Create a unix timestamp with a specified offset from now
510 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
511 * @param int Factor to multiply with the offset
512 * @return int Unix timestamp
514 function get_offset_time($offset_str, $factor=1)
516 if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
518 $amount = (int)$regs[1];
519 $unit = strtolower($regs[2]);
523 $amount = (int)$offset_str;
539 $ts += $amount * $factor;
547 * A method to guess the mime_type of an attachment.
549 * @param string $path Path to the file.
550 * @param string $failover Mime type supplied for failover.
553 * @author Till Klampaeckel <till@php.net>
554 * @see http://de2.php.net/manual/en/ref.fileinfo.php
555 * @see http://de2.php.net/mime_content_type
557 function rc_mime_content_type($path, $failover = 'unknown/unknown')
561 $mime_magic = $CONFIG['mime_magic'];
563 if (function_exists('mime_content_type')) {
564 return mime_content_type($path);
566 if (!extension_loaded('fileinfo')) {
567 if (!dl('fileinfo.' . PHP_SHLIB_SUFFIX)) {
571 $finfo = finfo_open(FILEINFO_MIME, $mime_magic);
575 $mime_type = finfo_file($finfo,$path);
586 * A method to guess encoding of a string.
588 * @param string $string String.
589 * @param string $failover Default result for failover.
593 function rc_detect_encoding($string, $failover='')
595 if (!function_exists('mb_detect_encoding')) {
599 // FIXME: the order is important, because sometimes
600 // iso string is detected as euc-jp and etc.
602 'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
603 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
604 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
605 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R'
608 $result = mb_detect_encoding($string, join(',', $enc));
610 return $result ? $result : $failover;