alecpl
2008-08-29 53bd8fae60e1663447efba9f44fc6b79b3a5c1de
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | rcube_shared.inc                                                      |
6  |                                                                       |
7  | This file is part of the RoundCube PHP suite                          |
f11541 8  | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland                 |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | CONTENTS:                                                             |
12  |   Shared functions and classes used in PHP projects                   |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id$
19
20 */
21
22
6d969b 23 /**
T 24  * RoundCube shared functions
25  * 
26  * @package Core
27  */
4e17e6 28
a0109c 29
6d969b 30 /**
T 31  * Provide details about the client's browser
32  *
33  * @return array Key-value pairs of browser properties
34  */
4e17e6 35 function rcube_browser()
6d969b 36 {
de2e1e 37   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
4e17e6 38
T 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'])
6d969b 53   {
4e17e6 54     $test = eregi("mozilla\/([0-9\.]+)", $HTTP_USER_AGENT, $regs);
T 55     $bw['ver'] = $test ? (float)$regs[1] : 0;
6d969b 56   }
4e17e6 57   if($bw['mz'])
6d969b 58   {
4e17e6 59     $test = ereg("rv:([0-9\.]+)", $HTTP_USER_AGENT, $regs);
T 60     $bw['ver'] = $test ? (float)$regs[1] : 0;
6d969b 61   }
4e17e6 62   if($bw['ie'])
6d969b 63   {
4e17e6 64     $test = eregi("msie ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
T 65     $bw['ver'] = $test ? (float)$regs[1] : 0;
6d969b 66   }
4e17e6 67   if($bw['opera'])
6d969b 68   {
4e17e6 69     $test = eregi("opera ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
T 70     $bw['ver'] = $test ? (float)$regs[1] : 0;
6d969b 71   }
4e17e6 72
T 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;
6d969b 83 }
4e17e6 84
T 85
6d969b 86 /**
T 87  * Send HTTP headers to prevent caching this page
88  */
4e17e6 89 function send_nocacheing_headers()
6d969b 90 {
4e17e6 91   if (headers_sent())
T 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");
6d969b 98 }
4e17e6 99
T 100
6d969b 101 /**
T 102  * Send header with expire date 30 days in future
103  *
104  * @param int Expiration time in seconds
105  */
ff52be 106 function send_future_expire_header($offset=2600000)
6d969b 107 {
1a98a6 108   if (headers_sent())
T 109     return;
110
ff52be 111   header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
T 112   header("Cache-Control: max-age=$offset");
1a98a6 113   header("Pragma: ");
6d969b 114 }
4e17e6 115
T 116
6d969b 117 /**
T 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  */
3f5cef 124 function send_modified_header($mdate, $etag=null, $skip_check=false)
ff52be 125 {
T 126   if (headers_sent())
127     return;
128     
129   $iscached = false;
130   $etag = $etag ? "\"$etag\"" : null;
3f5cef 131
A 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   }
ff52be 140   
T 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)
1b4d73 154     {
T 155     ob_end_clean();
ff52be 156     exit;
1b4d73 157     }
ff52be 158 }
T 159
160
f11541 161 /**
6d969b 162  * Convert a variable into a javascript object notation
T 163  *
164  * @param mixed Input value
165  * @return string Serialized JSON string
f11541 166  */
T 167 function json_serialize($var)
6d969b 168 {
T 169   if (is_object($var))
170     $var = get_object_vars($var);
171
172   if (is_array($var))
4e17e6 173   {
6d969b 174     // empty array
T 175     if (!sizeof($var))
176       return '[]';
f11541 177     else
6d969b 178     {
T 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     }
f11541 206   }
6d969b 207   else if (is_numeric($var) && strval(intval($var)) === strval($var))
T 208     return $var;
209   else if (is_bool($var))
210     return $var ? '1' : '0';
211   else
212     return "'".JQ($var)."'";
213
214 }
f11541 215
T 216 /**
6d969b 217  * Function to convert an array to a javascript array
T 218  * Actually an alias function for json_serialize()
f11541 219  * @deprecated
T 220  */
221 function array2js($arr, $type='')
6d969b 222 {
f11541 223   return json_serialize($arr);
6d969b 224 }
4e17e6 225
T 226
f11541 227 /**
T 228  * Similar function as in_array() but case-insensitive
6d969b 229  *
T 230  * @param mixed Needle value
231  * @param array Array to search in
232  * @return boolean True if found, False if not
f11541 233  */
4e17e6 234 function in_array_nocase($needle, $haystack)
6d969b 235 {
4e17e6 236   foreach ($haystack as $value)
T 237     if (strtolower($needle)===strtolower($value))
6d969b 238       return true;
T 239   
240   return false;
241 }
4e17e6 242
T 243
f11541 244 /**
T 245  * Find out if the string content means TRUE or FALSE
6d969b 246  *
T 247  * @param string Input value
248  * @return boolean Imagine what!
f11541 249  */
4e17e6 250 function get_boolean($str)
6d969b 251 {
4e17e6 252   $str = strtolower($str);
T 253   if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
254     return FALSE;
255   else
256     return TRUE;
6d969b 257 }
4e17e6 258
T 259
6d969b 260 /**
T 261  * Parse a human readable string for a number of bytes
262  *
263  * @param string Input string
264  * @return int Number of bytes
265  */
86df15 266 function parse_bytes($str)
6d969b 267 {
86df15 268   if (is_numeric($str))
T 269     return intval($str);
270     
271   if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
6d969b 272   {
T 273     $bytes = floatval($regs[1]);
274     switch (strtolower($regs[2]))
86df15 275     {
6d969b 276       case 'g':
T 277         $bytes *= 1073741824;
278         break;
279       case 'm':
280         $bytes *= 1048576;
281         break;
282       case 'k':
283         $bytes *= 1024;
284         break;
86df15 285     }
6d969b 286   }
86df15 287
T 288   return intval($bytes);
6d969b 289 }
86df15 290     
6d969b 291 /**
T 292  * Create a human readable string for a number of bytes
293  *
294  * @param int Number of bytes
295  * @return string Byte string
296  */
3ea0e3 297 function show_bytes($bytes)
6d969b 298 {
3ea0e3 299   if ($bytes > 1073741824)
6d969b 300   {
3ea0e3 301     $gb = $bytes/1073741824;
T 302     $str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
6d969b 303   }
3ea0e3 304   else if ($bytes > 1048576)
6d969b 305   {
3ea0e3 306     $mb = $bytes/1048576;
T 307     $str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
6d969b 308   }
3ea0e3 309   else if ($bytes > 1024)
T 310     $str = sprintf("%d KB",  round($bytes/1024));
4e17e6 311   else
3ea0e3 312     $str = sprintf('%d B', $bytes);
T 313
314   return $str;
6d969b 315 }
4e17e6 316
T 317
6d969b 318 /**
T 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  */
4e17e6 325 function make_absolute_url($path, $base_url)
6d969b 326 {
T 327   $host_url = $base_url;
328   $abs_path = $path;
97bd2c 329   
T 330   // check if path is an absolute URL
331   if (preg_match('/^[fhtps]+:\/\//', $path))
332     return $path;
4e17e6 333
6d969b 334   // cut base_url to the last directory
T 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)
4e17e6 351       {
6d969b 352         if (strrpos($base_url, '/'))
T 353           $base_url = substr($base_url, 0, strrpos($base_url, '/'));
354         
355         $path = substr($path, 3);
4e17e6 356       }
T 357
6d969b 358     $abs_path = $base_url.'/'.$path;
T 359   }
360     
361   return $abs_path;
362 }
4e17e6 363
T 364
6d969b 365 /**
T 366  * Wrapper function for strlen
367  */
86df15 368 function rc_strlen($str)
6d969b 369 {
T 370   if (function_exists('mb_strlen'))
371     return mb_strlen($str);
372   else
373     return strlen($str);
374 }
86df15 375   
6d969b 376 /**
T 377  * Wrapper function for strtolower
378  */
86df15 379 function rc_strtolower($str)
6d969b 380 {
T 381   if (function_exists('mb_strtolower'))
382     return mb_strtolower($str);
383   else
384     return strtolower($str);
385 }
86df15 386
6d969b 387 /**
T 388  * Wrapper function for substr
389  */
f11541 390 function rc_substr($str, $start, $len=null)
6d969b 391 {
86df15 392   if (function_exists('mb_substr'))
T 393     return mb_substr($str, $start, $len);
394   else
395     return substr($str, $start, $len);
6d969b 396 }
86df15 397
6d969b 398 /**
T 399  * Wrapper function for strpos
400  */
86df15 401 function rc_strpos($haystack, $needle, $offset=0)
6d969b 402 {
86df15 403   if (function_exists('mb_strpos'))
T 404     return mb_strpos($haystack, $needle, $offset);
405   else
406     return strpos($haystack, $needle, $offset);
6d969b 407 }
86df15 408
6d969b 409 /**
T 410  * Wrapper function for strrpos
411  */
86df15 412 function rc_strrpos($haystack, $needle, $offset=0)
6d969b 413 {
86df15 414   if (function_exists('mb_strrpos'))
T 415     return mb_strrpos($haystack, $needle, $offset);
416   else
417     return strrpos($haystack, $needle, $offset);
6d969b 418 }
86df15 419
T 420
6d969b 421 /**
88f66e 422  * Read a specific HTTP request header
T 423  *
0144c5 424  * @access static
T 425  * @param  string $name Header name
426  * @return mixed  Header value or null if not available
88f66e 427  */
T 428 function rc_request_header($name)
5a6eff 429 {
88f66e 430   if (function_exists('getallheaders'))
5a6eff 431   {
T 432     $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
0144c5 433     $key  = strtoupper($name);
5a6eff 434   }
88f66e 435   else
5a6eff 436   {
0144c5 437     $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
db401b 438     $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
5a6eff 439   }
T 440
441   return $hdrs[$key];
88f66e 442   }
T 443
444
445 /**
6d969b 446  * Replace the middle part of a string with ...
T 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
6f2f2d 452  * @return string Abbreviated string
6d969b 453  */
6f2f2d 454 function abbreviate_string($str, $maxlength, $place_holder='...')
6d969b 455 {
86df15 456   $length = rc_strlen($str);
T 457   $first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
9fee0e 458   
T 459   if ($length > $maxlength)
6d969b 460   {
9fee0e 461     $second_starting_location = $length - $maxlength + $first_part_length + 1;
86df15 462     $str = rc_substr($str, 0, $first_part_length) . $place_holder . rc_substr($str, $second_starting_location, $length);
6d969b 463   }
9fee0e 464
T 465   return $str;
6d969b 466 }
1cded8 467
T 468
6d969b 469 /**
T 470  * Make sure the string ends with a slash
471  */
bac7d1 472 function slashify($str)
6d969b 473 {
bac7d1 474   return unslashify($str).'/';
6d969b 475 }
bac7d1 476
T 477
6d969b 478 /**
T 479  * Remove slash at the end of the string
480  */
bac7d1 481 function unslashify($str)
6d969b 482 {
bac7d1 483   return preg_replace('/\/$/', '', $str);
6d969b 484 }
bac7d1 485   
T 486
6d969b 487 /**
T 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  */
1cded8 493 function clear_directory($dir_path)
6d969b 494 {
1cded8 495   $dir = @opendir($dir_path);
T 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;
6d969b 504 }
9fee0e 505
T 506
6d969b 507 /**
T 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  */
cc9570 514 function get_offset_time($offset_str, $factor=1)
T 515   {
516   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
6d969b 517   {
cc9570 518     $amount = (int)$regs[1];
T 519     $unit = strtolower($regs[2]);
6d969b 520   }
cc9570 521   else
6d969b 522   {
cc9570 523     $amount = (int)$offset_str;
T 524     $unit = 's';
6d969b 525   }
cc9570 526     
T 527   $ts = mktime();
528   switch ($unit)
6d969b 529   {
cc9570 530     case 'w':
T 531       $amount *= 7;
532     case 'd':
533       $amount *= 24;
534     case 'h':
535       $amount *= 60;
bd4959 536     case 'm':
cc9570 537       $amount *= 60;
T 538     case 's':
539       $ts += $amount * $factor;
6d969b 540   }
cc9570 541
T 542   return $ts;
6d969b 543 }
cc9570 544
T 545
a0109c 546 /**
734584 547  * A method to guess the mime_type of an attachment.
T 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 {
6d5dba 559     $mime_type = null;
T 560     $mime_magic = rcmail::get_instance()->config->get('mime_magic');
a0109c 561
6d5dba 562     if (!extension_loaded('fileinfo')) {
T 563         @dl('fileinfo.' . PHP_SHLIB_SUFFIX);
734584 564     }
6d5dba 565
T 566     if (function_exists('finfo_open')) {
567         if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
568             $mime_type = finfo_file($finfo, $path);
569             finfo_close($finfo);
734584 570         }
T 571     }
6d5dba 572     else if (function_exists('mime_content_type')) {
T 573       $mime_type = mime_content_type($path); 
574     }
403e3f 575     
734584 576     if (!$mime_type) {
6d5dba 577         $mime_type = $failover;
734584 578     }
T 579
580     return $mime_type;
581 }
582
b54121 583
A 584 /**
585  * A method to guess encoding of a string.
586  *
587  * @param string $string         String.
588  * @param string $failover     Default result for failover.
589  *
590  * @return string
591  */
592 function rc_detect_encoding($string, $failover='')
593 {
594     if (!function_exists('mb_detect_encoding')) {
595         return $failover;
596     }
597
598     // FIXME: the order is important, because sometimes 
599     // iso string is detected as euc-jp and etc.
600     $enc = array(
601     'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
602     'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
603     'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
604     'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R'
605     );
606
607     $result = mb_detect_encoding($string, join(',', $enc));
608
609     return $result ? $result : $failover;
610 }
611
612 ?>