1<?php
2
3/**
4 * The Mail_Mime class is used to create MIME E-mail messages
5 *
6 * The Mail_Mime class provides an OO interface to create MIME
7 * enabled email messages. This way you can create emails that
8 * contain plain-text bodies, HTML bodies, attachments, inline
9 * images and specific headers.
10 *
11 * Compatible with PHP >= 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    Tomas V.V. Cox <cox@idecnet.com>
47 * @author    Cipriano Groenendal <cipri@php.net>
48 * @author    Sean Coates <sean@php.net>
49 * @author    Aleksander Machniak <alec@php.net>
50 * @copyright 2003-2006 PEAR <pear-group@php.net>
51 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
52 * @version   Release: @package_version@
53 * @link      http://pear.php.net/package/Mail_mime
54 *
55 *            This class is based on HTML Mime Mail class from
56 *            Richard Heyes <richard@phpguru.org> which was based also
57 *            in the mime_mail.class by Tobias Ratschiller <tobias@dnet.it>
58 *            and Sascha Schumann <sascha@schumann.cx>
59 */
60
61
62require_once 'PEAR.php';
63require_once 'Mail/mimePart.php';
64
65
66/**
67 * The Mail_Mime class provides an OO interface to create MIME
68 * enabled email messages. This way you can create emails that
69 * contain plain-text bodies, HTML bodies, attachments, inline
70 * images and specific headers.
71 *
72 * @category  Mail
73 * @package   Mail_Mime
74 * @author    Richard Heyes  <richard@phpguru.org>
75 * @author    Tomas V.V. Cox <cox@idecnet.com>
76 * @author    Cipriano Groenendal <cipri@php.net>
77 * @author    Sean Coates <sean@php.net>
78 * @copyright 2003-2006 PEAR <pear-group@php.net>
79 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
80 * @version   Release: @package_version@
81 * @link      http://pear.php.net/package/Mail_mime
82 */
83class Mail_mime
84{
85    /**
86     * Contains the plain text part of the email
87     *
88     * @var string
89     */
90    protected $txtbody;
91
92    /**
93     * Contains the html part of the email
94     *
95     * @var string
96     */
97    protected $htmlbody;
98
99    /**
100     * Contains the text/calendar part of the email
101     *
102     * @var string
103     */
104    protected $calbody;
105
106    /**
107     * list of the attached images
108     *
109     * @var array
110     */
111    protected $html_images = array();
112
113    /**
114     * list of the attachements
115     *
116     * @var array
117     */
118    protected $parts = array();
119
120    /**
121     * Headers for the mail
122     *
123     * @var array
124     */
125    protected $headers = array();
126
127    /**
128     * Build parameters
129     *
130     * @var array
131     */
132    protected $build_params = array(
133        // What encoding to use for the headers
134        // Options: quoted-printable or base64
135        'head_encoding' => 'quoted-printable',
136        // What encoding to use for plain text
137        // Options: 7bit, 8bit, base64, or quoted-printable
138        'text_encoding' => 'quoted-printable',
139        // What encoding to use for html
140        // Options: 7bit, 8bit, base64, or quoted-printable
141        'html_encoding' => 'quoted-printable',
142        // What encoding to use for calendar part
143        // Options: 7bit, 8bit, base64, or quoted-printable
144        'calendar_encoding' => 'quoted-printable',
145        // The character set to use for html
146        'html_charset'  => 'ISO-8859-1',
147        // The character set to use for text
148        'text_charset'  => 'ISO-8859-1',
149        // The character set to use for calendar part
150        'calendar_charset'  => 'UTF-8',
151        // The character set to use for headers
152        'head_charset'  => 'ISO-8859-1',
153        // End-of-line sequence
154        'eol'           => "\r\n",
155        // Delay attachment files IO until building the message
156        'delay_file_io' => false,
157        // Default calendar method
158        'calendar_method' => 'request',
159        // multipart part preamble (RFC2046 5.1.1)
160        'preamble' => '',
161    );
162
163
164    /**
165     * Constructor function
166     *
167     * @param mixed $params Build parameters that change the way the email
168     *                      is built. Should be an associative array.
169     *                      See $_build_params.
170     *
171     * @return void
172     */
173    public function __construct($params = array())
174    {
175        // Backward-compatible EOL setting
176        if (is_string($params)) {
177            $this->build_params['eol'] = $params;
178        } else if (defined('MAIL_MIME_CRLF') && !isset($params['eol'])) {
179            $this->build_params['eol'] = MAIL_MIME_CRLF;
180        }
181
182        // Update build parameters
183        if (!empty($params) && is_array($params)) {
184            while (list($key, $value) = each($params)) {
185                $this->build_params[$key] = $value;
186            }
187        }
188    }
189
190    /**
191     * Set build parameter value
192     *
193     * @param string $name  Parameter name
194     * @param string $value Parameter value
195     *
196     * @return void
197     * @since 1.6.0
198     */
199    public function setParam($name, $value)
200    {
201        $this->build_params[$name] = $value;
202    }
203
204    /**
205     * Get build parameter value
206     *
207     * @param string $name Parameter name
208     *
209     * @return mixed Parameter value
210     * @since 1.6.0
211     */
212    public function getParam($name)
213    {
214        return isset($this->build_params[$name]) ? $this->build_params[$name] : null;
215    }
216
217    /**
218     * Accessor function to set the body text. Body text is used if
219     * it's not an html mail being sent or else is used to fill the
220     * text/plain part that emails clients who don't support
221     * html should show.
222     *
223     * @param string $data   Either a string or the file name with the contents
224     * @param bool   $isfile If true the first param should be treated
225     *                       as a file name, else as a string (default)
226     * @param bool   $append If true the text or file is appended to
227     *                       the existing body, else the old body is
228     *                       overwritten
229     *
230     * @return mixed True on success or PEAR_Error object
231     */
232    public function setTXTBody($data, $isfile = false, $append = false)
233    {
234        return $this->setBody('txtbody', $data, $isfile, $append);
235    }
236
237    /**
238     * Get message text body
239     *
240     * @return string Text body
241     * @since 1.6.0
242     */
243    public function getTXTBody()
244    {
245        return $this->txtbody;
246    }
247
248    /**
249     * Adds a html part to the mail.
250     *
251     * @param string $data   Either a string or the file name with the contents
252     * @param bool   $isfile A flag that determines whether $data is a
253     *                       filename, or a string(false, default)
254     *
255     * @return bool True on success or PEAR_Error object
256     */
257    public function setHTMLBody($data, $isfile = false)
258    {
259        return $this->setBody('htmlbody', $data, $isfile);
260    }
261
262    /**
263     * Get message HTML body
264     *
265     * @return string HTML body
266     * @since 1.6.0
267     */
268    public function getHTMLBody()
269    {
270        return $this->htmlbody;
271    }
272
273    /**
274     * Function to set a body of text/calendar part (not attachment)
275     *
276     * @param string $data     Either a string or the file name with the contents
277     * @param bool   $isfile   If true the first param should be treated
278     *                         as a file name, else as a string (default)
279     * @param bool   $append   If true the text or file is appended to
280     *                         the existing body, else the old body is
281     *                         overwritten
282     * @param string $method   iCalendar object method
283     * @param string $charset  iCalendar character set
284     * @param string $encoding Transfer encoding
285     *
286     * @return mixed True on success or PEAR_Error object
287     * @since 1.9.0
288     */
289    public function setCalendarBody($data, $isfile = false, $append = false,
290        $method = 'request', $charset = 'UTF-8', $encoding = 'quoted-printable'
291    ) {
292        $result = $this->setBody('calbody', $data, $isfile, $append);
293
294        if ($result === true) {
295            $this->build_params['calendar_method']  = $method;
296            $this->build_params['calendar_charset'] = $charset;
297            $this->build_params['calendar_encoding'] = $encoding;
298        }
299    }
300
301    /**
302     * Get body of calendar part
303     *
304     * @return string Calendar part body
305     * @since 1.9.0
306     */
307    public function getCalendarBody()
308    {
309        return $this->calbody;
310    }
311
312    /**
313     * Adds an image to the list of embedded images.
314     * Images added this way will be added as related parts of the HTML message.
315     *
316     * To correctly match the HTML image with the related attachment
317     * HTML should refer to it by a filename (specified in $file or $name
318     * arguments) or by cid:<content-id> (specified in $content_id arg).
319     *
320     * @param string $file       The image file name OR image data itself
321     * @param string $c_type     The content type
322     * @param string $name       The filename of the image. Used to find
323     *                           the image in HTML content.
324     * @param bool   $isfile     Whether $file is a filename or not.
325     *                           Defaults to true
326     * @param string $content_id Desired Content-ID of MIME part
327     *                           Defaults to generated unique ID
328     *
329     * @return bool True on success
330     */
331    public function addHTMLImage($file,
332        $c_type = 'application/octet-stream',
333        $name = '',
334        $isfile = true,
335        $content_id = null
336    ) {
337        $bodyfile = null;
338
339        if ($isfile) {
340            // Don't load file into memory
341            if ($this->build_params['delay_file_io']) {
342                $filedata = null;
343                $bodyfile = $file;
344            } else {
345                if (self::isError($filedata = $this->file2str($file))) {
346                    return $filedata;
347                }
348            }
349
350            $filename = $name ? $name : $file;
351        } else {
352            $filedata = $file;
353            $filename = $name;
354        }
355
356        if (!$content_id) {
357            $content_id = preg_replace('/[^0-9a-zA-Z]/', '', uniqid(time(), true));
358        }
359
360        $this->html_images[] = array(
361            'body'      => $filedata,
362            'body_file' => $bodyfile,
363            'name'      => $filename,
364            'c_type'    => $c_type,
365            'cid'       => $content_id
366        );
367
368        return true;
369    }
370
371    /**
372     * Adds a file to the list of attachments.
373     *
374     * @param mixed  $file        The file name or the file contents itself,
375     *                            it can be also Mail_mimePart object
376     * @param string $c_type      The content type
377     * @param string $name        The filename of the attachment
378     *                            Only use if $file is the contents
379     * @param bool   $isfile      Whether $file is a filename or not. Defaults to true
380     * @param string $encoding    The type of encoding to use. Defaults to base64.
381     *                            Possible values: 7bit, 8bit, base64 or quoted-printable.
382     * @param string $disposition The content-disposition of this file
383     *                            Defaults to attachment.
384     *                            Possible values: attachment, inline.
385     * @param string $charset     The character set of attachment's content.
386     * @param string $language    The language of the attachment
387     * @param string $location    The RFC 2557.4 location of the attachment
388     * @param string $n_encoding  Encoding of the attachment's name in Content-Type
389     *                            By default filenames are encoded using RFC2231 method
390     *                            Here you can set RFC2047 encoding (quoted-printable
391     *                            or base64) instead
392     * @param string $f_encoding  Encoding of the attachment's filename
393     *                            in Content-Disposition header.
394     * @param string $description Content-Description header
395     * @param string $h_charset   The character set of the headers e.g. filename
396     *                            If not specified, $charset will be used
397     * @param array  $add_headers Additional part headers. Array keys can be in form
398     *                            of <header_name>:<parameter_name>
399     *
400     * @return mixed True on success or PEAR_Error object
401     */
402    public function addAttachment($file,
403        $c_type      = 'application/octet-stream',
404        $name        = '',
405        $isfile      = true,
406        $encoding    = 'base64',
407        $disposition = 'attachment',
408        $charset     = '',
409        $language    = '',
410        $location    = '',
411        $n_encoding  = null,
412        $f_encoding  = null,
413        $description = '',
414        $h_charset   = null,
415        $add_headers = array()
416    ) {
417        if ($file instanceof Mail_mimePart) {
418            $this->parts[] = $file;
419            return true;
420        }
421
422        $bodyfile = null;
423
424        if ($isfile) {
425            // Don't load file into memory
426            if ($this->build_params['delay_file_io']) {
427                $filedata = null;
428                $bodyfile = $file;
429            } else {
430                if (self::isError($filedata = $this->file2str($file))) {
431                    return $filedata;
432                }
433            }
434            // Force the name the user supplied, otherwise use $file
435            $filename = ($name ? $name : $this->basename($file));
436        } else {
437            $filedata = $file;
438            $filename = $name;
439        }
440
441        if (!strlen($filename)) {
442            $msg = "The supplied filename for the attachment can't be empty";
443            return self::raiseError($msg);
444        }
445
446        $this->parts[] = array(
447            'body'        => $filedata,
448            'body_file'   => $bodyfile,
449            'name'        => $filename,
450            'c_type'      => $c_type,
451            'charset'     => $charset,
452            'encoding'    => $encoding,
453            'language'    => $language,
454            'location'    => $location,
455            'disposition' => $disposition,
456            'description' => $description,
457            'add_headers' => $add_headers,
458            'name_encoding'     => $n_encoding,
459            'filename_encoding' => $f_encoding,
460            'headers_charset'   => $h_charset,
461        );
462
463        return true;
464    }
465
466    /**
467     * Checks if the current message has many parts
468     *
469     * @return bool True if the message has many parts, False otherwise.
470     * @since 1.9.0
471     */
472    public function isMultipart()
473    {
474        return count($this->parts) > 0 || count($this->html_images) > 0
475            || (strlen($this->htmlbody) > 0 && strlen($this->txtbody) > 0);
476    }
477
478    /**
479     * Get the contents of the given file name as string
480     *
481     * @param string $file_name Path of file to process
482     *
483     * @return string Contents of $file_name
484     */
485    protected function file2str($file_name)
486    {
487        // Check state of file and raise an error properly
488        if (!file_exists($file_name)) {
489            return self::raiseError('File not found: ' . $file_name);
490        }
491        if (!is_file($file_name)) {
492            return self::raiseError('Not a regular file: ' . $file_name);
493        }
494        if (!is_readable($file_name)) {
495            return self::raiseError('File is not readable: ' . $file_name);
496        }
497
498        // Temporarily reset magic_quotes_runtime and read file contents
499        if ($magic_quote_setting = get_magic_quotes_runtime()) {
500            @ini_set('magic_quotes_runtime', 0);
501        }
502
503        $cont = file_get_contents($file_name);
504
505        if ($magic_quote_setting) {
506            @ini_set('magic_quotes_runtime', $magic_quote_setting);
507        }
508
509        return $cont;
510    }
511
512    /**
513     * Adds a text subpart to the mimePart object and
514     * returns it during the build process.
515     *
516     * @param mixed $obj The object to add the part to, or
517     *                   anything else if a new object is to be created.
518     *
519     * @return object The text mimePart object
520     */
521    protected function addTextPart($obj = null)
522    {
523        return $this->addBodyPart($obj, $this->txtbody, 'text/plain', 'text');
524    }
525
526    /**
527     * Adds a html subpart to the mimePart object and
528     * returns it during the build process.
529     *
530     * @param mixed $obj The object to add the part to, or
531     *                   anything else if a new object is to be created.
532     *
533     * @return object The html mimePart object
534     */
535    protected function addHtmlPart($obj = null)
536    {
537        return $this->addBodyPart($obj, $this->htmlbody, 'text/html', 'html');
538    }
539
540    /**
541     * Adds a calendar subpart to the mimePart object and
542     * returns it during the build process.
543     *
544     * @param mixed $obj The object to add the part to, or
545     *                   anything else if a new object is to be created.
546     *
547     * @return object The text mimePart object
548     */
549    protected function addCalendarPart($obj = null)
550    {
551        $ctype = 'text/calendar; method='. $this->build_params['calendar_method'];
552
553        return $this->addBodyPart($obj, $this->calbody, $ctype, 'calendar');
554    }
555
556    /**
557     * Creates a new mimePart object, using multipart/mixed as
558     * the initial content-type and returns it during the
559     * build process.
560     *
561     * @param array $params Additional part parameters
562     *
563     * @return object The multipart/mixed mimePart object
564     */
565    protected function addMixedPart($params = array())
566    {
567        $params['content_type'] = 'multipart/mixed';
568        $params['eol']          = $this->build_params['eol'];
569
570        // Create empty multipart/mixed Mail_mimePart object to return
571        return new Mail_mimePart('', $params);
572    }
573
574    /**
575     * Adds a multipart/alternative part to a mimePart
576     * object (or creates one), and returns it during
577     * the build process.
578     *
579     * @param mixed $obj The object to add the part to, or
580     *                   anything else if a new object is to be created.
581     *
582     * @return object The multipart/mixed mimePart object
583     */
584    protected function addAlternativePart($obj = null)
585    {
586        $params['content_type'] = 'multipart/alternative';
587        $params['eol']          = $this->build_params['eol'];
588
589        if (is_object($obj)) {
590            $ret = $obj->addSubpart('', $params);
591        } else {
592            $ret = new Mail_mimePart('', $params);
593        }
594
595        return $ret;
596    }
597
598    /**
599     * Adds a multipart/related part to a mimePart
600     * object (or creates one), and returns it during
601     * the build process.
602     *
603     * @param mixed $obj The object to add the part to, or
604     *                   anything else if a new object is to be created
605     *
606     * @return object The multipart/mixed mimePart object
607     */
608    protected function addRelatedPart($obj = null)
609    {
610        $params['content_type'] = 'multipart/related';
611        $params['eol']          = $this->build_params['eol'];
612
613        if (is_object($obj)) {
614            $ret = $obj->addSubpart('', $params);
615        } else {
616            $ret = new Mail_mimePart('', $params);
617        }
618
619        return $ret;
620    }
621
622    /**
623     * Adds an html image subpart to a mimePart object
624     * and returns it during the build process.
625     *
626     * @param object $obj   The mimePart to add the image to
627     * @param array  $value The image information
628     *
629     * @return object The image mimePart object
630     */
631    protected function addHtmlImagePart($obj, $value)
632    {
633        $params['content_type'] = $value['c_type'];
634        $params['encoding']     = 'base64';
635        $params['disposition']  = 'inline';
636        $params['filename']     = $value['name'];
637        $params['cid']          = $value['cid'];
638        $params['body_file']    = $value['body_file'];
639        $params['eol']          = $this->build_params['eol'];
640
641        if (!empty($value['name_encoding'])) {
642            $params['name_encoding'] = $value['name_encoding'];
643        }
644        if (!empty($value['filename_encoding'])) {
645            $params['filename_encoding'] = $value['filename_encoding'];
646        }
647
648        return $obj->addSubpart($value['body'], $params);
649    }
650
651    /**
652     * Adds an attachment subpart to a mimePart object
653     * and returns it during the build process.
654     *
655     * @param object $obj   The mimePart to add the image to
656     * @param mixed  $value The attachment information array or Mail_mimePart object
657     *
658     * @return object The image mimePart object
659     */
660    protected function addAttachmentPart($obj, $value)
661    {
662        if ($value instanceof Mail_mimePart) {
663            return $obj->addSubpart($value);
664        }
665
666        $params['eol']          = $this->build_params['eol'];
667        $params['filename']     = $value['name'];
668        $params['encoding']     = $value['encoding'];
669        $params['content_type'] = $value['c_type'];
670        $params['body_file']    = $value['body_file'];
671        $params['disposition']  = isset($value['disposition']) ?
672                                  $value['disposition'] : 'attachment';
673
674        // content charset
675        if (!empty($value['charset'])) {
676            $params['charset'] = $value['charset'];
677        }
678        // headers charset (filename, description)
679        if (!empty($value['headers_charset'])) {
680            $params['headers_charset'] = $value['headers_charset'];
681        }
682        elseif (isset($this->build_params['head_charset'])) {
683            $params['headers_charset'] = $this->build_params['head_charset'];
684        }
685        if (!empty($value['language'])) {
686            $params['language'] = $value['language'];
687        }
688        if (!empty($value['location'])) {
689            $params['location'] = $value['location'];
690        }
691        if (!empty($value['name_encoding'])) {
692            $params['name_encoding'] = $value['name_encoding'];
693        }
694        if (!empty($value['filename_encoding'])) {
695            $params['filename_encoding'] = $value['filename_encoding'];
696        }
697        if (!empty($value['description'])) {
698            $params['description'] = $value['description'];
699        }
700        if (is_array($value['add_headers'])) {
701            $params['headers'] = $value['add_headers'];
702        }
703
704        return $obj->addSubpart($value['body'], $params);
705    }
706
707    /**
708     * Returns the complete e-mail, ready to send using an alternative
709     * mail delivery method. Note that only the mailpart that is made
710     * with Mail_Mime is created. This means that,
711     * YOU WILL HAVE NO TO: HEADERS UNLESS YOU SET IT YOURSELF
712     * using the $headers parameter!
713     *
714     * @param string $separation The separation between these two parts.
715     * @param array  $params     The Build parameters passed to the
716     *                           get() function. See get() for more info.
717     * @param array  $headers    The extra headers that should be passed
718     *                           to the headers() method.
719     *                           See that function for more info.
720     * @param bool   $overwrite  Overwrite the existing headers with new.
721     *
722     * @return mixed The complete e-mail or PEAR error object
723     */
724    public function getMessage($separation = null, $params = null, $headers = null,
725        $overwrite = false
726    ) {
727        if ($separation === null) {
728            $separation = $this->build_params['eol'];
729        }
730
731        $body = $this->get($params);
732
733        if (self::isError($body)) {
734            return $body;
735        }
736
737        return $this->txtHeaders($headers, $overwrite) . $separation . $body;
738    }
739
740    /**
741     * Returns the complete e-mail body, ready to send using an alternative
742     * mail delivery method.
743     *
744     * @param array $params The Build parameters passed to the
745     *                      get() method. See get() for more info.
746     *
747     * @return mixed The e-mail body or PEAR error object
748     * @since 1.6.0
749     */
750    public function getMessageBody($params = null)
751    {
752        return $this->get($params, null, true);
753    }
754
755    /**
756     * Writes (appends) the complete e-mail into file.
757     *
758     * @param string $filename  Output file location
759     * @param array  $params    The Build parameters passed to the
760     *                          get() method. See get() for more info.
761     * @param array  $headers   The extra headers that should be passed
762     *                          to the headers() function.
763     *                          See that function for more info.
764     * @param bool   $overwrite Overwrite the existing headers with new.
765     *
766     * @return mixed True or PEAR error object
767     * @since 1.6.0
768     */
769    public function saveMessage($filename, $params = null, $headers = null, $overwrite = false)
770    {
771        // Check state of file and raise an error properly
772        if (file_exists($filename) && !is_writable($filename)) {
773            return self::raiseError('File is not writable: ' . $filename);
774        }
775
776        // Temporarily reset magic_quotes_runtime and read file contents
777        if ($magic_quote_setting = get_magic_quotes_runtime()) {
778            @ini_set('magic_quotes_runtime', 0);
779        }
780
781        if (!($fh = fopen($filename, 'ab'))) {
782            return self::raiseError('Unable to open file: ' . $filename);
783        }
784
785        // Write message headers into file (skipping Content-* headers)
786        $head = $this->txtHeaders($headers, $overwrite, true);
787        if (fwrite($fh, $head) === false) {
788            return self::raiseError('Error writing to file: ' . $filename);
789        }
790
791        fclose($fh);
792
793        if ($magic_quote_setting) {
794            @ini_set('magic_quotes_runtime', $magic_quote_setting);
795        }
796
797        // Write the rest of the message into file
798        $res = $this->get($params, $filename);
799
800        return $res ? $res : true;
801    }
802
803    /**
804     * Writes (appends) the complete e-mail body into file or stream.
805     *
806     * @param mixed $filename Output filename or file pointer where to save
807     *                        the message instead of returning it
808     * @param array $params   The Build parameters passed to the
809     *                        get() method. See get() for more info.
810     *
811     * @return mixed True or PEAR error object
812     * @since 1.6.0
813     */
814    public function saveMessageBody($filename, $params = null)
815    {
816        if (!is_resource($filename)) {
817            // Check state of file and raise an error properly
818            if (!file_exists($filename) || !is_writable($filename)) {
819                return self::raiseError('File is not writable: ' . $filename);
820            }
821
822            if (!($fh = fopen($filename, 'ab'))) {
823                return self::raiseError('Unable to open file: ' . $filename);
824            }
825        } else {
826            $fh = $filename;
827        }
828
829        // Temporarily reset magic_quotes_runtime and read file contents
830        if ($magic_quote_setting = get_magic_quotes_runtime()) {
831            @ini_set('magic_quotes_runtime', 0);
832        }
833
834        // Write the rest of the message into file
835        $res = $this->get($params, $fh, true);
836
837        if (!is_resource($filename)) {
838            fclose($fh);
839        }
840
841        if ($magic_quote_setting) {
842            @ini_set('magic_quotes_runtime', $magic_quote_setting);
843        }
844
845        return $res ? $res : true;
846    }
847
848    /**
849     * Builds the multipart message from the list ($this->parts) and
850     * returns the mime content.
851     *
852     * @param array   $params    Build parameters that change the way the email
853     *                           is built. Should be associative. See $_build_params.
854     * @param mixed   $filename  Output filename or file pointer where to save
855     *                           the message instead of returning it
856     * @param boolean $skip_head True if you want to return/save only the message
857     *                           without headers
858     *
859     * @return mixed The MIME message content string, null or PEAR error object
860     */
861    public function get($params = null, $filename = null, $skip_head = false)
862    {
863        if (isset($params)) {
864            while (list($key, $value) = each($params)) {
865                $this->build_params[$key] = $value;
866            }
867        }
868
869        if (isset($this->headers['From'])) {
870            // Bug #11381: Illegal characters in domain ID
871            if (preg_match('#(@[0-9a-zA-Z\-\.]+)#', $this->headers['From'], $matches)) {
872                $domainID = $matches[1];
873            } else {
874                $domainID = '@localhost';
875            }
876
877            foreach ($this->html_images as $i => $img) {
878                $cid = $this->html_images[$i]['cid'];
879                if (!preg_match('#'.preg_quote($domainID).'$#', $cid)) {
880                    $this->html_images[$i]['cid'] = $cid . $domainID;
881                }
882            }
883        }
884
885        if (count($this->html_images) && isset($this->htmlbody)) {
886            foreach ($this->html_images as $key => $value) {
887                $rval  = preg_quote($value['name'], '#');
888                $regex = array(
889                    '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' . $rval . '\3#',
890                    '#(?i)url(?-i)\(\s*(["\']?)' . $rval . '\1\s*\)#',
891                );
892
893                $rep = array(
894                    '\1\2=\3cid:' . $value['cid'] .'\3',
895                    'url(\1cid:' . $value['cid'] . '\1)',
896                );
897
898                $this->htmlbody = preg_replace($regex, $rep, $this->htmlbody);
899                $this->html_images[$key]['name']
900                    = $this->basename($this->html_images[$key]['name']);
901            }
902        }
903
904        $this->checkParams();
905
906        $attachments = count($this->parts) > 0;
907        $html_images = count($this->html_images) > 0;
908        $html        = strlen($this->htmlbody) > 0;
909        $calendar    = strlen($this->calbody) > 0;
910        $has_text    = strlen($this->txtbody) > 0;
911        $text        = !$html && $has_text;
912        $mixed_params = array('preamble' => $this->build_params['preamble']);
913
914        switch (true) {
915        case $calendar && !$attachments && !$text && !$html:
916            $message = $this->addCalendarPart();
917            break;
918
919        case $calendar && !$attachments:
920            $message = $this->addAlternativePart($mixed_params);
921            if ($has_text) {
922                $this->addTextPart($message);
923            }
924            if ($html) {
925                $this->addHtmlPart($message);
926            }
927            $this->addCalendarPart($message);
928            break;
929
930        case $text && !$attachments:
931            $message = $this->addTextPart();
932            break;
933
934        case !$text && !$html && $attachments:
935            $message = $this->addMixedPart($mixed_params);
936            for ($i = 0; $i < count($this->parts); $i++) {
937                $this->addAttachmentPart($message, $this->parts[$i]);
938            }
939            break;
940
941        case $text && $attachments:
942            $message = $this->addMixedPart($mixed_params);
943            $this->addTextPart($message);
944            for ($i = 0; $i < count($this->parts); $i++) {
945                $this->addAttachmentPart($message, $this->parts[$i]);
946            }
947            break;
948
949        case $html && !$attachments && !$html_images:
950            if (isset($this->txtbody)) {
951                $message = $this->addAlternativePart();
952                $this->addTextPart($message);
953                $this->addHtmlPart($message);
954            } else {
955                $message = $this->addHtmlPart();
956            }
957            break;
958
959        case $html && !$attachments && $html_images:
960            // * Content-Type: multipart/alternative;
961            //    * text
962            //    * Content-Type: multipart/related;
963            //       * html
964            //       * image...
965            if (isset($this->txtbody)) {
966                $message = $this->addAlternativePart();
967                $this->addTextPart($message);
968
969                $ht = $this->addRelatedPart($message);
970                $this->addHtmlPart($ht);
971                for ($i = 0; $i < count($this->html_images); $i++) {
972                    $this->addHtmlImagePart($ht, $this->html_images[$i]);
973                }
974            } else {
975                // * Content-Type: multipart/related;
976                //    * html
977                //    * image...
978                $message = $this->addRelatedPart();
979                $this->addHtmlPart($message);
980                for ($i = 0; $i < count($this->html_images); $i++) {
981                    $this->addHtmlImagePart($message, $this->html_images[$i]);
982                }
983            }
984            /*
985            // #13444, #9725: the code below was a non-RFC compliant hack
986            // * Content-Type: multipart/related;
987            //    * Content-Type: multipart/alternative;
988            //        * text
989            //        * html
990            //    * image...
991            $message = $this->addRelatedPart();
992            if (isset($this->txtbody)) {
993                $alt = $this->addAlternativePart($message);
994                $this->addTextPart($alt);
995                $this->addHtmlPart($alt);
996            } else {
997                $this->addHtmlPart($message);
998            }
999            for ($i = 0; $i < count($this->html_images); $i++) {
1000                $this->addHtmlImagePart($message, $this->html_images[$i]);
1001            }
1002            */
1003            break;
1004
1005        case $html && $attachments && !$html_images:
1006            $message = $this->addMixedPart($mixed_params);
1007            if (isset($this->txtbody)) {
1008                $alt = $this->addAlternativePart($message);
1009                $this->addTextPart($alt);
1010                $this->addHtmlPart($alt);
1011            } else {
1012                $this->addHtmlPart($message);
1013            }
1014            for ($i = 0; $i < count($this->parts); $i++) {
1015                $this->addAttachmentPart($message, $this->parts[$i]);
1016            }
1017            break;
1018
1019        case $html && $attachments && $html_images:
1020            $message = $this->addMixedPart($mixed_params);
1021            if (isset($this->txtbody)) {
1022                $alt = $this->addAlternativePart($message);
1023                $this->addTextPart($alt);
1024                $rel = $this->addRelatedPart($alt);
1025            } else {
1026                $rel = $this->addRelatedPart($message);
1027            }
1028            $this->addHtmlPart($rel);
1029            for ($i = 0; $i < count($this->html_images); $i++) {
1030                $this->addHtmlImagePart($rel, $this->html_images[$i]);
1031            }
1032            for ($i = 0; $i < count($this->parts); $i++) {
1033                $this->addAttachmentPart($message, $this->parts[$i]);
1034            }
1035            break;
1036        }
1037
1038        if (!isset($message)) {
1039            return null;
1040        }
1041
1042        // Use saved boundary
1043        if (!empty($this->build_params['boundary'])) {
1044            $boundary = $this->build_params['boundary'];
1045        } else {
1046            $boundary = null;
1047        }
1048
1049        // Write output to file
1050        if ($filename) {
1051            // Append mimePart message headers and body into file
1052            $headers = $message->encodeToFile($filename, $boundary, $skip_head);
1053            if (self::isError($headers)) {
1054                return $headers;
1055            }
1056            $this->headers = array_merge($this->headers, $headers);
1057            return null;
1058        } else {
1059            $output = $message->encode($boundary, $skip_head);
1060            if (self::isError($output)) {
1061                return $output;
1062            }
1063            $this->headers = array_merge($this->headers, $output['headers']);
1064            return $output['body'];
1065        }
1066    }
1067
1068    /**
1069     * Returns an array with the headers needed to prepend to the email
1070     * (MIME-Version and Content-Type). Format of argument is:
1071     * $array['header-name'] = 'header-value';
1072     *
1073     * @param array $xtra_headers Assoc array with any extra headers (optional)
1074     *                            (Don't set Content-Type for multipart messages here!)
1075     * @param bool  $overwrite    Overwrite already existing headers.
1076     * @param bool  $skip_content Don't return content headers: Content-Type,
1077     *                            Content-Disposition and Content-Transfer-Encoding
1078     *
1079     * @return array Assoc array with the mime headers
1080     */
1081    public function headers($xtra_headers = null, $overwrite = false, $skip_content = false)
1082    {
1083        // Add mime version header
1084        $headers['MIME-Version'] = '1.0';
1085
1086        // Content-Type and Content-Transfer-Encoding headers should already
1087        // be present if get() was called, but we'll re-set them to make sure
1088        // we got them when called before get() or something in the message
1089        // has been changed after get() [#14780]
1090        if (!$skip_content) {
1091            $headers += $this->contentHeaders();
1092        }
1093
1094        if (!empty($xtra_headers)) {
1095            $headers = array_merge($headers, $xtra_headers);
1096        }
1097
1098        if ($overwrite) {
1099            $this->headers = array_merge($this->headers, $headers);
1100        } else {
1101            $this->headers = array_merge($headers, $this->headers);
1102        }
1103
1104        $headers = $this->headers;
1105
1106        if ($skip_content) {
1107            unset($headers['Content-Type']);
1108            unset($headers['Content-Transfer-Encoding']);
1109            unset($headers['Content-Disposition']);
1110        } else if (!empty($this->build_params['ctype'])) {
1111            $headers['Content-Type'] = $this->build_params['ctype'];
1112        }
1113
1114        $encodedHeaders = $this->encodeHeaders($headers);
1115        return $encodedHeaders;
1116    }
1117
1118    /**
1119     * Get the text version of the headers
1120     * (usefull if you want to use the PHP mail() function)
1121     *
1122     * @param array $xtra_headers Assoc array with any extra headers (optional)
1123     *                            (Don't set Content-Type for multipart messages here!)
1124     * @param bool  $overwrite    Overwrite the existing headers with new.
1125     * @param bool  $skip_content Don't return content headers: Content-Type,
1126     *                            Content-Disposition and Content-Transfer-Encoding
1127     *
1128     * @return string Plain text headers
1129     */
1130    public function txtHeaders($xtra_headers = null, $overwrite = false, $skip_content = false)
1131    {
1132        $headers = $this->headers($xtra_headers, $overwrite, $skip_content);
1133
1134        // Place Received: headers at the beginning of the message
1135        // Spam detectors often flag messages with it after the Subject: as spam
1136        if (isset($headers['Received'])) {
1137            $received = $headers['Received'];
1138            unset($headers['Received']);
1139            $headers = array('Received' => $received) + $headers;
1140        }
1141
1142        $ret = '';
1143        $eol = $this->build_params['eol'];
1144
1145        foreach ($headers as $key => $val) {
1146            if (is_array($val)) {
1147                foreach ($val as $value) {
1148                    $ret .= "$key: $value" . $eol;
1149                }
1150            } else {
1151                $ret .= "$key: $val" . $eol;
1152            }
1153        }
1154
1155        return $ret;
1156    }
1157
1158    /**
1159     * Sets message Content-Type header.
1160     * Use it to build messages with various content-types e.g. miltipart/raport
1161     * not supported by contentHeaders() function.
1162     *
1163     * @param string $type   Type name
1164     * @param array  $params Hash array of header parameters
1165     *
1166     * @return void
1167     * @since 1.7.0
1168     */
1169    public function setContentType($type, $params = array())
1170    {
1171        $header = $type;
1172
1173        $eol = !empty($this->build_params['eol'])
1174            ? $this->build_params['eol'] : "\r\n";
1175
1176        // add parameters
1177        $token_regexp = '#([^\x21\x23-\x27\x2A\x2B\x2D'
1178            . '\x2E\x30-\x39\x41-\x5A\x5E-\x7E])#';
1179
1180        if (is_array($params)) {
1181            foreach ($params as $name => $value) {
1182                if ($name == 'boundary') {
1183                    $this->build_params['boundary'] = $value;
1184                }
1185                if (!preg_match($token_regexp, $value)) {
1186                    $header .= ";$eol $name=$value";
1187                } else {
1188                    $value = addcslashes($value, '\\"');
1189                    $header .= ";$eol $name=\"$value\"";
1190                }
1191            }
1192        }
1193
1194        // add required boundary parameter if not defined
1195        if (stripos($type, 'multipart/') === 0) {
1196            if (empty($this->build_params['boundary'])) {
1197                $this->build_params['boundary'] = '=_' . md5(rand() . microtime());
1198            }
1199
1200            $header .= ";$eol boundary=\"".$this->build_params['boundary']."\"";
1201        }
1202
1203        $this->build_params['ctype'] = $header;
1204    }
1205
1206    /**
1207     * Sets the Subject header
1208     *
1209     * @param string $subject String to set the subject to.
1210     *
1211     * @return void
1212     */
1213    public function setSubject($subject)
1214    {
1215        $this->headers['Subject'] = $subject;
1216    }
1217
1218    /**
1219     * Set an email to the From (the sender) header
1220     *
1221     * @param string $email The email address to use
1222     *
1223     * @return void
1224     */
1225    public function setFrom($email)
1226    {
1227        $this->headers['From'] = $email;
1228    }
1229
1230    /**
1231     * Add an email to the To header
1232     * (multiple calls to this method are allowed)
1233     *
1234     * @param string $email The email direction to add
1235     *
1236     * @return void
1237     */
1238    public function addTo($email)
1239    {
1240        if (isset($this->headers['To'])) {
1241            $this->headers['To'] .= ", $email";
1242        } else {
1243            $this->headers['To'] = $email;
1244        }
1245    }
1246
1247    /**
1248     * Add an email to the Cc (carbon copy) header
1249     * (multiple calls to this method are allowed)
1250     *
1251     * @param string $email The email direction to add
1252     *
1253     * @return void
1254     */
1255    public function addCc($email)
1256    {
1257        if (isset($this->headers['Cc'])) {
1258            $this->headers['Cc'] .= ", $email";
1259        } else {
1260            $this->headers['Cc'] = $email;
1261        }
1262    }
1263
1264    /**
1265     * Add an email to the Bcc (blank carbon copy) header
1266     * (multiple calls to this method are allowed)
1267     *
1268     * @param string $email The email direction to add
1269     *
1270     * @return void
1271     */
1272    public function addBcc($email)
1273    {
1274        if (isset($this->headers['Bcc'])) {
1275            $this->headers['Bcc'] .= ", $email";
1276        } else {
1277            $this->headers['Bcc'] = $email;
1278        }
1279    }
1280
1281    /**
1282     * Since the PHP send function requires you to specify
1283     * recipients (To: header) separately from the other
1284     * headers, the To: header is not properly encoded.
1285     * To fix this, you can use this public method to encode
1286     * your recipients before sending to the send function.
1287     *
1288     * @param string $recipients A comma-delimited list of recipients
1289     *
1290     * @return string Encoded data
1291     */
1292    public function encodeRecipients($recipients)
1293    {
1294        $input  = array('To' => $recipients);
1295        $retval = $this->encodeHeaders($input);
1296
1297        return $retval['To'] ;
1298    }
1299
1300    /**
1301     * Encodes headers as per RFC2047
1302     *
1303     * @param array $input  The header data to encode
1304     * @param array $params Extra build parameters
1305     *
1306     * @return array Encoded data
1307     */
1308    protected function encodeHeaders($input, $params = array())
1309    {
1310        $build_params = $this->build_params;
1311
1312        if (!empty($params)) {
1313            $build_params = array_merge($build_params, $params);
1314        }
1315
1316        foreach ($input as $hdr_name => $hdr_value) {
1317            if (is_array($hdr_value)) {
1318                foreach ($hdr_value as $idx => $value) {
1319                    $input[$hdr_name][$idx] = $this->encodeHeader(
1320                        $hdr_name, $value,
1321                        $build_params['head_charset'], $build_params['head_encoding']
1322                    );
1323                }
1324            } else if ($hdr_value !== null) {
1325                $input[$hdr_name] = $this->encodeHeader(
1326                    $hdr_name, $hdr_value,
1327                    $build_params['head_charset'], $build_params['head_encoding']
1328                );
1329            } else {
1330                unset($input[$hdr_name]);
1331            }
1332        }
1333
1334        return $input;
1335    }
1336
1337    /**
1338     * Encodes a header as per RFC2047
1339     *
1340     * @param string $name     The header name
1341     * @param string $value    The header data to encode
1342     * @param string $charset  Character set name
1343     * @param string $encoding Encoding name (base64 or quoted-printable)
1344     *
1345     * @return string Encoded header data (without a name)
1346     * @since 1.5.3
1347     */
1348    public function encodeHeader($name, $value, $charset, $encoding)
1349    {
1350        return Mail_mimePart::encodeHeader(
1351            $name, $value, $charset, $encoding, $this->build_params['eol']
1352        );
1353    }
1354
1355    /**
1356     * Get file's basename (locale independent)
1357     *
1358     * @param string $filename Filename
1359     *
1360     * @return string Basename
1361     */
1362    protected function basename($filename)
1363    {
1364        // basename() is not unicode safe and locale dependent
1365        if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
1366            return preg_replace('/^.*[\\\\\\/]/', '', $filename);
1367        } else {
1368            return preg_replace('/^.*[\/]/', '', $filename);
1369        }
1370    }
1371
1372    /**
1373     * Get Content-Type and Content-Transfer-Encoding headers of the message
1374     *
1375     * @return array Headers array
1376     */
1377    protected function contentHeaders()
1378    {
1379        $attachments = count($this->parts) > 0;
1380        $html_images = count($this->html_images) > 0;
1381        $html        = strlen($this->htmlbody) > 0;
1382        $calendar    = strlen($this->calbody) > 0;
1383        $has_text    = strlen($this->txtbody) > 0;
1384        $text        = !$html && $has_text;
1385        $headers     = array();
1386
1387        // See get()
1388        switch (true) {
1389        case $calendar && !$attachments && !$html && !$has_text:
1390            $headers['Content-Type'] = 'text/calendar';
1391            break;
1392
1393        case $calendar && !$attachments:
1394            $headers['Content-Type'] = 'multipart/alternative';
1395            break;
1396
1397        case $text && !$attachments:
1398            $headers['Content-Type'] = 'text/plain';
1399            break;
1400
1401        case !$text && !$html && $attachments:
1402        case $text && $attachments:
1403        case $html && $attachments && !$html_images:
1404        case $html && $attachments && $html_images:
1405            $headers['Content-Type'] = 'multipart/mixed';
1406            break;
1407
1408        case $html && !$attachments && !$html_images && $has_text:
1409        case $html && !$attachments && $html_images && $has_text:
1410            $headers['Content-Type'] = 'multipart/alternative';
1411            break;
1412
1413        case $html && !$attachments && !$html_images && !$has_text:
1414            $headers['Content-Type'] = 'text/html';
1415            break;
1416
1417        case $html && !$attachments && $html_images && !$has_text:
1418            $headers['Content-Type'] = 'multipart/related';
1419            break;
1420
1421        default:
1422            return $headers;
1423        }
1424
1425        $this->checkParams();
1426
1427        $eol = !empty($this->build_params['eol'])
1428            ? $this->build_params['eol'] : "\r\n";
1429
1430        if ($headers['Content-Type'] == 'text/plain') {
1431            // single-part message: add charset and encoding
1432            if ($this->build_params['text_charset']) {
1433                $charset = 'charset=' . $this->build_params['text_charset'];
1434                // place charset parameter in the same line, if possible
1435                // 26 = strlen("Content-Type: text/plain; ")
1436                $headers['Content-Type']
1437                    .= (strlen($charset) + 26 <= 76) ? "; $charset" : ";$eol $charset";
1438            }
1439
1440            $headers['Content-Transfer-Encoding']
1441                = $this->build_params['text_encoding'];
1442        } else if ($headers['Content-Type'] == 'text/html') {
1443            // single-part message: add charset and encoding
1444            if ($this->build_params['html_charset']) {
1445                $charset = 'charset=' . $this->build_params['html_charset'];
1446                // place charset parameter in the same line, if possible
1447                $headers['Content-Type']
1448                    .= (strlen($charset) + 25 <= 76) ? "; $charset" : ";$eol $charset";
1449            }
1450            $headers['Content-Transfer-Encoding']
1451                = $this->build_params['html_encoding'];
1452        }
1453        else if ($headers['Content-Type'] == 'text/calendar') {
1454            // single-part message: add charset and encoding
1455            if ($this->build_params['calendar_charset']) {
1456                $charset = 'charset=' . $this->build_params['calendar_charset'];
1457                $headers['Content-Type'] .= "; $charset";
1458            }
1459
1460            if ($this->build_params['calendar_method']) {
1461                $method = 'method=' . $this->build_params['calendar_method'];
1462                $headers['Content-Type'] .= "; $method";
1463            }
1464
1465            $headers['Content-Transfer-Encoding']
1466                = $this->build_params['calendar_encoding'];
1467        } else {
1468            // multipart message: and boundary
1469            if (!empty($this->build_params['boundary'])) {
1470                $boundary = $this->build_params['boundary'];
1471            } else if (!empty($this->headers['Content-Type'])
1472                && preg_match('/boundary="([^"]+)"/', $this->headers['Content-Type'], $m)
1473            ) {
1474                $boundary = $m[1];
1475            } else {
1476                $boundary = '=_' . md5(rand() . microtime());
1477            }
1478
1479            $this->build_params['boundary'] = $boundary;
1480            $headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
1481        }
1482
1483        return $headers;
1484    }
1485
1486    /**
1487     * Validate and set build parameters
1488     *
1489     * @return void
1490     */
1491    protected function checkParams()
1492    {
1493        $encodings = array('7bit', '8bit', 'base64', 'quoted-printable');
1494
1495        $this->build_params['text_encoding']
1496            = strtolower($this->build_params['text_encoding']);
1497        $this->build_params['html_encoding']
1498            = strtolower($this->build_params['html_encoding']);
1499        $this->build_params['calendar_encoding']
1500            = strtolower($this->build_params['calendar_encoding']);
1501
1502        if (!in_array($this->build_params['text_encoding'], $encodings)) {
1503            $this->build_params['text_encoding'] = '7bit';
1504        }
1505        if (!in_array($this->build_params['html_encoding'], $encodings)) {
1506            $this->build_params['html_encoding'] = '7bit';
1507        }
1508        if (!in_array($this->build_params['calendar_encoding'], $encodings)) {
1509            $this->build_params['calendar_encoding'] = '7bit';
1510        }
1511
1512        // text body
1513        if ($this->build_params['text_encoding'] == '7bit'
1514            && !preg_match('/ascii/i', $this->build_params['text_charset'])
1515            && preg_match('/[^\x00-\x7F]/', $this->txtbody)
1516        ) {
1517            $this->build_params['text_encoding'] = 'quoted-printable';
1518        }
1519        // html body
1520        if ($this->build_params['html_encoding'] == '7bit'
1521            && !preg_match('/ascii/i', $this->build_params['html_charset'])
1522            && preg_match('/[^\x00-\x7F]/', $this->htmlbody)
1523        ) {
1524            $this->build_params['html_encoding'] = 'quoted-printable';
1525        }
1526        // calendar body
1527        if ($this->build_params['calendar_encoding'] == '7bit'
1528            && !preg_match('/ascii/i', $this->build_params['calendar_charset'])
1529            && preg_match('/[^\x00-\x7F]/', $this->calbody)
1530        ) {
1531            $this->build_params['calendar_encoding'] = 'quoted-printable';
1532        }
1533    }
1534
1535    /**
1536     * Set body of specified message part
1537     *
1538     * @param string $type   One of: txtbody, calbody, htmlbody
1539     * @param string $data   Either a string or the file name with the contents
1540     * @param bool   $isfile If true the first param should be treated
1541     *                       as a file name, else as a string (default)
1542     * @param bool   $append If true the text or file is appended to
1543     *                       the existing body, else the old body is
1544     *                       overwritten
1545     *
1546     * @return mixed True on success or PEAR_Error object
1547     */
1548    protected function setBody($type, $data, $isfile = false, $append = false)
1549    {
1550        if (!$isfile) {
1551            if (!$append) {
1552                $this->{$type} = $data;
1553            } else {
1554                $this->{$type} .= $data;
1555            }
1556        } else {
1557            $cont = $this->file2str($data);
1558            if (self::isError($cont)) {
1559                return $cont;
1560            }
1561
1562            if (!$append) {
1563                $this->{$type} = $cont;
1564            } else {
1565                $this->{$type} .= $cont;
1566            }
1567        }
1568
1569        return true;
1570    }
1571
1572    /**
1573     * Adds a subpart to the mimePart object and
1574     * returns it during the build process.
1575     *
1576     * @param mixed  $obj   The object to add the part to, or
1577     *                      anything else if a new object is to be created.
1578     * @param string $body  Part body
1579     * @param string $ctype Part content type
1580     * @param string $type  Internal part type
1581     *
1582     * @return object The mimePart object
1583     */
1584    protected function addBodyPart($obj, $body, $ctype, $type)
1585    {
1586        $params['content_type'] = $ctype;
1587        $params['encoding']     = $this->build_params[$type . '_encoding'];
1588        $params['charset']      = $this->build_params[$type . '_charset'];
1589        $params['eol']          = $this->build_params['eol'];
1590
1591        if (is_object($obj)) {
1592            $ret = $obj->addSubpart($body, $params);
1593        } else {
1594            $ret = new Mail_mimePart($body, $params);
1595        }
1596
1597        return $ret;
1598    }
1599
1600    /**
1601     * PEAR::isError implementation
1602     *
1603     * @param mixed $data Object
1604     *
1605     * @return bool True if object is an instance of PEAR_Error
1606     */
1607    public static function isError($data)
1608    {
1609        // PEAR::isError() is not PHP 5.4 compatible (see Bug #19473)
1610        if (is_a($data, 'PEAR_Error')) {
1611            return true;
1612        }
1613
1614        return false;
1615    }
1616
1617    /**
1618     * PEAR::raiseError implementation
1619     *
1620     * @param string $message A text error message
1621     *
1622     * @return PEAR_Error Instance of PEAR_Error
1623     */
1624    public static function raiseError($message)
1625    {
1626        // PEAR::raiseError() is not PHP 5.4 compatible
1627        return new PEAR_Error($message);
1628    }
1629}
1630