Debian Codegraph @

vendor/pear/mail_mime/Mail/mimePart.php

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