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