alecpl
2009-02-08 0ea8d3a08e6055293aaa689bff6525522986e71c
commit | author | age
4e17e6 1 <?php
ab6f80 2 /**
T 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
4e17e6 54
T 55 /**
ab6f80 56  * The Mail_mimePart class is used to create MIME E-mail messages
T 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  */
4e17e6 74 class Mail_mimePart {
T 75
76    /**
77     * The encoding type of this part
ab6f80 78     *
4e17e6 79     * @var string
ab6f80 80     * @access private
4e17e6 81     */
T 82     var $_encoding;
83
84    /**
85     * An array of subparts
ab6f80 86     *
4e17e6 87     * @var array
ab6f80 88     * @access private
4e17e6 89     */
T 90     var $_subparts;
91
92    /**
93     * The output of this part after being built
ab6f80 94     *
4e17e6 95     * @var string
ab6f80 96     * @access private
4e17e6 97     */
T 98     var $_encoded;
99
100    /**
101     * Headers for this part
ab6f80 102     *
4e17e6 103     * @var array
ab6f80 104     * @access private
4e17e6 105     */
T 106     var $_headers;
107
108    /**
109     * The body of this part (not encoded)
ab6f80 110     *
4e17e6 111     * @var string
ab6f80 112     * @access private
4e17e6 113     */
T 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
ee289d 138         $contentType = array();
A 139         $contentDisp = array();
4e17e6 140         foreach ($params as $key => $value) {
T 141             switch ($key) {
142                 case 'content_type':
ee289d 143                     $contentType['type'] = $value;
A 144                     //$headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
4e17e6 145                     break;
T 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':
ee289d 157                     $contentDisp['disp'] = $value;
4e17e6 158                     break;
T 159
160                 case 'dfilename':
ee289d 161                     $contentDisp['filename'] = $value;
A 162                     $contentType['name'] = $value;
4e17e6 163                     break;
T 164
165                 case 'description':
166                     $headers['Content-Description'] = $value;
167                     break;
168
169                 case 'charset':
ee289d 170                     $contentType['charset'] = $value;
A 171                     $contentDisp['charset'] = $value;
4e17e6 172                     break;
ee289d 173
A 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         }
ffae15 185     
ee289d 186         if (isset($contentType['type'])) {
A 187             $headers['Content-Type'] = $contentType['type'];
781f34 188         if (isset($contentType['charset'])) {
A 189                 $headers['Content-Type'] .= "; charset=\"{$contentType['charset']}\"";
190             }
ee289d 191             if (isset($contentType['name'])) {
A 192                 $headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF;
ffae15 193                 $headers['Content-Type'] .=
A 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);
4e17e6 198             }
T 199         }
200
ee289d 201
A 202         if (isset($contentDisp['disp'])) {
203             $headers['Content-Disposition'] = $contentDisp['disp'];
204             if (isset($contentDisp['filename'])) {
205                 $headers['Content-Disposition'] .= ';' . MAIL_MIMEPART_CRLF;
ffae15 206                 $headers['Content-Disposition'] .=
A 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);
ee289d 211             }
A 212         }
ffae15 213
4e17e6 214         // Default content-type
T 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
ee289d 245         if (count($this->_subparts)) {
4e17e6 246             $boundary = '=_' . md5(rand() . microtime());
T 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                 }
ee289d 256                 $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'] . MAIL_MIMEPART_CRLF;
4e17e6 257             }
T 258
ee289d 259             $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF . 
68af64 260                 implode('--' . $boundary . MAIL_MIMEPART_CRLF , $subparts) .
A 261                             '--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
4e17e6 262
T 263         } else {
ee289d 264             $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding);
4e17e6 265         }
T 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     /**
ab6f80 326      * quotedPrintableEncode()
4e17e6 327      *
T 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
ee289d 343         while (list(, $line) = each($lines)) {
4e17e6 344
ab6f80 345             $line    = preg_split('||', $line, -1, PREG_SPLIT_NO_EMPTY);
T 346             $linlen     = count($line);
4e17e6 347             $newline = '';
T 348
349             for ($i = 0; $i < $linlen; $i++) {
ab6f80 350                 $char = $line[$i];
4e17e6 351                 $dec  = ord($char);
T 352
ee289d 353                 if (($dec == 32) AND ($i == ($linlen - 1))) {    // convert space at eol only
4e17e6 354                     $char = '=20';
T 355
ee289d 356                 } elseif (($dec == 9) AND ($i == ($linlen - 1))) {  // convert tab at eol only
4e17e6 357                     $char = '=09';
ee289d 358                 } elseif ($dec == 9) {
4e17e6 359                     ; // Do nothing if a tab.
ee289d 360                 } elseif (($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
4e17e6 361                     $char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
ee289d 362                 } elseif (($dec == 46) AND (($newline == '') || ((strlen($newline) + strlen("=2E")) >= $line_max))) {
A 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';
4e17e6 368                 }
T 369
ee289d 370                 //Note, when changing this line, also change the ($dec == 46)
A 371                 //check line, as it mimics this line due to Bug #11731
4e17e6 372                 if ((strlen($newline) + strlen($char)) >= $line_max) {        // MAIL_MIMEPART_CRLF is not counted
T 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     }
ee289d 383
A 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
ffae15 393      * @param $paramEnc     Parameter encoding type
e8a1b7 394      * @param $maxLength    The maximum length of a line. Defauls to 78
ee289d 395      *
A 396      * @access private
397      */
ffae15 398     function _buildHeaderParam($name, $value, $charset=NULL, $language=NULL, $paramEnc=NULL, $maxLength=78)
ee289d 399     {
e8a1b7 400         // RFC 2183/2184/2822: 
A 401     // value needs encoding if contains non-ASCII chars or is longer than 78 chars
5ec762 402         if (!preg_match('#[^\x20-\x7E]#', $value)) { // ASCII
e8a1b7 403         $quoted = addcslashes($value, '\\"');
A 404         if (strlen($name) + strlen($quoted) + 6 <= $maxLength)
405         return " {$name}=\"{$quoted}\"; ";
406     }
ffae15 407
A 408     // use quoted-printable/base64 encoding (RFC2047)
409     if ($paramEnc == 'quoted-printable' || $paramEnc == 'base64')
410         return $this->_buildRFC2047Param($name, $value, $charset, $paramEnc);
e8a1b7 411
A 412         $encValue = preg_replace('#([^\x20-\x7E])#e', '"%" . strtoupper(dechex(ord("\1")))', $value);
413         $value = "$charset'$language'$encValue";
414
415         $header = " {$name}*=\"{$value}\"; ";
ee289d 416         if (strlen($header) <= $maxLength) {
A 417             return $header;
418         }
419
e8a1b7 420         $preLength = strlen(" {$name}*0*=\"");
ee289d 421         $sufLength = strlen("\";");
ffae15 422         $maxLength = max(16, $maxLength - $preLength - $sufLength - 2);
ee289d 423         $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
A 424
425         $headers = array();
426         $headCount = 0;
427         while ($value) {
428             $matches = array();
429             $found = preg_match($maxLengthReg, $value, $matches);
430             if ($found) {
e8a1b7 431                 $headers[] = " {$name}*{$headCount}*=\"{$matches[0]}\"";
ee289d 432                 $value = substr($value, strlen($matches[0]));
A 433             } else {
e8a1b7 434                 $headers[] = " {$name}*{$headCount}*=\"{$value}\"";
ee289d 435                 $value = "";
A 436             }
437             $headCount++;
438         }
0ea8d3 439         $headers = implode(';' . MAIL_MIMEPART_CRLF, $headers) . ';';
ee289d 440         return $headers;
A 441     }
ffae15 442
A 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
4e17e6 522 } // End of class