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 839 2007-09-29 18:15:05Z thomasb $
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 * Get localized text in the desired language
89 * @param mixed Named parameters array or label name
90 * @return string Localized text
92 function rcube_label($attrib)
94 global $sess_user_lang, $INSTALL_PATH, $OUTPUT;
95 static $sa_text_data, $s_language, $utf8_decode;
98 if (is_string($attrib))
99 $attrib = array('name' => $attrib);
101 $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
102 $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
104 $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
105 $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
108 // load localized texts
109 if (!$sa_text_data || $s_language != $sess_user_lang)
111 $sa_text_data = array();
113 // get english labels (these should be complete)
114 @include($INSTALL_PATH.'program/localization/en_US/labels.inc');
115 @include($INSTALL_PATH.'program/localization/en_US/messages.inc');
117 if (is_array($labels))
118 $sa_text_data = $labels;
119 if (is_array($messages))
120 $sa_text_data = array_merge($sa_text_data, $messages);
122 // include user language files
123 if ($sess_user_lang!='en' && is_dir($INSTALL_PATH.'program/localization/'.$sess_user_lang))
125 include_once($INSTALL_PATH.'program/localization/'.$sess_user_lang.'/labels.inc');
126 include_once($INSTALL_PATH.'program/localization/'.$sess_user_lang.'/messages.inc');
128 if (is_array($labels))
129 $sa_text_data = array_merge($sa_text_data, $labels);
130 if (is_array($messages))
131 $sa_text_data = array_merge($sa_text_data, $messages);
134 $s_language = $sess_user_lang;
137 // text does not exist
138 if (!($text_item = $sa_text_data[$alias]))
146 'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
151 // make text item array
152 $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
154 // decide which text to use
156 $text = $a_text_item['single'];
158 $text = $a_text_item['multiple'];
161 if ($a_text_item['none'])
162 $text = $a_text_item['none'];
163 else if ($a_text_item['single'])
164 $text = $a_text_item['single'];
165 else if ($a_text_item['multiple'])
166 $text = $a_text_item['multiple'];
169 // default text is single
171 $text = $a_text_item['single'];
173 // replace vars in text
174 if (is_array($attrib['vars']))
176 foreach ($attrib['vars'] as $var_key=>$var_value)
177 $a_replace_vars[substr($var_key, 0, 1)=='$' ? substr($var_key, 1) : $var_key] = $var_value;
181 $text = preg_replace('/\${?([_a-z]{1}[_a-z0-9]*)}?/ei', '$a_replace_vars["\1"]', $text);
183 // remove variables in text which were not available in arg $vars and $nr
184 eval("\$text = <<<EOF
190 if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
191 return ucfirst($text);
192 else if ($attrib['uppercase'])
193 return strtoupper($text);
194 else if ($attrib['lowercase'])
195 return strtolower($text);
202 * Send HTTP headers to prevent caching this page
204 function send_nocacheing_headers()
209 header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
210 header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
211 header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
212 header("Pragma: no-cache");
217 * Send header with expire date 30 days in future
219 * @param int Expiration time in seconds
221 function send_future_expire_header($offset=2600000)
226 header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
227 header("Cache-Control: max-age=$offset");
233 * Check request for If-Modified-Since and send an according response.
234 * This will terminate the current script if headers match the given values
236 * @param int Modified date as unix timestamp
237 * @param string Etag value for caching
239 function send_modified_header($mdate, $etag=null)
245 if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
248 $etag = $etag ? "\"$etag\"" : null;
249 if ($etag && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag)
253 header("HTTP/1.x 304 Not Modified");
255 header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
257 header("Cache-Control: max-age=0");
262 header("Etag: $etag");
270 * Convert a variable into a javascript object notation
272 * @param mixed Input value
273 * @return string Serialized JSON string
275 function json_serialize($var)
278 $var = get_object_vars($var);
287 $keys_arr = array_keys($var);
288 $is_assoc = $have_numeric = 0;
290 for ($i=0; $i<sizeof($keys_arr); ++$i)
292 if (is_numeric($keys_arr[$i]))
294 if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
296 if ($is_assoc && $have_numeric)
300 $brackets = $is_assoc ? '{}' : '[]';
303 foreach ($var as $key => $value)
305 // enclose key with quotes if it is not variable-name conform
306 if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) /* || is_js_reserved_word($key) */)
309 $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
312 return $brackets{0} . implode(',', $pairs) . $brackets{1};
315 else if (is_numeric($var) && strval(intval($var)) === strval($var))
317 else if (is_bool($var))
318 return $var ? '1' : '0';
320 return "'".JQ($var)."'";
325 * Function to convert an array to a javascript array
326 * Actually an alias function for json_serialize()
329 function array2js($arr, $type='')
331 return json_serialize($arr);
336 * Similar function as in_array() but case-insensitive
338 * @param mixed Needle value
339 * @param array Array to search in
340 * @return boolean True if found, False if not
342 function in_array_nocase($needle, $haystack)
344 foreach ($haystack as $value)
345 if (strtolower($needle)===strtolower($value))
353 * Find out if the string content means TRUE or FALSE
355 * @param string Input value
356 * @return boolean Imagine what!
358 function get_boolean($str)
360 $str = strtolower($str);
361 if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
369 * Parse a human readable string for a number of bytes
371 * @param string Input string
372 * @return int Number of bytes
374 function parse_bytes($str)
376 if (is_numeric($str))
379 if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
381 $bytes = floatval($regs[1]);
382 switch (strtolower($regs[2]))
385 $bytes *= 1073741824;
396 return intval($bytes);
400 * Create a human readable string for a number of bytes
402 * @param int Number of bytes
403 * @return string Byte string
405 function show_bytes($bytes)
407 if ($bytes > 1073741824)
409 $gb = $bytes/1073741824;
410 $str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
412 else if ($bytes > 1048576)
414 $mb = $bytes/1048576;
415 $str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
417 else if ($bytes > 1024)
418 $str = sprintf("%d KB", round($bytes/1024));
420 $str = sprintf('%d B', $bytes);
427 * Convert paths like ../xxx to an absolute path using a base url
429 * @param string Relative path
430 * @param string Base URL
431 * @return string Absolute URL
433 function make_absolute_url($path, $base_url)
435 $host_url = $base_url;
438 // check if path is an absolute URL
439 if (preg_match('/^[fhtps]+:\/\//', $path))
442 // cut base_url to the last directory
443 if (strpos($base_url, '/')>7)
445 $host_url = substr($base_url, 0, strpos($base_url, '/'));
446 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
451 $abs_path = $host_url.$path;
454 // strip './' because its the same as ''
455 $path = preg_replace('/^\.\//', '', $path);
457 if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
458 foreach ($matches as $a_match)
460 if (strrpos($base_url, '/'))
461 $base_url = substr($base_url, 0, strrpos($base_url, '/'));
463 $path = substr($path, 3);
466 $abs_path = $base_url.'/'.$path;
474 * Wrapper function for strlen
476 function rc_strlen($str)
478 if (function_exists('mb_strlen'))
479 return mb_strlen($str);
485 * Wrapper function for strtolower
487 function rc_strtolower($str)
489 if (function_exists('mb_strtolower'))
490 return mb_strtolower($str);
492 return strtolower($str);
496 * Wrapper function for substr
498 function rc_substr($str, $start, $len=null)
500 if (function_exists('mb_substr'))
501 return mb_substr($str, $start, $len);
503 return substr($str, $start, $len);
507 * Wrapper function for strpos
509 function rc_strpos($haystack, $needle, $offset=0)
511 if (function_exists('mb_strpos'))
512 return mb_strpos($haystack, $needle, $offset);
514 return strpos($haystack, $needle, $offset);
518 * Wrapper function for strrpos
520 function rc_strrpos($haystack, $needle, $offset=0)
522 if (function_exists('mb_strrpos'))
523 return mb_strrpos($haystack, $needle, $offset);
525 return strrpos($haystack, $needle, $offset);
530 * Read a specific HTTP request header
533 * @param string $name Header name
534 * @return mixed Header value or null if not available
536 function rc_request_header($name)
538 if (function_exists('getallheaders'))
540 $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
541 $key = strtoupper($name);
545 $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
546 $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
554 * Replace the middle part of a string with ...
555 * if it is longer than the allowed length
557 * @param string Input string
558 * @param int Max. length
559 * @param string Replace removed chars with this
560 * @return string Abbrevated string
562 function abbrevate_string($str, $maxlength, $place_holder='...')
564 $length = rc_strlen($str);
565 $first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
567 if ($length > $maxlength)
569 $second_starting_location = $length - $maxlength + $first_part_length + 1;
570 $str = rc_substr($str, 0, $first_part_length) . $place_holder . rc_substr($str, $second_starting_location, $length);
578 * Make sure the string ends with a slash
580 function slashify($str)
582 return unslashify($str).'/';
587 * Remove slash at the end of the string
589 function unslashify($str)
591 return preg_replace('/\/$/', '', $str);
596 * Delete all files within a folder
598 * @param string Path to directory
599 * @return boolean True on success, False if directory was not found
601 function clear_directory($dir_path)
603 $dir = @opendir($dir_path);
604 if(!$dir) return FALSE;
606 while ($file = readdir($dir))
608 unlink("$dir_path/$file");
616 * Create a unix timestamp with a specified offset from now
618 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
619 * @param int Factor to multiply with the offset
620 * @return int Unix timestamp
622 function get_offset_time($offset_str, $factor=1)
624 if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
626 $amount = (int)$regs[1];
627 $unit = strtolower($regs[2]);
631 $amount = (int)$offset_str;
647 $ts += $amount * $factor;
655 * Return the last occurence of a string in another string
657 * @param haystack string string in which to search
658 * @param needle string string for which to search
659 * @return index of needle within haystack, or false if not found
661 function strrstr($haystack, $needle)
663 $pver = phpversion();
665 return strrpos($haystack, $needle);
668 $index = strpos(strrev($haystack), strrev($needle));
672 $index = strlen($haystack) - strlen($needle) - $index;