source: github/program/lib/Mail/mimePart.php @ 9843dc7

HEADdev-browser-capabilitiespdo
Last change on this file since 9843dc7 was 9843dc7, checked in by Aleksander Machniak <alec@…>, 12 months ago

Mail_Mime 1.8.4

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