source: trunk/library/mime/mimePart.php @ 7673

Revision 7673, 42.4 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

  • Property svn:executable set to *
RevLine 
[4414]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 * @author    Aleksander Machniak <alec@php.net>
49 * @copyright 2003-2006 PEAR <pear-group@php.net>
50 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
[5135]51 * @version   CVS: $Id: mimePart.php 314695 2011-08-10 07:18:07Z alec $
[4414]52 * @link      http://pear.php.net/package/Mail_mime
53 */
54
55
56/**
57 * The Mail_mimePart class is used to create MIME E-mail messages
58 *
59 * This class enables you to manipulate and build a mime email
60 * from the ground up. The Mail_Mime class is a userfriendly api
61 * to this class for people who aren't interested in the internals
62 * of mime mail.
63 * This class however allows full control over the email.
64 *
65 * @category  Mail
66 * @package   Mail_Mime
67 * @author    Richard Heyes  <richard@phpguru.org>
68 * @author    Cipriano Groenendal <cipri@php.net>
69 * @author    Sean Coates <sean@php.net>
70 * @author    Aleksander Machniak <alec@php.net>
71 * @copyright 2003-2006 PEAR <pear-group@php.net>
72 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
73 * @version   Release: @package_version@
74 * @link      http://pear.php.net/package/Mail_mime
75 */
76class Mail_mimePart
77{
78    /**
79    * The encoding type of this part
80    *
81    * @var string
82    * @access private
83    */
84    var $_encoding;
85
86    /**
87    * An array of subparts
88    *
89    * @var array
90    * @access private
91    */
92    var $_subparts;
93
94    /**
95    * The output of this part after being built
96    *
97    * @var string
98    * @access private
99    */
100    var $_encoded;
101
102    /**
103    * Headers for this part
104    *
105    * @var array
106    * @access private
107    */
108    var $_headers;
109
110    /**
111    * The body of this part (not encoded)
112    *
113    * @var string
114    * @access private
115    */
116    var $_body;
117
118    /**
119    * The location of file with body of this part (not encoded)
120    *
121    * @var string
122    * @access private
123    */
124    var $_body_file;
125
126    /**
127    * The end-of-line sequence
128    *
129    * @var string
130    * @access private
131    */
132    var $_eol = "\r\n";
133
134    /**
135    * Constructor.
136    *
137    * Sets up the object.
138    *
139    * @param string $body   The body of the mime part if any.
140    * @param array  $params An associative array of optional parameters:
141    *     content_type      - The content type for this part eg multipart/mixed
142    *     encoding          - The encoding to use, 7bit, 8bit,
143    *                         base64, or quoted-printable
144    *     charset           - Content character set
145    *     cid               - Content ID to apply
146    *     disposition       - Content disposition, inline or attachment
[5135]147    *     filename          - Filename parameter for content disposition
[4414]148    *     description       - Content description
149    *     name_encoding     - Encoding of the attachment name (Content-Type)
150    *                         By default filenames are encoded using RFC2231
151    *                         Here you can set RFC2047 encoding (quoted-printable
152    *                         or base64) instead
153    *     filename_encoding - Encoding of the attachment filename (Content-Disposition)
154    *                         See 'name_encoding'
155    *     headers_charset   - Charset of the headers e.g. filename, description.
156    *                         If not set, 'charset' will be used
157    *     eol               - End of line sequence. Default: "\r\n"
158    *     body_file         - Location of file with part's body (instead of $body)
159    *
160    * @access public
161    */
162    function Mail_mimePart($body = '', $params = array())
163    {
164        if (!empty($params['eol'])) {
165            $this->_eol = $params['eol'];
166        } else if (defined('MAIL_MIMEPART_CRLF')) { // backward-copat.
167            $this->_eol = MAIL_MIMEPART_CRLF;
168        }
169
170        foreach ($params as $key => $value) {
171            switch ($key) {
172            case 'encoding':
173                $this->_encoding = $value;
174                $headers['Content-Transfer-Encoding'] = $value;
175                break;
176
177            case 'cid':
178                $headers['Content-ID'] = '<' . $value . '>';
179                break;
180
181            case 'location':
182                $headers['Content-Location'] = $value;
183                break;
184
185            case 'body_file':
186                $this->_body_file = $value;
187                break;
[5135]188
189            // for backward compatibility
190            case 'dfilename':
191                $params['filename'] = $value;
192                break;
[4414]193            }
194        }
195
196        // Default content-type
197        if (empty($params['content_type'])) {
198            $params['content_type'] = 'text/plain';
199        }
200
201        // Content-Type
202        $headers['Content-Type'] = $params['content_type'];
203        if (!empty($params['charset'])) {
204            $charset = "charset={$params['charset']}";
205            // place charset parameter in the same line, if possible
206            if ((strlen($headers['Content-Type']) + strlen($charset) + 16) <= 76) {
207                $headers['Content-Type'] .= '; ';
208            } else {
209                $headers['Content-Type'] .= ';' . $this->_eol . ' ';
210            }
211            $headers['Content-Type'] .= $charset;
212
213            // Default headers charset
214            if (!isset($params['headers_charset'])) {
215                $params['headers_charset'] = $params['charset'];
216            }
217        }
218        if (!empty($params['filename'])) {
219            $headers['Content-Type'] .= ';' . $this->_eol;
220            $headers['Content-Type'] .= $this->_buildHeaderParam(
221                'name', $params['filename'],
222                !empty($params['headers_charset']) ? $params['headers_charset'] : 'US-ASCII',
223                !empty($params['language']) ? $params['language'] : null,
224                !empty($params['name_encoding']) ? $params['name_encoding'] : null
225            );
226        }
227
228        // Content-Disposition
229        if (!empty($params['disposition'])) {
230            $headers['Content-Disposition'] = $params['disposition'];
231            if (!empty($params['filename'])) {
232                $headers['Content-Disposition'] .= ';' . $this->_eol;
233                $headers['Content-Disposition'] .= $this->_buildHeaderParam(
234                    'filename', $params['filename'],
235                    !empty($params['headers_charset']) ? $params['headers_charset'] : 'US-ASCII',
236                    !empty($params['language']) ? $params['language'] : null,
237                    !empty($params['filename_encoding']) ? $params['filename_encoding'] : null
238                );
239            }
240        }
241
242        if (!empty($params['description'])) {
243            $headers['Content-Description'] = $this->encodeHeader(
244                'Content-Description', $params['description'],
245                !empty($params['headers_charset']) ? $params['headers_charset'] : 'US-ASCII',
246                !empty($params['name_encoding']) ? $params['name_encoding'] : 'quoted-printable',
247                $this->_eol
248            );
249        }
250
251        // Default encoding
252        if (!isset($this->_encoding)) {
253            $this->_encoding = '7bit';
254        }
255
256        // Assign stuff to member variables
257        $this->_encoded  = array();
258        $this->_headers  = $headers;
259        $this->_body     = $body;
260    }
261
262    /**
263     * Encodes and returns the email. Also stores
264     * it in the encoded member variable
265     *
266     * @param string $boundary Pre-defined boundary string
267     *
268     * @return An associative array containing two elements,
269     *         body and headers. The headers element is itself
270     *         an indexed array. On error returns PEAR error object.
271     * @access public
272     */
273    function encode($boundary=null)
274    {
275        $encoded =& $this->_encoded;
276
277        if (count($this->_subparts)) {
278            $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
279            $eol = $this->_eol;
280
281            $this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
282
283            $encoded['body'] = '';
284
[7673]285            $subparts_count = count($this->_subparts);
286            for ($i = 0; $i < $subparts_count; ++$i) {
[4414]287                $encoded['body'] .= '--' . $boundary . $eol;
288                $tmp = $this->_subparts[$i]->encode();
289                if (PEAR::isError($tmp)) {
290                    return $tmp;
291                }
292                foreach ($tmp['headers'] as $key => $value) {
293                    $encoded['body'] .= $key . ': ' . $value . $eol;
294                }
295                $encoded['body'] .= $eol . $tmp['body'] . $eol;
296            }
297
298            $encoded['body'] .= '--' . $boundary . '--' . $eol;
299
300        } else if ($this->_body) {
301            $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding);
302        } else if ($this->_body_file) {
303            // Temporarily reset magic_quotes_runtime for file reads and writes
304            if ($magic_quote_setting = get_magic_quotes_runtime()) {
305                @ini_set('magic_quotes_runtime', 0);
306            }
307            $body = $this->_getEncodedDataFromFile($this->_body_file, $this->_encoding);
308            if ($magic_quote_setting) {
309                @ini_set('magic_quotes_runtime', $magic_quote_setting);
310            }
311
312            if (PEAR::isError($body)) {
313                return $body;
314            }
315            $encoded['body'] = $body;
316        } else {
317            $encoded['body'] = '';
318        }
319
320        // Add headers to $encoded
321        $encoded['headers'] =& $this->_headers;
322
323        return $encoded;
324    }
325
326    /**
327     * Encodes and saves the email into file. File must exist.
328     * Data will be appended to the file.
329     *
330     * @param string  $filename  Output file location
331     * @param string  $boundary  Pre-defined boundary string
332     * @param boolean $skip_head True if you don't want to save headers
333     *
334     * @return array An associative array containing message headers
335     *               or PEAR error object
336     * @access public
337     * @since 1.6.0
338     */
339    function encodeToFile($filename, $boundary=null, $skip_head=false)
340    {
341        if (file_exists($filename) && !is_writable($filename)) {
342            $err = PEAR::raiseError('File is not writeable: ' . $filename);
343            return $err;
344        }
345
346        if (!($fh = fopen($filename, 'ab'))) {
347            $err = PEAR::raiseError('Unable to open file: ' . $filename);
348            return $err;
349        }
350
351        // Temporarily reset magic_quotes_runtime for file reads and writes
352        if ($magic_quote_setting = get_magic_quotes_runtime()) {
353            @ini_set('magic_quotes_runtime', 0);
354        }
355
356        $res = $this->_encodePartToFile($fh, $boundary, $skip_head);
357
358        fclose($fh);
359
360        if ($magic_quote_setting) {
361            @ini_set('magic_quotes_runtime', $magic_quote_setting);
362        }
363
364        return PEAR::isError($res) ? $res : $this->_headers;
365    }
366
367    /**
368     * Encodes given email part into file
369     *
370     * @param string  $fh        Output file handle
371     * @param string  $boundary  Pre-defined boundary string
372     * @param boolean $skip_head True if you don't want to save headers
373     *
374     * @return array True on sucess or PEAR error object
375     * @access private
376     */
377    function _encodePartToFile($fh, $boundary=null, $skip_head=false)
378    {
379        $eol = $this->_eol;
380
381        if (count($this->_subparts)) {
382            $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
383            $this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
384        }
385
386        if (!$skip_head) {
387            foreach ($this->_headers as $key => $value) {
388                fwrite($fh, $key . ': ' . $value . $eol);
389            }
390            $f_eol = $eol;
391        } else {
392            $f_eol = '';
393        }
394
395        if (count($this->_subparts)) {
[7673]396            $subparts_count = count($this->_subparts);
397            for ($i = 0; $i < $subparts_count; ++$i) {
[4414]398                fwrite($fh, $f_eol . '--' . $boundary . $eol);
399                $res = $this->_subparts[$i]->_encodePartToFile($fh);
400                if (PEAR::isError($res)) {
401                    return $res;
402                }
403                $f_eol = $eol;
404            }
405
406            fwrite($fh, $eol . '--' . $boundary . '--' . $eol);
407
408        } else if ($this->_body) {
409            fwrite($fh, $f_eol . $this->_getEncodedData($this->_body, $this->_encoding));
410        } else if ($this->_body_file) {
411            fwrite($fh, $f_eol);
412            $res = $this->_getEncodedDataFromFile(
413                $this->_body_file, $this->_encoding, $fh
414            );
415            if (PEAR::isError($res)) {
416                return $res;
417            }
418        }
419
420        return true;
421    }
422
423    /**
424     * Adds a subpart to current mime part and returns
425     * a reference to it
426     *
427     * @param string $body   The body of the subpart, if any.
428     * @param array  $params The parameters for the subpart, same
429     *                       as the $params argument for constructor.
430     *
431     * @return Mail_mimePart A reference to the part you just added. It is
432     *                       crucial if using multipart/* in your subparts that
433     *                       you use =& in your script when calling this function,
434     *                       otherwise you will not be able to add further subparts.
435     * @access public
436     */
437    function &addSubpart($body, $params)
438    {
439        $this->_subparts[] = new Mail_mimePart($body, $params);
440        return $this->_subparts[count($this->_subparts) - 1];
441    }
442
443    /**
444     * Returns encoded data based upon encoding passed to it
445     *
446     * @param string $data     The data to encode.
447     * @param string $encoding The encoding type to use, 7bit, base64,
448     *                         or quoted-printable.
449     *
450     * @return string
451     * @access private
452     */
453    function _getEncodedData($data, $encoding)
454    {
455        switch ($encoding) {
456        case 'quoted-printable':
457            return $this->_quotedPrintableEncode($data);
458            break;
459
460        case 'base64':
461            return rtrim(chunk_split(base64_encode($data), 76, $this->_eol));
462            break;
463
464        case '8bit':
465        case '7bit':
466        default:
467            return $data;
468        }
469    }
470
471    /**
472     * Returns encoded data based upon encoding passed to it
473     *
474     * @param string   $filename Data file location
475     * @param string   $encoding The encoding type to use, 7bit, base64,
476     *                           or quoted-printable.
477     * @param resource $fh       Output file handle. If set, data will be
478     *                           stored into it instead of returning it
479     *
480     * @return string Encoded data or PEAR error object
481     * @access private
482     */
483    function _getEncodedDataFromFile($filename, $encoding, $fh=null)
484    {
485        if (!is_readable($filename)) {
486            $err = PEAR::raiseError('Unable to read file: ' . $filename);
487            return $err;
488        }
489
490        if (!($fd = fopen($filename, 'rb'))) {
491            $err = PEAR::raiseError('Could not open file: ' . $filename);
492            return $err;
493        }
494
495        $data = '';
496
497        switch ($encoding) {
498        case 'quoted-printable':
499            while (!feof($fd)) {
500                $buffer = $this->_quotedPrintableEncode(fgets($fd));
501                if ($fh) {
502                    fwrite($fh, $buffer);
503                } else {
504                    $data .= $buffer;
505                }
506            }
507            break;
508
509        case 'base64':
510            while (!feof($fd)) {
511                // Should read in a multiple of 57 bytes so that
512                // the output is 76 bytes per line. Don't use big chunks
513                // because base64 encoding is memory expensive
514                $buffer = fread($fd, 57 * 9198); // ca. 0.5 MB
515                $buffer = base64_encode($buffer);
516                $buffer = chunk_split($buffer, 76, $this->_eol);
517                if (feof($fd)) {
518                    $buffer = rtrim($buffer);
519                }
520
521                if ($fh) {
522                    fwrite($fh, $buffer);
523                } else {
524                    $data .= $buffer;
525                }
526            }
527            break;
528
529        case '8bit':
530        case '7bit':
531        default:
532            while (!feof($fd)) {
533                $buffer = fread($fd, 1048576); // 1 MB
534                if ($fh) {
535                    fwrite($fh, $buffer);
536                } else {
537                    $data .= $buffer;
538                }
539            }
540        }
541
542        fclose($fd);
543
544        if (!$fh) {
545            return $data;
546        }
547    }
548
549    /**
550     * Encodes data to quoted-printable standard.
551     *
552     * @param string $input    The data to encode
553     * @param int    $line_max Optional max line length. Should
554     *                         not be more than 76 chars
555     *
556     * @return string Encoded data
557     *
558     * @access private
559     */
560    function _quotedPrintableEncode($input , $line_max = 76)
561    {
562        $eol = $this->_eol;
563        /*
564        // imap_8bit() is extremely fast, but doesn't handle properly some characters
565        if (function_exists('imap_8bit') && $line_max == 76) {
566            $input = preg_replace('/\r?\n/', "\r\n", $input);
567            $input = imap_8bit($input);
568            if ($eol != "\r\n") {
569                $input = str_replace("\r\n", $eol, $input);
570            }
571            return $input;
572        }
573        */
[6057]574        $lines  = preg_split('/\r?\n/', $input);
[4414]575        $escape = '=';
576        $output = '';
577
578        while (list($idx, $line) = each($lines)) {
579            $newline = '';
580            $i = 0;
581
582            while (isset($line[$i])) {
583                $char = $line[$i];
584                $dec  = ord($char);
[7655]585                ++$i;
[4414]586
587                if (($dec == 32) && (!isset($line[$i]))) {
588                    // convert space at eol only
589                    $char = '=20';
590                } elseif ($dec == 9 && isset($line[$i])) {
591                    ; // Do nothing if a TAB is not on eol
592                } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {
593                    $char = $escape . sprintf('%02X', $dec);
594                } elseif (($dec == 46) && (($newline == '')
595                    || ((strlen($newline) + strlen("=2E")) >= $line_max))
596                ) {
597                    // Bug #9722: convert full-stop at bol,
598                    // some Windows servers need this, won't break anything (cipri)
599                    // Bug #11731: full-stop at bol also needs to be encoded
600                    // if this line would push us over the line_max limit.
601                    $char = '=2E';
602                }
603
604                // Note, when changing this line, also change the ($dec == 46)
605                // check line, as it mimics this line due to Bug #11731
606                // EOL is not counted
607                if ((strlen($newline) + strlen($char)) >= $line_max) {
608                    // soft line break; " =\r\n" is okay
609                    $output  .= $newline . $escape . $eol;
610                    $newline  = '';
611                }
612                $newline .= $char;
613            } // end of for
614            $output .= $newline . $eol;
615            unset($lines[$idx]);
616        }
617        // Don't want last crlf
618        $output = substr($output, 0, -1 * strlen($eol));
619        return $output;
620    }
621
622    /**
623     * Encodes the paramater of a header.
624     *
625     * @param string $name      The name of the header-parameter
626     * @param string $value     The value of the paramter
627     * @param string $charset   The characterset of $value
628     * @param string $language  The language used in $value
629     * @param string $encoding  Parameter encoding. If not set, parameter value
630     *                          is encoded according to RFC2231
631     * @param int    $maxLength The maximum length of a line. Defauls to 75
632     *
633     * @return string
634     *
635     * @access private
636     */
637    function _buildHeaderParam($name, $value, $charset=null, $language=null,
638        $encoding=null, $maxLength=75
639    ) {
640        // RFC 2045:
641        // value needs encoding if contains non-ASCII chars or is longer than 78 chars
642        if (!preg_match('#[^\x20-\x7E]#', $value)) {
643            $token_regexp = '#([^\x21,\x23-\x27,\x2A,\x2B,\x2D'
644                . ',\x2E,\x30-\x39,\x41-\x5A,\x5E-\x7E])#';
645            if (!preg_match($token_regexp, $value)) {
646                // token
647                if (strlen($name) + strlen($value) + 3 <= $maxLength) {
648                    return " {$name}={$value}";
649                }
650            } else {
651                // quoted-string
652                $quoted = addcslashes($value, '\\"');
653                if (strlen($name) + strlen($quoted) + 5 <= $maxLength) {
654                    return " {$name}=\"{$quoted}\"";
655                }
656            }
657        }
658
659        // RFC2047: use quoted-printable/base64 encoding
660        if ($encoding == 'quoted-printable' || $encoding == 'base64') {
661            return $this->_buildRFC2047Param($name, $value, $charset, $encoding);
662        }
663
664        // RFC2231:
665        $encValue = preg_replace_callback(
666            '/([^\x21,\x23,\x24,\x26,\x2B,\x2D,\x2E,\x30-\x39,\x41-\x5A,\x5E-\x7E])/',
667            array($this, '_encodeReplaceCallback'), $value
668        );
669        $value = "$charset'$language'$encValue";
670
671        $header = " {$name}*={$value}";
672        if (strlen($header) <= $maxLength) {
673            return $header;
674        }
675
676        $preLength = strlen(" {$name}*0*=");
677        $maxLength = max(16, $maxLength - $preLength - 3);
678        $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
679
680        $headers = array();
681        $headCount = 0;
682        while ($value) {
683            $matches = array();
684            $found = preg_match($maxLengthReg, $value, $matches);
685            if ($found) {
686                $headers[] = " {$name}*{$headCount}*={$matches[0]}";
687                $value = substr($value, strlen($matches[0]));
688            } else {
689                $headers[] = " {$name}*{$headCount}*={$value}";
690                $value = '';
691            }
[7655]692            ++$headCount;
[4414]693        }
694
695        $headers = implode(';' . $this->_eol, $headers);
696        return $headers;
697    }
698
699    /**
700     * Encodes header parameter as per RFC2047 if needed
701     *
702     * @param string $name      The parameter name
703     * @param string $value     The parameter value
704     * @param string $charset   The parameter charset
705     * @param string $encoding  Encoding type (quoted-printable or base64)
706     * @param int    $maxLength Encoded parameter max length. Default: 76
707     *
708     * @return string Parameter line
709     * @access private
710     */
711    function _buildRFC2047Param($name, $value, $charset,
712        $encoding='quoted-printable', $maxLength=76
713    ) {
714        // WARNING: RFC 2047 says: "An 'encoded-word' MUST NOT be used in
715        // parameter of a MIME Content-Type or Content-Disposition field",
716        // but... it's supported by many clients/servers
717        $quoted = '';
718
719        if ($encoding == 'base64') {
720            $value = base64_encode($value);
721            $prefix = '=?' . $charset . '?B?';
722            $suffix = '?=';
723
724            // 2 x SPACE, 2 x '"', '=', ';'
725            $add_len = strlen($prefix . $suffix) + strlen($name) + 6;
726            $len = $add_len + strlen($value);
727
728            while ($len > $maxLength) {
729                // We can cut base64-encoded string every 4 characters
730                $real_len = floor(($maxLength - $add_len) / 4) * 4;
731                $_quote = substr($value, 0, $real_len);
732                $value = substr($value, $real_len);
733
734                $quoted .= $prefix . $_quote . $suffix . $this->_eol . ' ';
735                $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
736                $len = strlen($value) + $add_len;
737            }
738            $quoted .= $prefix . $value . $suffix;
739
740        } else {
741            // quoted-printable
742            $value = $this->encodeQP($value);
743            $prefix = '=?' . $charset . '?Q?';
744            $suffix = '?=';
745
746            // 2 x SPACE, 2 x '"', '=', ';'
747            $add_len = strlen($prefix . $suffix) + strlen($name) + 6;
748            $len = $add_len + strlen($value);
749
750            while ($len > $maxLength) {
751                $length = $maxLength - $add_len;
752                // don't break any encoded letters
753                if (preg_match("/^(.{0,$length}[^\=][^\=])/", $value, $matches)) {
754                    $_quote = $matches[1];
755                }
756
757                $quoted .= $prefix . $_quote . $suffix . $this->_eol . ' ';
758                $value = substr($value, strlen($_quote));
759                $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
760                $len = strlen($value) + $add_len;
761            }
762
763            $quoted .= $prefix . $value . $suffix;
764        }
765
766        return " {$name}=\"{$quoted}\"";
767    }
768
769    /**
770     * Encodes a header as per RFC2047
771     *
772     * @param string $name     The header name
773     * @param string $value    The header data to encode
774     * @param string $charset  Character set name
775     * @param string $encoding Encoding name (base64 or quoted-printable)
776     * @param string $eol      End-of-line sequence. Default: "\r\n"
777     *
778     * @return string          Encoded header data (without a name)
779     * @access public
780     * @since 1.6.1
781     */
782    function encodeHeader($name, $value, $charset='ISO-8859-1',
783        $encoding='quoted-printable', $eol="\r\n"
784    ) {
785        // Structured headers
786        $comma_headers = array(
787            'from', 'to', 'cc', 'bcc', 'sender', 'reply-to',
788            'resent-from', 'resent-to', 'resent-cc', 'resent-bcc',
789            'resent-sender', 'resent-reply-to',
790            'return-receipt-to', 'disposition-notification-to',
791        );
792        $other_headers = array(
793            'references', 'in-reply-to', 'message-id', 'resent-message-id',
794        );
795
796        $name = strtolower($name);
797
798        if (in_array($name, $comma_headers)) {
799            $separator = ',';
800        } else if (in_array($name, $other_headers)) {
801            $separator = ' ';
802        }
803
804        if (!$charset) {
805            $charset = 'ISO-8859-1';
806        }
807
808        // Structured header (make sure addr-spec inside is not encoded)
809        if (!empty($separator)) {
[5135]810            // Simple e-mail address regexp
811            $email_regexp = '(\S+|("[^\r\n"]+"))@\S+';
812
[4414]813            $parts = Mail_mimePart::_explodeQuotedString($separator, $value);
814            $value = '';
815
816            foreach ($parts as $part) {
817                $part = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $part);
818                $part = trim($part);
819
820                if (!$part) {
821                    continue;
822                }
823                if ($value) {
824                    $value .= $separator==',' ? $separator.' ' : ' ';
825                } else {
826                    $value = $name . ': ';
827                }
828
829                // let's find phrase (name) and/or addr-spec
[5135]830                if (preg_match('/^<' . $email_regexp . '>$/', $part)) {
[4414]831                    $value .= $part;
[5135]832                } else if (preg_match('/^' . $email_regexp . '$/', $part)) {
[4414]833                    // address without brackets and without name
834                    $value .= $part;
[5135]835                } else if (preg_match('/<*' . $email_regexp . '>*$/', $part, $matches)) {
[4414]836                    // address with name (handle name)
837                    $address = $matches[0];
838                    $word = str_replace($address, '', $part);
839                    $word = trim($word);
840                    // check if phrase requires quoting
841                    if ($word) {
842                        // non-ASCII: require encoding
843                        if (preg_match('#([\x80-\xFF]){1}#', $word)) {
844                            if ($word[0] == '"' && $word[strlen($word)-1] == '"') {
845                                // de-quote quoted-string, encoding changes
846                                // string to atom
847                                $search = array("\\\"", "\\\\");
848                                $replace = array("\"", "\\");
849                                $word = str_replace($search, $replace, $word);
850                                $word = substr($word, 1, -1);
851                            }
852                            // find length of last line
853                            if (($pos = strrpos($value, $eol)) !== false) {
854                                $last_len = strlen($value) - $pos;
855                            } else {
856                                $last_len = strlen($value);
857                            }
858                            $word = Mail_mimePart::encodeHeaderValue(
859                                $word, $charset, $encoding, $last_len, $eol
860                            );
861                        } else if (($word[0] != '"' || $word[strlen($word)-1] != '"')
862                            && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $word)
863                        ) {
864                            // ASCII: quote string if needed
865                            $word = '"'.addcslashes($word, '\\"').'"';
866                        }
867                    }
868                    $value .= $word.' '.$address;
869                } else {
870                    // addr-spec not found, don't encode (?)
871                    $value .= $part;
872                }
873
874                // RFC2822 recommends 78 characters limit, use 76 from RFC2047
875                $value = wordwrap($value, 76, $eol . ' ');
876            }
877
878            // remove header name prefix (there could be EOL too)
879            $value = preg_replace(
880                '/^'.$name.':('.preg_quote($eol, '/').')* /', '', $value
881            );
882
883        } else {
884            // Unstructured header
885            // non-ASCII: require encoding
886            if (preg_match('#([\x80-\xFF]){1}#', $value)) {
887                if ($value[0] == '"' && $value[strlen($value)-1] == '"') {
888                    // de-quote quoted-string, encoding changes
889                    // string to atom
890                    $search = array("\\\"", "\\\\");
891                    $replace = array("\"", "\\");
892                    $value = str_replace($search, $replace, $value);
893                    $value = substr($value, 1, -1);
894                }
895                $value = Mail_mimePart::encodeHeaderValue(
896                    $value, $charset, $encoding, strlen($name) + 2, $eol
897                );
898            } else if (strlen($name.': '.$value) > 78) {
899                // ASCII: check if header line isn't too long and use folding
900                $value = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $value);
901                $tmp = wordwrap($name.': '.$value, 78, $eol . ' ');
902                $value = preg_replace('/^'.$name.':\s*/', '', $tmp);
903                // hard limit 998 (RFC2822)
904                $value = wordwrap($value, 998, $eol . ' ', true);
905            }
906        }
907
908        return $value;
909    }
910
911    /**
912     * Explode quoted string
913     *
914     * @param string $delimiter Delimiter expression string for preg_match()
915     * @param string $string    Input string
916     *
917     * @return array            String tokens array
918     * @access private
919     */
920    function _explodeQuotedString($delimiter, $string)
921    {
922        $result = array();
923        $strlen = strlen($string);
924
[7655]925        for ($q=$p=$i=0; $i < $strlen; ++$i) {
[4414]926            if ($string[$i] == "\""
927                && (empty($string[$i-1]) || $string[$i-1] != "\\")
928            ) {
929                $q = $q ? false : true;
930            } else if (!$q && preg_match("/$delimiter/", $string[$i])) {
931                $result[] = substr($string, $p, $i - $p);
932                $p = $i + 1;
933            }
934        }
935
936        $result[] = substr($string, $p);
937        return $result;
938    }
939
940    /**
941     * Encodes a header value as per RFC2047
942     *
943     * @param string $value      The header data to encode
944     * @param string $charset    Character set name
945     * @param string $encoding   Encoding name (base64 or quoted-printable)
946     * @param int    $prefix_len Prefix length. Default: 0
947     * @param string $eol        End-of-line sequence. Default: "\r\n"
948     *
949     * @return string            Encoded header data
950     * @access public
951     * @since 1.6.1
952     */
953    function encodeHeaderValue($value, $charset, $encoding, $prefix_len=0, $eol="\r\n")
954    {
955        // #17311: Use multibyte aware method (requires mbstring extension)
956        if ($result = Mail_mimePart::encodeMB($value, $charset, $encoding, $prefix_len, $eol)) {
957            return $result;
958        }
959
960        // Generate the header using the specified params and dynamicly
961        // determine the maximum length of such strings.
962        // 75 is the value specified in the RFC.
963        $encoding = $encoding == 'base64' ? 'B' : 'Q';
964        $prefix = '=?' . $charset . '?' . $encoding .'?';
965        $suffix = '?=';
966        $maxLength = 75 - strlen($prefix . $suffix);
967        $maxLength1stLine = $maxLength - $prefix_len;
968
969        if ($encoding == 'B') {
970            // Base64 encode the entire string
971            $value = base64_encode($value);
972
973            // We can cut base64 every 4 characters, so the real max
974            // we can get must be rounded down.
975            $maxLength = $maxLength - ($maxLength % 4);
976            $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
977
978            $cutpoint = $maxLength1stLine;
979            $output = '';
980
981            while ($value) {
982                // Split translated string at every $maxLength
983                $part = substr($value, 0, $cutpoint);
984                $value = substr($value, $cutpoint);
985                $cutpoint = $maxLength;
986                // RFC 2047 specifies that any split header should
987                // be seperated by a CRLF SPACE.
988                if ($output) {
989                    $output .= $eol . ' ';
990                }
991                $output .= $prefix . $part . $suffix;
992            }
993            $value = $output;
994        } else {
995            // quoted-printable encoding has been selected
996            $value = Mail_mimePart::encodeQP($value);
997
998            // This regexp will break QP-encoded text at every $maxLength
999            // but will not break any encoded letters.
1000            $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
1001            $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
1002
1003            if (strlen($value) > $maxLength1stLine) {
1004                // Begin with the regexp for the first line.
1005                $reg = $reg1st;
1006                $output = '';
1007                while ($value) {
1008                    // Split translated string at every $maxLength
1009                    // But make sure not to break any translated chars.
1010                    $found = preg_match($reg, $value, $matches);
1011
1012                    // After this first line, we need to use a different
1013                    // regexp for the first line.
1014                    $reg = $reg2nd;
1015
1016                    // Save the found part and encapsulate it in the
1017                    // prefix & suffix. Then remove the part from the
1018                    // $value_out variable.
1019                    if ($found) {
1020                        $part = $matches[0];
1021                        $len = strlen($matches[0]);
1022                        $value = substr($value, $len);
1023                    } else {
1024                        $part = $value;
1025                        $value = '';
1026                    }
1027
1028                    // RFC 2047 specifies that any split header should
1029                    // be seperated by a CRLF SPACE
1030                    if ($output) {
1031                        $output .= $eol . ' ';
1032                    }
1033                    $output .= $prefix . $part . $suffix;
1034                }
1035                $value = $output;
1036            } else {
1037                $value = $prefix . $value . $suffix;
1038            }
1039        }
1040
1041        return $value;
1042    }
1043
1044    /**
1045     * Encodes the given string using quoted-printable
1046     *
1047     * @param string $str String to encode
1048     *
1049     * @return string     Encoded string
1050     * @access public
1051     * @since 1.6.0
1052     */
1053    function encodeQP($str)
1054    {
1055        // Bug #17226 RFC 2047 restricts some characters
1056        // if the word is inside a phrase, permitted chars are only:
1057        // ASCII letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
1058
1059        // "=",  "_",  "?" must be encoded
1060        $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
1061        $str = preg_replace_callback(
1062            $regexp, array('Mail_mimePart', '_qpReplaceCallback'), $str
1063        );
1064
1065        return str_replace(' ', '_', $str);
1066    }
1067
1068    /**
1069     * Encodes the given string using base64 or quoted-printable.
1070     * This method makes sure that encoded-word represents an integral
1071     * number of characters as per RFC2047.
1072     *
1073     * @param string $str        String to encode
1074     * @param string $charset    Character set name
1075     * @param string $encoding   Encoding name (base64 or quoted-printable)
1076     * @param int    $prefix_len Prefix length. Default: 0
1077     * @param string $eol        End-of-line sequence. Default: "\r\n"
1078     *
1079     * @return string     Encoded string
1080     * @access public
1081     * @since 1.8.0
1082     */
1083    function encodeMB($str, $charset, $encoding, $prefix_len=0, $eol="\r\n")
1084    {
1085        if (!function_exists('mb_substr') || !function_exists('mb_strlen')) {
1086            return;
1087        }
1088
1089        $encoding = $encoding == 'base64' ? 'B' : 'Q';
1090        // 75 is the value specified in the RFC
1091        $prefix = '=?' . $charset . '?'.$encoding.'?';
1092        $suffix = '?=';
1093        $maxLength = 75 - strlen($prefix . $suffix);
1094
1095        // A multi-octet character may not be split across adjacent encoded-words
1096        // So, we'll loop over each character
1097        // mb_stlen() with wrong charset will generate a warning here and return null
1098        $length      = mb_strlen($str, $charset);
1099        $result      = '';
1100        $line_length = $prefix_len;
1101
1102        if ($encoding == 'B') {
1103            // base64
1104            $start = 0;
1105            $prev  = '';
1106
[7655]1107            for ($i=1; $i<=$length; ++$i) {
[4414]1108                // See #17311
1109                $chunk = mb_substr($str, $start, $i-$start, $charset);
1110                $chunk = base64_encode($chunk);
1111                $chunk_len = strlen($chunk);
1112
1113                if ($line_length + $chunk_len == $maxLength || $i == $length) {
1114                    if ($result) {
1115                        $result .= "\n";
1116                    }
1117                    $result .= $chunk;
1118                    $line_length = 0;
1119                    $start = $i;
1120                } else if ($line_length + $chunk_len > $maxLength) {
1121                    if ($result) {
1122                        $result .= "\n";
1123                    }
1124                    if ($prev) {
1125                        $result .= $prev;
1126                    }
1127                    $line_length = 0;
1128                    $start = $i - 1;
1129                } else {
1130                    $prev = $chunk;
1131                }
1132            }
1133        } else {
1134            // quoted-printable
1135            // see encodeQP()
1136            $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
1137
[7655]1138            for ($i=0; $i<=$length; ++$i) {
[4414]1139                $char = mb_substr($str, $i, 1, $charset);
1140                // RFC recommends underline (instead of =20) in place of the space
1141                // that's one of the reasons why we're not using iconv_mime_encode()
1142                if ($char == ' ') {
1143                    $char = '_';
1144                    $char_len = 1;
1145                } else {
1146                    $char = preg_replace_callback(
1147                        $regexp, array('Mail_mimePart', '_qpReplaceCallback'), $char
1148                    );
1149                    $char_len = strlen($char);
1150                }
1151
1152                if ($line_length + $char_len > $maxLength) {
1153                    if ($result) {
1154                        $result .= "\n";
1155                    }
1156                    $line_length = 0;
1157                }
1158
1159                $result      .= $char;
1160                $line_length += $char_len;
1161            }
1162        }
1163
1164        if ($result) {
1165            $result = $prefix
1166                .str_replace("\n", $suffix.$eol.' '.$prefix, $result).$suffix;
1167        }
1168
1169        return $result;
1170    }
1171
1172    /**
1173     * Callback function to replace extended characters (\x80-xFF) with their
1174     * ASCII values (RFC2047: quoted-printable)
1175     *
1176     * @param array $matches Preg_replace's matches array
1177     *
1178     * @return string        Encoded character string
1179     * @access private
1180     */
1181    function _qpReplaceCallback($matches)
1182    {
1183        return sprintf('=%02X', ord($matches[1]));
1184    }
1185
1186    /**
1187     * Callback function to replace extended characters (\x80-xFF) with their
1188     * ASCII values (RFC2231)
1189     *
1190     * @param array $matches Preg_replace's matches array
1191     *
1192     * @return string        Encoded character string
1193     * @access private
1194     */
1195    function _encodeReplaceCallback($matches)
1196    {
1197        return sprintf('%%%02X', ord($matches[1]));
1198    }
1199
1200} // End of class
Note: See TracBrowser for help on using the repository browser.