]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_shared.inc
Fix symlink mess
[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 5770 2012-01-13 11:23:17Z 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  * Wrapper function for wordwrap
168  */
169 function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
170 {
171   $para = explode($break, $string);
172   $string = '';
173   while (count($para)) {
174     $line = array_shift($para);
175     if ($line[0] == '>') {
176       $string .= $line.$break;
177       continue;
178     }
179     $list = explode(' ', $line);
180     $len = 0;
181     while (count($list)) {
182       $line = array_shift($list);
183       $l = mb_strlen($line);
184       $newlen = $len + $l + ($len ? 1 : 0);
185
186       if ($newlen <= $width) {
187         $string .= ($len ? ' ' : '').$line;
188         $len += (1 + $l);
189       } else {
190         if ($l > $width) {
191           if ($cut) {
192             $start = 0;
193             while ($l) {
194               $str = mb_substr($line, $start, $width);
195               $strlen = mb_strlen($str);
196               $string .= ($len ? $break : '').$str;
197               $start += $strlen;
198               $l -= $strlen;
199               $len = $strlen;
200             }
201           } else {
202                 $string .= ($len ? $break : '').$line;
203             if (count($list)) $string .= $break;
204             $len = 0;
205           }
206         } else {
207           $string .= $break.$line;
208           $len = $l;
209         }
210       }
211     }
212     if (count($para)) $string .= $break;
213   }
214   return $string;
215 }
216
217 /**
218  * Read a specific HTTP request header
219  *
220  * @access static
221  * @param  string $name Header name
222  * @return mixed  Header value or null if not available
223  */
224 function rc_request_header($name)
225 {
226   if (function_exists('getallheaders'))
227   {
228     $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
229     $key  = strtoupper($name);
230   }
231   else
232   {
233     $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
234     $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
235   }
236
237   return $hdrs[$key];
238 }
239
240
241 /**
242  * Make sure the string ends with a slash
243  */
244 function slashify($str)
245 {
246   return unslashify($str).'/';
247 }
248
249
250 /**
251  * Remove slash at the end of the string
252  */
253 function unslashify($str)
254 {
255   return preg_replace('/\/$/', '', $str);
256 }
257
258
259 /**
260  * Delete all files within a folder
261  *
262  * @param string Path to directory
263  * @return boolean True on success, False if directory was not found
264  */
265 function clear_directory($dir_path)
266 {
267   $dir = @opendir($dir_path);
268   if(!$dir) return FALSE;
269
270   while ($file = readdir($dir))
271     if (strlen($file)>2)
272       unlink("$dir_path/$file");
273
274   closedir($dir);
275   return TRUE;
276 }
277
278
279 /**
280  * Create a unix timestamp with a specified offset from now
281  *
282  * @param string String representation of the offset (e.g. 20min, 5h, 2days)
283  * @param int Factor to multiply with the offset
284  * @return int Unix timestamp
285  */
286 function get_offset_time($offset_str, $factor=1)
287 {
288   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
289   {
290     $amount = (int)$regs[1];
291     $unit = strtolower($regs[2]);
292   }
293   else
294   {
295     $amount = (int)$offset_str;
296     $unit = 's';
297   }
298
299   $ts = mktime();
300   switch ($unit)
301   {
302     case 'w':
303       $amount *= 7;
304     case 'd':
305       $amount *= 24;
306     case 'h':
307       $amount *= 60;
308     case 'm':
309       $amount *= 60;
310     case 's':
311       $ts += $amount * $factor;
312   }
313
314   return $ts;
315 }
316
317
318 /**
319  * Truncate string if it is longer than the allowed length
320  * Replace the middle or the ending part of a string with a placeholder
321  *
322  * @param string Input string
323  * @param int    Max. length
324  * @param string Replace removed chars with this
325  * @param bool   Set to True if string should be truncated from the end
326  * @return string Abbreviated string
327  */
328 function abbreviate_string($str, $maxlength, $place_holder='...', $ending=false)
329 {
330   $length = mb_strlen($str);
331
332   if ($length > $maxlength)
333   {
334     if ($ending)
335       return mb_substr($str, 0, $maxlength) . $place_holder;
336
337     $place_holder_length = mb_strlen($place_holder);
338     $first_part_length = floor(($maxlength - $place_holder_length)/2);
339     $second_starting_location = $length - $maxlength + $first_part_length + $place_holder_length;
340     $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location);
341   }
342
343   return $str;
344 }
345
346
347 /**
348  * A method to guess the mime_type of an attachment.
349  *
350  * @param string $path      Path to the file.
351  * @param string $name      File name (with suffix)
352  * @param string $failover  Mime type supplied for failover.
353  * @param string $is_stream Set to True if $path contains file body
354  *
355  * @return string
356  * @author Till Klampaeckel <till@php.net>
357  * @see    http://de2.php.net/manual/en/ref.fileinfo.php
358  * @see    http://de2.php.net/mime_content_type
359  */
360 function rc_mime_content_type($path, $name, $failover = 'application/octet-stream', $is_stream=false)
361 {
362     $mime_type = null;
363     $mime_magic = rcmail::get_instance()->config->get('mime_magic');
364     $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
365
366     // use file name suffix with hard-coded mime-type map
367     if (is_array($mime_ext) && $name) {
368         if ($suffix = substr($name, strrpos($name, '.')+1)) {
369             $mime_type = $mime_ext[strtolower($suffix)];
370         }
371     }
372
373     // try fileinfo extension if available
374     if (!$mime_type && function_exists('finfo_open')) {
375         if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
376             if ($is_stream)
377                 $mime_type = finfo_buffer($finfo, $path);
378             else
379                 $mime_type = finfo_file($finfo, $path);
380             finfo_close($finfo);
381         }
382     }
383
384     // try PHP's mime_content_type
385     if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
386       $mime_type = @mime_content_type($path);
387     }
388
389     // fall back to user-submitted string
390     if (!$mime_type) {
391         $mime_type = $failover;
392     }
393     else {
394         // Sometimes (PHP-5.3?) content-type contains charset definition,
395         // Remove it (#1487122) also "charset=binary" is useless
396         $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
397     }
398
399     return $mime_type;
400 }
401
402
403 /**
404  * Detect image type of the given binary data by checking magic numbers
405  *
406  * @param string  Binary file content
407  * @return string Detected mime-type or jpeg as fallback
408  */
409 function rc_image_content_type($data)
410 {
411     $type = 'jpeg';
412     if      (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
413     else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
414     else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
415 //  else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';
416
417     return 'image/' . $type;
418 }
419
420
421 /**
422  * A method to guess encoding of a string.
423  *
424  * @param string $string        String.
425  * @param string $failover      Default result for failover.
426  *
427  * @return string
428  */
429 function rc_detect_encoding($string, $failover='')
430 {
431     if (!function_exists('mb_detect_encoding')) {
432         return $failover;
433     }
434
435     // FIXME: the order is important, because sometimes 
436     // iso string is detected as euc-jp and etc.
437     $enc = array(
438       'UTF-8', 'SJIS', 'BIG5', 'GB2312',
439       'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
440       'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
441       'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
442       'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R', 
443       'ISO-2022-KR', 'ISO-2022-JP'
444     );
445
446     $result = mb_detect_encoding($string, join(',', $enc));
447
448     return $result ? $result : $failover;
449 }
450
451 /**
452  * Removes non-unicode characters from input
453  *
454  * @param mixed $input String or array.
455  * @return string
456  */
457 function rc_utf8_clean($input)
458 {
459   // handle input of type array
460   if (is_array($input)) {
461     foreach ($input as $idx => $val)
462       $input[$idx] = rc_utf8_clean($val);
463     return $input;
464   }
465
466   if (!is_string($input) || $input == '')
467     return $input;
468
469   // iconv/mbstring are much faster (especially with long strings)
470   if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
471     return $res;
472
473   if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
474     return $res;
475
476   $regexp = '/^('.
477 //    '[\x00-\x7F]'.                                  // UTF8-1
478     '|[\xC2-\xDF][\x80-\xBF]'.                      // UTF8-2
479     '|\xE0[\xA0-\xBF][\x80-\xBF]'.                  // UTF8-3
480     '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
481     '|\xED[\x80-\x9F][\x80-\xBF]'.                  // UTF8-3
482     '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
483     '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
484     '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
485     '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
486     ')$/';
487
488   $seq = '';
489   $out = '';
490
491   for ($i = 0, $len = strlen($input); $i < $len; $i++) {
492     $chr = $input[$i];
493     $ord = ord($chr);
494     // 1-byte character
495     if ($ord <= 0x7F) {
496       if ($seq)
497         $out .= preg_match($regexp, $seq) ? $seq : '';
498       $seq = '';
499       $out .= $chr;
500     // first (or second) byte of multibyte sequence
501     } else if ($ord >= 0xC0) {
502       if (strlen($seq)>1) {
503         $out .= preg_match($regexp, $seq) ? $seq : '';
504         $seq = '';
505       } else if ($seq && ord($seq) < 0xC0) {
506         $seq = '';
507       }
508       $seq .= $chr;
509     // next byte of multibyte sequence
510     } else if ($seq) {
511       $seq .= $chr;
512     }
513   }
514
515   if ($seq)
516     $out .= preg_match($regexp, $seq) ? $seq : '';
517
518   return $out;
519 }
520
521
522 /**
523  * Convert a variable into a javascript object notation
524  *
525  * @param mixed Input value
526  * @return string Serialized JSON string
527  */
528 function json_serialize($input)
529 {
530   $input = rc_utf8_clean($input);
531
532   // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
533   // that's why we have @ here
534   return @json_encode($input);
535 }
536
537
538 /**
539  * Explode quoted string
540  * 
541  * @param string Delimiter expression string for preg_match()
542  * @param string Input string
543  */
544 function rcube_explode_quoted_string($delimiter, $string)
545 {
546   $result = array();
547   $strlen = strlen($string);
548
549   for ($q=$p=$i=0; $i < $strlen; $i++) {
550     if ($string[$i] == "\"" && $string[$i-1] != "\\") {
551       $q = $q ? false : true;
552     } 
553     else if (!$q && preg_match("/$delimiter/", $string[$i])) {
554       $result[] = substr($string, $p, $i - $p);
555       $p = $i + 1;
556     }
557   }
558
559   $result[] = substr($string, $p);
560   return $result;
561 }
562
563
564 /**
565  * Get all keys from array (recursive)
566  * 
567  * @param array Input array
568  * @return array
569  */
570 function array_keys_recursive($array)
571 {
572   $keys = array();
573
574   if (!empty($array))
575     foreach ($array as $key => $child) {
576       $keys[] = $key;
577       foreach (array_keys_recursive($child) as $val)
578         $keys[] = $val;
579     }
580   return $keys;
581 }
582
583
584 /**
585  * mbstring replacement functions
586  */
587
588 if (!extension_loaded('mbstring'))
589 {
590     function mb_strlen($str)
591     {
592         return strlen($str);
593     }
594
595     function mb_strtolower($str)
596     {
597         return strtolower($str);
598     }
599
600     function mb_strtoupper($str)
601     {
602         return strtoupper($str);
603     }
604
605     function mb_substr($str, $start, $len=null)
606     {
607         return substr($str, $start, $len);
608     }
609
610     function mb_strpos($haystack, $needle, $offset=0)
611     {
612         return strpos($haystack, $needle, $offset);
613     }
614
615     function mb_strrpos($haystack, $needle, $offset=0)
616     {
617         return strrpos($haystack, $needle, $offset);
618     }
619 }
620
621 /**
622  * intl replacement functions
623  */
624
625 if (!function_exists('idn_to_utf8'))
626 {
627     function idn_to_utf8($domain, $flags=null)
628     {
629         static $idn, $loaded;
630
631         if (!$loaded) {
632             $idn = new Net_IDNA2();
633             $loaded = true;
634         }
635
636         if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
637             try {
638                 $domain = $idn->decode($domain);
639             }
640             catch (Exception $e) {
641             }
642         }
643         return $domain;
644     }
645 }
646
647 if (!function_exists('idn_to_ascii'))
648 {
649     function idn_to_ascii($domain, $flags=null)
650     {
651         static $idn, $loaded;
652
653         if (!$loaded) {
654             $idn = new Net_IDNA2();
655             $loaded = true;
656         }
657
658         if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
659             try {
660                 $domain = $idn->encode($domain);
661             }
662             catch (Exception $e) {
663             }
664         }
665         return $domain;
666     }
667 }
668