alecpl
2009-08-29 e83f035887e3a463568465673ae92f365788c2a5
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");
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 /**
c02bb9 112  * Returns whether an $str is a reserved word for any of the version of Javascript or ECMAScript
A 113  * @param str String to check
114  * @return boolean True if $str is a reserver word, False if not
115  */
116 function is_js_reserved_word($str)
117 {
118   return in_array($str, array(
119     // ECMASript ver 4 reserved words
120     'as','break','case','catch','class','const','continue',
121     'default','delete','do','else','export','extends','false','finally','for','function',
122     'if','import','in','instanceof','is','namespace','new','null','package','private',
123     'public','return','super','switch','this','throw','true','try','typeof','use','var',
124     'void','while','with',
125     // ECMAScript ver 4 future reserved words
126     'abstract','debugger','enum','goto','implements','interface','native','protected',
127     'synchronized','throws','transient','volatile',
128     // special meaning in some contexts
129     'get','set',
130     // were reserved in ECMAScript ver 3
131     'boolean','byte','char','double','final','float','int','long','short','static'
132   ));
133 }
134
135
136 /**
6d969b 137  * Convert a variable into a javascript object notation
T 138  *
139  * @param mixed Input value
140  * @return string Serialized JSON string
f11541 141  */
T 142 function json_serialize($var)
6d969b 143 {
T 144   if (is_object($var))
145     $var = get_object_vars($var);
146
147   if (is_array($var))
4e17e6 148   {
6d969b 149     // empty array
T 150     if (!sizeof($var))
151       return '[]';
f11541 152     else
6d969b 153     {
T 154       $keys_arr = array_keys($var);
155       $is_assoc = $have_numeric = 0;
156
157       for ($i=0; $i<sizeof($keys_arr); ++$i)
158       {
159         if (is_numeric($keys_arr[$i]))
160           $have_numeric = 1;
161         if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
162           $is_assoc = 1;
163         if ($is_assoc && $have_numeric)
164           break;
165       }
166       
167       $brackets = $is_assoc ? '{}' : '[]';
168       $pairs = array();
169
170       foreach ($var as $key => $value)
171       {
172         // enclose key with quotes if it is not variable-name conform
23a2ee 173         if (!preg_match('/^[_a-zA-Z]{1}[_a-zA-Z0-9]*$/', $key) || is_js_reserved_word($key))
6d969b 174           $key = "'$key'";
T 175
176         $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
177       }
178
179       return $brackets{0} . implode(',', $pairs) . $brackets{1};
180     }
f11541 181   }
8498dc 182   else if (!is_string($var) && strval(intval($var)) === strval($var))
6d969b 183     return $var;
T 184   else if (is_bool($var))
185     return $var ? '1' : '0';
186   else
187     return "'".JQ($var)."'";
188 }
f11541 189
c02bb9 190
f11541 191 /**
6d969b 192  * Function to convert an array to a javascript array
T 193  * Actually an alias function for json_serialize()
f11541 194  * @deprecated
T 195  */
196 function array2js($arr, $type='')
6d969b 197 {
f11541 198   return json_serialize($arr);
6d969b 199 }
4e17e6 200
T 201
f11541 202 /**
T 203  * Similar function as in_array() but case-insensitive
6d969b 204  *
T 205  * @param mixed Needle value
206  * @param array Array to search in
207  * @return boolean True if found, False if not
f11541 208  */
4e17e6 209 function in_array_nocase($needle, $haystack)
6d969b 210 {
ee258c 211   $needle = mb_strtolower($needle);
4e17e6 212   foreach ($haystack as $value)
ee258c 213     if ($needle===mb_strtolower($value))
6d969b 214       return true;
T 215   
216   return false;
217 }
4e17e6 218
T 219
f11541 220 /**
T 221  * Find out if the string content means TRUE or FALSE
6d969b 222  *
T 223  * @param string Input value
224  * @return boolean Imagine what!
f11541 225  */
4e17e6 226 function get_boolean($str)
6d969b 227 {
4e17e6 228   $str = strtolower($str);
ee258c 229   if (in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
4e17e6 230     return FALSE;
T 231   else
232     return TRUE;
6d969b 233 }
4e17e6 234
T 235
6d969b 236 /**
T 237  * Parse a human readable string for a number of bytes
238  *
239  * @param string Input string
47f072 240  * @return float Number of bytes
6d969b 241  */
86df15 242 function parse_bytes($str)
6d969b 243 {
86df15 244   if (is_numeric($str))
47f072 245     return floatval($str);
86df15 246     
T 247   if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
6d969b 248   {
T 249     $bytes = floatval($regs[1]);
250     switch (strtolower($regs[2]))
86df15 251     {
6d969b 252       case 'g':
T 253         $bytes *= 1073741824;
254         break;
255       case 'm':
256         $bytes *= 1048576;
257         break;
258       case 'k':
259         $bytes *= 1024;
260         break;
86df15 261     }
6d969b 262   }
86df15 263
47f072 264   return floatval($bytes);
6d969b 265 }
86df15 266     
6d969b 267 /**
T 268  * Create a human readable string for a number of bytes
269  *
270  * @param int Number of bytes
271  * @return string Byte string
272  */
3ea0e3 273 function show_bytes($bytes)
6d969b 274 {
3ea0e3 275   if ($bytes > 1073741824)
6d969b 276   {
3ea0e3 277     $gb = $bytes/1073741824;
f613a1 278     $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
6d969b 279   }
3ea0e3 280   else if ($bytes > 1048576)
6d969b 281   {
3ea0e3 282     $mb = $bytes/1048576;
f613a1 283     $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
6d969b 284   }
3ea0e3 285   else if ($bytes > 1024)
f613a1 286     $str = sprintf("%d ",  round($bytes/1024)) . rcube_label('KB');
4e17e6 287   else
f613a1 288     $str = sprintf('%d ', $bytes) . rcube_label('B');
3ea0e3 289
T 290   return $str;
6d969b 291 }
4e17e6 292
T 293
6d969b 294 /**
T 295  * Convert paths like ../xxx to an absolute path using a base url
296  *
297  * @param string Relative path
298  * @param string Base URL
299  * @return string Absolute URL
300  */
4e17e6 301 function make_absolute_url($path, $base_url)
6d969b 302 {
T 303   $host_url = $base_url;
304   $abs_path = $path;
97bd2c 305   
T 306   // check if path is an absolute URL
307   if (preg_match('/^[fhtps]+:\/\//', $path))
308     return $path;
4e17e6 309
6d969b 310   // cut base_url to the last directory
aa055c 311   if (strrpos($base_url, '/')>7)
6d969b 312   {
T 313     $host_url = substr($base_url, 0, strpos($base_url, '/'));
314     $base_url = substr($base_url, 0, strrpos($base_url, '/'));
315   }
316
317   // $path is absolute
318   if ($path{0}=='/')
319     $abs_path = $host_url.$path;
320   else
321   {
322     // strip './' because its the same as ''
323     $path = preg_replace('/^\.\//', '', $path);
324
325     if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
326       foreach ($matches as $a_match)
4e17e6 327       {
6d969b 328         if (strrpos($base_url, '/'))
T 329           $base_url = substr($base_url, 0, strrpos($base_url, '/'));
330         
331         $path = substr($path, 3);
4e17e6 332       }
T 333
6d969b 334     $abs_path = $base_url.'/'.$path;
T 335   }
336     
337   return $abs_path;
338 }
4e17e6 339
7145e0 340 /**
A 341  * Wrapper function for wordwrap
342  */
343 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
344 {
345   $para = explode($break, $string);
346   $string = '';
347   while (count($para)) {
348     $list = explode(' ', array_shift($para));
349     $len = 0;
350     while (count($list)) {
351       $line = array_shift($list);
352       $l = mb_strlen($line);
353       $newlen = $len + $l + ($len ? 1 : 0);
354
355       if ($newlen <= $width) {
356         $string .= ($len ? ' ' : '').$line;
78ebe7 357         $len += (1 + $l);
7145e0 358       } else {
A 359     if ($l > $width) {
360       if ($cut) {
361         $start = 0;
362         while ($l) {
363           $str = mb_substr($line, $start, $width);
364           $strlen = mb_strlen($str);
365           $string .= ($len ? $break : '').$str;
366           $start += $strlen;
367           $l -= $strlen;
368           $len = $strlen;
369         }
370       } else {
371             $string .= ($len ? $break : '').$line;
372         if (count($list)) $string .= $break;
373         $len = 0;
374       }
375     } else {
376           $string .= $break.$line;
377       $len = $l;
378         }
379       }
380     }
381     if (count($para)) $string .= $break;
382   }
383   return $string;
384 }
86df15 385
6d969b 386 /**
88f66e 387  * Read a specific HTTP request header
T 388  *
0144c5 389  * @access static
T 390  * @param  string $name Header name
391  * @return mixed  Header value or null if not available
88f66e 392  */
T 393 function rc_request_header($name)
5a6eff 394 {
88f66e 395   if (function_exists('getallheaders'))
5a6eff 396   {
T 397     $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
0144c5 398     $key  = strtoupper($name);
5a6eff 399   }
88f66e 400   else
5a6eff 401   {
0144c5 402     $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
db401b 403     $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
5a6eff 404   }
T 405
406   return $hdrs[$key];
88f66e 407   }
1cded8 408
T 409
6d969b 410 /**
T 411  * Make sure the string ends with a slash
412  */
bac7d1 413 function slashify($str)
6d969b 414 {
bac7d1 415   return unslashify($str).'/';
6d969b 416 }
bac7d1 417
T 418
6d969b 419 /**
T 420  * Remove slash at the end of the string
421  */
bac7d1 422 function unslashify($str)
6d969b 423 {
bac7d1 424   return preg_replace('/\/$/', '', $str);
6d969b 425 }
bac7d1 426   
T 427
6d969b 428 /**
T 429  * Delete all files within a folder
430  *
431  * @param string Path to directory
432  * @return boolean True on success, False if directory was not found
433  */
1cded8 434 function clear_directory($dir_path)
6d969b 435 {
1cded8 436   $dir = @opendir($dir_path);
T 437   if(!$dir) return FALSE;
438
439   while ($file = readdir($dir))
440     if (strlen($file)>2)
441       unlink("$dir_path/$file");
442
443   closedir($dir);
444   return TRUE;
6d969b 445 }
9fee0e 446
T 447
6d969b 448 /**
T 449  * Create a unix timestamp with a specified offset from now
450  *
451  * @param string String representation of the offset (e.g. 20min, 5h, 2days)
452  * @param int Factor to multiply with the offset
453  * @return int Unix timestamp
454  */
cc9570 455 function get_offset_time($offset_str, $factor=1)
T 456   {
457   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
6d969b 458   {
cc9570 459     $amount = (int)$regs[1];
T 460     $unit = strtolower($regs[2]);
6d969b 461   }
cc9570 462   else
6d969b 463   {
cc9570 464     $amount = (int)$offset_str;
T 465     $unit = 's';
6d969b 466   }
cc9570 467     
T 468   $ts = mktime();
469   switch ($unit)
6d969b 470   {
cc9570 471     case 'w':
T 472       $amount *= 7;
473     case 'd':
474       $amount *= 24;
475     case 'h':
476       $amount *= 60;
bd4959 477     case 'm':
cc9570 478       $amount *= 60;
T 479     case 's':
480       $ts += $amount * $factor;
6d969b 481   }
cc9570 482
T 483   return $ts;
6d969b 484 }
cc9570 485
ee258c 486
A 487 /**
488  * Replace the middle part of a string with ...
489  * if it is longer than the allowed length
490  *
491  * @param string Input string
492  * @param int    Max. length
493  * @param string Replace removed chars with this
494  * @return string Abbreviated string
495  */
496 function abbreviate_string($str, $maxlength, $place_holder='...')
497 {
498   $length = mb_strlen($str);
499   $first_part_length = floor($maxlength/2) - mb_strlen($place_holder);
500   
501   if ($length > $maxlength)
502   {
503     $second_starting_location = $length - $maxlength + $first_part_length + 1;
504     $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location, $length);
505   }
506
507   return $str;
508 }
cc9570 509
a0109c 510 /**
734584 511  * A method to guess the mime_type of an attachment.
T 512  *
513  * @param string $path     Path to the file.
0ea569 514  * @param string $name     File name (with suffix)
734584 515  * @param string $failover Mime type supplied for failover.
T 516  *
517  * @return string
518  * @author Till Klampaeckel <till@php.net>
519  * @see    http://de2.php.net/manual/en/ref.fileinfo.php
520  * @see    http://de2.php.net/mime_content_type
521  */
0ea569 522 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream')
734584 523 {
6d5dba 524     $mime_type = null;
T 525     $mime_magic = rcmail::get_instance()->config->get('mime_magic');
0ea569 526     $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
T 527     $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
a0109c 528
0ea569 529     // use file name suffix with hard-coded mime-type map
T 530     if (is_array($mime_ext)) {
531         $mime_type = $mime_ext[$suffix];
734584 532     }
0ea569 533     // try fileinfo extension if available
T 534     if (!$mime_type) {
535         if (!extension_loaded('fileinfo')) {
536             @dl('fileinfo.' . PHP_SHLIB_SUFFIX);
537         }
538         if (function_exists('finfo_open')) {
539             if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
540                 $mime_type = finfo_file($finfo, $path);
541                 finfo_close($finfo);
542             }
734584 543         }
T 544     }
0ea569 545     // try PHP's mime_content_type
35dc0b 546     if (!$mime_type && function_exists('mime_content_type')) {
6d5dba 547       $mime_type = mime_content_type($path); 
T 548     }
0ea569 549     // fall back to user-submitted string
734584 550     if (!$mime_type) {
6d5dba 551         $mime_type = $failover;
734584 552     }
T 553
554     return $mime_type;
555 }
556
b54121 557
A 558 /**
559  * A method to guess encoding of a string.
560  *
561  * @param string $string         String.
562  * @param string $failover     Default result for failover.
563  *
564  * @return string
565  */
566 function rc_detect_encoding($string, $failover='')
567 {
568     if (!function_exists('mb_detect_encoding')) {
569         return $failover;
570     }
571
572     // FIXME: the order is important, because sometimes 
573     // iso string is detected as euc-jp and etc.
574     $enc = array(
b58f11 575       'UTF-8', 'SJIS', 'BIG5', 'GB2312',
T 576       'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
577       'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
578       'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
579       'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R', 
580       'ISO-2022-KR', 'ISO-2022-JP'
b54121 581     );
A 582
583     $result = mb_detect_encoding($string, join(',', $enc));
584
585     return $result ? $result : $failover;
586 }
587
0ff635 588
A 589 /**
590  * Explode quoted string
591  * 
592  * @param string Delimiter expression string for preg_match()
593  * @param string Input string
594  */
595 function rcube_explode_quoted_string($delimiter, $string)
596 {
597   $result = array();
598   $strlen = strlen($string);
599
600   for ($q=$p=$i=0; $i < $strlen; $i++) {
601     if ($string[$i] == "\"" && $string[$i-1] != "\\") {
602       $q = $q ? false : true;
603     } 
604     else if (!$q && preg_match("/$delimiter/", $string[$i])) {
605       $result[] = substr($string, $p, $i - $p);
606       $p = $i + 1;
607     }
608   }
609   
610   $result[] = substr($string, $p);
611   return $result;
612 }
613
ee258c 614
A 615 /**
616  * mbstring replacement functions
617  */
618
8f6a46 619 if (!extension_loaded('mbstring'))
A 620 {
ee258c 621     function mb_strlen($str)
A 622     {
623     return strlen($str);
624     }
625
626     function mb_strtolower($str)
627     {
628         return strtolower($str);
629     }
630
631     function mb_strtoupper($str)
632     {
633         return strtoupper($str);
634     }
635
636     function mb_substr($str, $start, $len=null)
637     {
638         return substr($str, $start, $len);
639     }
640
641     function mb_strpos($haystack, $needle, $offset=0)
642     {
643         return strpos($haystack, $needle, $offset);
644     }
645
646     function mb_strrpos($haystack, $needle, $offset=0)
647     {
648         return strrpos($haystack, $needle, $offset);
649     }
650 }
651
b54121 652 ?>