source: github/program/lib/Mail/mime.php @ 505f6e5

release-0.8
Last change on this file since 505f6e5 was 505f6e5, checked in by Aleksander Machniak <alec@…>, 11 months ago

Update to Mail_Mime-1.8.5 (#1488521)

Conflicts:

CHANGELOG
program/lib/Mail/mime.php
program/lib/Mail/mimePart.php

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