alecpl
2008-09-20 c17dc6aa31aaa6e7f61bd25993be55354e428996
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  * Send HTTP headers to prevent caching this page
32  */
4e17e6 33 function send_nocacheing_headers()
6d969b 34 {
4e17e6 35   if (headers_sent())
T 36     return;
37
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");
0dbac3 40   header("Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
4e17e6 41   header("Pragma: no-cache");
0dbac3 42   
T 43   // We need to set the following headers to make downloads work using IE in HTTPS mode.
44   if (isset($_SERVER['HTTPS'])) {
45     header('Pragma: ');
46     header('Cache-Control: ');
47   }
6d969b 48 }
4e17e6 49
T 50
6d969b 51 /**
T 52  * Send header with expire date 30 days in future
53  *
54  * @param int Expiration time in seconds
55  */
ff52be 56 function send_future_expire_header($offset=2600000)
6d969b 57 {
1a98a6 58   if (headers_sent())
T 59     return;
60
ff52be 61   header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
T 62   header("Cache-Control: max-age=$offset");
1a98a6 63   header("Pragma: ");
6d969b 64 }
4e17e6 65
T 66
6d969b 67 /**
T 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
70  *
71  * @param int Modified date as unix timestamp
72  * @param string Etag value for caching
73  */
3f5cef 74 function send_modified_header($mdate, $etag=null, $skip_check=false)
ff52be 75 {
T 76   if (headers_sent())
77     return;
78     
79   $iscached = false;
80   $etag = $etag ? "\"$etag\"" : null;
3f5cef 81
A 82   if (!$skip_check)
83   {
84     if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
85       $iscached = true;
86   
87     if ($etag)
88       $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
89   }
ff52be 90   
T 91   if ($iscached)
92     header("HTTP/1.x 304 Not Modified");
93   else
94     header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
95   
96   header("Cache-Control: max-age=0");
97   header("Expires: ");
98   header("Pragma: ");
99   
100   if ($etag)
101     header("Etag: $etag");
102   
103   if ($iscached)
1b4d73 104     {
T 105     ob_end_clean();
ff52be 106     exit;
1b4d73 107     }
ff52be 108 }
T 109
110
f11541 111 /**
6d969b 112  * Convert a variable into a javascript object notation
T 113  *
114  * @param mixed Input value
115  * @return string Serialized JSON string
f11541 116  */
T 117 function json_serialize($var)
6d969b 118 {
T 119   if (is_object($var))
120     $var = get_object_vars($var);
121
122   if (is_array($var))
4e17e6 123   {
6d969b 124     // empty array
T 125     if (!sizeof($var))
126       return '[]';
f11541 127     else
6d969b 128     {
T 129       $keys_arr = array_keys($var);
130       $is_assoc = $have_numeric = 0;
131
132       for ($i=0; $i<sizeof($keys_arr); ++$i)
133       {
134         if (is_numeric($keys_arr[$i]))
135           $have_numeric = 1;
136         if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
137           $is_assoc = 1;
138         if ($is_assoc && $have_numeric)
139           break;
140       }
141       
142       $brackets = $is_assoc ? '{}' : '[]';
143       $pairs = array();
144
145       foreach ($var as $key => $value)
146       {
147         // enclose key with quotes if it is not variable-name conform
148         if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) /* || is_js_reserved_word($key) */)
149           $key = "'$key'";
150
151         $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
152       }
153
154       return $brackets{0} . implode(',', $pairs) . $brackets{1};
155     }
f11541 156   }
6d969b 157   else if (is_numeric($var) && strval(intval($var)) === strval($var))
T 158     return $var;
159   else if (is_bool($var))
160     return $var ? '1' : '0';
161   else
162     return "'".JQ($var)."'";
163
164 }
f11541 165
T 166 /**
6d969b 167  * Function to convert an array to a javascript array
T 168  * Actually an alias function for json_serialize()
f11541 169  * @deprecated
T 170  */
171 function array2js($arr, $type='')
6d969b 172 {
f11541 173   return json_serialize($arr);
6d969b 174 }
4e17e6 175
T 176
f11541 177 /**
T 178  * Similar function as in_array() but case-insensitive
6d969b 179  *
T 180  * @param mixed Needle value
181  * @param array Array to search in
182  * @return boolean True if found, False if not
f11541 183  */
4e17e6 184 function in_array_nocase($needle, $haystack)
6d969b 185 {
4e17e6 186   foreach ($haystack as $value)
T 187     if (strtolower($needle)===strtolower($value))
6d969b 188       return true;
T 189   
190   return false;
191 }
4e17e6 192
T 193
f11541 194 /**
T 195  * Find out if the string content means TRUE or FALSE
6d969b 196  *
T 197  * @param string Input value
198  * @return boolean Imagine what!
f11541 199  */
4e17e6 200 function get_boolean($str)
6d969b 201 {
4e17e6 202   $str = strtolower($str);
T 203   if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
204     return FALSE;
205   else
206     return TRUE;
6d969b 207 }
4e17e6 208
T 209
6d969b 210 /**
T 211  * Parse a human readable string for a number of bytes
212  *
213  * @param string Input string
214  * @return int Number of bytes
215  */
86df15 216 function parse_bytes($str)
6d969b 217 {
86df15 218   if (is_numeric($str))
T 219     return intval($str);
220     
221   if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
6d969b 222   {
T 223     $bytes = floatval($regs[1]);
224     switch (strtolower($regs[2]))
86df15 225     {
6d969b 226       case 'g':
T 227         $bytes *= 1073741824;
228         break;
229       case 'm':
230         $bytes *= 1048576;
231         break;
232       case 'k':
233         $bytes *= 1024;
234         break;
86df15 235     }
6d969b 236   }
86df15 237
T 238   return intval($bytes);
6d969b 239 }
86df15 240     
6d969b 241 /**
T 242  * Create a human readable string for a number of bytes
243  *
244  * @param int Number of bytes
245  * @return string Byte string
246  */
3ea0e3 247 function show_bytes($bytes)
6d969b 248 {
3ea0e3 249   if ($bytes > 1073741824)
6d969b 250   {
3ea0e3 251     $gb = $bytes/1073741824;
T 252     $str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
6d969b 253   }
3ea0e3 254   else if ($bytes > 1048576)
6d969b 255   {
3ea0e3 256     $mb = $bytes/1048576;
T 257     $str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
6d969b 258   }
3ea0e3 259   else if ($bytes > 1024)
T 260     $str = sprintf("%d KB",  round($bytes/1024));
4e17e6 261   else
3ea0e3 262     $str = sprintf('%d B', $bytes);
T 263
264   return $str;
6d969b 265 }
4e17e6 266
T 267
6d969b 268 /**
T 269  * Convert paths like ../xxx to an absolute path using a base url
270  *
271  * @param string Relative path
272  * @param string Base URL
273  * @return string Absolute URL
274  */
4e17e6 275 function make_absolute_url($path, $base_url)
6d969b 276 {
T 277   $host_url = $base_url;
278   $abs_path = $path;
97bd2c 279   
T 280   // check if path is an absolute URL
281   if (preg_match('/^[fhtps]+:\/\//', $path))
282     return $path;
4e17e6 283
6d969b 284   // cut base_url to the last directory
T 285   if (strpos($base_url, '/')>7)
286   {
287     $host_url = substr($base_url, 0, strpos($base_url, '/'));
288     $base_url = substr($base_url, 0, strrpos($base_url, '/'));
289   }
290
291   // $path is absolute
292   if ($path{0}=='/')
293     $abs_path = $host_url.$path;
294   else
295   {
296     // strip './' because its the same as ''
297     $path = preg_replace('/^\.\//', '', $path);
298
299     if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
300       foreach ($matches as $a_match)
4e17e6 301       {
6d969b 302         if (strrpos($base_url, '/'))
T 303           $base_url = substr($base_url, 0, strrpos($base_url, '/'));
304         
305         $path = substr($path, 3);
4e17e6 306       }
T 307
6d969b 308     $abs_path = $base_url.'/'.$path;
T 309   }
310     
311   return $abs_path;
312 }
4e17e6 313
T 314
6d969b 315 /**
T 316  * Wrapper function for strlen
317  */
86df15 318 function rc_strlen($str)
6d969b 319 {
T 320   if (function_exists('mb_strlen'))
321     return mb_strlen($str);
322   else
323     return strlen($str);
324 }
86df15 325   
6d969b 326 /**
T 327  * Wrapper function for strtolower
328  */
86df15 329 function rc_strtolower($str)
6d969b 330 {
T 331   if (function_exists('mb_strtolower'))
332     return mb_strtolower($str);
333   else
334     return strtolower($str);
335 }
86df15 336
6d969b 337 /**
T 338  * Wrapper function for substr
339  */
f11541 340 function rc_substr($str, $start, $len=null)
6d969b 341 {
86df15 342   if (function_exists('mb_substr'))
T 343     return mb_substr($str, $start, $len);
344   else
345     return substr($str, $start, $len);
6d969b 346 }
86df15 347
6d969b 348 /**
T 349  * Wrapper function for strpos
350  */
86df15 351 function rc_strpos($haystack, $needle, $offset=0)
6d969b 352 {
86df15 353   if (function_exists('mb_strpos'))
T 354     return mb_strpos($haystack, $needle, $offset);
355   else
356     return strpos($haystack, $needle, $offset);
6d969b 357 }
86df15 358
6d969b 359 /**
T 360  * Wrapper function for strrpos
361  */
86df15 362 function rc_strrpos($haystack, $needle, $offset=0)
6d969b 363 {
86df15 364   if (function_exists('mb_strrpos'))
T 365     return mb_strrpos($haystack, $needle, $offset);
366   else
367     return strrpos($haystack, $needle, $offset);
6d969b 368 }
86df15 369
T 370
6d969b 371 /**
88f66e 372  * Read a specific HTTP request header
T 373  *
0144c5 374  * @access static
T 375  * @param  string $name Header name
376  * @return mixed  Header value or null if not available
88f66e 377  */
T 378 function rc_request_header($name)
5a6eff 379 {
88f66e 380   if (function_exists('getallheaders'))
5a6eff 381   {
T 382     $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
0144c5 383     $key  = strtoupper($name);
5a6eff 384   }
88f66e 385   else
5a6eff 386   {
0144c5 387     $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
db401b 388     $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
5a6eff 389   }
T 390
391   return $hdrs[$key];
88f66e 392   }
T 393
394
395 /**
6d969b 396  * Replace the middle part of a string with ...
T 397  * if it is longer than the allowed length
398  *
399  * @param string Input string
400  * @param int    Max. length
401  * @param string Replace removed chars with this
6f2f2d 402  * @return string Abbreviated string
6d969b 403  */
6f2f2d 404 function abbreviate_string($str, $maxlength, $place_holder='...')
6d969b 405 {
86df15 406   $length = rc_strlen($str);
T 407   $first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
9fee0e 408   
T 409   if ($length > $maxlength)
6d969b 410   {
9fee0e 411     $second_starting_location = $length - $maxlength + $first_part_length + 1;
86df15 412     $str = rc_substr($str, 0, $first_part_length) . $place_holder . rc_substr($str, $second_starting_location, $length);
6d969b 413   }
9fee0e 414
T 415   return $str;
6d969b 416 }
1cded8 417
T 418
6d969b 419 /**
T 420  * Make sure the string ends with a slash
421  */
bac7d1 422 function slashify($str)
6d969b 423 {
bac7d1 424   return unslashify($str).'/';
6d969b 425 }
bac7d1 426
T 427
6d969b 428 /**
T 429  * Remove slash at the end of the string
430  */
bac7d1 431 function unslashify($str)
6d969b 432 {
bac7d1 433   return preg_replace('/\/$/', '', $str);
6d969b 434 }
bac7d1 435   
T 436
6d969b 437 /**
T 438  * Delete all files within a folder
439  *
440  * @param string Path to directory
441  * @return boolean True on success, False if directory was not found
442  */
1cded8 443 function clear_directory($dir_path)
6d969b 444 {
1cded8 445   $dir = @opendir($dir_path);
T 446   if(!$dir) return FALSE;
447
448   while ($file = readdir($dir))
449     if (strlen($file)>2)
450       unlink("$dir_path/$file");
451
452   closedir($dir);
453   return TRUE;
6d969b 454 }
9fee0e 455
T 456
6d969b 457 /**
T 458  * Create a unix timestamp with a specified offset from now
459  *
460  * @param string String representation of the offset (e.g. 20min, 5h, 2days)
461  * @param int Factor to multiply with the offset
462  * @return int Unix timestamp
463  */
cc9570 464 function get_offset_time($offset_str, $factor=1)
T 465   {
466   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
6d969b 467   {
cc9570 468     $amount = (int)$regs[1];
T 469     $unit = strtolower($regs[2]);
6d969b 470   }
cc9570 471   else
6d969b 472   {
cc9570 473     $amount = (int)$offset_str;
T 474     $unit = 's';
6d969b 475   }
cc9570 476     
T 477   $ts = mktime();
478   switch ($unit)
6d969b 479   {
cc9570 480     case 'w':
T 481       $amount *= 7;
482     case 'd':
483       $amount *= 24;
484     case 'h':
485       $amount *= 60;
bd4959 486     case 'm':
cc9570 487       $amount *= 60;
T 488     case 's':
489       $ts += $amount * $factor;
6d969b 490   }
cc9570 491
T 492   return $ts;
6d969b 493 }
cc9570 494
T 495
a0109c 496 /**
734584 497  * A method to guess the mime_type of an attachment.
T 498  *
499  * @param string $path     Path to the file.
500  * @param string $failover Mime type supplied for failover.
501  *
502  * @return string
503  * @author Till Klampaeckel <till@php.net>
504  * @see    http://de2.php.net/manual/en/ref.fileinfo.php
505  * @see    http://de2.php.net/mime_content_type
506  */
bce034 507 function rc_mime_content_type($path, $failover = 'application/octet-stream')
734584 508 {
6d5dba 509     $mime_type = null;
T 510     $mime_magic = rcmail::get_instance()->config->get('mime_magic');
a0109c 511
6d5dba 512     if (!extension_loaded('fileinfo')) {
T 513         @dl('fileinfo.' . PHP_SHLIB_SUFFIX);
734584 514     }
6d5dba 515
T 516     if (function_exists('finfo_open')) {
517         if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
518             $mime_type = finfo_file($finfo, $path);
519             finfo_close($finfo);
734584 520         }
T 521     }
35dc0b 522     if (!$mime_type && function_exists('mime_content_type')) {
6d5dba 523       $mime_type = mime_content_type($path); 
T 524     }
403e3f 525     
734584 526     if (!$mime_type) {
6d5dba 527         $mime_type = $failover;
734584 528     }
T 529
530     return $mime_type;
531 }
532
b54121 533
A 534 /**
535  * A method to guess encoding of a string.
536  *
537  * @param string $string         String.
538  * @param string $failover     Default result for failover.
539  *
540  * @return string
541  */
542 function rc_detect_encoding($string, $failover='')
543 {
544     if (!function_exists('mb_detect_encoding')) {
545         return $failover;
546     }
547
548     // FIXME: the order is important, because sometimes 
549     // iso string is detected as euc-jp and etc.
550     $enc = array(
551     'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
552     'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
553     'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
554     'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R'
555     );
556
557     $result = mb_detect_encoding($string, join(',', $enc));
558
559     return $result ? $result : $failover;
560 }
561
562 ?>