blob: af48757bbf3447d072231db18fd7baf913ede4ec [file] [log] [blame]
Derek Allard2067d1a2008-11-13 22:59:24 +00001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
Derek Jones7f3719f2010-01-05 13:35:37 +00009 * @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
Derek Allard2067d1a2008-11-13 22:59:24 +000010 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * CodeIgniter Email Class
20 *
21 * Permits email to be sent using Mail, Sendmail, or SMTP.
22 *
23 * @package CodeIgniter
24 * @subpackage Libraries
25 * @category Libraries
26 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/libraries/email.html
28 */
29class CI_Email {
30
31 var $useragent = "CodeIgniter";
32 var $mailpath = "/usr/sbin/sendmail"; // Sendmail path
33 var $protocol = "mail"; // mail/sendmail/smtp
34 var $smtp_host = ""; // SMTP Server. Example: mail.earthlink.net
35 var $smtp_user = ""; // SMTP Username
36 var $smtp_pass = ""; // SMTP Password
37 var $smtp_port = "25"; // SMTP Port
38 var $smtp_timeout = 5; // SMTP Timeout in seconds
39 var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
40 var $wrapchars = "76"; // Number of characters to wrap at.
41 var $mailtype = "text"; // text/html Defines email formatting
42 var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii
43 var $multipart = "mixed"; // "mixed" (in the body) or "related" (separate)
44 var $alt_message = ''; // Alternative message for HTML emails
45 var $validate = FALSE; // TRUE/FALSE. Enables email validation
46 var $priority = "3"; // Default priority (1 - 5)
47 var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
48 var $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
49 // even on the receiving end think they need to muck with CRLFs, so using "\n", while
50 // distasteful, is the only thing that seems to work for all environments.
51 var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
52 var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature
53 var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
54 var $_safe_mode = FALSE;
55 var $_subject = "";
56 var $_body = "";
57 var $_finalbody = "";
58 var $_alt_boundary = "";
59 var $_atc_boundary = "";
60 var $_header_str = "";
61 var $_smtp_connect = "";
62 var $_encoding = "8bit";
63 var $_IP = FALSE;
64 var $_smtp_auth = FALSE;
65 var $_replyto_flag = FALSE;
66 var $_debug_msg = array();
67 var $_recipients = array();
68 var $_cc_array = array();
69 var $_bcc_array = array();
70 var $_headers = array();
71 var $_attach_name = array();
72 var $_attach_type = array();
73 var $_attach_disp = array();
74 var $_protocols = array('mail', 'sendmail', 'smtp');
75 var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
76 var $_bit_depths = array('7bit', '8bit');
77 var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
78
79
80 /**
81 * Constructor - Sets Email Preferences
82 *
83 * The constructor can be passed an array of config values
84 */
85 function CI_Email($config = array())
86 {
87 if (count($config) > 0)
88 {
89 $this->initialize($config);
90 }
91 else
92 {
93 $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
94 $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
95 }
96
97 log_message('debug', "Email Class Initialized");
98 }
99
100 // --------------------------------------------------------------------
101
102 /**
103 * Initialize preferences
104 *
105 * @access public
106 * @param array
107 * @return void
108 */
109 function initialize($config = array())
110 {
111 $this->clear();
112 foreach ($config as $key => $val)
113 {
114 if (isset($this->$key))
115 {
116 $method = 'set_'.$key;
117
118 if (method_exists($this, $method))
119 {
120 $this->$method($val);
121 }
122 else
123 {
124 $this->$key = $val;
125 }
126 }
127 }
128
129 $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
130 $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
131 }
132
133 // --------------------------------------------------------------------
134
135 /**
136 * Initialize the Email Data
137 *
138 * @access public
139 * @return void
140 */
141 function clear($clear_attachments = FALSE)
142 {
143 $this->_subject = "";
144 $this->_body = "";
145 $this->_finalbody = "";
146 $this->_header_str = "";
147 $this->_replyto_flag = FALSE;
148 $this->_recipients = array();
Derek Jonesd1606352010-09-01 11:16:07 -0500149 $this->_cc_array = array();
150 $this->_bcc_array = array();
Derek Allard2067d1a2008-11-13 22:59:24 +0000151 $this->_headers = array();
152 $this->_debug_msg = array();
153
154 $this->_set_header('User-Agent', $this->useragent);
155 $this->_set_header('Date', $this->_set_date());
156
157 if ($clear_attachments !== FALSE)
158 {
159 $this->_attach_name = array();
160 $this->_attach_type = array();
161 $this->_attach_disp = array();
162 }
163 }
164
165 // --------------------------------------------------------------------
166
167 /**
168 * Set FROM
169 *
170 * @access public
171 * @param string
172 * @param string
173 * @return void
174 */
175 function from($from, $name = '')
176 {
177 if (preg_match( '/\<(.*)\>/', $from, $match))
178 {
179 $from = $match['1'];
180 }
181
182 if ($this->validate)
183 {
184 $this->validate_email($this->_str_to_array($from));
185 }
186
187 // prepare the display name
188 if ($name != '')
189 {
190 // only use Q encoding if there are characters that would require it
191 if ( ! preg_match('/[\200-\377]/', $name))
192 {
193 // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
Derek Jonesc630bcf2008-11-17 21:09:45 +0000194 $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
Derek Allard2067d1a2008-11-13 22:59:24 +0000195 }
196 else
197 {
198 $name = $this->_prep_q_encoding($name, TRUE);
199 }
200 }
201
202 $this->_set_header('From', $name.' <'.$from.'>');
203 $this->_set_header('Return-Path', '<'.$from.'>');
204 }
205
206 // --------------------------------------------------------------------
207
208 /**
209 * Set Reply-to
210 *
211 * @access public
212 * @param string
213 * @param string
214 * @return void
215 */
216 function reply_to($replyto, $name = '')
217 {
218 if (preg_match( '/\<(.*)\>/', $replyto, $match))
219 {
220 $replyto = $match['1'];
221 }
222
223 if ($this->validate)
224 {
225 $this->validate_email($this->_str_to_array($replyto));
226 }
227
228 if ($name == '')
229 {
230 $name = $replyto;
231 }
232
233 if (strncmp($name, '"', 1) != 0)
234 {
235 $name = '"'.$name.'"';
236 }
237
238 $this->_set_header('Reply-To', $name.' <'.$replyto.'>');
239 $this->_replyto_flag = TRUE;
240 }
241
242 // --------------------------------------------------------------------
243
244 /**
245 * Set Recipients
246 *
247 * @access public
248 * @param string
249 * @return void
250 */
251 function to($to)
252 {
253 $to = $this->_str_to_array($to);
254 $to = $this->clean_email($to);
255
256 if ($this->validate)
257 {
258 $this->validate_email($to);
259 }
260
261 if ($this->_get_protocol() != 'mail')
262 {
263 $this->_set_header('To', implode(", ", $to));
264 }
265
266 switch ($this->_get_protocol())
267 {
268 case 'smtp' : $this->_recipients = $to;
269 break;
270 case 'sendmail' : $this->_recipients = implode(", ", $to);
271 break;
272 case 'mail' : $this->_recipients = implode(", ", $to);
273 break;
274 }
275 }
276
277 // --------------------------------------------------------------------
278
279 /**
280 * Set CC
281 *
282 * @access public
283 * @param string
284 * @return void
285 */
286 function cc($cc)
287 {
288 $cc = $this->_str_to_array($cc);
289 $cc = $this->clean_email($cc);
290
291 if ($this->validate)
292 {
293 $this->validate_email($cc);
294 }
295
296 $this->_set_header('Cc', implode(", ", $cc));
297
298 if ($this->_get_protocol() == "smtp")
299 {
300 $this->_cc_array = $cc;
301 }
302 }
303
304 // --------------------------------------------------------------------
305
306 /**
307 * Set BCC
308 *
309 * @access public
310 * @param string
311 * @param string
312 * @return void
313 */
314 function bcc($bcc, $limit = '')
315 {
316 if ($limit != '' && is_numeric($limit))
317 {
318 $this->bcc_batch_mode = TRUE;
319 $this->bcc_batch_size = $limit;
320 }
321
322 $bcc = $this->_str_to_array($bcc);
323 $bcc = $this->clean_email($bcc);
324
325 if ($this->validate)
326 {
327 $this->validate_email($bcc);
328 }
329
330 if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
331 {
332 $this->_bcc_array = $bcc;
333 }
334 else
335 {
336 $this->_set_header('Bcc', implode(", ", $bcc));
337 }
338 }
339
340 // --------------------------------------------------------------------
341
342 /**
343 * Set Email Subject
344 *
345 * @access public
346 * @param string
347 * @return void
348 */
349 function subject($subject)
350 {
351 $subject = $this->_prep_q_encoding($subject);
352 $this->_set_header('Subject', $subject);
353 }
354
355 // --------------------------------------------------------------------
356
357 /**
358 * Set Body
359 *
360 * @access public
361 * @param string
362 * @return void
363 */
364 function message($body)
365 {
366 $this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));
367 }
368
369 // --------------------------------------------------------------------
370
371 /**
372 * Assign file attachments
373 *
374 * @access public
375 * @param string
376 * @return void
377 */
378 function attach($filename, $disposition = 'attachment')
379 {
380 $this->_attach_name[] = $filename;
381 $this->_attach_type[] = $this->_mime_types(next(explode('.', basename($filename))));
382 $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters
383 }
384
385 // --------------------------------------------------------------------
386
387 /**
388 * Add a Header Item
389 *
390 * @access private
391 * @param string
392 * @param string
393 * @return void
394 */
395 function _set_header($header, $value)
396 {
397 $this->_headers[$header] = $value;
398 }
399
400 // --------------------------------------------------------------------
401
402 /**
403 * Convert a String to an Array
404 *
405 * @access private
406 * @param string
407 * @return array
408 */
409 function _str_to_array($email)
410 {
411 if ( ! is_array($email))
412 {
413 if (strpos($email, ',') !== FALSE)
414 {
415 $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY);
416 }
417 else
418 {
419 $email = trim($email);
420 settype($email, "array");
421 }
422 }
423 return $email;
424 }
425
426 // --------------------------------------------------------------------
427
428 /**
429 * Set Multipart Value
430 *
431 * @access public
432 * @param string
433 * @return void
434 */
435 function set_alt_message($str = '')
436 {
437 $this->alt_message = ($str == '') ? '' : $str;
438 }
439
440 // --------------------------------------------------------------------
441
442 /**
443 * Set Mailtype
444 *
445 * @access public
446 * @param string
447 * @return void
448 */
449 function set_mailtype($type = 'text')
450 {
451 $this->mailtype = ($type == 'html') ? 'html' : 'text';
452 }
453
454 // --------------------------------------------------------------------
455
456 /**
457 * Set Wordwrap
458 *
459 * @access public
460 * @param string
461 * @return void
462 */
463 function set_wordwrap($wordwrap = TRUE)
464 {
465 $this->wordwrap = ($wordwrap === FALSE) ? FALSE : TRUE;
466 }
467
468 // --------------------------------------------------------------------
469
470 /**
471 * Set Protocol
472 *
473 * @access public
474 * @param string
475 * @return void
476 */
477 function set_protocol($protocol = 'mail')
478 {
479 $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol);
480 }
481
482 // --------------------------------------------------------------------
483
484 /**
485 * Set Priority
486 *
487 * @access public
488 * @param integer
489 * @return void
490 */
491 function set_priority($n = 3)
492 {
493 if ( ! is_numeric($n))
494 {
495 $this->priority = 3;
496 return;
497 }
498
499 if ($n < 1 OR $n > 5)
500 {
501 $this->priority = 3;
502 return;
503 }
504
505 $this->priority = $n;
506 }
507
508 // --------------------------------------------------------------------
509
510 /**
511 * Set Newline Character
512 *
513 * @access public
514 * @param string
515 * @return void
516 */
517 function set_newline($newline = "\n")
518 {
519 if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r")
520 {
521 $this->newline = "\n";
522 return;
523 }
524
525 $this->newline = $newline;
526 }
527
528 // --------------------------------------------------------------------
529
530 /**
531 * Set CRLF
532 *
533 * @access public
534 * @param string
535 * @return void
536 */
537 function set_crlf($crlf = "\n")
538 {
539 if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r")
540 {
541 $this->crlf = "\n";
542 return;
543 }
544
545 $this->crlf = $crlf;
546 }
547
548 // --------------------------------------------------------------------
549
550 /**
551 * Set Message Boundary
552 *
553 * @access private
554 * @return void
555 */
556 function _set_boundaries()
557 {
558 $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative
559 $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary
560 }
561
562 // --------------------------------------------------------------------
563
564 /**
565 * Get the Message ID
566 *
567 * @access private
568 * @return string
569 */
570 function _get_message_id()
571 {
572 $from = $this->_headers['Return-Path'];
573 $from = str_replace(">", "", $from);
574 $from = str_replace("<", "", $from);
575
576 return "<".uniqid('').strstr($from, '@').">";
577 }
578
579 // --------------------------------------------------------------------
580
581 /**
582 * Get Mail Protocol
583 *
584 * @access private
585 * @param bool
586 * @return string
587 */
588 function _get_protocol($return = TRUE)
589 {
590 $this->protocol = strtolower($this->protocol);
591 $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol;
592
593 if ($return == TRUE)
594 {
595 return $this->protocol;
596 }
597 }
598
599 // --------------------------------------------------------------------
600
601 /**
602 * Get Mail Encoding
603 *
604 * @access private
605 * @param bool
606 * @return string
607 */
608 function _get_encoding($return = TRUE)
609 {
610 $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding;
611
612 foreach ($this->_base_charsets as $charset)
613 {
614 if (strncmp($charset, $this->charset, strlen($charset)) == 0)
615 {
616 $this->_encoding = '7bit';
617 }
618 }
619
620 if ($return == TRUE)
621 {
622 return $this->_encoding;
623 }
624 }
625
626 // --------------------------------------------------------------------
627
628 /**
629 * Get content type (text/html/attachment)
630 *
631 * @access private
632 * @return string
633 */
634 function _get_content_type()
635 {
636 if ($this->mailtype == 'html' && count($this->_attach_name) == 0)
637 {
638 return 'html';
639 }
640 elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0)
641 {
642 return 'html-attach';
643 }
644 elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0)
645 {
646 return 'plain-attach';
647 }
648 else
649 {
650 return 'plain';
651 }
652 }
653
654 // --------------------------------------------------------------------
655
656 /**
657 * Set RFC 822 Date
658 *
659 * @access private
660 * @return string
661 */
662 function _set_date()
663 {
664 $timezone = date("Z");
665 $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+';
666 $timezone = abs($timezone);
667 $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60;
668
669 return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone);
670 }
671
672 // --------------------------------------------------------------------
673
674 /**
675 * Mime message
676 *
677 * @access private
678 * @return string
679 */
680 function _get_mime_message()
681 {
682 return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format.";
683 }
684
685 // --------------------------------------------------------------------
686
687 /**
688 * Validate Email Address
689 *
690 * @access public
691 * @param string
692 * @return bool
693 */
694 function validate_email($email)
695 {
696 if ( ! is_array($email))
697 {
698 $this->_set_error_message('email_must_be_array');
699 return FALSE;
700 }
701
702 foreach ($email as $val)
703 {
704 if ( ! $this->valid_email($val))
705 {
706 $this->_set_error_message('email_invalid_address', $val);
707 return FALSE;
708 }
709 }
710
711 return TRUE;
712 }
713
714 // --------------------------------------------------------------------
715
716 /**
717 * Email Validation
718 *
719 * @access public
720 * @param string
721 * @return bool
722 */
723 function valid_email($address)
724 {
725 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
726 }
727
728 // --------------------------------------------------------------------
729
730 /**
731 * Clean Extended Email Address: Joe Smith <joe@smith.com>
732 *
733 * @access public
734 * @param string
735 * @return string
736 */
737 function clean_email($email)
738 {
739 if ( ! is_array($email))
740 {
741 if (preg_match('/\<(.*)\>/', $email, $match))
742 {
743 return $match['1'];
744 }
745 else
746 {
747 return $email;
748 }
749 }
750
751 $clean_email = array();
752
753 foreach ($email as $addy)
754 {
755 if (preg_match( '/\<(.*)\>/', $addy, $match))
756 {
757 $clean_email[] = $match['1'];
758 }
759 else
760 {
761 $clean_email[] = $addy;
762 }
763 }
764
765 return $clean_email;
766 }
767
768 // --------------------------------------------------------------------
769
770 /**
771 * Build alternative plain text message
772 *
773 * This function provides the raw message for use
774 * in plain-text headers of HTML-formatted emails.
775 * If the user hasn't specified his own alternative message
776 * it creates one by stripping the HTML
777 *
778 * @access private
779 * @return string
780 */
781 function _get_alt_message()
782 {
783 if ($this->alt_message != "")
784 {
785 return $this->word_wrap($this->alt_message, '76');
786 }
787
788 if (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match))
789 {
790 $body = $match['1'];
791 }
792 else
793 {
794 $body = $this->_body;
795 }
796
797 $body = trim(strip_tags($body));
798 $body = preg_replace( '#<!--(.*)--\>#', "", $body);
799 $body = str_replace("\t", "", $body);
800
801 for ($i = 20; $i >= 3; $i--)
802 {
803 $n = "";
804
805 for ($x = 1; $x <= $i; $x ++)
806 {
807 $n .= "\n";
808 }
809
810 $body = str_replace($n, "\n\n", $body);
811 }
812
813 return $this->word_wrap($body, '76');
814 }
815
816 // --------------------------------------------------------------------
817
818 /**
819 * Word Wrap
820 *
821 * @access public
822 * @param string
823 * @param integer
824 * @return string
825 */
826 function word_wrap($str, $charlim = '')
827 {
828 // Se the character limit
829 if ($charlim == '')
830 {
831 $charlim = ($this->wrapchars == "") ? "76" : $this->wrapchars;
832 }
833
834 // Reduce multiple spaces
835 $str = preg_replace("| +|", " ", $str);
836
837 // Standardize newlines
838 if (strpos($str, "\r") !== FALSE)
839 {
840 $str = str_replace(array("\r\n", "\r"), "\n", $str);
841 }
842
843 // If the current word is surrounded by {unwrap} tags we'll
844 // strip the entire chunk and replace it with a marker.
845 $unwrap = array();
846 if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
847 {
848 for ($i = 0; $i < count($matches['0']); $i++)
849 {
850 $unwrap[] = $matches['1'][$i];
851 $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
852 }
853 }
854
855 // Use PHP's native function to do the initial wordwrap.
856 // We set the cut flag to FALSE so that any individual words that are
857 // too long get left alone. In the next step we'll deal with them.
858 $str = wordwrap($str, $charlim, "\n", FALSE);
859
860 // Split the string into individual lines of text and cycle through them
861 $output = "";
862 foreach (explode("\n", $str) as $line)
863 {
864 // Is the line within the allowed character count?
865 // If so we'll join it to the output and continue
866 if (strlen($line) <= $charlim)
867 {
868 $output .= $line.$this->newline;
869 continue;
870 }
871
872 $temp = '';
873 while((strlen($line)) > $charlim)
874 {
875 // If the over-length word is a URL we won't wrap it
876 if (preg_match("!\[url.+\]|://|wwww.!", $line))
877 {
878 break;
879 }
880
881 // Trim the word down
882 $temp .= substr($line, 0, $charlim-1);
883 $line = substr($line, $charlim-1);
884 }
885
886 // If $temp contains data it means we had to split up an over-length
887 // word into smaller chunks so we'll add it back to our current line
888 if ($temp != '')
889 {
890 $output .= $temp.$this->newline.$line;
891 }
892 else
893 {
894 $output .= $line;
895 }
896
897 $output .= $this->newline;
898 }
899
900 // Put our markers back
901 if (count($unwrap) > 0)
902 {
903 foreach ($unwrap as $key => $val)
904 {
905 $output = str_replace("{{unwrapped".$key."}}", $val, $output);
906 }
907 }
908
909 return $output;
910 }
911
912 // --------------------------------------------------------------------
913
914 /**
915 * Build final headers
916 *
917 * @access private
918 * @param string
919 * @return string
920 */
921 function _build_headers()
922 {
923 $this->_set_header('X-Sender', $this->clean_email($this->_headers['From']));
924 $this->_set_header('X-Mailer', $this->useragent);
925 $this->_set_header('X-Priority', $this->_priorities[$this->priority - 1]);
926 $this->_set_header('Message-ID', $this->_get_message_id());
927 $this->_set_header('Mime-Version', '1.0');
928 }
929
930 // --------------------------------------------------------------------
931
932 /**
933 * Write Headers as a string
934 *
935 * @access private
936 * @return void
937 */
938 function _write_headers()
939 {
940 if ($this->protocol == 'mail')
941 {
942 $this->_subject = $this->_headers['Subject'];
943 unset($this->_headers['Subject']);
944 }
945
946 reset($this->_headers);
947 $this->_header_str = "";
948
949 foreach($this->_headers as $key => $val)
950 {
951 $val = trim($val);
952
953 if ($val != "")
954 {
955 $this->_header_str .= $key.": ".$val.$this->newline;
956 }
957 }
958
959 if ($this->_get_protocol() == 'mail')
960 {
Derek Jones1d890882009-02-10 20:32:14 +0000961 $this->_header_str = rtrim($this->_header_str);
Derek Allard2067d1a2008-11-13 22:59:24 +0000962 }
963 }
964
965 // --------------------------------------------------------------------
966
967 /**
968 * Build Final Body and attachments
969 *
970 * @access private
971 * @return void
972 */
973 function _build_message()
974 {
975 if ($this->wordwrap === TRUE AND $this->mailtype != 'html')
976 {
977 $this->_body = $this->word_wrap($this->_body);
978 }
979
980 $this->_set_boundaries();
981 $this->_write_headers();
982
983 $hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';
984
985 switch ($this->_get_content_type())
986 {
987 case 'plain' :
988
989 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
990 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
991
992 if ($this->_get_protocol() == 'mail')
993 {
994 $this->_header_str .= $hdr;
995 $this->_finalbody = $this->_body;
996
997 return;
998 }
999
1000 $hdr .= $this->newline . $this->newline . $this->_body;
1001
1002 $this->_finalbody = $hdr;
1003 return;
1004
1005 break;
1006 case 'html' :
1007
1008 if ($this->send_multipart === FALSE)
1009 {
1010 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1011 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1012 }
1013 else
1014 {
Derek Jonesa45e7612009-02-10 18:33:01 +00001015 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline;
Derek Allard2067d1a2008-11-13 22:59:24 +00001016 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1017 $hdr .= "--" . $this->_alt_boundary . $this->newline;
1018
1019 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1020 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1021 $hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1022
1023 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1024 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1025 }
1026
1027 $this->_body = $this->_prep_quoted_printable($this->_body);
1028
1029 if ($this->_get_protocol() == 'mail')
1030 {
1031 $this->_header_str .= $hdr;
1032 $this->_finalbody = $this->_body . $this->newline . $this->newline;
1033
1034 if ($this->send_multipart !== FALSE)
1035 {
1036 $this->_finalbody .= "--" . $this->_alt_boundary . "--";
1037 }
1038
1039 return;
1040 }
1041
1042 $hdr .= $this->newline . $this->newline;
1043 $hdr .= $this->_body . $this->newline . $this->newline;
1044
1045 if ($this->send_multipart !== FALSE)
1046 {
1047 $hdr .= "--" . $this->_alt_boundary . "--";
1048 }
1049
1050 $this->_finalbody = $hdr;
1051 return;
1052
1053 break;
1054 case 'plain-attach' :
1055
Derek Jonesa45e7612009-02-10 18:33:01 +00001056 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
Derek Allard2067d1a2008-11-13 22:59:24 +00001057 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1058 $hdr .= "--" . $this->_atc_boundary . $this->newline;
1059
1060 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1061 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
1062
1063 if ($this->_get_protocol() == 'mail')
1064 {
1065 $this->_header_str .= $hdr;
1066
1067 $body = $this->_body . $this->newline . $this->newline;
1068 }
1069
1070 $hdr .= $this->newline . $this->newline;
1071 $hdr .= $this->_body . $this->newline . $this->newline;
1072
1073 break;
1074 case 'html-attach' :
1075
Derek Jonesa45e7612009-02-10 18:33:01 +00001076 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
Derek Allard2067d1a2008-11-13 22:59:24 +00001077 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1078 $hdr .= "--" . $this->_atc_boundary . $this->newline;
1079
1080 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
1081 $hdr .= "--" . $this->_alt_boundary . $this->newline;
1082
1083 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1084 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1085 $hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1086
1087 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1088 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1089
1090 $this->_body = $this->_prep_quoted_printable($this->_body);
1091
1092 if ($this->_get_protocol() == 'mail')
1093 {
1094 $this->_header_str .= $hdr;
1095
1096 $body = $this->_body . $this->newline . $this->newline;
1097 $body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1098 }
1099
1100 $hdr .= $this->newline . $this->newline;
1101 $hdr .= $this->_body . $this->newline . $this->newline;
1102 $hdr .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1103
1104 break;
1105 }
1106
1107 $attachment = array();
1108
1109 $z = 0;
1110
1111 for ($i=0; $i < count($this->_attach_name); $i++)
1112 {
1113 $filename = $this->_attach_name[$i];
1114 $basename = basename($filename);
1115 $ctype = $this->_attach_type[$i];
1116
1117 if ( ! file_exists($filename))
1118 {
1119 $this->_set_error_message('email_attachment_missing', $filename);
1120 return FALSE;
1121 }
1122
1123 $h = "--".$this->_atc_boundary.$this->newline;
1124 $h .= "Content-type: ".$ctype."; ";
1125 $h .= "name=\"".$basename."\"".$this->newline;
1126 $h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline;
1127 $h .= "Content-Transfer-Encoding: base64".$this->newline;
1128
1129 $attachment[$z++] = $h;
1130 $file = filesize($filename) +1;
1131
1132 if ( ! $fp = fopen($filename, FOPEN_READ))
1133 {
1134 $this->_set_error_message('email_attachment_unreadable', $filename);
1135 return FALSE;
1136 }
1137
1138 $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file)));
1139 fclose($fp);
1140 }
1141
1142 if ($this->_get_protocol() == 'mail')
1143 {
1144 $this->_finalbody = $body . implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1145
1146 return;
1147 }
1148
1149 $this->_finalbody = $hdr.implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1150
1151 return;
1152 }
1153
1154 // --------------------------------------------------------------------
1155
1156 /**
1157 * Prep Quoted Printable
1158 *
1159 * Prepares string for Quoted-Printable Content-Transfer-Encoding
1160 * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
1161 *
1162 * @access private
1163 * @param string
1164 * @param integer
1165 * @return string
1166 */
1167 function _prep_quoted_printable($str, $charlim = '')
1168 {
1169 // Set the character limit
1170 // Don't allow over 76, as that will make servers and MUAs barf
1171 // all over quoted-printable data
1172 if ($charlim == '' OR $charlim > '76')
1173 {
1174 $charlim = '76';
1175 }
1176
1177 // Reduce multiple spaces
1178 $str = preg_replace("| +|", " ", $str);
1179
1180 // kill nulls
1181 $str = preg_replace('/\x00+/', '', $str);
1182
1183 // Standardize newlines
1184 if (strpos($str, "\r") !== FALSE)
1185 {
1186 $str = str_replace(array("\r\n", "\r"), "\n", $str);
1187 }
1188
1189 // We are intentionally wrapping so mail servers will encode characters
1190 // properly and MUAs will behave, so {unwrap} must go!
1191 $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
1192
1193 // Break into an array of lines
1194 $lines = explode("\n", $str);
1195
1196 $escape = '=';
1197 $output = '';
1198
1199 foreach ($lines as $line)
1200 {
1201 $length = strlen($line);
1202 $temp = '';
1203
1204 // Loop through each character in the line to add soft-wrap
1205 // characters at the end of a line " =\r\n" and add the newly
1206 // processed line(s) to the output (see comment on $crlf class property)
1207 for ($i = 0; $i < $length; $i++)
1208 {
1209 // Grab the next character
1210 $char = substr($line, $i, 1);
1211 $ascii = ord($char);
1212
1213 // Convert spaces and tabs but only if it's the end of the line
1214 if ($i == ($length - 1))
1215 {
1216 $char = ($ascii == '32' OR $ascii == '9') ? $escape.sprintf('%02s', dechex($ascii)) : $char;
1217 }
1218
1219 // encode = signs
1220 if ($ascii == '61')
1221 {
1222 $char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D
1223 }
1224
1225 // If we're at the character limit, add the line to the output,
1226 // reset our temp variable, and keep on chuggin'
1227 if ((strlen($temp) + strlen($char)) >= $charlim)
1228 {
1229 $output .= $temp.$escape.$this->crlf;
1230 $temp = '';
1231 }
1232
1233 // Add the character to our temporary line
1234 $temp .= $char;
1235 }
1236
1237 // Add our completed line to the output
1238 $output .= $temp.$this->crlf;
1239 }
1240
1241 // get rid of extra CRLF tacked onto the end
1242 $output = substr($output, 0, strlen($this->crlf) * -1);
1243
1244 return $output;
1245 }
1246
1247 // --------------------------------------------------------------------
1248
1249 /**
1250 * Prep Q Encoding
1251 *
1252 * Performs "Q Encoding" on a string for use in email headers. It's related
1253 * but not identical to quoted-printable, so it has its own method
1254 *
1255 * @access public
1256 * @param str
1257 * @param bool // set to TRUE for processing From: headers
1258 * @return str
1259 */
1260 function _prep_q_encoding($str, $from = FALSE)
1261 {
1262 $str = str_replace(array("\r", "\n"), array('', ''), $str);
1263
1264 // Line length must not exceed 76 characters, so we adjust for
1265 // a space, 7 extra characters =??Q??=, and the charset that we will add to each line
1266 $limit = 75 - 7 - strlen($this->charset);
1267
1268 // these special characters must be converted too
1269 $convert = array('_', '=', '?');
1270
1271 if ($from === TRUE)
1272 {
1273 $convert[] = ',';
1274 $convert[] = ';';
1275 }
1276
1277 $output = '';
1278 $temp = '';
1279
1280 for ($i = 0, $length = strlen($str); $i < $length; $i++)
1281 {
1282 // Grab the next character
1283 $char = substr($str, $i, 1);
1284 $ascii = ord($char);
1285
1286 // convert ALL non-printable ASCII characters and our specials
1287 if ($ascii < 32 OR $ascii > 126 OR in_array($char, $convert))
1288 {
1289 $char = '='.dechex($ascii);
1290 }
1291
1292 // handle regular spaces a bit more compactly than =20
1293 if ($ascii == 32)
1294 {
1295 $char = '_';
1296 }
1297
1298 // If we're at the character limit, add the line to the output,
1299 // reset our temp variable, and keep on chuggin'
1300 if ((strlen($temp) + strlen($char)) >= $limit)
1301 {
1302 $output .= $temp.$this->crlf;
1303 $temp = '';
1304 }
1305
1306 // Add the character to our temporary line
1307 $temp .= $char;
1308 }
1309
1310 $str = $output.$temp;
1311
1312 // wrap each line with the shebang, charset, and transfer encoding
1313 // the preceding space on successive lines is required for header "folding"
1314 $str = trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $str));
1315
1316 return $str;
1317 }
1318
1319 // --------------------------------------------------------------------
1320
1321 /**
1322 * Send Email
1323 *
1324 * @access public
1325 * @return bool
1326 */
1327 function send()
1328 {
1329 if ($this->_replyto_flag == FALSE)
1330 {
1331 $this->reply_to($this->_headers['From']);
1332 }
1333
1334 if (( ! isset($this->_recipients) AND ! isset($this->_headers['To'])) AND
1335 ( ! isset($this->_bcc_array) AND ! isset($this->_headers['Bcc'])) AND
1336 ( ! isset($this->_headers['Cc'])))
1337 {
1338 $this->_set_error_message('email_no_recipients');
1339 return FALSE;
1340 }
1341
1342 $this->_build_headers();
1343
1344 if ($this->bcc_batch_mode AND count($this->_bcc_array) > 0)
1345 {
1346 if (count($this->_bcc_array) > $this->bcc_batch_size)
1347 return $this->batch_bcc_send();
1348 }
1349
1350 $this->_build_message();
1351
1352 if ( ! $this->_spool_email())
1353 {
1354 return FALSE;
1355 }
1356 else
1357 {
1358 return TRUE;
1359 }
1360 }
1361
1362 // --------------------------------------------------------------------
1363
1364 /**
1365 * Batch Bcc Send. Sends groups of BCCs in batches
1366 *
1367 * @access public
1368 * @return bool
1369 */
1370 function batch_bcc_send()
1371 {
1372 $float = $this->bcc_batch_size -1;
1373
1374 $set = "";
1375
1376 $chunk = array();
1377
1378 for ($i = 0; $i < count($this->_bcc_array); $i++)
1379 {
1380 if (isset($this->_bcc_array[$i]))
1381 {
1382 $set .= ", ".$this->_bcc_array[$i];
1383 }
1384
1385 if ($i == $float)
1386 {
1387 $chunk[] = substr($set, 1);
1388 $float = $float + $this->bcc_batch_size;
1389 $set = "";
1390 }
1391
1392 if ($i == count($this->_bcc_array)-1)
1393 {
1394 $chunk[] = substr($set, 1);
1395 }
1396 }
1397
1398 for ($i = 0; $i < count($chunk); $i++)
1399 {
1400 unset($this->_headers['Bcc']);
1401 unset($bcc);
1402
1403 $bcc = $this->_str_to_array($chunk[$i]);
1404 $bcc = $this->clean_email($bcc);
1405
1406 if ($this->protocol != 'smtp')
1407 {
1408 $this->_set_header('Bcc', implode(", ", $bcc));
1409 }
1410 else
1411 {
1412 $this->_bcc_array = $bcc;
1413 }
1414
1415 $this->_build_message();
1416 $this->_spool_email();
1417 }
1418 }
1419
1420 // --------------------------------------------------------------------
1421
1422 /**
1423 * Unwrap special elements
1424 *
1425 * @access private
1426 * @return void
1427 */
1428 function _unwrap_specials()
1429 {
1430 $this->_finalbody = preg_replace_callback("/\{unwrap\}(.*?)\{\/unwrap\}/si", array($this, '_remove_nl_callback'), $this->_finalbody);
1431 }
1432
1433 // --------------------------------------------------------------------
1434
1435 /**
1436 * Strip line-breaks via callback
1437 *
1438 * @access private
1439 * @return string
1440 */
1441 function _remove_nl_callback($matches)
1442 {
1443 if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
1444 {
1445 $matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
1446 }
1447
1448 return $matches[1];
1449 }
1450
1451 // --------------------------------------------------------------------
1452
1453 /**
1454 * Spool mail to the mail server
1455 *
1456 * @access private
1457 * @return bool
1458 */
1459 function _spool_email()
1460 {
1461 $this->_unwrap_specials();
1462
1463 switch ($this->_get_protocol())
1464 {
1465 case 'mail' :
1466
1467 if ( ! $this->_send_with_mail())
1468 {
1469 $this->_set_error_message('email_send_failure_phpmail');
1470 return FALSE;
1471 }
1472 break;
1473 case 'sendmail' :
1474
1475 if ( ! $this->_send_with_sendmail())
1476 {
1477 $this->_set_error_message('email_send_failure_sendmail');
1478 return FALSE;
1479 }
1480 break;
1481 case 'smtp' :
1482
1483 if ( ! $this->_send_with_smtp())
1484 {
1485 $this->_set_error_message('email_send_failure_smtp');
1486 return FALSE;
1487 }
1488 break;
1489
1490 }
1491
1492 $this->_set_error_message('email_sent', $this->_get_protocol());
1493 return TRUE;
1494 }
1495
1496 // --------------------------------------------------------------------
1497
1498 /**
1499 * Send using mail()
1500 *
1501 * @access private
1502 * @return bool
1503 */
1504 function _send_with_mail()
1505 {
1506 if ($this->_safe_mode == TRUE)
1507 {
1508 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str))
1509 {
1510 return FALSE;
1511 }
1512 else
1513 {
1514 return TRUE;
1515 }
1516 }
1517 else
1518 {
1519 // most documentation of sendmail using the "-f" flag lacks a space after it, however
1520 // we've encountered servers that seem to require it to be in place.
1521 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))
1522 {
1523 return FALSE;
1524 }
1525 else
1526 {
1527 return TRUE;
1528 }
1529 }
1530 }
1531
1532 // --------------------------------------------------------------------
1533
1534 /**
1535 * Send using Sendmail
1536 *
1537 * @access private
1538 * @return bool
1539 */
1540 function _send_with_sendmail()
1541 {
1542 $fp = @popen($this->mailpath . " -oi -f ".$this->clean_email($this->_headers['From'])." -t", 'w');
1543
Derek Jones4cefaa42009-04-29 19:13:56 +00001544 if ($fp === FALSE OR $fp === NULL)
1545 {
1546 // server probably has popen disabled, so nothing we can do to get a verbose error.
1547 return FALSE;
1548 }
Derek Jones71141ce2010-03-02 16:41:20 -06001549
Derek Jonesc630bcf2008-11-17 21:09:45 +00001550 fputs($fp, $this->_header_str);
1551 fputs($fp, $this->_finalbody);
1552
1553 $status = pclose($fp);
1554
1555 if (version_compare(PHP_VERSION, '4.2.3') == -1)
1556 {
1557 $status = $status >> 8 & 0xFF;
1558 }
Derek Jones71141ce2010-03-02 16:41:20 -06001559
Derek Jones604873f2008-11-18 15:57:24 +00001560 if ($status != 0)
Derek Allard2067d1a2008-11-13 22:59:24 +00001561 {
Derek Jones604873f2008-11-18 15:57:24 +00001562 $this->_set_error_message('email_exit_status', $status);
Derek Allard2067d1a2008-11-13 22:59:24 +00001563 $this->_set_error_message('email_no_socket');
1564 return FALSE;
1565 }
1566
Derek Allard2067d1a2008-11-13 22:59:24 +00001567 return TRUE;
1568 }
1569
1570 // --------------------------------------------------------------------
1571
1572 /**
1573 * Send using SMTP
1574 *
1575 * @access private
1576 * @return bool
1577 */
1578 function _send_with_smtp()
1579 {
1580 if ($this->smtp_host == '')
1581 {
1582 $this->_set_error_message('email_no_hostname');
1583 return FALSE;
1584 }
1585
1586 $this->_smtp_connect();
1587 $this->_smtp_authenticate();
1588
1589 $this->_send_command('from', $this->clean_email($this->_headers['From']));
1590
1591 foreach($this->_recipients as $val)
1592 {
1593 $this->_send_command('to', $val);
1594 }
1595
1596 if (count($this->_cc_array) > 0)
1597 {
1598 foreach($this->_cc_array as $val)
1599 {
1600 if ($val != "")
1601 {
1602 $this->_send_command('to', $val);
1603 }
1604 }
1605 }
1606
1607 if (count($this->_bcc_array) > 0)
1608 {
1609 foreach($this->_bcc_array as $val)
1610 {
1611 if ($val != "")
1612 {
1613 $this->_send_command('to', $val);
1614 }
1615 }
1616 }
1617
1618 $this->_send_command('data');
1619
1620 // perform dot transformation on any lines that begin with a dot
1621 $this->_send_data($this->_header_str . preg_replace('/^\./m', '..$1', $this->_finalbody));
1622
1623 $this->_send_data('.');
1624
1625 $reply = $this->_get_smtp_data();
1626
1627 $this->_set_error_message($reply);
1628
1629 if (strncmp($reply, '250', 3) != 0)
1630 {
1631 $this->_set_error_message('email_smtp_error', $reply);
1632 return FALSE;
1633 }
1634
1635 $this->_send_command('quit');
1636 return TRUE;
1637 }
1638
1639 // --------------------------------------------------------------------
1640
1641 /**
1642 * SMTP Connect
1643 *
1644 * @access private
1645 * @param string
1646 * @return string
1647 */
1648 function _smtp_connect()
1649 {
1650 $this->_smtp_connect = fsockopen($this->smtp_host,
1651 $this->smtp_port,
1652 $errno,
1653 $errstr,
1654 $this->smtp_timeout);
1655
1656 if( ! is_resource($this->_smtp_connect))
1657 {
1658 $this->_set_error_message('email_smtp_error', $errno." ".$errstr);
1659 return FALSE;
1660 }
1661
1662 $this->_set_error_message($this->_get_smtp_data());
1663 return $this->_send_command('hello');
1664 }
1665
1666 // --------------------------------------------------------------------
1667
1668 /**
1669 * Send SMTP command
1670 *
1671 * @access private
1672 * @param string
1673 * @param string
1674 * @return string
1675 */
1676 function _send_command($cmd, $data = '')
1677 {
1678 switch ($cmd)
1679 {
1680 case 'hello' :
1681
1682 if ($this->_smtp_auth OR $this->_get_encoding() == '8bit')
1683 $this->_send_data('EHLO '.$this->_get_hostname());
1684 else
1685 $this->_send_data('HELO '.$this->_get_hostname());
1686
1687 $resp = 250;
1688 break;
1689 case 'from' :
1690
1691 $this->_send_data('MAIL FROM:<'.$data.'>');
1692
1693 $resp = 250;
1694 break;
1695 case 'to' :
1696
1697 $this->_send_data('RCPT TO:<'.$data.'>');
1698
1699 $resp = 250;
1700 break;
1701 case 'data' :
1702
1703 $this->_send_data('DATA');
1704
1705 $resp = 354;
1706 break;
1707 case 'quit' :
1708
1709 $this->_send_data('QUIT');
1710
1711 $resp = 221;
1712 break;
1713 }
1714
1715 $reply = $this->_get_smtp_data();
1716
1717 $this->_debug_msg[] = "<pre>".$cmd.": ".$reply."</pre>";
1718
1719 if (substr($reply, 0, 3) != $resp)
1720 {
1721 $this->_set_error_message('email_smtp_error', $reply);
1722 return FALSE;
1723 }
1724
1725 if ($cmd == 'quit')
1726 {
1727 fclose($this->_smtp_connect);
1728 }
1729
1730 return TRUE;
1731 }
1732
1733 // --------------------------------------------------------------------
1734
1735 /**
1736 * SMTP Authenticate
1737 *
1738 * @access private
1739 * @return bool
1740 */
1741 function _smtp_authenticate()
1742 {
1743 if ( ! $this->_smtp_auth)
1744 {
1745 return TRUE;
1746 }
1747
1748 if ($this->smtp_user == "" AND $this->smtp_pass == "")
1749 {
1750 $this->_set_error_message('email_no_smtp_unpw');
1751 return FALSE;
1752 }
1753
1754 $this->_send_data('AUTH LOGIN');
1755
1756 $reply = $this->_get_smtp_data();
1757
1758 if (strncmp($reply, '334', 3) != 0)
1759 {
1760 $this->_set_error_message('email_failed_smtp_login', $reply);
1761 return FALSE;
1762 }
1763
1764 $this->_send_data(base64_encode($this->smtp_user));
1765
1766 $reply = $this->_get_smtp_data();
1767
1768 if (strncmp($reply, '334', 3) != 0)
1769 {
1770 $this->_set_error_message('email_smtp_auth_un', $reply);
1771 return FALSE;
1772 }
1773
1774 $this->_send_data(base64_encode($this->smtp_pass));
1775
1776 $reply = $this->_get_smtp_data();
1777
1778 if (strncmp($reply, '235', 3) != 0)
1779 {
1780 $this->_set_error_message('email_smtp_auth_pw', $reply);
1781 return FALSE;
1782 }
1783
1784 return TRUE;
1785 }
1786
1787 // --------------------------------------------------------------------
1788
1789 /**
1790 * Send SMTP data
1791 *
1792 * @access private
1793 * @return bool
1794 */
1795 function _send_data($data)
1796 {
1797 if ( ! fwrite($this->_smtp_connect, $data . $this->newline))
1798 {
1799 $this->_set_error_message('email_smtp_data_failure', $data);
1800 return FALSE;
1801 }
1802 else
1803 {
1804 return TRUE;
1805 }
1806 }
1807
1808 // --------------------------------------------------------------------
1809
1810 /**
1811 * Get SMTP data
1812 *
1813 * @access private
1814 * @return string
1815 */
1816 function _get_smtp_data()
1817 {
1818 $data = "";
1819
1820 while ($str = fgets($this->_smtp_connect, 512))
1821 {
1822 $data .= $str;
1823
1824 if (substr($str, 3, 1) == " ")
1825 {
1826 break;
1827 }
1828 }
1829
1830 return $data;
1831 }
1832
1833 // --------------------------------------------------------------------
1834
1835 /**
1836 * Get Hostname
1837 *
1838 * @access private
1839 * @return string
1840 */
1841 function _get_hostname()
1842 {
1843 return (isset($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
1844 }
1845
1846 // --------------------------------------------------------------------
1847
1848 /**
1849 * Get IP
1850 *
1851 * @access private
1852 * @return string
1853 */
1854 function _get_ip()
1855 {
1856 if ($this->_IP !== FALSE)
1857 {
1858 return $this->_IP;
1859 }
1860
1861 $cip = (isset($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] != "") ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
1862 $rip = (isset($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] != "") ? $_SERVER['REMOTE_ADDR'] : FALSE;
1863 $fip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
1864
1865 if ($cip && $rip) $this->_IP = $cip;
1866 elseif ($rip) $this->_IP = $rip;
1867 elseif ($cip) $this->_IP = $cip;
1868 elseif ($fip) $this->_IP = $fip;
1869
Robin Sowell76b369e2010-03-19 11:15:28 -04001870 if (strpos($this->_IP, ',') !== FALSE)
Derek Allard2067d1a2008-11-13 22:59:24 +00001871 {
1872 $x = explode(',', $this->_IP);
1873 $this->_IP = end($x);
1874 }
1875
1876 if ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $this->_IP))
1877 {
1878 $this->_IP = '0.0.0.0';
1879 }
1880
1881 unset($cip);
1882 unset($rip);
1883 unset($fip);
1884
1885 return $this->_IP;
1886 }
1887
1888 // --------------------------------------------------------------------
1889
1890 /**
1891 * Get Debug Message
1892 *
1893 * @access public
1894 * @return string
1895 */
1896 function print_debugger()
1897 {
1898 $msg = '';
1899
1900 if (count($this->_debug_msg) > 0)
1901 {
1902 foreach ($this->_debug_msg as $val)
1903 {
1904 $msg .= $val;
1905 }
1906 }
1907
1908 $msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
1909 return $msg;
1910 }
1911
1912 // --------------------------------------------------------------------
1913
1914 /**
1915 * Set Message
1916 *
1917 * @access private
1918 * @param string
1919 * @return string
1920 */
1921 function _set_error_message($msg, $val = '')
1922 {
1923 $CI =& get_instance();
1924 $CI->lang->load('email');
1925
1926 if (FALSE === ($line = $CI->lang->line($msg)))
1927 {
1928 $this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
1929 }
1930 else
1931 {
1932 $this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
1933 }
1934 }
1935
1936 // --------------------------------------------------------------------
1937
1938 /**
1939 * Mime Types
1940 *
1941 * @access private
1942 * @param string
1943 * @return string
1944 */
1945 function _mime_types($ext = "")
1946 {
1947 $mimes = array( 'hqx' => 'application/mac-binhex40',
1948 'cpt' => 'application/mac-compactpro',
1949 'doc' => 'application/msword',
1950 'bin' => 'application/macbinary',
1951 'dms' => 'application/octet-stream',
1952 'lha' => 'application/octet-stream',
1953 'lzh' => 'application/octet-stream',
1954 'exe' => 'application/octet-stream',
1955 'class' => 'application/octet-stream',
1956 'psd' => 'application/octet-stream',
1957 'so' => 'application/octet-stream',
1958 'sea' => 'application/octet-stream',
1959 'dll' => 'application/octet-stream',
1960 'oda' => 'application/oda',
1961 'pdf' => 'application/pdf',
1962 'ai' => 'application/postscript',
1963 'eps' => 'application/postscript',
1964 'ps' => 'application/postscript',
1965 'smi' => 'application/smil',
1966 'smil' => 'application/smil',
1967 'mif' => 'application/vnd.mif',
1968 'xls' => 'application/vnd.ms-excel',
1969 'ppt' => 'application/vnd.ms-powerpoint',
1970 'wbxml' => 'application/vnd.wap.wbxml',
1971 'wmlc' => 'application/vnd.wap.wmlc',
1972 'dcr' => 'application/x-director',
1973 'dir' => 'application/x-director',
1974 'dxr' => 'application/x-director',
1975 'dvi' => 'application/x-dvi',
1976 'gtar' => 'application/x-gtar',
1977 'php' => 'application/x-httpd-php',
1978 'php4' => 'application/x-httpd-php',
1979 'php3' => 'application/x-httpd-php',
1980 'phtml' => 'application/x-httpd-php',
1981 'phps' => 'application/x-httpd-php-source',
1982 'js' => 'application/x-javascript',
1983 'swf' => 'application/x-shockwave-flash',
1984 'sit' => 'application/x-stuffit',
1985 'tar' => 'application/x-tar',
1986 'tgz' => 'application/x-tar',
1987 'xhtml' => 'application/xhtml+xml',
1988 'xht' => 'application/xhtml+xml',
1989 'zip' => 'application/zip',
1990 'mid' => 'audio/midi',
1991 'midi' => 'audio/midi',
1992 'mpga' => 'audio/mpeg',
1993 'mp2' => 'audio/mpeg',
1994 'mp3' => 'audio/mpeg',
1995 'aif' => 'audio/x-aiff',
1996 'aiff' => 'audio/x-aiff',
1997 'aifc' => 'audio/x-aiff',
1998 'ram' => 'audio/x-pn-realaudio',
1999 'rm' => 'audio/x-pn-realaudio',
2000 'rpm' => 'audio/x-pn-realaudio-plugin',
2001 'ra' => 'audio/x-realaudio',
2002 'rv' => 'video/vnd.rn-realvideo',
2003 'wav' => 'audio/x-wav',
2004 'bmp' => 'image/bmp',
2005 'gif' => 'image/gif',
2006 'jpeg' => 'image/jpeg',
2007 'jpg' => 'image/jpeg',
2008 'jpe' => 'image/jpeg',
2009 'png' => 'image/png',
2010 'tiff' => 'image/tiff',
2011 'tif' => 'image/tiff',
2012 'css' => 'text/css',
2013 'html' => 'text/html',
2014 'htm' => 'text/html',
2015 'shtml' => 'text/html',
2016 'txt' => 'text/plain',
2017 'text' => 'text/plain',
2018 'log' => 'text/plain',
2019 'rtx' => 'text/richtext',
2020 'rtf' => 'text/rtf',
2021 'xml' => 'text/xml',
2022 'xsl' => 'text/xml',
2023 'mpeg' => 'video/mpeg',
2024 'mpg' => 'video/mpeg',
2025 'mpe' => 'video/mpeg',
2026 'qt' => 'video/quicktime',
2027 'mov' => 'video/quicktime',
2028 'avi' => 'video/x-msvideo',
2029 'movie' => 'video/x-sgi-movie',
2030 'doc' => 'application/msword',
2031 'word' => 'application/msword',
2032 'xl' => 'application/excel',
2033 'eml' => 'message/rfc822'
2034 );
2035
2036 return ( ! isset($mimes[strtolower($ext)])) ? "application/x-unknown-content-type" : $mimes[strtolower($ext)];
2037 }
2038
2039}
2040// END CI_Email class
2041
2042/* End of file Email.php */
Derek Jonesa3ffbbb2008-05-11 18:18:29 +00002043/* Location: ./system/libraries/Email.php */