Aleksander Machniak
2016-01-21 c9e2ab488e047295eae76bdd0cb2d1807c191ee5
commit | author | age
f7427f 1 <?php
AM 2
3 /**
4  +-----------------------------------------------------------------------+
5  | This file is part of the Roundcube Webmail client                     |
6  | Copyright (C) 2005-2015, The Roundcube Dev Team                       |
7  | Copyright (C) 2011-2015, Kolab Systems AG                             |
8  |                                                                       |
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.                     |
12  |                                                                       |
13  | PURPOSE:                                                              |
14  |   MIME message parsing utilities derived from Mail_mimeDecode         |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  | Author: Aleksander Machniak <alec@alec.pl>                            |
18  | Author: Richard Heyes <richard@phpguru.org>                           |
19  +-----------------------------------------------------------------------+
20 */
21
22 /**
23  * Class for parsing MIME messages
24  *
25  * @package    Framework
26  * @subpackage Storage
27  * @author     Aleksander Machniak <alec@alec.pl>
28  */
29 class rcube_mime_decode
30 {
31     /**
32      * Class configuration parameters.
33      *
34      * @var array
35      */
36     protected $params = array(
37         'include_bodies'  => true,
38         'decode_bodies'   => true,
39         'decode_headers'  => true,
40         'crlf'            => "\r\n",
41         'default_charset' => RCUBE_CHARSET,
42     );
43
44
45     /**
46      * Constructor.
47      *
48      * Sets up the object, initialise the variables, and splits and
49      * stores the header and body of the input.
50      *
51      * @param array $params An array of various parameters that determine
52      *                       various things:
53      *              include_bodies - Whether to include the body in the returned
54      *                               object.
55      *              decode_bodies  - Whether to decode the bodies
56      *                               of the parts. (Transfer encoding)
57      *              decode_headers - Whether to decode headers
58      *              crlf           - CRLF type to use (CRLF/LF/CR)
59      */
60     public function __construct($params = array())
61     {
62         if (!empty($params)) {
63             $this->params = array_merge($this->params, (array) $params);
64         }
65     }
66
67     /**
68      * Performs the decoding process.
69      *
70      * @param string $input The input to decode
71      *
72      * @return object|bool Decoded results or False on failure
73      */
74     public function decode($input)
75     {
76         list($header, $body) = $this->splitBodyHeader($input);
77
78         // @TODO: Since this is a part of Roundcube Framework
79         // we should return rcube_message_part structure
80
81         if ($struct = $this->do_decode($header, $body)) {
82             $struct = $this->structure_part($struct);
83         }
84
85         return $struct;
86     }
87
88     /**
89      * Performs the decoding. Decodes the body string passed to it
90      * If it finds certain content-types it will call itself in a
91      * recursive fashion
92      *
93      * @param string $headers       Header section
94      * @param string $body          Body section
95      * @param string $default_ctype Default content type
96      *
97      * @return object|bool Decoded results or False on error
98      */
99     protected function do_decode($headers, $body, $default_ctype = 'text/plain')
100     {
101         $return  = new stdClass;
102         $headers = $this->parseHeaders($headers);
103
104         while (list($key, $value) = each($headers)) {
105             $header_name = strtolower($value['name']);
106
107             if (isset($return->headers[$header_name]) && !is_array($return->headers[$header_name])) {
108                 $return->headers[$header_name]   = array($return->headers[$header_name]);
109                 $return->headers[$header_name][] = $value['value'];
110             }
111             else if (isset($return->headers[$header_name])) {
112                 $return->headers[$header_name][] = $value['value'];
113             }
114             else {
115                 $return->headers[$header_name] = $value['value'];
116             }
117
118             switch ($header_name) {
119             case 'content-type':
120                 $content_type = $this->parseHeaderValue($value['value']);
121
122                 if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
123                     $return->ctype_primary   = $regs[1];
124                     $return->ctype_secondary = $regs[2];
125                 }
126
127                 if (isset($content_type['other'])) {
128                     while (list($p_name, $p_value) = each($content_type['other'])) {
129                         $return->ctype_parameters[$p_name] = $p_value;
130                     }
131                 }
132
133                 break;
134
135             case 'content-disposition';
136                 $content_disposition = $this->parseHeaderValue($value['value']);
137                 $return->disposition = $content_disposition['value'];
138
139                 if (isset($content_disposition['other'])) {
140                     while (list($p_name, $p_value) = each($content_disposition['other'])) {
141                         $return->d_parameters[$p_name] = $p_value;
142                     }
143                 }
144
145                 break;
146
147             case 'content-transfer-encoding':
148                 $content_transfer_encoding = $this->parseHeaderValue($value['value']);
149                 break;
150             }
151         }
152
153         if (isset($content_type)) {
154             $ctype = strtolower($content_type['value']);
155
156             switch ($ctype) {
157             case 'text/plain':
158                 $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
159
160                 if ($this->params['include_bodies']) {
161                     $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body, $encoding) : $body;
162                 }
163
164                 break;
165
166             case 'text/html':
167                 $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
168
169                 if ($this->params['include_bodies']) {
170                     $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body, $encoding) : $body;
171                 }
172
173                 break;
174
175             case 'multipart/digest':
176             case 'multipart/alternative':
177             case 'multipart/related':
178             case 'multipart/mixed':
c9e2ab 179             case 'multipart/signed':
AM 180             case 'multipart/encrypted':
f7427f 181                 if (!isset($content_type['other']['boundary'])) {
AM 182                     return false;
183                 }
184
185                 $default_ctype = $ctype === 'multipart/digest' ? 'message/rfc822' : 'text/plain';
186                 $parts         = $this->boundarySplit($body, $content_type['other']['boundary']);
187
188                 for ($i = 0; $i < count($parts); $i++) {
189                     list($part_header, $part_body) = $this->splitBodyHeader($parts[$i]);
190                     $return->parts[] = $this->do_decode($part_header, $part_body, $default_ctype);
191                 }
192
193                 break;
194
195             case 'message/rfc822':
196                 $obj = new rcube_mime_decode($this->params);
197                 $return->parts[] = $obj->decode($body);
198                 unset($obj);
199                 break;
200
201             default:
202                 if ($this->params['include_bodies']) {
203                     $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body, $content_transfer_encoding['value']) : $body;
204                 }
205
206                 break;
207             }
208         }
209         else {
210             $ctype = explode('/', $default_ctype);
211             $return->ctype_primary   = $ctype[0];
212             $return->ctype_secondary = $ctype[1];
213
214             if ($this->params['include_bodies']) {
215                 $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body) : $body;
216             }
217         }
218
219         return $return;
220     }
221
222     /**
223      * Given a string containing a header and body
224      * section, this function will split them (at the first
225      * blank line) and return them.
226      *
227      * @param string $input Input to split apart
228      *
229      * @return array Contains header and body section
230      */
231     protected function splitBodyHeader($input)
232     {
233         $pos = strpos($input, $this->params['crlf'] . $this->params['crlf']);
234         if ($pos === false) {
235             return false;
236         }
237
238         $crlf_len = strlen($this->params['crlf']);
239         $header   = substr($input, 0, $pos);
240         $body     = substr($input, $pos + 2 * $crlf_len);
241
242         if (substr_compare($body, $this->params['crlf'], -$crlf_len) === 0) {
243             $body = substr($body, 0, -$crlf_len);
244         }
245
246         return array($header, $body);
247     }
248
249     /**
250      * Parse headers given in $input and return as assoc array.
251      *
252      * @param string $input Headers to parse
253      *
254      * @return array Contains parsed headers
255      */
256     protected function parseHeaders($input)
257     {
258         if ($input !== '') {
259             // Unfold the input
260             $input   = preg_replace('/' . $this->params['crlf'] . "(\t| )/", ' ', $input);
261             $headers = explode($this->params['crlf'], trim($input));
262
263             foreach ($headers as $value) {
264                 $hdr_name  = substr($value, 0, $pos = strpos($value, ':'));
265                 $hdr_value = substr($value, $pos+1);
266
267                 if ($hdr_value[0] == ' ') {
268                     $hdr_value = substr($hdr_value, 1);
269                 }
270
271                 $return[] = array(
272                     'name'  => $hdr_name,
273                     'value' => $this->params['decode_headers'] ? $this->decodeHeader($hdr_value) : $hdr_value,
274                 );
275             }
276         }
277         else {
278             $return = array();
279         }
280
281         return $return;
282     }
283
284     /**
285      * Function to parse a header value, extract first part, and any secondary
286      * parts (after ;) This function is not as robust as it could be.
287      * Eg. header comments in the wrong place will probably break it.
288      *
289      * @param string $input Header value to parse
290      *
291      * @return array Contains parsed result
292      */
293     protected function parseHeaderValue($input)
294     {
295         $parts = preg_split('/;\s*/', $input);
296
297         if (!empty($parts)) {
298             $return['value'] = trim($parts[0]);
299
300             for ($n = 1; $n < count($parts); $n++) {
301                 if (preg_match_all('/(([[:alnum:]]+)="?([^"]*)"?\s?;?)+/i', $parts[$n], $matches)) {
302                     for ($i = 0; $i < count($matches[2]); $i++) {
303                         $return['other'][strtolower($matches[2][$i])] = $matches[3][$i];
304                     }
305                 }
306             }
307         }
308         else {
309             $return['value'] = trim($input);
310         }
311
312         return $return;
313     }
314
315     /**
316      * This function splits the input based on the given boundary
317      *
318      * @param string $input    Input to parse
319      * @param string $boundary Boundary
320      *
321      * @return array Contains array of resulting mime parts
322      */
323     protected function boundarySplit($input, $boundary)
324     {
325         $tmp = explode('--' . $boundary, $input);
326
327         for ($i = 1; $i < count($tmp)-1; $i++) {
328             $parts[] = $tmp[$i];
329         }
330
331         return $parts;
332     }
333
334     /**
335      * Given a header, this function will decode it according to RFC2047.
336      * Probably not *exactly* conformant, but it does pass all the given
337      * examples (in RFC2047).
338      *
339      * @param string $input Input header value to decode
340      *
341      * @return string Decoded header value
342      */
343     protected function decodeHeader($input)
344     {
345         return rcube_mime::decode_mime_string($input, $this->params['default_charset']);
346     }
347
348     /**
349      * Recursive method to convert a rcube_mime_decode structure
350      * into a rcube_message_part object.
351      *
352      * @param object $part   A message part struct
353      * @param int    $count  Part count
354      * @param string $parent Parent MIME ID
355      *
356      * @return object rcube_message_part
357      * @see self::decode()
358      */
359     protected function structure_part($part, $count = 0, $parent = '')
360     {
361         $struct = new rcube_message_part;
362         $struct->mime_id          = $part->mime_id ?: (empty($parent) ? (string)$count : "$parent.$count");
363         $struct->headers          = $part->headers;
364         $struct->mimetype         = $part->ctype_primary . '/' . $part->ctype_secondary;
365         $struct->ctype_primary    = $part->ctype_primary;
366         $struct->ctype_secondary  = $part->ctype_secondary;
367         $struct->ctype_parameters = $part->ctype_parameters;
368
369         if ($part->headers['content-transfer-encoding']) {
370             $struct->encoding = $part->headers['content-transfer-encoding'];
371         }
372
373         if ($part->ctype_parameters['charset']) {
374             $struct->charset = $part->ctype_parameters['charset'];
375         }
376
377         $part_charset = $struct->charset ?: $this->params['default_charset'];
378
379         // determine filename
380         if (($filename = $part->d_parameters['filename']) || ($filename = $part->ctype_parameters['name'])) {
381             if (!$this->params['decode_headers']) {
382                 $filename = $this->decodeHeader($filename);
383             }
384
385             $struct->filename = $filename;
386         }
387
388         $struct->body        = $part->body;
389         $struct->size        = strlen($part->body);
390         $struct->disposition = $part->disposition;
391
392         $count = 0;
393         foreach ((array)$part->parts as $child_part) {
394             $struct->parts[] = $this->structure_part($child_part, ++$count, $struct->mime_id);
395         }
396
397         return $struct;
398     }
399 }