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