source: subversion/trunk/roundcubemail/program/lib/Mail/mimePart.php @ 1897

Last change on this file since 1897 was 1897, checked in by alec, 5 years ago
  • Added 'mime_param_folding' option with possibility to choose long/non-ascii attachment names encoding eg. to be readable in MS Outlook/OE (#1485320)
  • Added "advanced options" feature in User Preferences
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.5 KB
Line 
1<?php
2/**
3 * The Mail_mimePart class is used to create MIME E-mail messages
4 *
5 * This class enables you to manipulate and build a mime email
6 * from the ground up. The Mail_Mime class is a userfriendly api
7 * to this class for people who aren't interested in the internals
8 * of mime mail.
9 * This class however allows full control over the email.
10 *
11 * Compatible with PHP versions 4 and 5
12 *
13 * LICENSE: This LICENSE is in the BSD license style.
14 * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>
15 * Copyright (c) 2003-2006, PEAR <pear-group@php.net>
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or
19 * without modification, are permitted provided that the following
20 * conditions are met:
21 *
22 * - Redistributions of source code must retain the above copyright
23 *   notice, this list of conditions and the following disclaimer.
24 * - Redistributions in binary form must reproduce the above copyright
25 *   notice, this list of conditions and the following disclaimer in the
26 *   documentation and/or other materials provided with the distribution.
27 * - Neither the name of the authors, nor the names of its contributors
28 *   may be used to endorse or promote products derived from this
29 *   software without specific prior written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
32 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
35 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
39 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
41 * THE POSSIBILITY OF SUCH DAMAGE.
42 *
43 * @category   Mail
44 * @package    Mail_Mime
45 * @author     Richard Heyes  <richard@phpguru.org>
46 * @author     Cipriano Groenendal <cipri@php.net>
47 * @author     Sean Coates <sean@php.net>
48 * @copyright  2003-2006 PEAR <pear-group@php.net>
49 * @license    http://www.opensource.org/licenses/bsd-license.php BSD License
50 * @version    CVS: $Id$
51 * @link       http://pear.php.net/package/Mail_mime
52 */
53
54
55/**
56 * The Mail_mimePart class is used to create MIME E-mail messages
57 *
58 * This class enables you to manipulate and build a mime email
59 * from the ground up. The Mail_Mime class is a userfriendly api
60 * to this class for people who aren't interested in the internals
61 * of mime mail.
62 * This class however allows full control over the email.
63 *
64 * @category   Mail
65 * @package    Mail_Mime
66 * @author     Richard Heyes  <richard@phpguru.org>
67 * @author     Cipriano Groenendal <cipri@php.net>
68 * @author     Sean Coates <sean@php.net>
69 * @copyright  2003-2006 PEAR <pear-group@php.net>
70 * @license    http://www.opensource.org/licenses/bsd-license.php BSD License
71 * @version    Release: @package_version@
72 * @link       http://pear.php.net/package/Mail_mime
73 */
74class Mail_mimePart {
75
76   /**
77    * The encoding type of this part
78    *
79    * @var string
80    * @access private
81    */
82    var $_encoding;
83
84   /**
85    * An array of subparts
86    *
87    * @var array
88    * @access private
89    */
90    var $_subparts;
91
92   /**
93    * The output of this part after being built
94    *
95    * @var string
96    * @access private
97    */
98    var $_encoded;
99
100   /**
101    * Headers for this part
102    *
103    * @var array
104    * @access private
105    */
106    var $_headers;
107
108   /**
109    * The body of this part (not encoded)
110    *
111    * @var string
112    * @access private
113    */
114    var $_body;
115
116    /**
117     * Constructor.
118     *
119     * Sets up the object.
120     *
121     * @param $body   - The body of the mime part if any.
122     * @param $params - An associative array of parameters:
123     *                  content_type - The content type for this part eg multipart/mixed
124     *                  encoding     - The encoding to use, 7bit, 8bit, base64, or quoted-printable
125     *                  cid          - Content ID to apply
126     *                  disposition  - Content disposition, inline or attachment
127     *                  dfilename    - Optional filename parameter for content disposition
128     *                  description  - Content description
129     *                  charset      - Character set to use
130     * @access public
131     */
132    function Mail_mimePart($body = '', $params = array())
133    {
134        if (!defined('MAIL_MIMEPART_CRLF')) {
135            define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", TRUE);
136        }
137
138        $contentType = array();
139        $contentDisp = array();
140        foreach ($params as $key => $value) {
141            switch ($key) {
142                case 'content_type':
143                    $contentType['type'] = $value;
144                    //$headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
145                    break;
146
147                case 'encoding':
148                    $this->_encoding = $value;
149                    $headers['Content-Transfer-Encoding'] = $value;
150                    break;
151
152                case 'cid':
153                    $headers['Content-ID'] = '<' . $value . '>';
154                    break;
155
156                case 'disposition':
157                    $contentDisp['disp'] = $value;
158                    break;
159
160                case 'dfilename':
161                    $contentDisp['filename'] = $value;
162                    $contentType['name'] = $value;
163                    break;
164
165                case 'description':
166                    $headers['Content-Description'] = $value;
167                    break;
168
169                case 'charset':
170                    $contentType['charset'] = $value;
171                    $contentDisp['charset'] = $value;
172                    break;
173
174                case 'language':
175                    $contentType['language'] = $value;
176                    $contentDisp['language'] = $value;
177                    break;
178
179                case 'location':
180                    $headers['Content-Location'] = $value;
181                    break;
182
183            }
184        }
185       
186        if (isset($contentType['type'])) {
187            $headers['Content-Type'] = $contentType['type'];
188            if (isset($contentType['name'])) {
189                $headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF;
190                $headers['Content-Type'] .=
191                    $this->_buildHeaderParam('name', $contentType['name'], 
192                        isset($contentType['charset']) ? $contentType['charset'] : 'US-ASCII', 
193                        isset($contentType['language']) ? $contentType['language'] : NULL,
194                        isset($params['name-encoding']) ?  $params['name-encoding'] : NULL);
195            } elseif (isset($contentType['charset'])) {
196                $headers['Content-Type'] .= "; charset=\"{$contentType['charset']}\"";
197            }
198        }
199
200
201        if (isset($contentDisp['disp'])) {
202            $headers['Content-Disposition'] = $contentDisp['disp'];
203            if (isset($contentDisp['filename'])) {
204                $headers['Content-Disposition'] .= ';' . MAIL_MIMEPART_CRLF;
205                $headers['Content-Disposition'] .=
206                    $this->_buildHeaderParam('filename', $contentDisp['filename'], 
207                        isset($contentDisp['charset']) ? $contentDisp['charset'] : 'US-ASCII', 
208                        isset($contentDisp['language']) ? $contentDisp['language'] : NULL,
209                        isset($params['filename-encoding']) ? $params['filename-encoding'] : NULL);
210            }
211        }
212
213        // Default content-type
214        if (!isset($headers['Content-Type'])) {
215            $headers['Content-Type'] = 'text/plain';
216        }
217
218        //Default encoding
219        if (!isset($this->_encoding)) {
220            $this->_encoding = '7bit';
221        }
222
223        // Assign stuff to member variables
224        $this->_encoded  = array();
225        $this->_headers  = $headers;
226        $this->_body     = $body;
227    }
228
229    /**
230     * encode()
231     *
232     * Encodes and returns the email. Also stores
233     * it in the encoded member variable
234     *
235     * @return An associative array containing two elements,
236     *         body and headers. The headers element is itself
237     *         an indexed array.
238     * @access public
239     */
240    function encode()
241    {
242        $encoded =& $this->_encoded;
243
244        if (count($this->_subparts)) {
245            srand((double)microtime()*1000000);
246            $boundary = '=_' . md5(rand() . microtime());
247            $this->_headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"';
248
249            // Add body parts to $subparts
250            for ($i = 0; $i < count($this->_subparts); $i++) {
251                $headers = array();
252                $tmp = $this->_subparts[$i]->encode();
253                foreach ($tmp['headers'] as $key => $value) {
254                    $headers[] = $key . ': ' . $value;
255                }
256                $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'] . MAIL_MIMEPART_CRLF;
257            }
258
259            $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF . 
260                               rtrim(implode('--' . $boundary . MAIL_MIMEPART_CRLF , $subparts), MAIL_MIMEPART_CRLF) . MAIL_MIMEPART_CRLF . 
261                               '--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
262
263        } else {
264            $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding);
265        }
266
267        // Add headers to $encoded
268        $encoded['headers'] =& $this->_headers;
269
270        return $encoded;
271    }
272
273    /**
274     * &addSubPart()
275     *
276     * Adds a subpart to current mime part and returns
277     * a reference to it
278     *
279     * @param $body   The body of the subpart, if any.
280     * @param $params The parameters for the subpart, same
281     *                as the $params argument for constructor.
282     * @return A reference to the part you just added. It is
283     *         crucial if using multipart/* in your subparts that
284     *         you use =& in your script when calling this function,
285     *         otherwise you will not be able to add further subparts.
286     * @access public
287     */
288    function &addSubPart($body, $params)
289    {
290        $this->_subparts[] = new Mail_mimePart($body, $params);
291        return $this->_subparts[count($this->_subparts) - 1];
292    }
293
294    /**
295     * _getEncodedData()
296     *
297     * Returns encoded data based upon encoding passed to it
298     *
299     * @param $data     The data to encode.
300     * @param $encoding The encoding type to use, 7bit, base64,
301     *                  or quoted-printable.
302     * @access private
303     */
304    function _getEncodedData($data, $encoding)
305    {
306        switch ($encoding) {
307            case '8bit':
308            case '7bit':
309                return $data;
310                break;
311
312            case 'quoted-printable':
313                return $this->_quotedPrintableEncode($data);
314                break;
315
316            case 'base64':
317                return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF));
318                break;
319
320            default:
321                return $data;
322        }
323    }
324
325    /**
326     * quotedPrintableEncode()
327     *
328     * Encodes data to quoted-printable standard.
329     *
330     * @param $input    The data to encode
331     * @param $line_max Optional max line length. Should
332     *                  not be more than 76 chars
333     *
334     * @access private
335     */
336    function _quotedPrintableEncode($input , $line_max = 76)
337    {
338        $lines  = preg_split("/\r?\n/", $input);
339        $eol    = MAIL_MIMEPART_CRLF;
340        $escape = '=';
341        $output = '';
342
343        while (list(, $line) = each($lines)) {
344
345            $line    = preg_split('||', $line, -1, PREG_SPLIT_NO_EMPTY);
346            $linlen     = count($line);
347            $newline = '';
348
349            for ($i = 0; $i < $linlen; $i++) {
350                $char = $line[$i];
351                $dec  = ord($char);
352
353                if (($dec == 32) AND ($i == ($linlen - 1))) {    // convert space at eol only
354                    $char = '=20';
355
356                } elseif (($dec == 9) AND ($i == ($linlen - 1))) {  // convert tab at eol only
357                    $char = '=09';
358                } elseif ($dec == 9) {
359                    ; // Do nothing if a tab.
360                } elseif (($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
361                    $char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
362                } elseif (($dec == 46) AND (($newline == '') || ((strlen($newline) + strlen("=2E")) >= $line_max))) {
363                    //Bug #9722: convert full-stop at bol,
364                    //some Windows servers need this, won't break anything (cipri)
365                    //Bug #11731: full-stop at bol also needs to be encoded
366                    //if this line would push us over the line_max limit.
367                    $char = '=2E';
368                }
369
370                //Note, when changing this line, also change the ($dec == 46)
371                //check line, as it mimics this line due to Bug #11731
372                if ((strlen($newline) + strlen($char)) >= $line_max) {        // MAIL_MIMEPART_CRLF is not counted
373                    $output  .= $newline . $escape . $eol;                    // soft line break; " =\r\n" is okay
374                    $newline  = '';
375                }
376                $newline .= $char;
377            } // end of for
378            $output .= $newline . $eol;
379        }
380        $output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf
381        return $output;
382    }
383
384    /**
385     * _buildHeaderParam()
386     *
387     * Encodes the paramater of a header.
388     *
389     * @param $name         The name of the header-parameter
390     * @param $value        The value of the paramter
391     * @param $charset      The characterset of $value
392     * @param $language     The language used in $value
393     * @param $paramEnc     Parameter encoding type
394     * @param $maxLength    The maximum length of a line. Defauls to 78
395     *
396     * @access private
397     */
398    function _buildHeaderParam($name, $value, $charset=NULL, $language=NULL, $paramEnc=NULL, $maxLength=78)
399    {
400        // RFC 2183/2184/2822:
401        // value needs encoding if contains non-ASCII chars or is longer than 78 chars
402        if (!preg_match('#[^\x20-\x7E]#', $value)) { // ASCII
403            $quoted = addcslashes($value, '\\"');
404            if (strlen($name) + strlen($quoted) + 6 <= $maxLength)
405                return " {$name}=\"{$quoted}\"; ";
406        }
407
408        // use quoted-printable/base64 encoding (RFC2047)
409        if ($paramEnc == 'quoted-printable' || $paramEnc == 'base64')
410            return $this->_buildRFC2047Param($name, $value, $charset, $paramEnc);
411
412        $encValue = preg_replace('#([^\x20-\x7E])#e', '"%" . strtoupper(dechex(ord("\1")))', $value);
413        $value = "$charset'$language'$encValue";
414
415        $header = " {$name}*=\"{$value}\"; ";
416        if (strlen($header) <= $maxLength) {
417            return $header;
418        }
419
420        $preLength = strlen(" {$name}*0*=\"");
421        $sufLength = strlen("\";");
422        $maxLength = max(16, $maxLength - $preLength - $sufLength - 2);
423        $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
424
425        $headers = array();
426        $headCount = 0;
427        while ($value) {
428            $matches = array();
429            $found = preg_match($maxLengthReg, $value, $matches);
430            if ($found) {
431                $headers[] = " {$name}*{$headCount}*=\"{$matches[0]}\"";
432                $value = substr($value, strlen($matches[0]));
433            } else {
434                $headers[] = " {$name}*{$headCount}*=\"{$value}\"";
435                $value = "";
436            }
437            $headCount++;
438        }
439        $headers = implode(MAIL_MIMEPART_CRLF, $headers) . ';';
440        return $headers;
441    }
442
443    /**
444     * Encodes header parameter as per RFC2047 if needed (values too long will be truncated)
445     *
446     * @param string $name  The parameter name
447     * @param string $value  The parameter value
448     * @param string $charset  The parameter charset
449     * @param string $encoding  Encoding type (quoted-printable or base64)
450     * @param int $maxLength  Encoded parameter max length (75 is the value specified in the RFC)
451     *
452     * @return string Parameter line
453     * @access private
454     */
455    function _buildRFC2047Param($name, $value, $charset, $encoding='quoted-printable', $maxLength=75)
456    {
457        if (!preg_match('#([^\x20-\x7E]){1}#', $value))
458        {
459            $quoted = addcslashes($value, '\\"');
460            $maxLength = $maxLength - 6;
461            if (strlen($quoted) > $maxLength)
462            {
463                // truncate filename leaving extension
464                $ext = strrchr($quoted, '.');
465                $quoted = substr($quoted, 0, $maxLength - strlen($ext));
466                // remove backslashes from the end of filename
467                preg_replace('/[\\\\]+$/', '', $quoted);
468                $quoted .= $ext;
469            }
470        }
471        else if ($encoding == 'base64')
472        {
473            $ext = strrchr($value, '.');
474            $value = substr($value, 0, strlen($value) - strlen($ext));
475           
476            $ext = base64_encode($ext);
477            $value = base64_encode($value);
478
479            $prefix = '=?' . $charset . '?B?';
480            $suffix = '?=';
481            $maxLength = $maxLength - strlen($prefix . $suffix) - strlen($ext) - 2;
482
483            //We can cut base64 every 4 characters, so the real max
484            //we can get must be rounded down.
485            $maxLength = $maxLength - ($maxLength % 4);
486            $quoted = $prefix . substr($value, 0, $maxLength) . $ext . $suffix;
487        }
488        else // quoted-printable
489        {
490            $ext = strrchr($value, '.');
491            $value = substr($value, 0, strlen($value) - strlen($ext));
492
493            // Replace all special characters used by the encoder.
494            $search  = array('=',   '_',   '?',   ' ');
495            $replace = array('=3D', '=5F', '=3F', '_');
496            $ext = str_replace($search, $replace, $ext);
497            $value = str_replace($search, $replace, $value);
498
499            // Replace all extended characters (\x80-xFF) with their
500            // ASCII values.
501            $ext = preg_replace('/([\x80-\xFF])/e', 
502                '"=" . strtoupper(dechex(ord("\1")))', $ext);
503            $value = preg_replace('/([\x80-\xFF])/e', 
504                '"=" . strtoupper(dechex(ord("\1")))', $value);
505
506            $prefix = '=?' . $charset . '?Q?';
507            $suffix = '?=';
508
509            $maxLength = $maxLength - strlen($prefix . $suffix) - strlen($ext) - 2;
510           
511            // Truncate QP-encoded text at $maxLength
512            // but not break any encoded letters.
513            if(preg_match("/^(.{0,$maxLength}[^\=][^\=])/", $value, $matches))
514                $value = $matches[1];
515       
516            $quoted = $prefix . $value . $ext . $suffix;
517        }
518
519        return " {$name}=\"{$quoted}\"; ";
520    }
521
522} // End of class
Note: See TracBrowser for help on using the repository browser.