thomascube
2010-06-08 af3cf8a0a7de74ab169f44277eda73f5f9e18cd7
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");
456c7e 40   header("Cache-Control: private, must-revalidate, post-check=0, pre-check=0");
4e17e6 41   header("Pragma: no-cache");
ebc619 42   // Request browser to disable DNS prefetching (CVE-2010-0464)
A 43   header("X-DNS-Prefetch-Control: off");
0dbac3 44   
T 45   // We need to set the following headers to make downloads work using IE in HTTPS mode.
5818e4 46   if (rcube_https_check()) {
0dbac3 47     header('Pragma: ');
T 48     header('Cache-Control: ');
49   }
6d969b 50 }
4e17e6 51
T 52
6d969b 53 /**
T 54  * Send header with expire date 30 days in future
55  *
56  * @param int Expiration time in seconds
57  */
ff52be 58 function send_future_expire_header($offset=2600000)
6d969b 59 {
1a98a6 60   if (headers_sent())
T 61     return;
62
ff52be 63   header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
T 64   header("Cache-Control: max-age=$offset");
1a98a6 65   header("Pragma: ");
6d969b 66 }
4e17e6 67
T 68
6d969b 69 /**
T 70  * Check request for If-Modified-Since and send an according response.
71  * This will terminate the current script if headers match the given values
72  *
73  * @param int Modified date as unix timestamp
74  * @param string Etag value for caching
75  */
3f5cef 76 function send_modified_header($mdate, $etag=null, $skip_check=false)
ff52be 77 {
T 78   if (headers_sent())
79     return;
80     
81   $iscached = false;
82   $etag = $etag ? "\"$etag\"" : null;
3f5cef 83
A 84   if (!$skip_check)
85   {
86     if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
87       $iscached = true;
88   
89     if ($etag)
90       $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
91   }
ff52be 92   
T 93   if ($iscached)
94     header("HTTP/1.x 304 Not Modified");
95   else
96     header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
97   
496da6 98   header("Cache-Control: private, must-revalidate, max-age=0");
ff52be 99   header("Expires: ");
T 100   header("Pragma: ");
101   
102   if ($etag)
103     header("Etag: $etag");
104   
105   if ($iscached)
1b4d73 106     {
T 107     ob_end_clean();
ff52be 108     exit;
1b4d73 109     }
ff52be 110 }
T 111
112
f11541 113 /**
T 114  * Similar function as in_array() but case-insensitive
6d969b 115  *
T 116  * @param mixed Needle value
117  * @param array Array to search in
118  * @return boolean True if found, False if not
f11541 119  */
4e17e6 120 function in_array_nocase($needle, $haystack)
6d969b 121 {
ee258c 122   $needle = mb_strtolower($needle);
4e17e6 123   foreach ($haystack as $value)
ee258c 124     if ($needle===mb_strtolower($value))
6d969b 125       return true;
T 126   
127   return false;
128 }
4e17e6 129
T 130
f11541 131 /**
T 132  * Find out if the string content means TRUE or FALSE
6d969b 133  *
T 134  * @param string Input value
135  * @return boolean Imagine what!
f11541 136  */
4e17e6 137 function get_boolean($str)
6d969b 138 {
4e17e6 139   $str = strtolower($str);
ee258c 140   if (in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
4e17e6 141     return FALSE;
T 142   else
143     return TRUE;
6d969b 144 }
4e17e6 145
T 146
6d969b 147 /**
T 148  * Parse a human readable string for a number of bytes
149  *
150  * @param string Input string
47f072 151  * @return float Number of bytes
6d969b 152  */
86df15 153 function parse_bytes($str)
6d969b 154 {
86df15 155   if (is_numeric($str))
47f072 156     return floatval($str);
892af4 157
A 158   if (preg_match('/([0-9\.]+)\s*([a-z]*)/i', $str, $regs))
6d969b 159   {
T 160     $bytes = floatval($regs[1]);
161     switch (strtolower($regs[2]))
86df15 162     {
6d969b 163       case 'g':
892af4 164       case 'gb':
6d969b 165         $bytes *= 1073741824;
T 166         break;
167       case 'm':
892af4 168       case 'mb':
6d969b 169         $bytes *= 1048576;
T 170         break;
171       case 'k':
892af4 172       case 'kb':
6d969b 173         $bytes *= 1024;
T 174         break;
86df15 175     }
6d969b 176   }
86df15 177
47f072 178   return floatval($bytes);
6d969b 179 }
86df15 180     
6d969b 181 /**
T 182  * Create a human readable string for a number of bytes
183  *
184  * @param int Number of bytes
185  * @return string Byte string
186  */
3ea0e3 187 function show_bytes($bytes)
6d969b 188 {
3ea0e3 189   if ($bytes > 1073741824)
6d969b 190   {
3ea0e3 191     $gb = $bytes/1073741824;
f613a1 192     $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
6d969b 193   }
3ea0e3 194   else if ($bytes > 1048576)
6d969b 195   {
3ea0e3 196     $mb = $bytes/1048576;
f613a1 197     $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
6d969b 198   }
3ea0e3 199   else if ($bytes > 1024)
f613a1 200     $str = sprintf("%d ",  round($bytes/1024)) . rcube_label('KB');
4e17e6 201   else
f613a1 202     $str = sprintf('%d ', $bytes) . rcube_label('B');
3ea0e3 203
T 204   return $str;
6d969b 205 }
4e17e6 206
T 207
6d969b 208 /**
T 209  * Convert paths like ../xxx to an absolute path using a base url
210  *
211  * @param string Relative path
212  * @param string Base URL
213  * @return string Absolute URL
214  */
4e17e6 215 function make_absolute_url($path, $base_url)
6d969b 216 {
T 217   $host_url = $base_url;
218   $abs_path = $path;
97bd2c 219   
T 220   // check if path is an absolute URL
221   if (preg_match('/^[fhtps]+:\/\//', $path))
222     return $path;
4e17e6 223
6d969b 224   // cut base_url to the last directory
aa055c 225   if (strrpos($base_url, '/')>7)
6d969b 226   {
T 227     $host_url = substr($base_url, 0, strpos($base_url, '/'));
228     $base_url = substr($base_url, 0, strrpos($base_url, '/'));
229   }
230
231   // $path is absolute
232   if ($path{0}=='/')
233     $abs_path = $host_url.$path;
234   else
235   {
236     // strip './' because its the same as ''
237     $path = preg_replace('/^\.\//', '', $path);
238
239     if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
240       foreach ($matches as $a_match)
4e17e6 241       {
6d969b 242         if (strrpos($base_url, '/'))
T 243           $base_url = substr($base_url, 0, strrpos($base_url, '/'));
244         
245         $path = substr($path, 3);
4e17e6 246       }
T 247
6d969b 248     $abs_path = $base_url.'/'.$path;
T 249   }
250     
251   return $abs_path;
252 }
4e17e6 253
7145e0 254 /**
A 255  * Wrapper function for wordwrap
256  */
257 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
258 {
259   $para = explode($break, $string);
260   $string = '';
261   while (count($para)) {
8ad5c8 262     $line = array_shift($para);
T 263     if ($line[0] == '>') {
264       $string .= $line.$break;
265       continue;
266     }
267     $list = explode(' ', $line);
7145e0 268     $len = 0;
A 269     while (count($list)) {
270       $line = array_shift($list);
271       $l = mb_strlen($line);
272       $newlen = $len + $l + ($len ? 1 : 0);
273
274       if ($newlen <= $width) {
275         $string .= ($len ? ' ' : '').$line;
78ebe7 276         $len += (1 + $l);
7145e0 277       } else {
8ad5c8 278         if ($l > $width) {
T 279           if ($cut) {
280             $start = 0;
281             while ($l) {
282               $str = mb_substr($line, $start, $width);
283               $strlen = mb_strlen($str);
284               $string .= ($len ? $break : '').$str;
285               $start += $strlen;
286               $l -= $strlen;
287               $len = $strlen;
288             }
289           } else {
290                 $string .= ($len ? $break : '').$line;
291             if (count($list)) $string .= $break;
292             $len = 0;
293           }
294         } else {
7145e0 295           $string .= $break.$line;
8ad5c8 296           $len = $l;
7145e0 297         }
A 298       }
299     }
300     if (count($para)) $string .= $break;
301   }
302   return $string;
303 }
86df15 304
6d969b 305 /**
88f66e 306  * Read a specific HTTP request header
T 307  *
0144c5 308  * @access static
T 309  * @param  string $name Header name
310  * @return mixed  Header value or null if not available
88f66e 311  */
T 312 function rc_request_header($name)
5a6eff 313 {
88f66e 314   if (function_exists('getallheaders'))
5a6eff 315   {
T 316     $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
0144c5 317     $key  = strtoupper($name);
5a6eff 318   }
88f66e 319   else
5a6eff 320   {
0144c5 321     $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
db401b 322     $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
5a6eff 323   }
T 324
325   return $hdrs[$key];
88f66e 326   }
1cded8 327
T 328
6d969b 329 /**
T 330  * Make sure the string ends with a slash
331  */
bac7d1 332 function slashify($str)
6d969b 333 {
bac7d1 334   return unslashify($str).'/';
6d969b 335 }
bac7d1 336
T 337
6d969b 338 /**
T 339  * Remove slash at the end of the string
340  */
bac7d1 341 function unslashify($str)
6d969b 342 {
bac7d1 343   return preg_replace('/\/$/', '', $str);
6d969b 344 }
bac7d1 345   
T 346
6d969b 347 /**
T 348  * Delete all files within a folder
349  *
350  * @param string Path to directory
351  * @return boolean True on success, False if directory was not found
352  */
1cded8 353 function clear_directory($dir_path)
6d969b 354 {
1cded8 355   $dir = @opendir($dir_path);
T 356   if(!$dir) return FALSE;
357
358   while ($file = readdir($dir))
359     if (strlen($file)>2)
360       unlink("$dir_path/$file");
361
362   closedir($dir);
363   return TRUE;
6d969b 364 }
9fee0e 365
T 366
6d969b 367 /**
T 368  * Create a unix timestamp with a specified offset from now
369  *
370  * @param string String representation of the offset (e.g. 20min, 5h, 2days)
371  * @param int Factor to multiply with the offset
372  * @return int Unix timestamp
373  */
cc9570 374 function get_offset_time($offset_str, $factor=1)
T 375   {
376   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
6d969b 377   {
cc9570 378     $amount = (int)$regs[1];
T 379     $unit = strtolower($regs[2]);
6d969b 380   }
cc9570 381   else
6d969b 382   {
cc9570 383     $amount = (int)$offset_str;
T 384     $unit = 's';
6d969b 385   }
cc9570 386     
T 387   $ts = mktime();
388   switch ($unit)
6d969b 389   {
cc9570 390     case 'w':
T 391       $amount *= 7;
392     case 'd':
393       $amount *= 24;
394     case 'h':
395       $amount *= 60;
bd4959 396     case 'm':
cc9570 397       $amount *= 60;
T 398     case 's':
399       $ts += $amount * $factor;
6d969b 400   }
cc9570 401
T 402   return $ts;
6d969b 403 }
cc9570 404
ee258c 405
A 406 /**
407  * Replace the middle part of a string with ...
408  * if it is longer than the allowed length
409  *
410  * @param string Input string
411  * @param int    Max. length
412  * @param string Replace removed chars with this
413  * @return string Abbreviated string
414  */
415 function abbreviate_string($str, $maxlength, $place_holder='...')
416 {
417   $length = mb_strlen($str);
418   
419   if ($length > $maxlength)
420   {
cea5bc 421     $place_holder_length = mb_strlen($place_holder);
A 422     $first_part_length = floor(($maxlength - $place_holder_length)/2);
423     $second_starting_location = $length - $maxlength + $first_part_length + $place_holder_length;
424     $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location);
ee258c 425   }
A 426
427   return $str;
428 }
cc9570 429
a0109c 430 /**
734584 431  * A method to guess the mime_type of an attachment.
T 432  *
d311d8 433  * @param string $path      Path to the file.
A 434  * @param string $name      File name (with suffix)
435  * @param string $failover  Mime type supplied for failover.
436  * @param string $is_stream Set to True if $path contains file body
734584 437  *
T 438  * @return string
439  * @author Till Klampaeckel <till@php.net>
440  * @see    http://de2.php.net/manual/en/ref.fileinfo.php
441  * @see    http://de2.php.net/mime_content_type
442  */
d311d8 443 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream', $is_stream=false)
734584 444 {
6d5dba 445     $mime_type = null;
T 446     $mime_magic = rcmail::get_instance()->config->get('mime_magic');
0ea569 447     $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
T 448     $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
a0109c 449
0ea569 450     // use file name suffix with hard-coded mime-type map
T 451     if (is_array($mime_ext)) {
452         $mime_type = $mime_ext[$suffix];
734584 453     }
0ea569 454     // try fileinfo extension if available
3e6380 455     if (!$mime_type && function_exists('finfo_open')) {
A 456         if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
d311d8 457             if ($is_stream)
A 458                 $mime_type = finfo_buffer($finfo, $path);
459             else
460                 $mime_type = finfo_file($finfo, $path);
3e6380 461             finfo_close($finfo);
734584 462         }
T 463     }
0ea569 464     // try PHP's mime_content_type
d311d8 465     if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
A 466       $mime_type = @mime_content_type($path);
6d5dba 467     }
0ea569 468     // fall back to user-submitted string
734584 469     if (!$mime_type) {
6d5dba 470         $mime_type = $failover;
734584 471     }
T 472
473     return $mime_type;
474 }
475
b54121 476 /**
A 477  * A method to guess encoding of a string.
478  *
479  * @param string $string         String.
480  * @param string $failover     Default result for failover.
481  *
482  * @return string
483  */
484 function rc_detect_encoding($string, $failover='')
485 {
486     if (!function_exists('mb_detect_encoding')) {
487         return $failover;
488     }
489
490     // FIXME: the order is important, because sometimes 
491     // iso string is detected as euc-jp and etc.
492     $enc = array(
b58f11 493       'UTF-8', 'SJIS', 'BIG5', 'GB2312',
T 494       'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
495       'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
496       'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
497       'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R', 
498       'ISO-2022-KR', 'ISO-2022-JP'
b54121 499     );
A 500
501     $result = mb_detect_encoding($string, join(',', $enc));
502
503     return $result ? $result : $failover;
504 }
505
1a00f1 506 /**
A 507  * Removes non-unicode characters from input
508  *
509  * @param mixed $input String or array.
510  * @return string
511  */
512 function rc_utf8_clean($input)
513 {
514   // handle input of type array
515   if (is_array($input)) {
516     foreach ($input as $idx => $val)
517       $input[$idx] = rc_utf8_clean($val);
518     return $input;
519   }
520   
b6c512 521   if (!is_string($input) || $input == '')
1a00f1 522     return $input;
2717f9 523
b6c512 524   // iconv/mbstring are much faster (especially with long strings)
6481d4 525   if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
b6c512 526     return $res;
A 527
ecbd5b 528   if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
b6c512 529     return $res;
1a00f1 530
A 531   $regexp = '/^('.
532 //    '[\x00-\x7F]'.                                  // UTF8-1
533     '|[\xC2-\xDF][\x80-\xBF]'.                      // UTF8-2
534     '|\xE0[\xA0-\xBF][\x80-\xBF]'.                  // UTF8-3
535     '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
536     '|\xED[\x80-\x9F][\x80-\xBF]'.                  // UTF8-3
537     '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
538     '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
539     '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
540     '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
541     ')$/';
542   
543   $seq = '';
544   $out = '';
545
6481d4 546   for ($i = 0, $len = strlen($input); $i < $len; $i++) {
1a00f1 547     $chr = $input[$i];
A 548     $ord = ord($chr);
549     // 1-byte character
550     if ($ord <= 0x7F) {
551       if ($seq)
552         $out .= preg_match($regexp, $seq) ? $seq : '';
553       $seq = '';
554       $out .= $chr;
555     // first (or second) byte of multibyte sequence
556     } else if ($ord >= 0xC0) {
557       if (strlen($seq)>1) {
558     $out .= preg_match($regexp, $seq) ? $seq : '';
559         $seq = '';
560       } else if ($seq && ord($seq) < 0xC0) {
561         $seq = '';
562       }
563       $seq .= $chr;
564     // next byte of multibyte sequence
565     } else if ($seq) {
566       $seq .= $chr;
567     }
568   }
569
570   if ($seq)
571     $out .= preg_match($regexp, $seq) ? $seq : '';
572
573   return $out;
574 }
0ff635 575
2717f9 576
A 577 /**
578  * Convert a variable into a javascript object notation
579  *
580  * @param mixed Input value
581  * @return string Serialized JSON string
582  */
583 function json_serialize($input)
584 {
585   $input = rc_utf8_clean($input);
63ffe3 586
a7dba8 587   // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
A 588   // that's why we have @ here
589   return @json_encode($input);
2717f9 590 }
A 591
592
0ff635 593 /**
A 594  * Explode quoted string
595  * 
596  * @param string Delimiter expression string for preg_match()
597  * @param string Input string
598  */
599 function rcube_explode_quoted_string($delimiter, $string)
600 {
601   $result = array();
602   $strlen = strlen($string);
603
604   for ($q=$p=$i=0; $i < $strlen; $i++) {
605     if ($string[$i] == "\"" && $string[$i-1] != "\\") {
606       $q = $q ? false : true;
607     } 
608     else if (!$q && preg_match("/$delimiter/", $string[$i])) {
609       $result[] = substr($string, $p, $i - $p);
610       $p = $i + 1;
611     }
612   }
613   
614   $result[] = substr($string, $p);
615   return $result;
616 }
617
ee258c 618
A 619 /**
f52c93 620  * Get all keys from array (recursive)
T 621  * 
622  * @param array Input array
623  * @return array
624  */
625 function array_keys_recursive($array)
626 {
627   $keys = array();
628   
629   if (!empty($array))
630     foreach ($array as $key => $child) {
631       $keys[] = $key;
632       if ($children = array_keys_recursive($child))
633         $keys = array_merge($keys, $children);
634     }
635   return $keys;
636 }
637
638
639 /**
ee258c 640  * mbstring replacement functions
A 641  */
642
8f6a46 643 if (!extension_loaded('mbstring'))
A 644 {
ee258c 645     function mb_strlen($str)
A 646     {
647     return strlen($str);
648     }
649
650     function mb_strtolower($str)
651     {
652         return strtolower($str);
653     }
654
655     function mb_strtoupper($str)
656     {
657         return strtoupper($str);
658     }
659
660     function mb_substr($str, $start, $len=null)
661     {
662         return substr($str, $start, $len);
663     }
664
665     function mb_strpos($haystack, $needle, $offset=0)
666     {
667         return strpos($haystack, $needle, $offset);
668     }
669
670     function mb_strrpos($haystack, $needle, $offset=0)
671     {
672         return strrpos($haystack, $needle, $offset);
673     }
674 }
675
b54121 676 ?>