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

Last change on this file since 2650 was 2650, checked in by alec, 4 years ago
  • grrrr, typo again
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.6 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['charset'])) {
189                $headers['Content-Type'] .= " charset={$contentType['charset']}";
190            }
191            if (isset($contentType['name'])) {
192                $headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF;
193                $headers['Content-Type'] .=
194                    $this->_buildHeaderParam('name', $contentType['name'], 
195                        isset($contentType['charset']) ? $contentType['charset'] : 'US-ASCII', 
196                        isset($contentType['language']) ? $contentType['language'] : NULL,
197                        isset($params['name-encoding']) ?  $params['name-encoding'] : NULL);
198            }
199        }
200
201
202        if (isset($contentDisp['disp'])) {
203            $headers['Content-Disposition'] = $contentDisp['disp'];
204            if (isset($contentDisp['filename'])) {
205                $headers['Content-Disposition'] .= ';' . MAIL_MIMEPART_CRLF;
206                $headers['Content-Disposition'] .=
207                    $this->_buildHeaderParam('filename', $contentDisp['filename'], 
208                        isset($contentDisp['charset']) ? $contentDisp['charset'] : 'US-ASCII', 
209                        isset($contentDisp['language']) ? $contentDisp['language'] : NULL,
210                        isset($params['filename-encoding']) ? $params['filename-encoding'] : NULL);
211            }
212        }
213
214        // Default content-type
215        if (!isset($headers['Content-Type'])) {
216            $headers['Content-Type'] = 'text/plain';
217        }
218
219        //Default encoding
220        if (!isset($this->_encoding)) {
221            $this->_encoding = '7bit';
222        }
223
224        // Assign stuff to member variables
225        $this->_encoded  = array();
226        $this->_headers  = $headers;
227        $this->_body     = $body;
228    }
229
230    /**
231     * encode()
232     *
233     * Encodes and returns the email. Also stores
234     * it in the encoded member variable
235     *
236     * @return An associative array containing two elements,
237     *         body and headers. The headers element is itself
238     *         an indexed array.
239     * @access public
240     */
241    function encode()
242    {
243        $encoded =& $this->_encoded;
244
245        if (count($this->_subparts)) {
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                                implode('--' . $boundary . MAIL_MIMEPART_CRLF , $subparts) .
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 2045:
401        // value needs encoding if contains non-ASCII chars or is longer than 78 chars
402        if (!preg_match('#[^\x20-\x7E]#', $value)) { // ASCII
403            // token
404            if (!preg_match('#([^\x21,\x23-\x27,\x2A,\x2B,\x2D,\x2E,\x30-\x39,\x41-\x5A,\x5E-\x7E])#', $value)) {
405                if (strlen($name) + strlen($value) + 3 <= $maxLength)
406                    return " {$name}={$value};";
407            } else { // quoted-string
408                $quoted = addcslashes($value, '\\"');
409                if (strlen($name) + strlen($quoted) + 5 <= $maxLength)
410                    return " {$name}=\"{$quoted}\";";
411            }
412        }
413
414        // RFC2047: use quoted-printable/base64 encoding
415        if ($paramEnc == 'quoted-printable' || $paramEnc == 'base64')
416            return $this->_buildRFC2047Param($name, $value, $charset, $paramEnc);
417
418        // RFC2231:
419        $encValue = preg_replace('#([^\x21,\x23,\x24,\x26,\x2B,\x2D,\x2E,\x30-\x39,\x41-\x5A,\x5E-\x7E])#e',
420                        '"%" . strtoupper(dechex(ord("\1")))', $value);
421        $value = "$charset'$language'$encValue";
422
423        $header = " {$name}*={$value};";
424        if (strlen($header) <= $maxLength) {
425            return $header;
426        }
427
428        $preLength = strlen(" {$name}*0*=");
429        $maxLength = max(16, $maxLength - $preLength - 3);
430        $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
431
432        $headers = array();
433        $headCount = 0;
434        while ($value) {
435            $matches = array();
436            $found = preg_match($maxLengthReg, $value, $matches);
437            if ($found) {
438                $headers[] = " {$name}*{$headCount}*={$matches[0]}";
439                $value = substr($value, strlen($matches[0]));
440            } else {
441                $headers[] = " {$name}*{$headCount}*={$value}";
442                $value = '';
443            }
444            $headCount++;
445        }
446        $headers = implode(';' . MAIL_MIMEPART_CRLF, $headers) . ';';
447        return $headers;
448    }
449
450    /**
451     * Encodes header parameter as per RFC2047 if needed (values too long will be truncated)
452     *
453     * @param string $name  The parameter name
454     * @param string $value  The parameter value
455     * @param string $charset  The parameter charset
456     * @param string $encoding  Encoding type (quoted-printable or base64)
457     * @param int $maxLength  Encoded parameter max length (75 is the value specified in the RFC)
458     *
459     * @return string Parameter line
460     * @access private
461     */
462    function _buildRFC2047Param($name, $value, $charset, $encoding='quoted-printable', $maxLength=75)
463    {
464        if (!preg_match('#([^\x20-\x7E]){1}#', $value))
465        {
466            $quoted = addcslashes($value, '\\"');
467            $maxLength = $maxLength - 6;
468            if (strlen($quoted) > $maxLength)
469            {
470                // truncate filename leaving extension
471                $ext = strrchr($quoted, '.');
472                $quoted = substr($quoted, 0, $maxLength - strlen($ext));
473                // remove backslashes from the end of filename
474                preg_replace('/[\\\\]+$/', '', $quoted);
475                $quoted .= $ext;
476            }
477        }
478        else if ($encoding == 'base64')
479        {
480            $ext = strrchr($value, '.');
481            $value = substr($value, 0, strlen($value) - strlen($ext));
482           
483            $ext = base64_encode($ext);
484            $value = base64_encode($value);
485
486            $prefix = '=?' . $charset . '?B?';
487            $suffix = '?=';
488            $maxLength = $maxLength - strlen($prefix . $suffix) - strlen($ext) - 2;
489
490            //We can cut base64 every 4 characters, so the real max
491            //we can get must be rounded down.
492            $maxLength = $maxLength - ($maxLength % 4);
493            $quoted = $prefix . substr($value, 0, $maxLength) . $ext . $suffix;
494        }
495        else // quoted-printable
496        {
497            $ext = strrchr($value, '.');
498            $value = substr($value, 0, strlen($value) - strlen($ext));
499
500            // Replace all special characters used by the encoder.
501            $search  = array('=',   '_',   '?',   ' ');
502            $replace = array('=3D', '=5F', '=3F', '_');
503            $ext = str_replace($search, $replace, $ext);
504            $value = str_replace($search, $replace, $value);
505
506            // Replace all extended characters (\x80-xFF) with their
507            // ASCII values.
508            $ext = preg_replace('/([\x80-\xFF])/e', 
509                '"=" . strtoupper(dechex(ord("\1")))', $ext);
510            $value = preg_replace('/([\x80-\xFF])/e', 
511                '"=" . strtoupper(dechex(ord("\1")))', $value);
512
513            $prefix = '=?' . $charset . '?Q?';
514            $suffix = '?=';
515
516            $maxLength = $maxLength - strlen($prefix . $suffix) - strlen($ext) - 2;
517           
518            // Truncate QP-encoded text at $maxLength
519            // but not break any encoded letters.
520            if(preg_match("/^(.{0,$maxLength}[^\=][^\=])/", $value, $matches))
521                $value = $matches[1];
522       
523            $quoted = $prefix . $value . $ext . $suffix;
524        }
525
526        return " {$name}=\"{$quoted}\"; ";
527    }
528
529} // End of class
Note: See TracBrowser for help on using the repository browser.