Aleksander Machniak
2015-06-27 a7e552b5a436375e233e7d4df4ed6cfc9e58d435
commit | author | age
1c4f23 1 <?php
A 2
8b92d2 3 /*
1c4f23 4  +-----------------------------------------------------------------------+
A 5  | This file is part of the Roundcube Webmail client                     |
6  | Copyright (C) 2005-2012, The Roundcube Dev Team                       |
7  | Copyright (C) 2011-2012, Kolab Systems AG                             |
7fe381 8  |                                                                       |
T 9  | Licensed under the GNU General Public License version 3 or            |
10  | any later version with exceptions for skins & plugins.                |
11  | See the README file for a full license statement.                     |
1c4f23 12  |                                                                       |
A 13  | PURPOSE:                                                              |
14  |   MIME message parsing utilities                                      |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  | Author: Aleksander Machniak <alec@alec.pl>                            |
18  +-----------------------------------------------------------------------+
19 */
20
21 /**
22  * Class for parsing MIME messages
23  *
9ab346 24  * @package    Framework
AM 25  * @subpackage Storage
26  * @author     Thomas Bruederli <roundcube@gmail.com>
27  * @author     Aleksander Machniak <alec@alec.pl>
1c4f23 28  */
A 29 class rcube_mime
30 {
eede51 31     private static $default_charset;
1c4f23 32
A 33
34     /**
35      * Object constructor.
36      */
37     function __construct($default_charset = null)
38     {
eede51 39         self::$default_charset = $default_charset;
0f5dee 40     }
AM 41
42
43     /**
44      * Returns message/object character set name
45      *
46      * @return string Characted set name
47      */
48     public static function get_charset()
49     {
50         if (self::$default_charset) {
51             return self::$default_charset;
1c4f23 52         }
0f5dee 53
AM 54         if ($charset = rcube::get_instance()->config->get('default_charset')) {
55             return $charset;
56         }
57
a92beb 58         return RCUBE_CHARSET;
1c4f23 59     }
A 60
61
62     /**
8b92d2 63      * Parse the given raw message source and return a structure
T 64      * of rcube_message_part objects.
65      *
a7e552 66      * It makes use of the rcube_mime_decode library
8b92d2 67      *
a7e552 68      * @param string $raw_body The message source
AM 69      *
8b92d2 70      * @return object rcube_message_part The message structure
T 71      */
72     public static function parse_message($raw_body)
73     {
a7e552 74         $conf = array(
AM 75             'include_bodies'  => true,
76             'decode_bodies'   => true,
77             'decode_headers'  => false,
78             'default_charset' => self::get_charset(),
79         );
8b92d2 80
a7e552 81         $mime = new rcube_mime_decode($conf);
8b92d2 82
a7e552 83         return $mime->decode($raw_body);
8b92d2 84     }
T 85
86
87     /**
1c4f23 88      * Split an address list into a structured array list
A 89      *
90      * @param string  $input    Input string
91      * @param int     $max      List only this number of addresses
92      * @param boolean $decode   Decode address strings
93      * @param string  $fallback Fallback charset if none specified
d2dff5 94      * @param boolean $addronly Return flat array with e-mail addresses only
1c4f23 95      *
d2dff5 96      * @return array Indexed list of addresses
1c4f23 97      */
d2dff5 98     static function decode_address_list($input, $max = null, $decode = true, $fallback = null, $addronly = false)
1c4f23 99     {
A 100         $a   = self::parse_address_list($input, $decode, $fallback);
101         $out = array();
102         $j   = 0;
103
104         // Special chars as defined by RFC 822 need to in quoted string (or escaped).
105         $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
106
107         if (!is_array($a))
108             return $out;
109
110         foreach ($a as $val) {
111             $j++;
112             $address = trim($val['address']);
113
d2dff5 114             if ($addronly) {
AM 115                 $out[$j] = $address;
116             }
117             else {
118                 $name = trim($val['name']);
119                 if ($name && $address && $name != $address)
120                     $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
121                 else if ($address)
122                     $string = $address;
123                 else if ($name)
124                     $string = $name;
1c4f23 125
d2dff5 126                 $out[$j] = array('name' => $name, 'mailto' => $address, 'string' => $string);
AM 127             }
1c4f23 128
A 129             if ($max && $j==$max)
130                 break;
131         }
132
133         return $out;
134     }
135
136
137     /**
138      * Decode a message header value
139      *
140      * @param string  $input         Header value
141      * @param string  $fallback      Fallback charset if none specified
142      *
143      * @return string Decoded string
144      */
145     public static function decode_header($input, $fallback = null)
146     {
147         $str = self::decode_mime_string((string)$input, $fallback);
148
149         return $str;
150     }
151
152
153     /**
154      * Decode a mime-encoded string to internal charset
155      *
156      * @param string $input    Header value
157      * @param string $fallback Fallback charset if none specified
158      *
159      * @return string Decoded string
160      */
161     public static function decode_mime_string($input, $fallback = null)
162     {
0f5dee 163         $default_charset = !empty($fallback) ? $fallback : self::get_charset();
1c4f23 164
A 165         // rfc: all line breaks or other characters not found
166         // in the Base64 Alphabet must be ignored by decoding software
167         // delete all blanks between MIME-lines, differently we can
168         // receive unnecessary blanks and broken utf-8 symbols
169         $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
170
171         // encoded-word regexp
172         $re = '/=\?([^?]+)\?([BbQq])\?([^\n]*?)\?=/';
173
174         // Find all RFC2047's encoded words
175         if (preg_match_all($re, $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
176             // Initialize variables
177             $tmp   = array();
178             $out   = '';
179             $start = 0;
180
181             foreach ($matches as $idx => $m) {
182                 $pos      = $m[0][1];
183                 $charset  = $m[1][0];
184                 $encoding = $m[2][0];
185                 $text     = $m[3][0];
186                 $length   = strlen($m[0][0]);
187
188                 // Append everything that is before the text to be decoded
189                 if ($start != $pos) {
190                     $substr = substr($input, $start, $pos-$start);
eebd44 191                     $out   .= rcube_charset::convert($substr, $default_charset);
1c4f23 192                     $start  = $pos;
A 193                 }
194                 $start += $length;
195
196                 // Per RFC2047, each string part "MUST represent an integral number
197                 // of characters . A multi-octet character may not be split across
198                 // adjacent encoded-words." However, some mailers break this, so we
199                 // try to handle characters spanned across parts anyway by iterating
200                 // through and aggregating sequential encoded parts with the same
201                 // character set and encoding, then perform the decoding on the
202                 // aggregation as a whole.
203
204                 $tmp[] = $text;
205                 if ($next_match = $matches[$idx+1]) {
206                     if ($next_match[0][1] == $start
207                         && $next_match[1][0] == $charset
208                         && $next_match[2][0] == $encoding
209                     ) {
210                         continue;
211                     }
212                 }
213
214                 $count = count($tmp);
215                 $text  = '';
216
217                 // Decode and join encoded-word's chunks
218                 if ($encoding == 'B' || $encoding == 'b') {
219                     // base64 must be decoded a segment at a time
220                     for ($i=0; $i<$count; $i++)
221                         $text .= base64_decode($tmp[$i]);
222                 }
223                 else { //if ($encoding == 'Q' || $encoding == 'q') {
224                     // quoted printable can be combined and processed at once
225                     for ($i=0; $i<$count; $i++)
226                         $text .= $tmp[$i];
227
228                     $text = str_replace('_', ' ', $text);
229                     $text = quoted_printable_decode($text);
230                 }
231
eebd44 232                 $out .= rcube_charset::convert($text, $charset);
1c4f23 233                 $tmp = array();
A 234             }
235
236             // add the last part of the input string
237             if ($start != strlen($input)) {
eebd44 238                 $out .= rcube_charset::convert(substr($input, $start), $default_charset);
1c4f23 239             }
A 240
241             // return the results
242             return $out;
243         }
244
245         // no encoding information, use fallback
eebd44 246         return rcube_charset::convert($input, $default_charset);
1c4f23 247     }
A 248
249
250     /**
251      * Decode a mime part
252      *
253      * @param string $input    Input string
254      * @param string $encoding Part encoding
255      * @return string Decoded string
256      */
257     public static function decode($input, $encoding = '7bit')
258     {
259         switch (strtolower($encoding)) {
260         case 'quoted-printable':
261             return quoted_printable_decode($input);
262         case 'base64':
263             return base64_decode($input);
264         case 'x-uuencode':
265         case 'x-uue':
266         case 'uue':
267         case 'uuencode':
268             return convert_uudecode($input);
269         case '7bit':
270         default:
271             return $input;
272         }
273     }
274
275
276     /**
277      * Split RFC822 header string into an associative array
278      * @access private
279      */
280     public static function parse_headers($headers)
281     {
282         $a_headers = array();
283         $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers);
284         $lines = explode("\n", $headers);
285         $c = count($lines);
286
287         for ($i=0; $i<$c; $i++) {
288             if ($p = strpos($lines[$i], ': ')) {
289                 $field = strtolower(substr($lines[$i], 0, $p));
290                 $value = trim(substr($lines[$i], $p+1));
291                 if (!empty($value))
292                     $a_headers[$field] = $value;
293             }
294         }
295
296         return $a_headers;
297     }
298
299
300     /**
301      * @access private
302      */
303     private static function parse_address_list($str, $decode = true, $fallback = null)
304     {
305         // remove any newlines and carriage returns before
306         $str = preg_replace('/\r?\n(\s|\t)?/', ' ', $str);
307
308         // extract list items, remove comments
309         $str = self::explode_header_string(',;', $str, true);
310         $result = array();
311
312         // simplified regexp, supporting quoted local part
313         $email_rx = '(\S+|("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+"))@\S+';
314
315         foreach ($str as $key => $val) {
316             $name    = '';
317             $address = '';
318             $val     = trim($val);
319
320             if (preg_match('/(.*)<('.$email_rx.')>$/', $val, $m)) {
321                 $address = $m[2];
322                 $name    = trim($m[1]);
323             }
324             else if (preg_match('/^('.$email_rx.')$/', $val, $m)) {
325                 $address = $m[1];
326                 $name    = '';
327             }
fd0fd3 328             // special case (#1489092)
AM 329             else if (preg_match('/(\s*<MAILER-DAEMON>)$/', $val, $m)) {
330                 $address = 'MAILER-DAEMON';
331                 $name    = substr($val, 0, -strlen($m[1]));
332             }
55d9d5 333             else if (preg_match('/('.$email_rx.')/', $val, $m)) {
AM 334                 $name = $m[1];
335             }
1c4f23 336             else {
A 337                 $name = $val;
338             }
339
340             // dequote and/or decode name
341             if ($name) {
342                 if ($name[0] == '"' && $name[strlen($name)-1] == '"') {
343                     $name = substr($name, 1, -1);
344                     $name = stripslashes($name);
345                 }
346                 if ($decode) {
347                     $name = self::decode_header($name, $fallback);
5140c3 348                     // some clients encode addressee name with quotes around it
AM 349                     if ($name[0] == '"' && $name[strlen($name)-1] == '"') {
350                         $name = substr($name, 1, -1);
351                     }
1c4f23 352                 }
A 353             }
354
355             if (!$address && $name) {
356                 $address = $name;
55d9d5 357                 $name    = '';
1c4f23 358             }
A 359
360             if ($address) {
dbf70c 361                 $address      = self::fix_email($address);
1c4f23 362                 $result[$key] = array('name' => $name, 'address' => $address);
A 363             }
364         }
365
366         return $result;
367     }
368
369
370     /**
371      * Explodes header (e.g. address-list) string into array of strings
372      * using specified separator characters with proper handling
373      * of quoted-strings and comments (RFC2822)
374      *
375      * @param string $separator       String containing separator characters
376      * @param string $str             Header string
377      * @param bool   $remove_comments Enable to remove comments
378      *
379      * @return array Header items
380      */
381     public static function explode_header_string($separator, $str, $remove_comments = false)
382     {
383         $length  = strlen($str);
384         $result  = array();
385         $quoted  = false;
386         $comment = 0;
387         $out     = '';
388
389         for ($i=0; $i<$length; $i++) {
390             // we're inside a quoted string
391             if ($quoted) {
392                 if ($str[$i] == '"') {
393                     $quoted = false;
394                 }
395                 else if ($str[$i] == "\\") {
396                     if ($comment <= 0) {
397                         $out .= "\\";
398                     }
399                     $i++;
400                 }
401             }
402             // we are inside a comment string
403             else if ($comment > 0) {
404                 if ($str[$i] == ')') {
405                     $comment--;
406                 }
407                 else if ($str[$i] == '(') {
408                     $comment++;
409                 }
410                 else if ($str[$i] == "\\") {
411                     $i++;
412                 }
413                 continue;
414             }
415             // separator, add to result array
416             else if (strpos($separator, $str[$i]) !== false) {
417                 if ($out) {
418                     $result[] = $out;
419                 }
420                 $out = '';
421                 continue;
422             }
423             // start of quoted string
424             else if ($str[$i] == '"') {
425                 $quoted = true;
426             }
427             // start of comment
428             else if ($remove_comments && $str[$i] == '(') {
429                 $comment++;
430             }
431
432             if ($comment <= 0) {
433                 $out .= $str[$i];
434             }
435         }
436
437         if ($out && $comment <= 0) {
438             $result[] = $out;
439         }
440
441         return $result;
442     }
443
444
445     /**
446      * Interpret a format=flowed message body according to RFC 2646
447      *
448      * @param string  $text Raw body formatted as flowed text
449      *
450      * @return string Interpreted text with unwrapped lines and stuffed space removed
451      */
452     public static function unfold_flowed($text)
453     {
454         $text = preg_split('/\r?\n/', $text);
455         $last = -1;
456         $q_level = 0;
457
458         foreach ($text as $idx => $line) {
b92ec5 459             if (preg_match('/^(>+)/', $line, $m)) {
AM 460                 // remove quote chars
461                 $q    = strlen($m[1]);
462                 $line = preg_replace('/^>+/', '', $line);
7ebed1 463                 // remove (optional) space-staffing
AM 464                 $line = preg_replace('/^ /', '', $line);
1c4f23 465
aabd62 466                 // The same paragraph (We join current line with the previous one) when:
AM 467                 // - the same level of quoting
468                 // - previous line was flowed
469                 // - previous line contains more than only one single space (and quote char(s))
6d41d8 470                 if ($q == $q_level
aabd62 471                     && isset($text[$last]) && $text[$last][strlen($text[$last])-1] == ' '
AM 472                     && !preg_match('/^>+ {0,1}$/', $text[$last])
1c4f23 473                 ) {
A 474                     $text[$last] .= $line;
475                     unset($text[$idx]);
476                 }
477                 else {
478                     $last = $idx;
479                 }
480             }
481             else {
482                 $q = 0;
483                 if ($line == '-- ') {
484                     $last = $idx;
485                 }
486                 else {
487                     // remove space-stuffing
488                     $line = preg_replace('/^\s/', '', $line);
489
ac9392 490                     if (isset($text[$last]) && $line && !$q_level
1c4f23 491                         && $text[$last] != '-- '
A 492                         && $text[$last][strlen($text[$last])-1] == ' '
493                     ) {
494                         $text[$last] .= $line;
495                         unset($text[$idx]);
496                     }
497                     else {
498                         $text[$idx] = $line;
499                         $last = $idx;
500                     }
501                 }
502             }
503             $q_level = $q;
504         }
505
506         return implode("\r\n", $text);
507     }
508
509
510     /**
511      * Wrap the given text to comply with RFC 2646
512      *
513      * @param string $text Text to wrap
514      * @param int $length Length
c72a96 515      * @param string $charset Character encoding of $text
1c4f23 516      *
A 517      * @return string Wrapped text
518      */
c72a96 519     public static function format_flowed($text, $length = 72, $charset=null)
1c4f23 520     {
A 521         $text = preg_split('/\r?\n/', $text);
522
523         foreach ($text as $idx => $line) {
524             if ($line != '-- ') {
b92ec5 525                 if (preg_match('/^(>+)/', $line, $m)) {
AM 526                     // remove quote chars
527                     $level  = strlen($m[1]);
528                     $line   = preg_replace('/^>+/', '', $line);
87a968 529                     // remove (optional) space-staffing and spaces before the line end
AM 530                     $line   = preg_replace('/(^ | +$)/', '', $line);
42b8a6 531                     $prefix = str_repeat('>', $level) . ' ';
AM 532                     $line   = $prefix . self::wordwrap($line, $length - $level - 2, " \r\n$prefix", false, $charset);
1c4f23 533                 }
A 534                 else if ($line) {
c72a96 535                     $line = self::wordwrap(rtrim($line), $length - 2, " \r\n", false, $charset);
1c4f23 536                     // space-stuffing
A 537                     $line = preg_replace('/(^|\r\n)(From| |>)/', '\\1 \\2', $line);
538                 }
539
540                 $text[$idx] = $line;
541             }
542         }
543
544         return implode("\r\n", $text);
545     }
546
b6a182 547
A 548     /**
7439d3 549      * Improved wordwrap function with multibyte support.
AM 550      * The code is based on Zend_Text_MultiByte::wordWrap().
b6a182 551      *
7439d3 552      * @param string $string      Text to wrap
AM 553      * @param int    $width       Line width
554      * @param string $break       Line separator
555      * @param bool   $cut         Enable to cut word
556      * @param string $charset     Charset of $string
557      * @param bool   $wrap_quoted When enabled quoted lines will not be wrapped
b6a182 558      *
A 559      * @return string Text
560      */
7439d3 561     public static function wordwrap($string, $width=75, $break="\n", $cut=false, $charset=null, $wrap_quoted=true)
b6a182 562     {
581a52 563         // Note: Never try to use iconv instead of mbstring functions here
AM 564         //       Iconv's substr/strlen are 100x slower (#1489113)
c72a96 565
581a52 566         if ($charset && $charset != RCUBE_CHARSET && function_exists('mb_internal_encoding')) {
AM 567             mb_internal_encoding($charset);
568         }
b6a182 569
7439d3 570         // Convert \r\n to \n, this is our line-separator
AM 571         $string       = str_replace("\r\n", "\n", $string);
572         $separator    = "\n"; // must be 1 character length
573         $result       = array();
b6a182 574
581a52 575         while (($stringLength = mb_strlen($string)) > 0) {
AM 576             $breakPos = mb_strpos($string, $separator, 0);
b6a182 577
7439d3 578             // quoted line (do not wrap)
AM 579             if ($wrap_quoted && $string[0] == '>') {
580                 if ($breakPos === $stringLength - 1 || $breakPos === false) {
581                     $subString = $string;
582                     $cutLength = null;
b6a182 583                 }
A 584                 else {
581a52 585                     $subString = mb_substr($string, 0, $breakPos);
7439d3 586                     $cutLength = $breakPos + 1;
AM 587                 }
588             }
589             // next line found and current line is shorter than the limit
590             else if ($breakPos !== false && $breakPos < $width) {
591                 if ($breakPos === $stringLength - 1) {
592                     $subString = $string;
593                     $cutLength = null;
594                 }
595                 else {
581a52 596                     $subString = mb_substr($string, 0, $breakPos);
7439d3 597                     $cutLength = $breakPos + 1;
AM 598                 }
599             }
600             else {
581a52 601                 $subString = mb_substr($string, 0, $width);
7439d3 602
AM 603                 // last line
1041aa 604                 if ($breakPos === false && $subString === $string) {
7439d3 605                     $cutLength = null;
AM 606                 }
607                 else {
581a52 608                     $nextChar = mb_substr($string, $width, 1);
7439d3 609
AM 610                     if ($nextChar === ' ' || $nextChar === $separator) {
581a52 611                         $afterNextChar = mb_substr($string, $width + 1, 1);
7439d3 612
0f1521 613                         // Note: mb_substr() does never return False
AM 614                         if ($afterNextChar === false || $afterNextChar === '') {
7439d3 615                             $subString .= $nextChar;
AM 616                         }
617
581a52 618                         $cutLength = mb_strlen($subString) + 1;
7439d3 619                     }
AM 620                     else {
581a52 621                         $spacePos = mb_strrpos($subString, ' ', 0);
7439d3 622
AM 623                         if ($spacePos !== false) {
581a52 624                             $subString = mb_substr($subString, 0, $spacePos);
7439d3 625                             $cutLength = $spacePos + 1;
AM 626                         }
627                         else if ($cut === false) {
581a52 628                             $spacePos = mb_strpos($string, ' ', 0);
7439d3 629
0f1521 630                             if ($spacePos !== false && ($breakPos === false || $spacePos < $breakPos)) {
581a52 631                                 $subString = mb_substr($string, 0, $spacePos);
7439d3 632                                 $cutLength = $spacePos + 1;
0f1521 633                             }
AM 634                             else if ($breakPos === false) {
635                                 $subString = $string;
636                                 $cutLength = null;
7439d3 637                             }
AM 638                             else {
581a52 639                                 $subString = mb_substr($string, 0, $breakPos);
2ce019 640                                 $cutLength = $breakPos + 1;
b6a182 641                             }
A 642                         }
643                         else {
7439d3 644                             $cutLength = $width;
b6a182 645                         }
A 646                     }
647                 }
648             }
649
7439d3 650             $result[] = $subString;
AM 651
652             if ($cutLength !== null) {
581a52 653                 $string = mb_substr($string, $cutLength, ($stringLength - $cutLength));
7439d3 654             }
AM 655             else {
656                 break;
b6a182 657             }
A 658         }
659
581a52 660         if ($charset && $charset != RCUBE_CHARSET && function_exists('mb_internal_encoding')) {
AM 661             mb_internal_encoding(RCUBE_CHARSET);
662         }
663
7439d3 664         return implode($break, $result);
b6a182 665     }
A 666
667
668     /**
669      * A method to guess the mime_type of an attachment.
670      *
0a8397 671      * @param string $path      Path to the file or file contents
b6a182 672      * @param string $name      File name (with suffix)
0a8397 673      * @param string $failover  Mime type supplied for failover
TB 674      * @param boolean $is_stream   Set to True if $path contains file contents
675      * @param boolean $skip_suffix Set to True if the config/mimetypes.php mappig should be ignored
b6a182 676      *
A 677      * @return string
678      * @author Till Klampaeckel <till@php.net>
679      * @see    http://de2.php.net/manual/en/ref.fileinfo.php
680      * @see    http://de2.php.net/mime_content_type
681      */
0a8397 682     public static function file_content_type($path, $name, $failover = 'application/octet-stream', $is_stream = false, $skip_suffix = false)
b6a182 683     {
9e9d62 684         static $mime_ext = array();
TB 685
b6a182 686         $mime_type = null;
9e9d62 687         $config = rcube::get_instance()->config;
TB 688         $mime_magic = $config->get('mime_magic');
689
690         if (!$skip_suffix && empty($mime_ext)) {
691             foreach ($config->resolve_paths('mimetypes.php') as $fpath) {
692                 $mime_ext = array_merge($mime_ext, (array) @include($fpath));
693             }
694         }
b6a182 695
A 696         // use file name suffix with hard-coded mime-type map
9e9d62 697         if (!$skip_suffix && is_array($mime_ext) && $name) {
b6a182 698             if ($suffix = substr($name, strrpos($name, '.')+1)) {
A 699                 $mime_type = $mime_ext[strtolower($suffix)];
700             }
701         }
702
703         // try fileinfo extension if available
704         if (!$mime_type && function_exists('finfo_open')) {
4f693e 705             // null as a 2nd argument should be the same as no argument
AM 706             // this however is not true on all systems/versions
707             if ($mime_magic) {
708                 $finfo = finfo_open(FILEINFO_MIME, $mime_magic);
709             }
710             else {
711                 $finfo = finfo_open(FILEINFO_MIME);
712             }
713
714             if ($finfo) {
b6a182 715                 if ($is_stream)
A 716                     $mime_type = finfo_buffer($finfo, $path);
717                 else
718                     $mime_type = finfo_file($finfo, $path);
719                 finfo_close($finfo);
720             }
721         }
722
723         // try PHP's mime_content_type
724         if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
725             $mime_type = @mime_content_type($path);
726         }
727
728         // fall back to user-submitted string
729         if (!$mime_type) {
730             $mime_type = $failover;
731         }
732         else {
733             // Sometimes (PHP-5.3?) content-type contains charset definition,
734             // Remove it (#1487122) also "charset=binary" is useless
735             $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
736         }
737
738         return $mime_type;
739     }
740
741
742     /**
0a8397 743      * Get mimetype => file extension mapping
TB 744      *
745      * @param string  Mime-Type to get extensions for
746      * @return array  List of extensions matching the given mimetype or a hash array with ext -> mimetype mappings if $mimetype is not given
747      */
748     public static function get_mime_extensions($mimetype = null)
749     {
750         static $mime_types, $mime_extensions;
751
752         // return cached data
753         if (is_array($mime_types)) {
754             return $mimetype ? $mime_types[$mimetype] : $mime_extensions;
755         }
756
757         // load mapping file
758         $file_paths = array();
759
02c9c9 760         if ($mime_types = rcube::get_instance()->config->get('mime_types')) {
0a8397 761             $file_paths[] = $mime_types;
02c9c9 762         }
0a8397 763
TB 764         // try common locations
02c9c9 765         if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
AM 766             $file_paths[] = 'C:/xampp/apache/conf/mime.types.';
767         }
768         else {
769             $file_paths[] = '/etc/mime.types';
770             $file_paths[] = '/etc/httpd/mime.types';
771             $file_paths[] = '/etc/httpd2/mime.types';
772             $file_paths[] = '/etc/apache/mime.types';
773             $file_paths[] = '/etc/apache2/mime.types';
774             $file_paths[] = '/usr/local/etc/httpd/conf/mime.types';
775             $file_paths[] = '/usr/local/etc/apache/conf/mime.types';
776         }
0a8397 777
TB 778         foreach ($file_paths as $fp) {
c16bd5 779             if (@is_readable($fp)) {
02c9c9 780                 $lines = file($fp, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
0a8397 781                 break;
TB 782             }
783         }
784
785         $mime_types = $mime_extensions = array();
1ece73 786         $regex = "/([\w\+\-\.\/]+)\s+([\w\s]+)/i";
0a8397 787         foreach((array)$lines as $line) {
TB 788              // skip comments or mime types w/o any extensions
789             if ($line[0] == '#' || !preg_match($regex, $line, $matches))
790                 continue;
791
792             $mime = $matches[1];
793             foreach (explode(' ', $matches[2]) as $ext) {
794                 $ext = trim($ext);
795                 $mime_types[$mime][] = $ext;
796                 $mime_extensions[$ext] = $mime;
797             }
798         }
799
800         // fallback to some well-known types most important for daily emails
801         if (empty($mime_types)) {
9e9d62 802             foreach (rcube::get_instance()->config->resolve_paths('mimetypes.php') as $fpath) {
TB 803                 $mime_extensions = array_merge($mime_extensions, (array) @include($fpath));
804             }
0a8397 805
99cfba 806             foreach ($mime_extensions as $ext => $mime) {
0a8397 807                 $mime_types[$mime][] = $ext;
99cfba 808             }
AM 809         }
810
811         // Add some known aliases that aren't included by some mime.types (#1488891)
812         // the order is important here so standard extensions have higher prio
813         $aliases = array(
814             'image/gif'      => array('gif'),
815             'image/png'      => array('png'),
816             'image/x-png'    => array('png'),
817             'image/jpeg'     => array('jpg', 'jpeg', 'jpe'),
818             'image/jpg'      => array('jpg', 'jpeg', 'jpe'),
819             'image/pjpeg'    => array('jpg', 'jpeg', 'jpe'),
820             'image/tiff'     => array('tif'),
821             'message/rfc822' => array('eml'),
822             'text/x-mail'    => array('eml'),
823         );
824
825         foreach ($aliases as $mime => $exts) {
826             $mime_types[$mime] = array_unique(array_merge((array) $mime_types[$mime], $exts));
827
828             foreach ($exts as $ext) {
829                 if (!isset($mime_extensions[$ext])) {
830                     $mime_extensions[$ext] = $mime;
831                 }
832             }
0a8397 833         }
TB 834
835         return $mimetype ? $mime_types[$mimetype] : $mime_extensions;
836     }
837
838
839     /**
b6a182 840      * Detect image type of the given binary data by checking magic numbers.
A 841      *
842      * @param string $data  Binary file content
843      *
844      * @return string Detected mime-type or jpeg as fallback
845      */
846     public static function image_content_type($data)
847     {
848         $type = 'jpeg';
849         if      (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
850         else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
851         else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
852     //  else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';
853
854         return 'image/' . $type;
855     }
856
dbf70c 857     /**
AM 858      * Try to fix invalid email addresses
859      */
860     public static function fix_email($email)
861     {
862         $parts = rcube_utils::explode_quoted_string('@', $email);
863         foreach ($parts as $idx => $part) {
864             // remove redundant quoting (#1490040)
865             if ($part[0] == '"' && preg_match('/^"([a-zA-Z0-9._+=-]+)"$/', $part, $m)) {
866                 $parts[$idx] = $m[1];
867             }
868         }
869
870         return implode('@', $parts);
871     }
1c4f23 872 }