]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_shared.inc
Imported Upstream version 0.2~alpha
[roundcube.git] / program / include / rcube_shared.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | rcube_shared.inc                                                      |
6  |                                                                       |
7  | This file is part of the RoundCube PHP suite                          |
8  | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | CONTENTS:                                                             |
12  |   Shared functions and classes used in PHP projects                   |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: rcube_shared.inc 1490 2008-06-07 18:48:59Z alec $
19
20 */
21
22
23 /**
24  * RoundCube shared functions
25  * 
26  * @package Core
27  */
28
29
30 /**
31  * Provide details about the client's browser
32  *
33  * @return array Key-value pairs of browser properties
34  */
35 function rcube_browser()
36 {
37   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
38
39   $bw['ver'] = 0;
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');
44
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');
51
52   if($bw['ns'])
53   {
54     $test = eregi("mozilla\/([0-9\.]+)", $HTTP_USER_AGENT, $regs);
55     $bw['ver'] = $test ? (float)$regs[1] : 0;
56   }
57   if($bw['mz'])
58   {
59     $test = ereg("rv:([0-9\.]+)", $HTTP_USER_AGENT, $regs);
60     $bw['ver'] = $test ? (float)$regs[1] : 0;
61   }
62   if($bw['ie'])
63   {
64     $test = eregi("msie ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
65     $bw['ver'] = $test ? (float)$regs[1] : 0;
66   }
67   if($bw['opera'])
68   {
69     $test = eregi("opera ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
70     $bw['ver'] = $test ? (float)$regs[1] : 0;
71   }
72
73   if(eregi(" ([a-z]{2})-([a-z]{2})", $HTTP_USER_AGENT, $regs))
74     $bw['lang'] =  $regs[1];
75   else
76     $bw['lang'] =  'en';
77
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;
81
82   return $bw;
83 }
84
85
86 /**
87  * Send HTTP headers to prevent caching this page
88  */
89 function send_nocacheing_headers()
90 {
91   if (headers_sent())
92     return;
93
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");
98 }
99
100
101 /**
102  * Send header with expire date 30 days in future
103  *
104  * @param int Expiration time in seconds
105  */
106 function send_future_expire_header($offset=2600000)
107 {
108   if (headers_sent())
109     return;
110
111   header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
112   header("Cache-Control: max-age=$offset");
113   header("Pragma: ");
114 }
115
116
117 /**
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
120  *
121  * @param int Modified date as unix timestamp
122  * @param string Etag value for caching
123  */
124 function send_modified_header($mdate, $etag=null, $skip_check=false)
125 {
126   if (headers_sent())
127     return;
128     
129   $iscached = false;
130   $etag = $etag ? "\"$etag\"" : null;
131
132   if (!$skip_check)
133   {
134     if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
135       $iscached = true;
136   
137     if ($etag)
138       $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
139   }
140   
141   if ($iscached)
142     header("HTTP/1.x 304 Not Modified");
143   else
144     header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
145   
146   header("Cache-Control: max-age=0");
147   header("Expires: ");
148   header("Pragma: ");
149   
150   if ($etag)
151     header("Etag: $etag");
152   
153   if ($iscached)
154     {
155     ob_end_clean();
156     exit;
157     }
158 }
159
160
161 /**
162  * Convert a variable into a javascript object notation
163  *
164  * @param mixed Input value
165  * @return string Serialized JSON string
166  */
167 function json_serialize($var)
168 {
169   if (is_object($var))
170     $var = get_object_vars($var);
171
172   if (is_array($var))
173   {
174     // empty array
175     if (!sizeof($var))
176       return '[]';
177     else
178     {
179       $keys_arr = array_keys($var);
180       $is_assoc = $have_numeric = 0;
181
182       for ($i=0; $i<sizeof($keys_arr); ++$i)
183       {
184         if (is_numeric($keys_arr[$i]))
185           $have_numeric = 1;
186         if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
187           $is_assoc = 1;
188         if ($is_assoc && $have_numeric)
189           break;
190       }
191       
192       $brackets = $is_assoc ? '{}' : '[]';
193       $pairs = array();
194
195       foreach ($var as $key => $value)
196       {
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) */)
199           $key = "'$key'";
200
201         $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
202       }
203
204       return $brackets{0} . implode(',', $pairs) . $brackets{1};
205     }
206   }
207   else if (is_numeric($var) && strval(intval($var)) === strval($var))
208     return $var;
209   else if (is_bool($var))
210     return $var ? '1' : '0';
211   else
212     return "'".JQ($var)."'";
213
214 }
215
216 /**
217  * Function to convert an array to a javascript array
218  * Actually an alias function for json_serialize()
219  * @deprecated
220  */
221 function array2js($arr, $type='')
222 {
223   return json_serialize($arr);
224 }
225
226
227 /**
228  * Similar function as in_array() but case-insensitive
229  *
230  * @param mixed Needle value
231  * @param array Array to search in
232  * @return boolean True if found, False if not
233  */
234 function in_array_nocase($needle, $haystack)
235 {
236   foreach ($haystack as $value)
237     if (strtolower($needle)===strtolower($value))
238       return true;
239   
240   return false;
241 }
242
243
244 /**
245  * Find out if the string content means TRUE or FALSE
246  *
247  * @param string Input value
248  * @return boolean Imagine what!
249  */
250 function get_boolean($str)
251 {
252   $str = strtolower($str);
253   if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
254     return FALSE;
255   else
256     return TRUE;
257 }
258
259
260 /**
261  * Parse a human readable string for a number of bytes
262  *
263  * @param string Input string
264  * @return int Number of bytes
265  */
266 function parse_bytes($str)
267 {
268   if (is_numeric($str))
269     return intval($str);
270     
271   if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
272   {
273     $bytes = floatval($regs[1]);
274     switch (strtolower($regs[2]))
275     {
276       case 'g':
277         $bytes *= 1073741824;
278         break;
279       case 'm':
280         $bytes *= 1048576;
281         break;
282       case 'k':
283         $bytes *= 1024;
284         break;
285     }
286   }
287
288   return intval($bytes);
289 }
290     
291 /**
292  * Create a human readable string for a number of bytes
293  *
294  * @param int Number of bytes
295  * @return string Byte string
296  */
297 function show_bytes($bytes)
298 {
299   if ($bytes > 1073741824)
300   {
301     $gb = $bytes/1073741824;
302     $str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
303   }
304   else if ($bytes > 1048576)
305   {
306     $mb = $bytes/1048576;
307     $str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
308   }
309   else if ($bytes > 1024)
310     $str = sprintf("%d KB",  round($bytes/1024));
311   else
312     $str = sprintf('%d B', $bytes);
313
314   return $str;
315 }
316
317
318 /**
319  * Convert paths like ../xxx to an absolute path using a base url
320  *
321  * @param string Relative path
322  * @param string Base URL
323  * @return string Absolute URL
324  */
325 function make_absolute_url($path, $base_url)
326 {
327   $host_url = $base_url;
328   $abs_path = $path;
329   
330   // check if path is an absolute URL
331   if (preg_match('/^[fhtps]+:\/\//', $path))
332     return $path;
333
334   // cut base_url to the last directory
335   if (strpos($base_url, '/')>7)
336   {
337     $host_url = substr($base_url, 0, strpos($base_url, '/'));
338     $base_url = substr($base_url, 0, strrpos($base_url, '/'));
339   }
340
341   // $path is absolute
342   if ($path{0}=='/')
343     $abs_path = $host_url.$path;
344   else
345   {
346     // strip './' because its the same as ''
347     $path = preg_replace('/^\.\//', '', $path);
348
349     if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
350       foreach ($matches as $a_match)
351       {
352         if (strrpos($base_url, '/'))
353           $base_url = substr($base_url, 0, strrpos($base_url, '/'));
354         
355         $path = substr($path, 3);
356       }
357
358     $abs_path = $base_url.'/'.$path;
359   }
360     
361   return $abs_path;
362 }
363
364
365 /**
366  * Wrapper function for strlen
367  */
368 function rc_strlen($str)
369 {
370   if (function_exists('mb_strlen'))
371     return mb_strlen($str);
372   else
373     return strlen($str);
374 }
375   
376 /**
377  * Wrapper function for strtolower
378  */
379 function rc_strtolower($str)
380 {
381   if (function_exists('mb_strtolower'))
382     return mb_strtolower($str);
383   else
384     return strtolower($str);
385 }
386
387 /**
388  * Wrapper function for substr
389  */
390 function rc_substr($str, $start, $len=null)
391 {
392   if (function_exists('mb_substr'))
393     return mb_substr($str, $start, $len);
394   else
395     return substr($str, $start, $len);
396 }
397
398 /**
399  * Wrapper function for strpos
400  */
401 function rc_strpos($haystack, $needle, $offset=0)
402 {
403   if (function_exists('mb_strpos'))
404     return mb_strpos($haystack, $needle, $offset);
405   else
406     return strpos($haystack, $needle, $offset);
407 }
408
409 /**
410  * Wrapper function for strrpos
411  */
412 function rc_strrpos($haystack, $needle, $offset=0)
413 {
414   if (function_exists('mb_strrpos'))
415     return mb_strrpos($haystack, $needle, $offset);
416   else
417     return strrpos($haystack, $needle, $offset);
418 }
419
420
421 /**
422  * Read a specific HTTP request header
423  *
424  * @access static
425  * @param  string $name Header name
426  * @return mixed  Header value or null if not available
427  */
428 function rc_request_header($name)
429 {
430   if (function_exists('getallheaders'))
431   {
432     $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
433     $key  = strtoupper($name);
434   }
435   else
436   {
437     $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
438     $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
439   }
440
441   return $hdrs[$key];
442   }
443
444
445 /**
446  * Replace the middle part of a string with ...
447  * if it is longer than the allowed length
448  *
449  * @param string Input string
450  * @param int    Max. length
451  * @param string Replace removed chars with this
452  * @return string Abbreviated string
453  */
454 function abbreviate_string($str, $maxlength, $place_holder='...')
455 {
456   $length = rc_strlen($str);
457   $first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
458   
459   if ($length > $maxlength)
460   {
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);
463   }
464
465   return $str;
466 }
467
468
469 /**
470  * Make sure the string ends with a slash
471  */
472 function slashify($str)
473 {
474   return unslashify($str).'/';
475 }
476
477
478 /**
479  * Remove slash at the end of the string
480  */
481 function unslashify($str)
482 {
483   return preg_replace('/\/$/', '', $str);
484 }
485   
486
487 /**
488  * Delete all files within a folder
489  *
490  * @param string Path to directory
491  * @return boolean True on success, False if directory was not found
492  */
493 function clear_directory($dir_path)
494 {
495   $dir = @opendir($dir_path);
496   if(!$dir) return FALSE;
497
498   while ($file = readdir($dir))
499     if (strlen($file)>2)
500       unlink("$dir_path/$file");
501
502   closedir($dir);
503   return TRUE;
504 }
505
506
507 /**
508  * Create a unix timestamp with a specified offset from now
509  *
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
513  */
514 function get_offset_time($offset_str, $factor=1)
515   {
516   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
517   {
518     $amount = (int)$regs[1];
519     $unit = strtolower($regs[2]);
520   }
521   else
522   {
523     $amount = (int)$offset_str;
524     $unit = 's';
525   }
526     
527   $ts = mktime();
528   switch ($unit)
529   {
530     case 'w':
531       $amount *= 7;
532     case 'd':
533       $amount *= 24;
534     case 'h':
535       $amount *= 60;
536     case 'm':
537       $amount *= 60;
538     case 's':
539       $ts += $amount * $factor;
540   }
541
542   return $ts;
543 }
544
545
546 /**
547  * A method to guess the mime_type of an attachment.
548  *
549  * @param string $path     Path to the file.
550  * @param string $failover Mime type supplied for failover.
551  *
552  * @return string
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
556  */
557 function rc_mime_content_type($path, $failover = 'unknown/unknown')
558 {
559     global $CONFIG;
560
561     $mime_magic = $CONFIG['mime_magic'];
562
563     if (function_exists('mime_content_type')) {
564         return mime_content_type($path);
565     }
566     if (!extension_loaded('fileinfo')) { 
567         if (!dl('fileinfo.' . PHP_SHLIB_SUFFIX)) {
568             return $failover;
569         }
570     }
571     $finfo = finfo_open(FILEINFO_MIME, $mime_magic);
572     if (!$finfo) {
573         return $failover;
574     }
575     $mime_type = finfo_file($finfo,$path);
576     if (!$mime_type) {
577         return $failover;
578     }
579     finfo_close($finfo);
580
581     return $mime_type;
582 }
583
584
585 /**
586  * A method to guess encoding of a string.
587  *
588  * @param string $string        String.
589  * @param string $failover      Default result for failover.
590  *
591  * @return string
592  */
593 function rc_detect_encoding($string, $failover='')
594 {
595     if (!function_exists('mb_detect_encoding')) {
596         return $failover;
597     }
598
599     // FIXME: the order is important, because sometimes 
600     // iso string is detected as euc-jp and etc.
601     $enc = array(
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'
606     );
607
608     $result = mb_detect_encoding($string, join(',', $enc));
609
610     return $result ? $result : $failover;
611 }
612
613 ?>