summaryrefslogtreecommitdiff
path: root/program/lib/Mail/mime.php
blob: 975ca48cea11f747c64bd3d309d29573361fc0e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
<?php
/**
 * The Mail_Mime class is used to create MIME E-mail messages
 *
 * The Mail_Mime class provides an OO interface to create MIME
 * enabled email messages. This way you can create emails that
 * contain plain-text bodies, HTML bodies, attachments, inline
 * images and specific headers.
 *
 * Compatible with PHP versions 4 and 5
 *
 * LICENSE: This LICENSE is in the BSD license style.
 * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>
 * Copyright (c) 2003-2006, PEAR <pear-group@php.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * - Neither the name of the authors, nor the names of its contributors 
 *   may be used to endorse or promote products derived from this 
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category  Mail
 * @package   Mail_Mime
 * @author    Richard Heyes  <richard@phpguru.org>
 * @author    Tomas V.V. Cox <cox@idecnet.com>
 * @author    Cipriano Groenendal <cipri@php.net>
 * @author    Sean Coates <sean@php.net>
 * @copyright 2003-2006 PEAR <pear-group@php.net>
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
 * @version   CVS: $Id$
 * @link      http://pear.php.net/package/Mail_mime
 *
 *            This class is based on HTML Mime Mail class from
 *            Richard Heyes <richard@phpguru.org> which was based also
 *            in the mime_mail.class by Tobias Ratschiller <tobias@dnet.it>
 *            and Sascha Schumann <sascha@schumann.cx>
 */


/**
 * require PEAR
 *
 * This package depends on PEAR to raise errors.
 */
require_once 'PEAR.php';

/**
 * require Mail_mimePart
 *
 * Mail_mimePart contains the code required to
 * create all the different parts a mail can
 * consist of.
 */
require_once 'Mail/mimePart.php';


/**
 * The Mail_Mime class provides an OO interface to create MIME
 * enabled email messages. This way you can create emails that
 * contain plain-text bodies, HTML bodies, attachments, inline
 * images and specific headers.
 *
 * @category  Mail
 * @package   Mail_Mime
 * @author    Richard Heyes  <richard@phpguru.org>
 * @author    Tomas V.V. Cox <cox@idecnet.com>
 * @author    Cipriano Groenendal <cipri@php.net>
 * @author    Sean Coates <sean@php.net>
 * @copyright 2003-2006 PEAR <pear-group@php.net>
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/Mail_mime
 */
class Mail_mime
{
    /**
     * Contains the plain text part of the email
     *
     * @var string
     * @access private
     */
    var $_txtbody;

    /**
     * Contains the html part of the email
     *
     * @var string
     * @access private
     */
    var $_htmlbody;

    /**
     * contains the mime encoded text
     *
     * @var string
     * @access private
     */
    var $_mime;

    /**
     * contains the multipart content
     *
     * @var string
     * @access private
     */
    var $_multipart;

    /**
     * list of the attached images
     *
     * @var array
     * @access private
     */
    var $_html_images = array();

    /**
     * list of the attachements
     *
     * @var array
     * @access private
     */
    var $_parts = array();

    /**
     * Build parameters
     *
     * @var array
     * @access private
     */
    var $_build_params = array();

    /**
     * Headers for the mail
     *
     * @var array
     * @access private
     */
    var $_headers = array();

    /**
     * End Of Line sequence (for serialize)
     *
     * @var string
     * @access private
     */
    var $_eol;


    /**
     * Constructor function.
     *
     * @param string $crlf what type of linebreak to use.
     *                     Defaults to "\r\n"
     *
     * @return void
     *
     * @access public
     */
    function Mail_mime($crlf = "\r\n")
    {
        $this->_setEOL($crlf);
        $this->_build_params = array(
                                     'head_encoding' => 'quoted-printable',
                                     'text_encoding' => '7bit',
                                     'html_encoding' => 'quoted-printable',
                                     '7bit_wrap'     => 998,
                                     'html_charset'  => 'ISO-8859-1',
                                     'text_charset'  => 'ISO-8859-1',
                                     'head_charset'  => 'ISO-8859-1'
                                    );
    }

    /**
     * wakeup function called by unserialize. It re-sets the EOL constant
     *
     * @access private
     * @return void
     */
    function __wakeup()
    {
        $this->_setEOL($this->_eol);
    }


    /**
     * Accessor function to set the body text. Body text is used if
     * it's not an html mail being sent or else is used to fill the
     * text/plain part that emails clients who don't support
     * html should show.
     *
     * @param string $data   Either a string or
     *                        the file name with the contents
     * @param bool   $isfile If true the first param should be treated
     *                        as a file name, else as a string (default)
     * @param bool   $append If true the text or file is appended to
     *                        the existing body, else the old body is
     *                        overwritten
     *
     * @return mixed   true on success or PEAR_Error object
     * @access public
     */
    function setTXTBody($data, $isfile = false, $append = false)
    {
        if (!$isfile) {
            if (!$append) {
                $this->_txtbody = $data;
            } else {
                $this->_txtbody .= $data;
            }
        } else {
            $cont = $this->_file2str($data);
            if (PEAR::isError($cont)) {
                return $cont;
            }
            if (!$append) {
                $this->_txtbody = $cont;
            } else {
                $this->_txtbody .= $cont;
            }
        }
        return true;
    }

    /**
     * Adds a html part to the mail.
     *
     * @param string $data   either a string or the file name with the
     *                        contents
     * @param bool   $isfile a flag that determines whether $data is a
     *                        filename, or a string(false, default)
     *
     * @return bool    true on success
     * @access public
     */
    function setHTMLBody($data, $isfile = false)
    {
        if (!$isfile) {
            $this->_htmlbody = $data;
        } else {
            $cont = $this->_file2str($data);
            if (PEAR::isError($cont)) {
                return $cont;
            }
            $this->_htmlbody = $cont;
        }

        return true;
    }

    /**
     * Adds an image to the list of embedded images.
     *
     * @param string $file   the image file name OR image data itself
     * @param string $c_type the content type
     * @param string $name   the filename of the image.
     *                        Only used if $file is the image data.
     * @param bool   $isfile whether $file is a filename or not.
     *                        Defaults to true
     *
     * @return bool          true on success
     * @access public
     */
    function addHTMLImage($file, $c_type='application/octet-stream',
                          $name = '', $isfile = true)
    {
        $filedata = ($isfile === true) ? $this->_file2str($file)
                                           : $file;
        if ($isfile === true) {
            $filename = ($name == '' ? $file : $name);
        } else {
            $filename = $name;
        }
        if (PEAR::isError($filedata)) {
            return $filedata;
        }
        $this->_html_images[] = array(
                                      'body'   => $filedata,
                                      'name'   => $filename,
                                      'c_type' => $c_type,
                                      'cid'    => md5(uniqid(time()))
                                     );
        return true;
    }

    /**
     * Adds a file to the list of attachments.
     *
     * @param string $file        The file name of the file to attach
     *                             OR the file contents itself
     * @param string $c_type      The content type
     * @param string $name        The filename of the attachment
     *                             Only use if $file is the contents
     * @param bool   $isfile      Whether $file is a filename or not
     *                             Defaults to true
     * @param string $encoding    The type of encoding to use.
     *                             Defaults to base64.
     *                             Possible values: 7bit, 8bit, base64, 
     *                             or quoted-printable.
     * @param string $disposition The content-disposition of this file
     *                             Defaults to attachment.
     *                             Possible values: attachment, inline.
     * @param string $charset     The character set used in the filename
     *                             of this attachment.
     * @param string $language    The language of the attachment
     * @param string $location    The RFC 2557.4 location of the attachment
     * @param string $n_encoding      Use RFC 2047 for attachment name (Content-Type) encoding
     * @param string $f_encoding      Use RFC 2047 for attachment filename (Content-Disposition) encoding
     *
     * @return mixed true on success or PEAR_Error object
     * @access public
     */
    function addAttachment($file,
                           $c_type      = 'application/octet-stream',
                           $name        = '',
                            $isfile     = true,
                           $encoding    = 'base64',
                           $disposition = 'attachment',
                           $charset     = '',
                            $language   = '',
                           $location    = '',
			   $n_encoding	= NULL,
			   $f_encoding   = NULL)
    {
        $filedata = ($isfile === true) ? $this->_file2str($file)
                                           : $file;
        if ($isfile === true) {
            // Force the name the user supplied, otherwise use $file
            $filename = (strlen($name)) ? $name : $file;
        } else {
            $filename = $name;
        }
        if (!strlen($filename)) {
            $msg = "The supplied filename for the attachment can't be empty";
            $err = PEAR::raiseError($msg);
            return $err;
        }
        $filename = $this->_basename($filename);
        if (PEAR::isError($filedata)) {
            return $filedata;
        }

        $this->_parts[] = array(
                                'body'        => $filedata,
                                'name'        => $filename,
                                'c_type'      => $c_type,
                                'encoding'    => $encoding,
                                'charset'     => $charset,
                                'language'    => $language,
                                'location'    => $location,
                                'disposition' => $disposition,
				'name-encoding'    => $n_encoding,
				'filename-encoding'=> $f_encoding
                               );
        return true;
    }

    /**
     * Get the contents of the given file name as string
     *
     * @param string $file_name path of file to process
     *
     * @return string  contents of $file_name
     * @access private
     */
    function &_file2str($file_name)
    {
        //Check state of file and raise an error properly
        if (!file_exists($file_name)) {
            $err = PEAR::raiseError('File not found: ' . $file_name);
            return $err;
        }
        if (!is_file($file_name)) {
            $err = PEAR::raiseError('Not a regular file: ' . $file_name);
            return $err;
        }
        if (!is_readable($file_name)) {
            $err = PEAR::raiseError('File is not readable: ' . $file_name);
            return $err;
        }
        
        //Temporarily reset magic_quotes_runtime and read file contents
        if ($magic_quote_setting = get_magic_quotes_runtime()) {
            set_magic_quotes_runtime(0);
        }
        $cont = file_get_contents($file_name);        
        if ($magic_quote_setting) {
            set_magic_quotes_runtime($magic_quote_setting);
        }
        
        return $cont;
    }

    /**
     * Adds a text subpart to the mimePart object and
     * returns it during the build process.
     *
     * @param mixed  &$obj The object to add the part to, or
     *                      null if a new object is to be created.
     * @param string $text The text to add.
     *
     * @return object  The text mimePart object
     * @access private
     */
    function &_addTextPart(&$obj, $text)
    {
        $params['content_type'] = 'text/plain';
        $params['encoding']     = $this->_build_params['text_encoding'];
        $params['charset']      = $this->_build_params['text_charset'];
        if (is_object($obj)) {
            $ret = $obj->addSubpart($text, $params);
            return $ret;
        } else {
            $ret = new Mail_mimePart($text, $params);
            return $ret;
        }
    }

    /**
     * Adds a html subpart to the mimePart object and
     * returns it during the build process.
     *
     * @param mixed &$obj The object to add the part to, or
     *                     null if a new object is to be created.
     *
     * @return object The html mimePart object
     * @access private
     */
    function &_addHtmlPart(&$obj)
    {
        $params['content_type'] = 'text/html';
        $params['encoding']     = $this->_build_params['html_encoding'];
        $params['charset']      = $this->_build_params['html_charset'];
        if (is_object($obj)) {
            $ret = $obj->addSubpart($this->_htmlbody, $params);
            return $ret;
        } else {
            $ret = new Mail_mimePart($this->_htmlbody, $params);
            return $ret;
        }
    }

    /**
     * Creates a new mimePart object, using multipart/mixed as
     * the initial content-type and returns it during the
     * build process.
     *
     * @return object The multipart/mixed mimePart object
     * @access private
     */
    function &_addMixedPart()
    {
        $params                 = array();
        $params['content_type'] = 'multipart/mixed';
        
        //Create empty multipart/mixed Mail_mimePart object to return
        $ret = new Mail_mimePart('', $params);
        return $ret;
    }

    /**
     * Adds a multipart/alternative part to a mimePart
     * object (or creates one), and returns it during
     * the build process.
     *
     * @param mixed &$obj The object to add the part to, or
     *                     null if a new object is to be created.
     *
     * @return object  The multipart/mixed mimePart object
     * @access private
     */
    function &_addAlternativePart(&$obj)
    {
        $params['content_type'] = 'multipart/alternative';
        if (is_object($obj)) {
            return $obj->addSubpart('', $params);
        } else {
            $ret = new Mail_mimePart('', $params);
            return $ret;
        }
    }

    /**
     * Adds a multipart/related part to a mimePart
     * object (or creates one), and returns it during
     * the build process.
     *
     * @param mixed &$obj The object to add the part to, or
     *                     null if a new object is to be created
     *
     * @return object  The multipart/mixed mimePart object
     * @access private
     */
    function &_addRelatedPart(&$obj)
    {
        $params['content_type'] = 'multipart/related';
        if (is_object($obj)) {
            return $obj->addSubpart('', $params);
        } else {
            $ret = new Mail_mimePart('', $params);
            return $ret;
        }
    }

    /**
     * Adds an html image subpart to a mimePart object
     * and returns it during the build process.
     *
     * @param object &$obj  The mimePart to add the image to
     * @param array  $value The image information
     *
     * @return object  The image mimePart object
     * @access private
     */
    function &_addHtmlImagePart(&$obj, $value)
    {
        $params['content_type'] = $value['c_type'];
        $params['encoding']     = 'base64';
        $params['disposition']  = 'inline';
        $params['dfilename']    = $value['name'];
        $params['cid']          = $value['cid'];
	if ($value['name-encoding']) {
	    $params['name-encoding'] = $value['name-encoding'];
	}
	if ($value['filename-encoding']) {
	    $params['filename-encoding'] = $value['filename-encoding'];
	}
        
        $ret = $obj->addSubpart($value['body'], $params);
        return $ret;
    
    }

    /**
     * Adds an attachment subpart to a mimePart object
     * and returns it during the build process.
     *
     * @param object &$obj  The mimePart to add the image to
     * @param array  $value The attachment information
     *
     * @return object  The image mimePart object
     * @access private
     */
    function &_addAttachmentPart(&$obj, $value)
    {
        $params['dfilename'] = $value['name'];
        $params['encoding']  = $value['encoding'];
        if ($value['charset']) {
            $params['charset'] = $value['charset'];
        }
        if ($value['language']) {
            $params['language'] = $value['language'];
        }
        if ($value['location']) {
            $params['location'] = $value['location'];
        }
	if ($value['name-encoding']) {
	    $params['name-encoding'] = $value['name-encoding'];
	}
	if ($value['filename-encoding']) {
	    $params['filename-encoding'] = $value['filename-encoding'];
	}
        $params['content_type'] = $value['c_type'];
        $params['disposition']  = isset($value['disposition']) ? 
                                  $value['disposition'] : 'attachment';
        $ret = $obj->addSubpart($value['body'], $params);
        return $ret;
    }

    /**
     * Returns the complete e-mail, ready to send using an alternative
     * mail delivery method. Note that only the mailpart that is made
     * with Mail_Mime is created. This means that,
     * YOU WILL HAVE NO TO: HEADERS UNLESS YOU SET IT YOURSELF 
     * using the $xtra_headers parameter!
     * 
     * @param string $separation   The separation etween these two parts.
     * @param array  $build_params The Build parameters passed to the
     *                             &get() function. See &get for more info.
     * @param array  $xtra_headers The extra headers that should be passed
     *                             to the &headers() function.
     *                             See that function for more info.
     * @param bool   $overwrite    Overwrite the existing headers with new.
     *
     * @return string The complete e-mail.
     * @access public
     */
    function getMessage(
                        $separation   = null, 
                        $build_params = null, 
                        $xtra_headers = null, 
                        $overwrite    = false
                       )
    {
        if ($separation === null) {
            $separation = MAIL_MIME_CRLF;
        }
        $body = $this->get($build_params);
        $head = $this->txtHeaders($xtra_headers, $overwrite);
        $mail = $head . $separation . $body;
        return $mail;
    }


    /**
     * Builds the multipart message from the list ($this->_parts) and
     * returns the mime content.
     *
     * @param array $build_params Build parameters that change the way the email
     *                             is built. Should be associative. Can contain:
     *                head_encoding  -  What encoding to use for the headers. 
     *                                  Options: quoted-printable or base64
     *                                  Default is quoted-printable
     *                text_encoding  -  What encoding to use for plain text
     *                                  Options: 7bit, 8bit,
     *                                  base64, or quoted-printable
     *                                  Default is 7bit
     *                html_encoding  -  What encoding to use for html
     *                                  Options: 7bit, 8bit,
     *                                  base64, or quoted-printable
     *                                  Default is quoted-printable
     *                7bit_wrap      -  Number of characters before text is
     *                                  wrapped in 7bit encoding
     *                                  Default is 998
     *                html_charset   -  The character set to use for html.
     *                                  Default is iso-8859-1
     *                text_charset   -  The character set to use for text.
     *                                  Default is iso-8859-1
     *                head_charset   -  The character set to use for headers.
     *                                  Default is iso-8859-1
     *
     * @return string The mime content
     * @access public
     */
    function &get($build_params = null)
    {
        if (isset($build_params)) {
            while (list($key, $value) = each($build_params)) {
                $this->_build_params[$key] = $value;
            }
        }
        
        if (isset($this->_headers['From'])){
            //Bug #11381: Illegal characters in domain ID
            if (preg_match("|(@[0-9a-zA-Z\-\.]+)|", $this->_headers['From'], $matches)){
                $domainID = $matches[1];
            }else{
                $domainID = "@localhost";
            }
            foreach($this->_html_images as $i => $img){
                $this->_html_images[$i]['cid'] = $this->_html_images[$i]['cid'] . $domainID;
            }
        }
        
        if (count($this->_html_images) AND isset($this->_htmlbody)) {
            foreach ($this->_html_images as $key => $value) {
                $regex   = array();
                $regex[] = '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' .
                            preg_quote($value['name'], '#') . '\3#';
                $regex[] = '#(?i)url(?-i)\(\s*(["\']?)' .
                            preg_quote($value['name'], '#') . '\1\s*\)#';

                $rep   = array();
                $rep[] = '\1\2=\3cid:' . $value['cid'] .'\3';
                $rep[] = 'url(\1cid:' . $value['cid'] . '\1)';

                $this->_htmlbody = preg_replace($regex, $rep, $this->_htmlbody);
                $this->_html_images[$key]['name'] = 
                    $this->_basename($this->_html_images[$key]['name']);
            }
        }

        $null        = null;
        $attachments = count($this->_parts)                 ? true : false;
        $html_images = count($this->_html_images)           ? true : false;
        $html        = strlen($this->_htmlbody)             ? true : false;
        $text        = (!$html AND strlen($this->_txtbody)) ? true : false;

        switch (true) {
        case $text AND !$attachments:
            $message =& $this->_addTextPart($null, $this->_txtbody);
            break;

        case !$text AND !$html AND $attachments:
            $message =& $this->_addMixedPart();
            for ($i = 0; $i < count($this->_parts); $i++) {
                $this->_addAttachmentPart($message, $this->_parts[$i]);
            }
            break;

        case $text AND $attachments:
            $message =& $this->_addMixedPart();
            $this->_addTextPart($message, $this->_txtbody);
            for ($i = 0; $i < count($this->_parts); $i++) {
                $this->_addAttachmentPart($message, $this->_parts[$i]);
            }
            break;

        case $html AND !$attachments AND !$html_images:
            if (isset($this->_txtbody)) {
                $message =& $this->_addAlternativePart($null);
                $this->_addTextPart($message, $this->_txtbody);
                $this->_addHtmlPart($message);
            } else {
                $message =& $this->_addHtmlPart($null);
            }
            break;

        case $html AND !$attachments AND $html_images:
            $message =& $this->_addRelatedPart($null);
            if (isset($this->_txtbody)) {
                $alt =& $this->_addAlternativePart($message);
                $this->_addTextPart($alt, $this->_txtbody);
                $this->_addHtmlPart($alt);
            } else {
                $this->_addHtmlPart($message);
            }
            for ($i = 0; $i < count($this->_html_images); $i++) {
                $this->_addHtmlImagePart($message, $this->_html_images[$i]);
            }
            break;

        case $html AND $attachments AND !$html_images:
            $message =& $this->_addMixedPart();
            if (isset($this->_txtbody)) {
                $alt =& $this->_addAlternativePart($message);
                $this->_addTextPart($alt, $this->_txtbody);
                $this->_addHtmlPart($alt);
            } else {
                $this->_addHtmlPart($message);
            }
            for ($i = 0; $i < count($this->_parts); $i++) {
                $this->_addAttachmentPart($message, $this->_parts[$i]);
            }
            break;

        case $html AND $attachments AND $html_images:
            $message =& $this->_addMixedPart();
            if (isset($this->_txtbody)) {
                $alt =& $this->_addAlternativePart($message);
                $this->_addTextPart($alt, $this->_txtbody);
                $rel =& $this->_addRelatedPart($alt);
            } else {
                $rel =& $this->_addRelatedPart($message);
            }
            $this->_addHtmlPart($rel);
            for ($i = 0; $i < count($this->_html_images); $i++) {
                $this->_addHtmlImagePart($rel, $this->_html_images[$i]);
            }
            for ($i = 0; $i < count($this->_parts); $i++) {
                $this->_addAttachmentPart($message, $this->_parts[$i]);
            }
            break;

        }

        if (isset($message)) {
            $output = $message->encode();
            
            $this->_headers = array_merge($this->_headers,
                                          $output['headers']);
            $body = $output['body'];
            return $body;

        } else {
            $ret = false;
            return $ret;
        }
    }

    /**
     * Returns an array with the headers needed to prepend to the email
     * (MIME-Version and Content-Type). Format of argument is:
     * $array['header-name'] = 'header-value';
     *
     * @param array $xtra_headers Assoc array with any extra headers.
     *                             Optional.
     * @param bool  $overwrite    Overwrite already existing headers.
     * 
     * @return array Assoc array with the mime headers
     * @access public
     */
    function &headers($xtra_headers = null, $overwrite = false)
    {
        // Content-Type header should already be present,
        // So just add mime version header
        $headers['MIME-Version'] = '1.0';
        if (isset($xtra_headers)) {
            $headers = array_merge($headers, $xtra_headers);
        }
        if ($overwrite) {
            $this->_headers = array_merge($this->_headers, $headers);
        } else {
            $this->_headers = array_merge($headers, $this->_headers);
        }

        $encodedHeaders = $this->_encodeHeaders($this->_headers);
        return $encodedHeaders;
    }

    /**
     * Get the text version of the headers
     * (usefull if you want to use the PHP mail() function)
     *
     * @param array $xtra_headers Assoc array with any extra headers.
     *                             Optional.
     * @param bool  $overwrite    Overwrite the existing heaers with new.
     *
     * @return string  Plain text headers
     * @access public
     */
    function txtHeaders($xtra_headers = null, $overwrite = false)
    {
        $headers = $this->headers($xtra_headers, $overwrite);
        
        $ret = '';
        foreach ($headers as $key => $val) {
            $ret .= "$key: $val" . MAIL_MIME_CRLF;
        }
        return $ret;
    }

    /**
     * Sets the Subject header
     *
     * @param string $subject String to set the subject to.
     *
     * @return void
     * @access public
     */
    function setSubject($subject)
    {
        $this->_headers['Subject'] = $subject;
    }

    /**
     * Set an email to the From (the sender) header
     *
     * @param string $email The email address to use
     *
     * @return void
     * @access public
     */
    function setFrom($email)
    {
        $this->_headers['From'] = $email;
    }

    /**
     * Add an email to the Cc (carbon copy) header
     * (multiple calls to this method are allowed)
     *
     * @param string $email The email direction to add
     *
     * @return void
     * @access public
     */
    function addCc($email)
    {
        if (isset($this->_headers['Cc'])) {
            $this->_headers['Cc'] .= ", $email";
        } else {
            $this->_headers['Cc'] = $email;
        }
    }

    /**
     * Add an email to the Bcc (blank carbon copy) header
     * (multiple calls to this method are allowed)
     *
     * @param string $email The email direction to add
     *
     * @return void
     * @access public
     */
    function addBcc($email)
    {
        if (isset($this->_headers['Bcc'])) {
            $this->_headers['Bcc'] .= ", $email";
        } else {
            $this->_headers['Bcc'] = $email;
        }
    }

    /**
     * Since the PHP send function requires you to specifiy 
     * recipients (To: header) separately from the other
     * headers, the To: header is not properly encoded.
     * To fix this, you can use this public method to 
     * encode your recipients before sending to the send
     * function
     *
     * @param string $recipients A comma-delimited list of recipients
     *
     * @return string Encoded data
     * @access public
     */
    function encodeRecipients($recipients)
    {
        $input = array("To" => $recipients);
        $retval = $this->_encodeHeaders($input);
        return $retval["To"] ;
    }

    /**
     * Encodes a header as per RFC2047
     *
     * @param array $input  The header data to encode
     * @param array $params Extra build parameters
     *
     * @return array Encoded data
     * @access private
     */
    function _encodeHeaders($input, $params = array())
    {
        $build_params = $this->_build_params;
        while (list($key, $value) = each($params)) {
            $build_params[$key] = $value;
        }
        //$hdr_name: Name of the heaer
        //$hdr_value: Full line of header value.
        //$atoms: The $hdr_value split into atoms*
        //$atom: A single atom to encode.*
        //$hdr_value_out: The recombined $hdr_val-atoms, or the encoded string.
        //Note: Atom as specified here is not exactly the same as an RFC822 atom,
        //as $atom's may contain just a single space.
                
        $useIconv = true;        
        if (isset($build_params['ignore-iconv'])) {
            $useIconv = !$build_params['ignore-iconv'];
        }            
        foreach ($input as $hdr_name => $hdr_value) {
            /*
            $parts = preg_split('/([ ])/', $hdr_value, -1, PREG_SPLIT_DELIM_CAPTURE);
            $atoms = array();
            foreach ($parts as $part){
                $atom .= $part;
                $quoteMatch = preg_match_all('|"|', $atom, $matches) % 2;
                if (!$quoteMatch){
                    $atoms[] = $atom;
                    $atom = null;
                }
            }
            if ($atom){
                $atoms[] = $atom;
            }
            foreach ($atoms as $atom){
            */
            if (preg_match('#([\x80-\xFF]){1}#', $hdr_value)) {
                if (function_exists('iconv_mime_encode') && $useIconv) {
                    $imePrefs = array();
                    if ($build_params['head_encoding'] == 'base64') {
                        $imePrefs['scheme'] = 'B';
                    } else {
                        $imePrefs['scheme'] = 'Q';
                    }
                    $imePrefs['input-charset']  = $build_params['head_charset'];
                    $imePrefs['output-charset'] = $build_params['head_charset'];
                    $imePrefs['line-length'] = 74;
                    $imePrefs['line-break-chars'] = "\r\n"; //Specified in RFC2047
                    
                    $hdr_value = iconv_mime_encode($hdr_name, $hdr_value, $imePrefs);
                    $hdr_value = preg_replace("#^{$hdr_name}\:\ #", "", $hdr_value);
                } elseif ($build_params['head_encoding'] == 'base64') {
                    //Base64 encoding has been selected.
                    //Base64 encode the entire string
                    $hdr_value = base64_encode($hdr_value);
                    
                    //Generate the header using the specified params and dynamicly 
                    //determine the maximum length of such strings.
                    //75 is the value specified in the RFC. The first -2 is there so 
                    //the later regexp doesn't break any of the translated chars.
                    //The -2 on the first line-regexp is to compensate for the ": "
                    //between the header-name and the header value
                    $prefix = '=?' . $build_params['head_charset'] . '?B?';
                    $suffix = '?=';
                    $maxLength = 75 - strlen($prefix . $suffix) - 2;
                    $maxLength1stLine = $maxLength - strlen($hdr_name) - 2;

                    //We can cut base4 every 4 characters, so the real max
                    //we can get must be rounded down.
                    $maxLength = $maxLength - ($maxLength % 4);
                    $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
                    
                    $cutpoint = $maxLength1stLine;
                    $hdr_value_out = $hdr_value;
                    $output = "";
                    while ($hdr_value_out) {
                        //Split translated string at every $maxLength
                        $part = substr($hdr_value_out, 0, $cutpoint);
                        $hdr_value_out = substr($hdr_value_out, $cutpoint);
                        $cutpoint = $maxLength;
                        //RFC 2047 specifies that any split header should 
                        //be seperated by a CRLF SPACE. 
                        if ($output) {
                            $output .=  "\r\n ";
                        }
                        $output .= $prefix . $part . $suffix;
                    }
                    $hdr_value = $output;
                } else {
                    //quoted-printable encoding has been selected

                    //Fix for Bug #10298, Ota Mares <om@viazenetti.de>
                    //Check if there is a double quote at beginning or end of
                    //the string to prevent that an open or closing quote gets 
                    //ignored because it is encapsuled by an encoding pre/suffix.
                    //Remove the double quote and set the specific prefix or 
                    //suffix variable so that we can concat the encoded string and
                    //the double quotes back together to get the intended string.
                    $quotePrefix = $quoteSuffix = '';
                    if ($hdr_value{0} == '"') {
                        $hdr_value = substr($hdr_value, 1);
                        $quotePrefix = '"';
                    }
                    if ($hdr_value{strlen($hdr_value)-1} == '"') {
                        $hdr_value = substr($hdr_value, 0, -1);
                        $quoteSuffix = '"';
                    }
                    
                    //Generate the header using the specified params and dynamicly 
                    //determine the maximum length of such strings.
                    //75 is the value specified in the RFC. The -2 is there so 
                    //the later regexp doesn't break any of the translated chars.
                    //The -2 on the first line-regexp is to compensate for the ": "
                    //between the header-name and the header value
                    $prefix = '=?' . $build_params['head_charset'] . '?Q?';
                    $suffix = '?=';
                    $maxLength = 75 - strlen($prefix . $suffix) - 2 - 1;
                    $maxLength1stLine = $maxLength - strlen($hdr_name) - 2;
                    $maxLength = $maxLength - 1;
                    
                    //Replace all special characters used by the encoder.
                    $search  = array('=',   '_',   '?',   ' ');
                    $replace = array('=3D', '=5F', '=3F', '_');
                    $hdr_value = str_replace($search, $replace, $hdr_value);
                    
                    //Replace all extended characters (\x80-xFF) with their
                    //ASCII values.
                    $hdr_value = preg_replace('#([\x80-\xFF])#e',
                        '"=" . strtoupper(dechex(ord("\1")))',
                        $hdr_value);

                    //This regexp will break QP-encoded text at every $maxLength
                    //but will not break any encoded letters.
                    $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
                    $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
                    //Fix for Bug #10298, Ota Mares <om@viazenetti.de>
                    //Concat the double quotes and encoded string together
                    $hdr_value = $quotePrefix . $hdr_value . $quoteSuffix;
                    
                    $hdr_value_out = $hdr_value;
                    $realMax = $maxLength1stLine + strlen($prefix . $suffix);
                    if (strlen($hdr_value_out) >= $realMax) {
                        //Begin with the regexp for the first line.
                        $reg = $reg1st;
                        $output = "";
                        while ($hdr_value_out) {
                            //Split translated string at every $maxLength
                            //But make sure not to break any translated chars.
                            $found = preg_match($reg, $hdr_value_out, $matches);
                            
                            //After this first line, we need to use a different
                            //regexp for the first line.
                            $reg = $reg2nd;
                            
                            //Save the found part and encapsulate it in the
                            //prefix & suffix. Then remove the part from the
                            //$hdr_value_out variable.
                            if ($found) {
                                $part = $matches[0];
                                $len = strlen($matches[0]);
                                $hdr_value_out = substr($hdr_value_out, $len);
                            } else {
                                $part = $hdr_value_out;
                                $hdr_value_out = "";
                            }
                            
                            //RFC 2047 specifies that any split header should 
                            //be seperated by a CRLF SPACE
                            if ($output) {
                                $output .=  "\r\n ";
                            }
                            $output .= $prefix . $part . $suffix;
                        }
                        $hdr_value_out = $output;
                    } else {
                        $hdr_value_out = $prefix . $hdr_value_out . $suffix;
                    }
                    $hdr_value = $hdr_value_out;
                }
            }
            $input[$hdr_name] = $hdr_value;
        }
        return $input;
    }

    /**
     * Set the object's end-of-line and define the constant if applicable.
     *
     * @param string $eol End Of Line sequence
     *
     * @return void
     * @access private
     */
    function _setEOL($eol)
    {
        $this->_eol = $eol;
        if (!defined('MAIL_MIME_CRLF')) {
            define('MAIL_MIME_CRLF', $this->_eol, true);
        }
    }

    /**
     * Get file's basename (locale independent) 
     *
     * @param string Filename
     *
     * @return string Basename
     * @access private
     */
    function _basename($filename)
    {
	// basename() is not unicode safe and locale dependent
	if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware'))
	    return preg_replace('/^.*[\\\\\\/]/', '', $filename);
	else
	    return preg_replace('/^.*[\/]/', '', $filename);
    }

} // End of class