Subversion-Projekte lars-tiefland.ci

Revision

Revision 2254 | Revision 2258 | Zur aktuellen Revision | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
68 lars 1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
2257 lars 9
 * Copyright (c) 2014 - 2018, British Columbia Institute of Technology
68 lars 10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
12
 * of this software and associated documentation files (the "Software"), to deal
13
 * in the Software without restriction, including without limitation the rights
14
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
 * copies of the Software, and to permit persons to whom the Software is
16
 * furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies or substantial portions of the Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
 * THE SOFTWARE.
28
 *
29
 * @package	CodeIgniter
30
 * @author	EllisLab Dev Team
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
2257 lars 32
 * @copyright	Copyright (c) 2014 - 2018, British Columbia Institute of Technology (http://bcit.ca/)
68 lars 33
 * @license	http://opensource.org/licenses/MIT	MIT License
34
 * @link	https://codeigniter.com
35
 * @since	Version 1.0.0
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * CodeIgniter Email Class
42
 *
43
 * Permits email to be sent using Mail, Sendmail, or SMTP.
44
 *
45
 * @package		CodeIgniter
46
 * @subpackage	Libraries
47
 * @category	Libraries
48
 * @author		EllisLab Dev Team
49
 * @link		https://codeigniter.com/user_guide/libraries/email.html
50
 */
51
class CI_Email {
52
 
53
	/**
54
	 * Used as the User-Agent and X-Mailer headers' value.
55
	 *
56
	 * @var	string
57
	 */
58
	public $useragent	= 'CodeIgniter';
59
 
60
	/**
61
	 * Path to the Sendmail binary.
62
	 *
63
	 * @var	string
64
	 */
65
	public $mailpath	= '/usr/sbin/sendmail';	// Sendmail path
66
 
67
	/**
68
	 * Which method to use for sending e-mails.
69
	 *
70
	 * @var	string	'mail', 'sendmail' or 'smtp'
71
	 */
72
	public $protocol	= 'mail';		// mail/sendmail/smtp
73
 
74
	/**
75
	 * STMP Server host
76
	 *
77
	 * @var	string
78
	 */
79
	public $smtp_host	= '';
80
 
81
	/**
82
	 * SMTP Username
83
	 *
84
	 * @var	string
85
	 */
86
	public $smtp_user	= '';
87
 
88
	/**
89
	 * SMTP Password
90
	 *
91
	 * @var	string
92
	 */
93
	public $smtp_pass	= '';
94
 
95
	/**
96
	 * SMTP Server port
97
	 *
98
	 * @var	int
99
	 */
100
	public $smtp_port	= 25;
101
 
102
	/**
103
	 * SMTP connection timeout in seconds
104
	 *
105
	 * @var	int
106
	 */
107
	public $smtp_timeout	= 5;
108
 
109
	/**
110
	 * SMTP persistent connection
111
	 *
112
	 * @var	bool
113
	 */
114
	public $smtp_keepalive	= FALSE;
115
 
116
	/**
117
	 * SMTP Encryption
118
	 *
119
	 * @var	string	empty, 'tls' or 'ssl'
120
	 */
121
	public $smtp_crypto	= '';
122
 
123
	/**
124
	 * Whether to apply word-wrapping to the message body.
125
	 *
126
	 * @var	bool
127
	 */
128
	public $wordwrap	= TRUE;
129
 
130
	/**
131
	 * Number of characters to wrap at.
132
	 *
133
	 * @see	CI_Email::$wordwrap
134
	 * @var	int
135
	 */
136
	public $wrapchars	= 76;
137
 
138
	/**
139
	 * Message format.
140
	 *
141
	 * @var	string	'text' or 'html'
142
	 */
143
	public $mailtype	= 'text';
144
 
145
	/**
146
	 * Character set (default: utf-8)
147
	 *
148
	 * @var	string
149
	 */
150
	public $charset		= 'UTF-8';
151
 
152
	/**
153
	 * Alternative message (for HTML messages only)
154
	 *
155
	 * @var	string
156
	 */
157
	public $alt_message	= '';
158
 
159
	/**
160
	 * Whether to validate e-mail addresses.
161
	 *
162
	 * @var	bool
163
	 */
164
	public $validate	= FALSE;
165
 
166
	/**
167
	 * X-Priority header value.
168
	 *
169
	 * @var	int	1-5
170
	 */
171
	public $priority	= 3;			// Default priority (1 - 5)
172
 
173
	/**
174
	 * Newline character sequence.
175
	 * Use "\r\n" to comply with RFC 822.
176
	 *
177
	 * @link	http://www.ietf.org/rfc/rfc822.txt
178
	 * @var	string	"\r\n" or "\n"
179
	 */
180
	public $newline		= "\n";			// Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
181
 
182
	/**
183
	 * CRLF character sequence
184
	 *
185
	 * RFC 2045 specifies that for 'quoted-printable' encoding,
186
	 * "\r\n" must be used. However, it appears that some servers
187
	 * (even on the receiving end) don't handle it properly and
188
	 * switching to "\n", while improper, is the only solution
189
	 * that seems to work for all environments.
190
	 *
191
	 * @link	http://www.ietf.org/rfc/rfc822.txt
192
	 * @var	string
193
	 */
194
	public $crlf		= "\n";
195
 
196
	/**
197
	 * Whether to use Delivery Status Notification.
198
	 *
199
	 * @var	bool
200
	 */
201
	public $dsn		= FALSE;
202
 
203
	/**
204
	 * Whether to send multipart alternatives.
205
	 * Yahoo! doesn't seem to like these.
206
	 *
207
	 * @var	bool
208
	 */
209
	public $send_multipart	= TRUE;
210
 
211
	/**
212
	 * Whether to send messages to BCC recipients in batches.
213
	 *
214
	 * @var	bool
215
	 */
216
	public $bcc_batch_mode	= FALSE;
217
 
218
	/**
219
	 * BCC Batch max number size.
220
	 *
221
	 * @see	CI_Email::$bcc_batch_mode
222
	 * @var	int
223
	 */
224
	public $bcc_batch_size	= 200;
225
 
226
	// --------------------------------------------------------------------
227
 
228
	/**
229
	 * Whether PHP is running in safe mode. Initialized by the class constructor.
230
	 *
231
	 * @var	bool
232
	 */
233
	protected $_safe_mode		= FALSE;
234
 
235
	/**
236
	 * Subject header
237
	 *
238
	 * @var	string
239
	 */
240
	protected $_subject		= '';
241
 
242
	/**
243
	 * Message body
244
	 *
245
	 * @var	string
246
	 */
247
	protected $_body		= '';
248
 
249
	/**
250
	 * Final message body to be sent.
251
	 *
252
	 * @var	string
253
	 */
254
	protected $_finalbody		= '';
255
 
256
	/**
257
	 * Final headers to send
258
	 *
259
	 * @var	string
260
	 */
261
	protected $_header_str		= '';
262
 
263
	/**
264
	 * SMTP Connection socket placeholder
265
	 *
266
	 * @var	resource
267
	 */
268
	protected $_smtp_connect	= '';
269
 
270
	/**
271
	 * Mail encoding
272
	 *
273
	 * @var	string	'8bit' or '7bit'
274
	 */
275
	protected $_encoding		= '8bit';
276
 
277
	/**
278
	 * Whether to perform SMTP authentication
279
	 *
280
	 * @var	bool
281
	 */
282
	protected $_smtp_auth		= FALSE;
283
 
284
	/**
285
	 * Whether to send a Reply-To header
286
	 *
287
	 * @var	bool
288
	 */
289
	protected $_replyto_flag	= FALSE;
290
 
291
	/**
292
	 * Debug messages
293
	 *
294
	 * @see	CI_Email::print_debugger()
295
	 * @var	string
296
	 */
297
	protected $_debug_msg		= array();
298
 
299
	/**
300
	 * Recipients
301
	 *
302
	 * @var	string[]
303
	 */
304
	protected $_recipients		= array();
305
 
306
	/**
307
	 * CC Recipients
308
	 *
309
	 * @var	string[]
310
	 */
311
	protected $_cc_array		= array();
312
 
313
	/**
314
	 * BCC Recipients
315
	 *
316
	 * @var	string[]
317
	 */
318
	protected $_bcc_array		= array();
319
 
320
	/**
321
	 * Message headers
322
	 *
323
	 * @var	string[]
324
	 */
325
	protected $_headers		= array();
326
 
327
	/**
328
	 * Attachment data
329
	 *
330
	 * @var	array
331
	 */
332
	protected $_attachments		= array();
333
 
334
	/**
335
	 * Valid $protocol values
336
	 *
337
	 * @see	CI_Email::$protocol
338
	 * @var	string[]
339
	 */
340
	protected $_protocols		= array('mail', 'sendmail', 'smtp');
341
 
342
	/**
343
	 * Base charsets
344
	 *
345
	 * Character sets valid for 7-bit encoding,
346
	 * excluding language suffix.
347
	 *
348
	 * @var	string[]
349
	 */
350
	protected $_base_charsets	= array('us-ascii', 'iso-2022-');
351
 
352
	/**
353
	 * Bit depths
354
	 *
355
	 * Valid mail encodings
356
	 *
357
	 * @see	CI_Email::$_encoding
358
	 * @var	string[]
359
	 */
360
	protected $_bit_depths		= array('7bit', '8bit');
361
 
362
	/**
363
	 * $priority translations
364
	 *
365
	 * Actual values to send with the X-Priority header
366
	 *
367
	 * @var	string[]
368
	 */
369
	protected $_priorities = array(
370
		1 => '1 (Highest)',
371
		2 => '2 (High)',
372
		3 => '3 (Normal)',
373
		4 => '4 (Low)',
374
		5 => '5 (Lowest)'
375
	);
376
 
1257 lars 377
	/**
2107 lars 378
	 * mbstring.func_overload flag
1257 lars 379
	 *
380
	 * @var	bool
381
	 */
2107 lars 382
	protected static $func_overload;
1257 lars 383
 
68 lars 384
	// --------------------------------------------------------------------
385
 
386
	/**
387
	 * Constructor - Sets Email Preferences
388
	 *
389
	 * The constructor can be passed an array of config values
390
	 *
391
	 * @param	array	$config = array()
392
	 * @return	void
393
	 */
394
	public function __construct(array $config = array())
395
	{
396
		$this->charset = config_item('charset');
397
		$this->initialize($config);
398
		$this->_safe_mode = ( ! is_php('5.4') && ini_get('safe_mode'));
399
 
2107 lars 400
		isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));
1257 lars 401
 
68 lars 402
		log_message('info', 'Email Class Initialized');
403
	}
404
 
405
	// --------------------------------------------------------------------
406
 
407
	/**
408
	 * Initialize preferences
409
	 *
410
	 * @param	array	$config
411
	 * @return	CI_Email
412
	 */
413
	public function initialize(array $config = array())
414
	{
415
		$this->clear();
416
 
417
		foreach ($config as $key => $val)
418
		{
419
			if (isset($this->$key))
420
			{
421
				$method = 'set_'.$key;
422
 
423
				if (method_exists($this, $method))
424
				{
425
					$this->$method($val);
426
				}
427
				else
428
				{
429
					$this->$key = $val;
430
				}
431
			}
432
		}
433
 
434
		$this->charset = strtoupper($this->charset);
435
		$this->_smtp_auth = isset($this->smtp_user[0], $this->smtp_pass[0]);
436
 
437
		return $this;
438
	}
439
 
440
	// --------------------------------------------------------------------
441
 
442
	/**
443
	 * Initialize the Email Data
444
	 *
445
	 * @param	bool
446
	 * @return	CI_Email
447
	 */
448
	public function clear($clear_attachments = FALSE)
449
	{
450
		$this->_subject		= '';
451
		$this->_body		= '';
452
		$this->_finalbody	= '';
453
		$this->_header_str	= '';
454
		$this->_replyto_flag	= FALSE;
455
		$this->_recipients	= array();
456
		$this->_cc_array	= array();
457
		$this->_bcc_array	= array();
458
		$this->_headers		= array();
459
		$this->_debug_msg	= array();
460
 
461
		$this->set_header('Date', $this->_set_date());
462
 
463
		if ($clear_attachments !== FALSE)
464
		{
465
			$this->_attachments = array();
466
		}
467
 
468
		return $this;
469
	}
470
 
471
	// --------------------------------------------------------------------
472
 
473
	/**
474
	 * Set FROM
475
	 *
476
	 * @param	string	$from
477
	 * @param	string	$name
478
	 * @param	string	$return_path = NULL	Return-Path
479
	 * @return	CI_Email
480
	 */
481
	public function from($from, $name = '', $return_path = NULL)
482
	{
483
		if (preg_match('/\<(.*)\>/', $from, $match))
484
		{
485
			$from = $match[1];
486
		}
487
 
488
		if ($this->validate)
489
		{
490
			$this->validate_email($this->_str_to_array($from));
491
			if ($return_path)
492
			{
493
				$this->validate_email($this->_str_to_array($return_path));
494
			}
495
		}
496
 
497
		// prepare the display name
498
		if ($name !== '')
499
		{
500
			// only use Q encoding if there are characters that would require it
501
			if ( ! preg_match('/[\200-\377]/', $name))
502
			{
503
				// add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
504
				$name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
505
			}
506
			else
507
			{
508
				$name = $this->_prep_q_encoding($name);
509
			}
510
		}
511
 
512
		$this->set_header('From', $name.' <'.$from.'>');
513
 
514
		isset($return_path) OR $return_path = $from;
515
		$this->set_header('Return-Path', '<'.$return_path.'>');
516
 
517
		return $this;
518
	}
519
 
520
	// --------------------------------------------------------------------
521
 
522
	/**
523
	 * Set Reply-to
524
	 *
525
	 * @param	string
526
	 * @param	string
527
	 * @return	CI_Email
528
	 */
529
	public function reply_to($replyto, $name = '')
530
	{
531
		if (preg_match('/\<(.*)\>/', $replyto, $match))
532
		{
533
			$replyto = $match[1];
534
		}
535
 
536
		if ($this->validate)
537
		{
538
			$this->validate_email($this->_str_to_array($replyto));
539
		}
540
 
541
		if ($name !== '')
542
		{
543
			// only use Q encoding if there are characters that would require it
544
			if ( ! preg_match('/[\200-\377]/', $name))
545
			{
546
				// add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
547
				$name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
548
			}
549
			else
550
			{
551
				$name = $this->_prep_q_encoding($name);
552
			}
553
		}
554
 
555
		$this->set_header('Reply-To', $name.' <'.$replyto.'>');
556
		$this->_replyto_flag = TRUE;
557
 
558
		return $this;
559
	}
560
 
561
	// --------------------------------------------------------------------
562
 
563
	/**
564
	 * Set Recipients
565
	 *
566
	 * @param	string
567
	 * @return	CI_Email
568
	 */
569
	public function to($to)
570
	{
571
		$to = $this->_str_to_array($to);
572
		$to = $this->clean_email($to);
573
 
574
		if ($this->validate)
575
		{
576
			$this->validate_email($to);
577
		}
578
 
579
		if ($this->_get_protocol() !== 'mail')
580
		{
581
			$this->set_header('To', implode(', ', $to));
582
		}
583
 
584
		$this->_recipients = $to;
585
 
586
		return $this;
587
	}
588
 
589
	// --------------------------------------------------------------------
590
 
591
	/**
592
	 * Set CC
593
	 *
594
	 * @param	string
595
	 * @return	CI_Email
596
	 */
597
	public function cc($cc)
598
	{
599
		$cc = $this->clean_email($this->_str_to_array($cc));
600
 
601
		if ($this->validate)
602
		{
603
			$this->validate_email($cc);
604
		}
605
 
606
		$this->set_header('Cc', implode(', ', $cc));
607
 
608
		if ($this->_get_protocol() === 'smtp')
609
		{
610
			$this->_cc_array = $cc;
611
		}
612
 
613
		return $this;
614
	}
615
 
616
	// --------------------------------------------------------------------
617
 
618
	/**
619
	 * Set BCC
620
	 *
621
	 * @param	string
622
	 * @param	string
623
	 * @return	CI_Email
624
	 */
625
	public function bcc($bcc, $limit = '')
626
	{
627
		if ($limit !== '' && is_numeric($limit))
628
		{
629
			$this->bcc_batch_mode = TRUE;
630
			$this->bcc_batch_size = $limit;
631
		}
632
 
633
		$bcc = $this->clean_email($this->_str_to_array($bcc));
634
 
635
		if ($this->validate)
636
		{
637
			$this->validate_email($bcc);
638
		}
639
 
640
		if ($this->_get_protocol() === 'smtp' OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
641
		{
642
			$this->_bcc_array = $bcc;
643
		}
644
		else
645
		{
646
			$this->set_header('Bcc', implode(', ', $bcc));
647
		}
648
 
649
		return $this;
650
	}
651
 
652
	// --------------------------------------------------------------------
653
 
654
	/**
655
	 * Set Email Subject
656
	 *
657
	 * @param	string
658
	 * @return	CI_Email
659
	 */
660
	public function subject($subject)
661
	{
662
		$subject = $this->_prep_q_encoding($subject);
663
		$this->set_header('Subject', $subject);
664
		return $this;
665
	}
666
 
667
	// --------------------------------------------------------------------
668
 
669
	/**
670
	 * Set Body
671
	 *
672
	 * @param	string
673
	 * @return	CI_Email
674
	 */
675
	public function message($body)
676
	{
677
		$this->_body = rtrim(str_replace("\r", '', $body));
678
 
679
		/* strip slashes only if magic quotes is ON
680
		   if we do it with magic quotes OFF, it strips real, user-inputted chars.
681
 
682
		   NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and
683
			 it will probably not exist in future versions at all.
684
		*/
685
		if ( ! is_php('5.4') && get_magic_quotes_gpc())
686
		{
687
			$this->_body = stripslashes($this->_body);
688
		}
689
 
690
		return $this;
691
	}
692
 
693
	// --------------------------------------------------------------------
694
 
695
	/**
696
	 * Assign file attachments
697
	 *
698
	 * @param	string	$file	Can be local path, URL or buffered content
699
	 * @param	string	$disposition = 'attachment'
700
	 * @param	string	$newname = NULL
701
	 * @param	string	$mime = ''
702
	 * @return	CI_Email
703
	 */
704
	public function attach($file, $disposition = '', $newname = NULL, $mime = '')
705
	{
706
		if ($mime === '')
707
		{
708
			if (strpos($file, '://') === FALSE && ! file_exists($file))
709
			{
710
				$this->_set_error_message('lang:email_attachment_missing', $file);
711
				return FALSE;
712
			}
713
 
714
			if ( ! $fp = @fopen($file, 'rb'))
715
			{
716
				$this->_set_error_message('lang:email_attachment_unreadable', $file);
717
				return FALSE;
718
			}
719
 
720
			$file_content = stream_get_contents($fp);
721
			$mime = $this->_mime_types(pathinfo($file, PATHINFO_EXTENSION));
722
			fclose($fp);
723
		}
724
		else
725
		{
726
			$file_content =& $file; // buffered file
727
		}
728
 
729
		$this->_attachments[] = array(
730
			'name'		=> array($file, $newname),
731
			'disposition'	=> empty($disposition) ? 'attachment' : $disposition,  // Can also be 'inline'  Not sure if it matters
732
			'type'		=> $mime,
733
			'content'	=> chunk_split(base64_encode($file_content)),
734
			'multipart'	=> 'mixed'
735
		);
736
 
737
		return $this;
738
	}
739
 
740
	// --------------------------------------------------------------------
741
 
742
	/**
743
	 * Set and return attachment Content-ID
744
	 *
745
	 * Useful for attached inline pictures
746
	 *
747
	 * @param	string	$filename
748
	 * @return	string
749
	 */
750
	public function attachment_cid($filename)
751
	{
752
		for ($i = 0, $c = count($this->_attachments); $i < $c; $i++)
753
		{
754
			if ($this->_attachments[$i]['name'][0] === $filename)
755
			{
756
				$this->_attachments[$i]['multipart'] = 'related';
757
				$this->_attachments[$i]['cid'] = uniqid(basename($this->_attachments[$i]['name'][0]).'@');
758
				return $this->_attachments[$i]['cid'];
759
			}
760
		}
761
 
762
		return FALSE;
763
	}
764
 
765
	// --------------------------------------------------------------------
766
 
767
	/**
768
	 * Add a Header Item
769
	 *
770
	 * @param	string
771
	 * @param	string
772
	 * @return	CI_Email
773
	 */
774
	public function set_header($header, $value)
775
	{
776
		$this->_headers[$header] = str_replace(array("\n", "\r"), '', $value);
777
		return $this;
778
	}
779
 
780
	// --------------------------------------------------------------------
781
 
782
	/**
783
	 * Convert a String to an Array
784
	 *
785
	 * @param	string
786
	 * @return	array
787
	 */
788
	protected function _str_to_array($email)
789
	{
790
		if ( ! is_array($email))
791
		{
792
			return (strpos($email, ',') !== FALSE)
793
				? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY)
794
				: (array) trim($email);
795
		}
796
 
797
		return $email;
798
	}
799
 
800
	// --------------------------------------------------------------------
801
 
802
	/**
803
	 * Set Multipart Value
804
	 *
805
	 * @param	string
806
	 * @return	CI_Email
807
	 */
808
	public function set_alt_message($str)
809
	{
810
		$this->alt_message = (string) $str;
811
		return $this;
812
	}
813
 
814
	// --------------------------------------------------------------------
815
 
816
	/**
817
	 * Set Mailtype
818
	 *
819
	 * @param	string
820
	 * @return	CI_Email
821
	 */
822
	public function set_mailtype($type = 'text')
823
	{
824
		$this->mailtype = ($type === 'html') ? 'html' : 'text';
825
		return $this;
826
	}
827
 
828
	// --------------------------------------------------------------------
829
 
830
	/**
831
	 * Set Wordwrap
832
	 *
833
	 * @param	bool
834
	 * @return	CI_Email
835
	 */
836
	public function set_wordwrap($wordwrap = TRUE)
837
	{
838
		$this->wordwrap = (bool) $wordwrap;
839
		return $this;
840
	}
841
 
842
	// --------------------------------------------------------------------
843
 
844
	/**
845
	 * Set Protocol
846
	 *
847
	 * @param	string
848
	 * @return	CI_Email
849
	 */
850
	public function set_protocol($protocol = 'mail')
851
	{
852
		$this->protocol = in_array($protocol, $this->_protocols, TRUE) ? strtolower($protocol) : 'mail';
853
		return $this;
854
	}
855
 
856
	// --------------------------------------------------------------------
857
 
858
	/**
859
	 * Set Priority
860
	 *
861
	 * @param	int
862
	 * @return	CI_Email
863
	 */
864
	public function set_priority($n = 3)
865
	{
866
		$this->priority = preg_match('/^[1-5]$/', $n) ? (int) $n : 3;
867
		return $this;
868
	}
869
 
870
	// --------------------------------------------------------------------
871
 
872
	/**
873
	 * Set Newline Character
874
	 *
875
	 * @param	string
876
	 * @return	CI_Email
877
	 */
878
	public function set_newline($newline = "\n")
879
	{
880
		$this->newline = in_array($newline, array("\n", "\r\n", "\r")) ? $newline : "\n";
881
		return $this;
882
	}
883
 
884
	// --------------------------------------------------------------------
885
 
886
	/**
887
	 * Set CRLF
888
	 *
889
	 * @param	string
890
	 * @return	CI_Email
891
	 */
892
	public function set_crlf($crlf = "\n")
893
	{
894
		$this->crlf = ($crlf !== "\n" && $crlf !== "\r\n" && $crlf !== "\r") ? "\n" : $crlf;
895
		return $this;
896
	}
897
 
898
	// --------------------------------------------------------------------
899
 
900
	/**
901
	 * Get the Message ID
902
	 *
903
	 * @return	string
904
	 */
905
	protected function _get_message_id()
906
	{
907
		$from = str_replace(array('>', '<'), '', $this->_headers['Return-Path']);
908
		return '<'.uniqid('').strstr($from, '@').'>';
909
	}
910
 
911
	// --------------------------------------------------------------------
912
 
913
	/**
914
	 * Get Mail Protocol
915
	 *
916
	 * @return	mixed
917
	 */
2107 lars 918
	protected function _get_protocol()
68 lars 919
	{
920
		$this->protocol = strtolower($this->protocol);
921
		in_array($this->protocol, $this->_protocols, TRUE) OR $this->protocol = 'mail';
2107 lars 922
		return $this->protocol;
68 lars 923
	}
924
 
925
	// --------------------------------------------------------------------
926
 
927
	/**
928
	 * Get Mail Encoding
929
	 *
930
	 * @return	string
931
	 */
2107 lars 932
	protected function _get_encoding()
68 lars 933
	{
934
		in_array($this->_encoding, $this->_bit_depths) OR $this->_encoding = '8bit';
935
 
936
		foreach ($this->_base_charsets as $charset)
937
		{
2107 lars 938
			if (strpos($this->charset, $charset) === 0)
68 lars 939
			{
940
				$this->_encoding = '7bit';
941
			}
942
		}
943
 
2107 lars 944
		return $this->_encoding;
68 lars 945
	}
946
 
947
	// --------------------------------------------------------------------
948
 
949
	/**
950
	 * Get content type (text/html/attachment)
951
	 *
952
	 * @return	string
953
	 */
954
	protected function _get_content_type()
955
	{
956
		if ($this->mailtype === 'html')
957
		{
958
			return empty($this->_attachments) ? 'html' : 'html-attach';
959
		}
960
		elseif	($this->mailtype === 'text' && ! empty($this->_attachments))
961
		{
962
			return 'plain-attach';
963
		}
2257 lars 964
 
965
		return 'plain';
68 lars 966
	}
967
 
968
	// --------------------------------------------------------------------
969
 
970
	/**
971
	 * Set RFC 822 Date
972
	 *
973
	 * @return	string
974
	 */
975
	protected function _set_date()
976
	{
977
		$timezone = date('Z');
978
		$operator = ($timezone[0] === '-') ? '-' : '+';
979
		$timezone = abs($timezone);
980
		$timezone = floor($timezone/3600) * 100 + ($timezone % 3600) / 60;
981
 
982
		return sprintf('%s %s%04d', date('D, j M Y H:i:s'), $operator, $timezone);
983
	}
984
 
985
	// --------------------------------------------------------------------
986
 
987
	/**
988
	 * Mime message
989
	 *
990
	 * @return	string
991
	 */
992
	protected function _get_mime_message()
993
	{
994
		return 'This is a multi-part message in MIME format.'.$this->newline.'Your email application may not support this format.';
995
	}
996
 
997
	// --------------------------------------------------------------------
998
 
999
	/**
1000
	 * Validate Email Address
1001
	 *
1002
	 * @param	string
1003
	 * @return	bool
1004
	 */
1005
	public function validate_email($email)
1006
	{
1007
		if ( ! is_array($email))
1008
		{
1009
			$this->_set_error_message('lang:email_must_be_array');
1010
			return FALSE;
1011
		}
1012
 
1013
		foreach ($email as $val)
1014
		{
1015
			if ( ! $this->valid_email($val))
1016
			{
1017
				$this->_set_error_message('lang:email_invalid_address', $val);
1018
				return FALSE;
1019
			}
1020
		}
1021
 
1022
		return TRUE;
1023
	}
1024
 
1025
	// --------------------------------------------------------------------
1026
 
1027
	/**
1028
	 * Email Validation
1029
	 *
1030
	 * @param	string
1031
	 * @return	bool
1032
	 */
1033
	public function valid_email($email)
1034
	{
2257 lars 1035
		if (function_exists('idn_to_ascii') && strpos($email, '@'))
68 lars 1036
		{
2257 lars 1037
			list($account, $domain) = explode('@', $email, 2);
1038
			$domain = defined('INTL_IDNA_VARIANT_UTS46')
1039
				? idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46)
1040
				: idn_to_ascii($domain);
1041
			$email = $account.'@'.$domain;
68 lars 1042
		}
1043
 
1044
		return (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
1045
	}
1046
 
1047
	// --------------------------------------------------------------------
1048
 
1049
	/**
1050
	 * Clean Extended Email Address: Joe Smith <joe@smith.com>
1051
	 *
1052
	 * @param	string
1053
	 * @return	string
1054
	 */
1055
	public function clean_email($email)
1056
	{
1057
		if ( ! is_array($email))
1058
		{
1059
			return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email;
1060
		}
1061
 
1062
		$clean_email = array();
1063
 
1064
		foreach ($email as $addy)
1065
		{
1066
			$clean_email[] = preg_match('/\<(.*)\>/', $addy, $match) ? $match[1] : $addy;
1067
		}
1068
 
1069
		return $clean_email;
1070
	}
1071
 
1072
	// --------------------------------------------------------------------
1073
 
1074
	/**
1075
	 * Build alternative plain text message
1076
	 *
1077
	 * Provides the raw message for use in plain-text headers of
1078
	 * HTML-formatted emails.
1079
	 * If the user hasn't specified his own alternative message
1080
	 * it creates one by stripping the HTML
1081
	 *
1082
	 * @return	string
1083
	 */
1084
	protected function _get_alt_message()
1085
	{
1086
		if ( ! empty($this->alt_message))
1087
		{
1088
			return ($this->wordwrap)
1089
				? $this->word_wrap($this->alt_message, 76)
1090
				: $this->alt_message;
1091
		}
1092
 
1093
		$body = preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match) ? $match[1] : $this->_body;
1094
		$body = str_replace("\t", '', preg_replace('#<!--(.*)--\>#', '', trim(strip_tags($body))));
1095
 
1096
		for ($i = 20; $i >= 3; $i--)
1097
		{
1098
			$body = str_replace(str_repeat("\n", $i), "\n\n", $body);
1099
		}
1100
 
1101
		// Reduce multiple spaces
1102
		$body = preg_replace('| +|', ' ', $body);
1103
 
1104
		return ($this->wordwrap)
1105
			? $this->word_wrap($body, 76)
1106
			: $body;
1107
	}
1108
 
1109
	// --------------------------------------------------------------------
1110
 
1111
	/**
1112
	 * Word Wrap
1113
	 *
1114
	 * @param	string
1115
	 * @param	int	line-length limit
1116
	 * @return	string
1117
	 */
1118
	public function word_wrap($str, $charlim = NULL)
1119
	{
1120
		// Set the character limit, if not already present
1121
		if (empty($charlim))
1122
		{
1123
			$charlim = empty($this->wrapchars) ? 76 : $this->wrapchars;
1124
		}
1125
 
1126
		// Standardize newlines
1127
		if (strpos($str, "\r") !== FALSE)
1128
		{
1129
			$str = str_replace(array("\r\n", "\r"), "\n", $str);
1130
		}
1131
 
1132
		// Reduce multiple spaces at end of line
1133
		$str = preg_replace('| +\n|', "\n", $str);
1134
 
1135
		// If the current word is surrounded by {unwrap} tags we'll
1136
		// strip the entire chunk and replace it with a marker.
1137
		$unwrap = array();
1138
		if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches))
1139
		{
1140
			for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
1141
			{
1142
				$unwrap[] = $matches[1][$i];
1143
				$str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str);
1144
			}
1145
		}
1146
 
1147
		// Use PHP's native function to do the initial wordwrap.
1148
		// We set the cut flag to FALSE so that any individual words that are
1149
		// too long get left alone. In the next step we'll deal with them.
1150
		$str = wordwrap($str, $charlim, "\n", FALSE);
1151
 
1152
		// Split the string into individual lines of text and cycle through them
1153
		$output = '';
1154
		foreach (explode("\n", $str) as $line)
1155
		{
1156
			// Is the line within the allowed character count?
1157
			// If so we'll join it to the output and continue
1257 lars 1158
			if (self::strlen($line) <= $charlim)
68 lars 1159
			{
1160
				$output .= $line.$this->newline;
1161
				continue;
1162
			}
1163
 
1164
			$temp = '';
1165
			do
1166
			{
1167
				// If the over-length word is a URL we won't wrap it
1168
				if (preg_match('!\[url.+\]|://|www\.!', $line))
1169
				{
1170
					break;
1171
				}
1172
 
1173
				// Trim the word down
1257 lars 1174
				$temp .= self::substr($line, 0, $charlim - 1);
1175
				$line = self::substr($line, $charlim - 1);
68 lars 1176
			}
1257 lars 1177
			while (self::strlen($line) > $charlim);
68 lars 1178
 
1179
			// If $temp contains data it means we had to split up an over-length
1180
			// word into smaller chunks so we'll add it back to our current line
1181
			if ($temp !== '')
1182
			{
1183
				$output .= $temp.$this->newline;
1184
			}
1185
 
1186
			$output .= $line.$this->newline;
1187
		}
1188
 
1189
		// Put our markers back
1190
		if (count($unwrap) > 0)
1191
		{
1192
			foreach ($unwrap as $key => $val)
1193
			{
1194
				$output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
1195
			}
1196
		}
1197
 
1198
		return $output;
1199
	}
1200
 
1201
	// --------------------------------------------------------------------
1202
 
1203
	/**
1204
	 * Build final headers
1205
	 *
1257 lars 1206
	 * @return	void
68 lars 1207
	 */
1208
	protected function _build_headers()
1209
	{
2049 lars 1210
		$this->set_header('User-Agent', $this->useragent);
68 lars 1211
		$this->set_header('X-Sender', $this->clean_email($this->_headers['From']));
1212
		$this->set_header('X-Mailer', $this->useragent);
1213
		$this->set_header('X-Priority', $this->_priorities[$this->priority]);
1214
		$this->set_header('Message-ID', $this->_get_message_id());
1215
		$this->set_header('Mime-Version', '1.0');
1216
	}
1217
 
1218
	// --------------------------------------------------------------------
1219
 
1220
	/**
1221
	 * Write Headers as a string
1222
	 *
1223
	 * @return	void
1224
	 */
1225
	protected function _write_headers()
1226
	{
1227
		if ($this->protocol === 'mail')
1228
		{
1229
			if (isset($this->_headers['Subject']))
1230
			{
1231
				$this->_subject = $this->_headers['Subject'];
1232
				unset($this->_headers['Subject']);
1233
			}
1234
		}
1235
 
1236
		reset($this->_headers);
1237
		$this->_header_str = '';
1238
 
1239
		foreach ($this->_headers as $key => $val)
1240
		{
1241
			$val = trim($val);
1242
 
1243
			if ($val !== '')
1244
			{
1245
				$this->_header_str .= $key.': '.$val.$this->newline;
1246
			}
1247
		}
1248
 
1249
		if ($this->_get_protocol() === 'mail')
1250
		{
1251
			$this->_header_str = rtrim($this->_header_str);
1252
		}
1253
	}
1254
 
1255
	// --------------------------------------------------------------------
1256
 
1257
	/**
1258
	 * Build Final Body and attachments
1259
	 *
1260
	 * @return	bool
1261
	 */
1262
	protected function _build_message()
1263
	{
1264
		if ($this->wordwrap === TRUE && $this->mailtype !== 'html')
1265
		{
1266
			$this->_body = $this->word_wrap($this->_body);
1267
		}
1268
 
1269
		$this->_write_headers();
1270
 
1271
		$hdr = ($this->_get_protocol() === 'mail') ? $this->newline : '';
1272
		$body = '';
1273
 
1274
		switch ($this->_get_content_type())
1275
		{
1276
			case 'plain':
1277
 
1278
				$hdr .= 'Content-Type: text/plain; charset='.$this->charset.$this->newline
1279
					.'Content-Transfer-Encoding: '.$this->_get_encoding();
1280
 
1281
				if ($this->_get_protocol() === 'mail')
1282
				{
1283
					$this->_header_str .= $hdr;
1284
					$this->_finalbody = $this->_body;
1285
				}
1286
				else
1287
				{
1288
					$this->_finalbody = $hdr.$this->newline.$this->newline.$this->_body;
1289
				}
1290
 
1291
				return;
1292
 
1293
			case 'html':
1294
 
1295
				if ($this->send_multipart === FALSE)
1296
				{
1297
					$hdr .= 'Content-Type: text/html; charset='.$this->charset.$this->newline
1298
						.'Content-Transfer-Encoding: quoted-printable';
1299
				}
1300
				else
1301
				{
1302
					$boundary = uniqid('B_ALT_');
1303
					$hdr .= 'Content-Type: multipart/alternative; boundary="'.$boundary.'"';
1304
 
1305
					$body .= $this->_get_mime_message().$this->newline.$this->newline
1306
						.'--'.$boundary.$this->newline
1307
 
1308
						.'Content-Type: text/plain; charset='.$this->charset.$this->newline
1309
						.'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline
1310
						.$this->_get_alt_message().$this->newline.$this->newline
1311
						.'--'.$boundary.$this->newline
1312
 
1313
						.'Content-Type: text/html; charset='.$this->charset.$this->newline
1314
						.'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline;
1315
				}
1316
 
1317
				$this->_finalbody = $body.$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline;
1318
 
1319
				if ($this->_get_protocol() === 'mail')
1320
				{
1321
					$this->_header_str .= $hdr;
1322
				}
1323
				else
1324
				{
1325
					$this->_finalbody = $hdr.$this->newline.$this->newline.$this->_finalbody;
1326
				}
1327
 
1328
				if ($this->send_multipart !== FALSE)
1329
				{
1330
					$this->_finalbody .= '--'.$boundary.'--';
1331
				}
1332
 
1333
				return;
1334
 
1335
			case 'plain-attach':
1336
 
1337
				$boundary = uniqid('B_ATC_');
1338
				$hdr .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"';
1339
 
1340
				if ($this->_get_protocol() === 'mail')
1341
				{
1342
					$this->_header_str .= $hdr;
1343
				}
1344
 
1345
				$body .= $this->_get_mime_message().$this->newline
1346
					.$this->newline
1347
					.'--'.$boundary.$this->newline
1348
					.'Content-Type: text/plain; charset='.$this->charset.$this->newline
1349
					.'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline
1350
					.$this->newline
1351
					.$this->_body.$this->newline.$this->newline;
1352
 
1353
				$this->_append_attachments($body, $boundary);
1354
 
1355
				break;
1356
			case 'html-attach':
1357
 
1358
				$alt_boundary = uniqid('B_ALT_');
1359
				$last_boundary = NULL;
1360
 
1361
				if ($this->_attachments_have_multipart('mixed'))
1362
				{
1363
					$atc_boundary = uniqid('B_ATC_');
1364
					$hdr .= 'Content-Type: multipart/mixed; boundary="'.$atc_boundary.'"';
1365
					$last_boundary = $atc_boundary;
1366
				}
1367
 
1368
				if ($this->_attachments_have_multipart('related'))
1369
				{
1370
					$rel_boundary = uniqid('B_REL_');
1371
					$rel_boundary_header = 'Content-Type: multipart/related; boundary="'.$rel_boundary.'"';
1372
 
1373
					if (isset($last_boundary))
1374
					{
1375
						$body .= '--'.$last_boundary.$this->newline.$rel_boundary_header;
1376
					}
1377
					else
1378
					{
1379
						$hdr .= $rel_boundary_header;
1380
					}
1381
 
1382
					$last_boundary = $rel_boundary;
1383
				}
1384
 
1385
				if ($this->_get_protocol() === 'mail')
1386
				{
1387
					$this->_header_str .= $hdr;
1388
				}
1389
 
1257 lars 1390
				self::strlen($body) && $body .= $this->newline.$this->newline;
68 lars 1391
				$body .= $this->_get_mime_message().$this->newline.$this->newline
1392
					.'--'.$last_boundary.$this->newline
1393
 
1394
					.'Content-Type: multipart/alternative; boundary="'.$alt_boundary.'"'.$this->newline.$this->newline
1395
					.'--'.$alt_boundary.$this->newline
1396
 
1397
					.'Content-Type: text/plain; charset='.$this->charset.$this->newline
1398
					.'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline
1399
					.$this->_get_alt_message().$this->newline.$this->newline
1400
					.'--'.$alt_boundary.$this->newline
1401
 
1402
					.'Content-Type: text/html; charset='.$this->charset.$this->newline
1403
					.'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline
1404
 
1405
					.$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline
1406
					.'--'.$alt_boundary.'--'.$this->newline.$this->newline;
1407
 
1408
				if ( ! empty($rel_boundary))
1409
				{
1410
					$body .= $this->newline.$this->newline;
1411
					$this->_append_attachments($body, $rel_boundary, 'related');
1412
				}
1413
 
1414
				// multipart/mixed attachments
1415
				if ( ! empty($atc_boundary))
1416
				{
1417
					$body .= $this->newline.$this->newline;
1418
					$this->_append_attachments($body, $atc_boundary, 'mixed');
1419
				}
1420
 
1421
				break;
1422
		}
1423
 
1424
		$this->_finalbody = ($this->_get_protocol() === 'mail')
1425
			? $body
1426
			: $hdr.$this->newline.$this->newline.$body;
1427
 
1428
		return TRUE;
1429
	}
1430
 
1431
	// --------------------------------------------------------------------
1432
 
1433
	protected function _attachments_have_multipart($type)
1434
	{
1435
		foreach ($this->_attachments as &$attachment)
1436
		{
1437
			if ($attachment['multipart'] === $type)
1438
			{
1439
				return TRUE;
1440
			}
1441
		}
1442
 
1443
		return FALSE;
1444
	}
1445
 
1446
	// --------------------------------------------------------------------
1447
 
1448
	/**
1449
	 * Prepares attachment string
1450
	 *
1451
	 * @param	string	$body		Message body to append to
1452
	 * @param	string	$boundary	Multipart boundary
1453
	 * @param	string	$multipart	When provided, only attachments of this type will be processed
1454
	 * @return	string
1455
	 */
1456
	protected function _append_attachments(&$body, $boundary, $multipart = null)
1457
	{
1458
		for ($i = 0, $c = count($this->_attachments); $i < $c; $i++)
1459
		{
1460
			if (isset($multipart) && $this->_attachments[$i]['multipart'] !== $multipart)
1461
			{
1462
				continue;
1463
			}
1464
 
1465
			$name = isset($this->_attachments[$i]['name'][1])
1466
				? $this->_attachments[$i]['name'][1]
1467
				: basename($this->_attachments[$i]['name'][0]);
1468
 
1469
			$body .= '--'.$boundary.$this->newline
1470
				.'Content-Type: '.$this->_attachments[$i]['type'].'; name="'.$name.'"'.$this->newline
1471
				.'Content-Disposition: '.$this->_attachments[$i]['disposition'].';'.$this->newline
1472
				.'Content-Transfer-Encoding: base64'.$this->newline
1257 lars 1473
				.(empty($this->_attachments[$i]['cid']) ? '' : 'Content-ID: <'.$this->_attachments[$i]['cid'].'>'.$this->newline)
1474
				.$this->newline
68 lars 1475
				.$this->_attachments[$i]['content'].$this->newline;
1476
		}
1477
 
1478
		// $name won't be set if no attachments were appended,
1479
		// and therefore a boundary wouldn't be necessary
1480
		empty($name) OR $body .= '--'.$boundary.'--';
1481
	}
1482
 
1483
	// --------------------------------------------------------------------
1484
 
1485
	/**
1486
	 * Prep Quoted Printable
1487
	 *
1488
	 * Prepares string for Quoted-Printable Content-Transfer-Encoding
1489
	 * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
1490
	 *
1491
	 * @param	string
1492
	 * @return	string
1493
	 */
1494
	protected function _prep_quoted_printable($str)
1495
	{
1496
		// ASCII code numbers for "safe" characters that can always be
1497
		// used literally, without encoding, as described in RFC 2049.
1498
		// http://www.ietf.org/rfc/rfc2049.txt
1499
		static $ascii_safe_chars = array(
1500
			// ' (  )   +   ,   -   .   /   :   =   ?
1501
			39, 40, 41, 43, 44, 45, 46, 47, 58, 61, 63,
1502
			// numbers
1503
			48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
1504
			// upper-case letters
1505
			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,
1506
			// lower-case letters
1507
			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
1508
		);
1509
 
1510
		// We are intentionally wrapping so mail servers will encode characters
1511
		// properly and MUAs will behave, so {unwrap} must go!
1512
		$str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
1513
 
1514
		// RFC 2045 specifies CRLF as "\r\n".
1515
		// However, many developers choose to override that and violate
1516
		// the RFC rules due to (apparently) a bug in MS Exchange,
1517
		// which only works with "\n".
1518
		if ($this->crlf === "\r\n")
1519
		{
1257 lars 1520
			return quoted_printable_encode($str);
68 lars 1521
		}
1522
 
1523
		// Reduce multiple spaces & remove nulls
1524
		$str = preg_replace(array('| +|', '/\x00+/'), array(' ', ''), $str);
1525
 
1526
		// Standardize newlines
1527
		if (strpos($str, "\r") !== FALSE)
1528
		{
1529
			$str = str_replace(array("\r\n", "\r"), "\n", $str);
1530
		}
1531
 
1532
		$escape = '=';
1533
		$output = '';
1534
 
1535
		foreach (explode("\n", $str) as $line)
1536
		{
1257 lars 1537
			$length = self::strlen($line);
68 lars 1538
			$temp = '';
1539
 
1540
			// Loop through each character in the line to add soft-wrap
1541
			// characters at the end of a line " =\r\n" and add the newly
1542
			// processed line(s) to the output (see comment on $crlf class property)
1543
			for ($i = 0; $i < $length; $i++)
1544
			{
1545
				// Grab the next character
1546
				$char = $line[$i];
1547
				$ascii = ord($char);
1548
 
1549
				// Convert spaces and tabs but only if it's the end of the line
1550
				if ($ascii === 32 OR $ascii === 9)
1551
				{
1552
					if ($i === ($length - 1))
1553
					{
1554
						$char = $escape.sprintf('%02s', dechex($ascii));
1555
					}
1556
				}
1557
				// DO NOT move this below the $ascii_safe_chars line!
1558
				//
1559
				// = (equals) signs are allowed by RFC2049, but must be encoded
1560
				// as they are the encoding delimiter!
1561
				elseif ($ascii === 61)
1562
				{
1563
					$char = $escape.strtoupper(sprintf('%02s', dechex($ascii)));  // =3D
1564
				}
1565
				elseif ( ! in_array($ascii, $ascii_safe_chars, TRUE))
1566
				{
1567
					$char = $escape.strtoupper(sprintf('%02s', dechex($ascii)));
1568
				}
1569
 
1570
				// If we're at the character limit, add the line to the output,
1571
				// reset our temp variable, and keep on chuggin'
1257 lars 1572
				if ((self::strlen($temp) + self::strlen($char)) >= 76)
68 lars 1573
				{
1574
					$output .= $temp.$escape.$this->crlf;
1575
					$temp = '';
1576
				}
1577
 
1578
				// Add the character to our temporary line
1579
				$temp .= $char;
1580
			}
1581
 
1582
			// Add our completed line to the output
1583
			$output .= $temp.$this->crlf;
1584
		}
1585
 
1586
		// get rid of extra CRLF tacked onto the end
1257 lars 1587
		return self::substr($output, 0, self::strlen($this->crlf) * -1);
68 lars 1588
	}
1589
 
1590
	// --------------------------------------------------------------------
1591
 
1592
	/**
1593
	 * Prep Q Encoding
1594
	 *
1595
	 * Performs "Q Encoding" on a string for use in email headers.
1596
	 * It's related but not identical to quoted-printable, so it has its
1597
	 * own method.
1598
	 *
1599
	 * @param	string
1600
	 * @return	string
1601
	 */
1602
	protected function _prep_q_encoding($str)
1603
	{
1604
		$str = str_replace(array("\r", "\n"), '', $str);
1605
 
1606
		if ($this->charset === 'UTF-8')
1607
		{
1608
			// Note: We used to have mb_encode_mimeheader() as the first choice
1609
			//       here, but it turned out to be buggy and unreliable. DO NOT
1610
			//       re-add it! -- Narf
1611
			if (ICONV_ENABLED === TRUE)
1612
			{
1613
				$output = @iconv_mime_encode('', $str,
1614
					array(
1615
						'scheme' => 'Q',
1616
						'line-length' => 76,
1617
						'input-charset' => $this->charset,
1618
						'output-charset' => $this->charset,
1619
						'line-break-chars' => $this->crlf
1620
					)
1621
				);
1622
 
1623
				// There are reports that iconv_mime_encode() might fail and return FALSE
1624
				if ($output !== FALSE)
1625
				{
1626
					// iconv_mime_encode() will always put a header field name.
1627
					// We've passed it an empty one, but it still prepends our
1628
					// encoded string with ': ', so we need to strip it.
1257 lars 1629
					return self::substr($output, 2);
68 lars 1630
				}
1631
 
1632
				$chars = iconv_strlen($str, 'UTF-8');
1633
			}
1634
			elseif (MB_ENABLED === TRUE)
1635
			{
1636
				$chars = mb_strlen($str, 'UTF-8');
1637
			}
1638
		}
1639
 
1640
		// We might already have this set for UTF-8
1257 lars 1641
		isset($chars) OR $chars = self::strlen($str);
68 lars 1642
 
1643
		$output = '=?'.$this->charset.'?Q?';
1257 lars 1644
		for ($i = 0, $length = self::strlen($output); $i < $chars; $i++)
68 lars 1645
		{
1646
			$chr = ($this->charset === 'UTF-8' && ICONV_ENABLED === TRUE)
1647
				? '='.implode('=', str_split(strtoupper(bin2hex(iconv_substr($str, $i, 1, $this->charset))), 2))
1648
				: '='.strtoupper(bin2hex($str[$i]));
1649
 
1650
			// RFC 2045 sets a limit of 76 characters per line.
1651
			// We'll append ?= to the end of each line though.
1257 lars 1652
			if ($length + ($l = self::strlen($chr)) > 74)
68 lars 1653
			{
1654
				$output .= '?='.$this->crlf // EOL
1655
					.' =?'.$this->charset.'?Q?'.$chr; // New line
1257 lars 1656
				$length = 6 + self::strlen($this->charset) + $l; // Reset the length for the new line
68 lars 1657
			}
1658
			else
1659
			{
1660
				$output .= $chr;
1661
				$length += $l;
1662
			}
1663
		}
1664
 
1665
		// End the header
1666
		return $output.'?=';
1667
	}
1668
 
1669
	// --------------------------------------------------------------------
1670
 
1671
	/**
1672
	 * Send Email
1673
	 *
1674
	 * @param	bool	$auto_clear = TRUE
1675
	 * @return	bool
1676
	 */
1677
	public function send($auto_clear = TRUE)
1678
	{
1679
		if ( ! isset($this->_headers['From']))
1680
		{
1681
			$this->_set_error_message('lang:email_no_from');
1682
			return FALSE;
1683
		}
1684
 
1685
		if ($this->_replyto_flag === FALSE)
1686
		{
1687
			$this->reply_to($this->_headers['From']);
1688
		}
1689
 
1690
		if ( ! isset($this->_recipients) && ! isset($this->_headers['To'])
1691
			&& ! isset($this->_bcc_array) && ! isset($this->_headers['Bcc'])
1692
			&& ! isset($this->_headers['Cc']))
1693
		{
1694
			$this->_set_error_message('lang:email_no_recipients');
1695
			return FALSE;
1696
		}
1697
 
1698
		$this->_build_headers();
1699
 
1700
		if ($this->bcc_batch_mode && count($this->_bcc_array) > $this->bcc_batch_size)
1701
		{
1702
			$result = $this->batch_bcc_send();
1703
 
1704
			if ($result && $auto_clear)
1705
			{
1706
				$this->clear();
1707
			}
1708
 
1709
			return $result;
1710
		}
1711
 
1712
		if ($this->_build_message() === FALSE)
1713
		{
1714
			return FALSE;
1715
		}
1716
 
1717
		$result = $this->_spool_email();
1718
 
1719
		if ($result && $auto_clear)
1720
		{
1721
			$this->clear();
1722
		}
1723
 
1724
		return $result;
1725
	}
1726
 
1727
	// --------------------------------------------------------------------
1728
 
1729
	/**
1730
	 * Batch Bcc Send. Sends groups of BCCs in batches
1731
	 *
1732
	 * @return	void
1733
	 */
1734
	public function batch_bcc_send()
1735
	{
1736
		$float = $this->bcc_batch_size - 1;
1737
		$set = '';
1738
		$chunk = array();
1739
 
1740
		for ($i = 0, $c = count($this->_bcc_array); $i < $c; $i++)
1741
		{
1742
			if (isset($this->_bcc_array[$i]))
1743
			{
1744
				$set .= ', '.$this->_bcc_array[$i];
1745
			}
1746
 
1747
			if ($i === $float)
1748
			{
1257 lars 1749
				$chunk[] = self::substr($set, 1);
68 lars 1750
				$float += $this->bcc_batch_size;
1751
				$set = '';
1752
			}
1753
 
1754
			if ($i === $c-1)
1755
			{
1257 lars 1756
				$chunk[] = self::substr($set, 1);
68 lars 1757
			}
1758
		}
1759
 
1760
		for ($i = 0, $c = count($chunk); $i < $c; $i++)
1761
		{
1762
			unset($this->_headers['Bcc']);
1763
 
1764
			$bcc = $this->clean_email($this->_str_to_array($chunk[$i]));
1765
 
1766
			if ($this->protocol !== 'smtp')
1767
			{
1768
				$this->set_header('Bcc', implode(', ', $bcc));
1769
			}
1770
			else
1771
			{
1772
				$this->_bcc_array = $bcc;
1773
			}
1774
 
1775
			if ($this->_build_message() === FALSE)
1776
			{
1777
				return FALSE;
1778
			}
1779
 
1780
			$this->_spool_email();
1781
		}
1782
	}
1783
 
1784
	// --------------------------------------------------------------------
1785
 
1786
	/**
1787
	 * Unwrap special elements
1788
	 *
1789
	 * @return	void
1790
	 */
1791
	protected function _unwrap_specials()
1792
	{
1793
		$this->_finalbody = preg_replace_callback('/\{unwrap\}(.*?)\{\/unwrap\}/si', array($this, '_remove_nl_callback'), $this->_finalbody);
1794
	}
1795
 
1796
	// --------------------------------------------------------------------
1797
 
1798
	/**
1799
	 * Strip line-breaks via callback
1800
	 *
1801
	 * @param	string	$matches
1802
	 * @return	string
1803
	 */
1804
	protected function _remove_nl_callback($matches)
1805
	{
1806
		if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
1807
		{
1808
			$matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
1809
		}
1810
 
1811
		return $matches[1];
1812
	}
1813
 
1814
	// --------------------------------------------------------------------
1815
 
1816
	/**
1817
	 * Spool mail to the mail server
1818
	 *
1819
	 * @return	bool
1820
	 */
1821
	protected function _spool_email()
1822
	{
1823
		$this->_unwrap_specials();
1824
 
2107 lars 1825
		$protocol = $this->_get_protocol();
1826
		$method   = '_send_with_'.$protocol;
68 lars 1827
		if ( ! $this->$method())
1828
		{
2107 lars 1829
			$this->_set_error_message('lang:email_send_failure_'.($protocol === 'mail' ? 'phpmail' : $protocol));
68 lars 1830
			return FALSE;
1831
		}
1832
 
2107 lars 1833
		$this->_set_error_message('lang:email_sent', $protocol);
68 lars 1834
		return TRUE;
1835
	}
1836
 
1837
	// --------------------------------------------------------------------
1838
 
1839
	/**
2049 lars 1840
	 * Validate email for shell
1841
	 *
1842
	 * Applies stricter, shell-safe validation to email addresses.
1843
	 * Introduced to prevent RCE via sendmail's -f option.
1844
	 *
1845
	 * @see	https://github.com/bcit-ci/CodeIgniter/issues/4963
1846
	 * @see	https://gist.github.com/Zenexer/40d02da5e07f151adeaeeaa11af9ab36
1847
	 * @license	https://creativecommons.org/publicdomain/zero/1.0/	CC0 1.0, Public Domain
1848
	 *
1849
	 * Credits for the base concept go to Paul Buonopane <paul@namepros.com>
1850
	 *
1851
	 * @param	string	$email
1852
	 * @return	bool
1853
	 */
1854
	protected function _validate_email_for_shell(&$email)
1855
	{
2257 lars 1856
		if (function_exists('idn_to_ascii') && strpos($email, '@'))
2049 lars 1857
		{
2257 lars 1858
			list($account, $domain) = explode('@', $email, 2);
1859
			$domain = defined('INTL_IDNA_VARIANT_UTS46')
1860
				? idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46)
1861
				: idn_to_ascii($domain);
1862
			$email = $account.'@'.$domain;
2049 lars 1863
		}
1864
 
1865
		return (filter_var($email, FILTER_VALIDATE_EMAIL) === $email && preg_match('#\A[a-z0-9._+-]+@[a-z0-9.-]{1,253}\z#i', $email));
1866
	}
1867
 
1868
	// --------------------------------------------------------------------
1869
 
1870
	/**
68 lars 1871
	 * Send using mail()
1872
	 *
1873
	 * @return	bool
1874
	 */
1875
	protected function _send_with_mail()
1876
	{
1877
		if (is_array($this->_recipients))
1878
		{
1879
			$this->_recipients = implode(', ', $this->_recipients);
1880
		}
1881
 
2049 lars 1882
		// _validate_email_for_shell() below accepts by reference,
1883
		// so this needs to be assigned to a variable
1884
		$from = $this->clean_email($this->_headers['Return-Path']);
1885
 
1886
		if ($this->_safe_mode === TRUE || ! $this->_validate_email_for_shell($from))
68 lars 1887
		{
1888
			return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str);
1889
		}
1890
		else
1891
		{
1892
			// most documentation of sendmail using the "-f" flag lacks a space after it, however
1893
			// we've encountered servers that seem to require it to be in place.
2049 lars 1894
			return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, '-f '.$from);
68 lars 1895
		}
1896
	}
1897
 
1898
	// --------------------------------------------------------------------
1899
 
1900
	/**
1901
	 * Send using Sendmail
1902
	 *
1903
	 * @return	bool
1904
	 */
1905
	protected function _send_with_sendmail()
1906
	{
2049 lars 1907
		// _validate_email_for_shell() below accepts by reference,
1908
		// so this needs to be assigned to a variable
1909
		$from = $this->clean_email($this->_headers['From']);
1910
		if ($this->_validate_email_for_shell($from))
1911
		{
1912
			$from = '-f '.$from;
1913
		}
1914
		else
1915
		{
1916
			$from = '';
1917
		}
1918
 
68 lars 1919
		// is popen() enabled?
2049 lars 1920
		if ( ! function_usable('popen')	OR FALSE === ($fp = @popen($this->mailpath.' -oi '.$from.' -t', 'w')))
68 lars 1921
		{
2049 lars 1922
			// server probably has popen disabled, so nothing we can do to get a verbose error.
68 lars 1923
			return FALSE;
1924
		}
1925
 
1926
		fputs($fp, $this->_header_str);
1927
		fputs($fp, $this->_finalbody);
1928
 
1929
		$status = pclose($fp);
1930
 
1931
		if ($status !== 0)
1932
		{
1933
			$this->_set_error_message('lang:email_exit_status', $status);
1934
			$this->_set_error_message('lang:email_no_socket');
1935
			return FALSE;
1936
		}
1937
 
1938
		return TRUE;
1939
	}
1940
 
1941
	// --------------------------------------------------------------------
1942
 
1943
	/**
1944
	 * Send using SMTP
1945
	 *
1946
	 * @return	bool
1947
	 */
1948
	protected function _send_with_smtp()
1949
	{
1950
		if ($this->smtp_host === '')
1951
		{
1952
			$this->_set_error_message('lang:email_no_hostname');
1953
			return FALSE;
1954
		}
1955
 
1956
		if ( ! $this->_smtp_connect() OR ! $this->_smtp_authenticate())
1957
		{
1958
			return FALSE;
1959
		}
1960
 
1961
		if ( ! $this->_send_command('from', $this->clean_email($this->_headers['From'])))
1962
		{
1963
			$this->_smtp_end();
1964
			return FALSE;
1965
		}
1966
 
1967
		foreach ($this->_recipients as $val)
1968
		{
1969
			if ( ! $this->_send_command('to', $val))
1970
			{
1971
				$this->_smtp_end();
1972
				return FALSE;
1973
			}
1974
		}
1975
 
1976
		if (count($this->_cc_array) > 0)
1977
		{
1978
			foreach ($this->_cc_array as $val)
1979
			{
1980
				if ($val !== '' && ! $this->_send_command('to', $val))
1981
				{
1982
					$this->_smtp_end();
1983
					return FALSE;
1984
				}
1985
			}
1986
		}
1987
 
1988
		if (count($this->_bcc_array) > 0)
1989
		{
1990
			foreach ($this->_bcc_array as $val)
1991
			{
1992
				if ($val !== '' && ! $this->_send_command('to', $val))
1993
				{
1994
					$this->_smtp_end();
1995
					return FALSE;
1996
				}
1997
			}
1998
		}
1999
 
2000
		if ( ! $this->_send_command('data'))
2001
		{
2002
			$this->_smtp_end();
2003
			return FALSE;
2004
		}
2005
 
2006
		// perform dot transformation on any lines that begin with a dot
2007
		$this->_send_data($this->_header_str.preg_replace('/^\./m', '..$1', $this->_finalbody));
2008
 
2009
		$this->_send_data('.');
2010
 
2011
		$reply = $this->_get_smtp_data();
2012
		$this->_set_error_message($reply);
2013
 
2014
		$this->_smtp_end();
2015
 
2016
		if (strpos($reply, '250') !== 0)
2017
		{
2018
			$this->_set_error_message('lang:email_smtp_error', $reply);
2019
			return FALSE;
2020
		}
2021
 
2022
		return TRUE;
2023
	}
2024
 
2025
	// --------------------------------------------------------------------
2026
 
2027
	/**
2028
	 * SMTP End
2029
	 *
2030
	 * Shortcut to send RSET or QUIT depending on keep-alive
2031
	 *
2032
	 * @return	void
2033
	 */
2034
	protected function _smtp_end()
2035
	{
2036
		($this->smtp_keepalive)
2037
			? $this->_send_command('reset')
2038
			: $this->_send_command('quit');
2039
	}
2040
 
2041
	// --------------------------------------------------------------------
2042
 
2043
	/**
2044
	 * SMTP Connect
2045
	 *
2046
	 * @return	string
2047
	 */
2048
	protected function _smtp_connect()
2049
	{
2050
		if (is_resource($this->_smtp_connect))
2051
		{
2052
			return TRUE;
2053
		}
2054
 
2055
		$ssl = ($this->smtp_crypto === 'ssl') ? 'ssl://' : '';
2056
 
2057
		$this->_smtp_connect = fsockopen($ssl.$this->smtp_host,
2058
							$this->smtp_port,
2059
							$errno,
2060
							$errstr,
2061
							$this->smtp_timeout);
2062
 
2063
		if ( ! is_resource($this->_smtp_connect))
2064
		{
2065
			$this->_set_error_message('lang:email_smtp_error', $errno.' '.$errstr);
2066
			return FALSE;
2067
		}
2068
 
2069
		stream_set_timeout($this->_smtp_connect, $this->smtp_timeout);
2070
		$this->_set_error_message($this->_get_smtp_data());
2071
 
2072
		if ($this->smtp_crypto === 'tls')
2073
		{
2074
			$this->_send_command('hello');
2075
			$this->_send_command('starttls');
2076
 
2257 lars 2077
			/**
2078
			 * STREAM_CRYPTO_METHOD_TLS_CLIENT is quite the mess ...
2079
			 *
2080
			 * - On PHP <5.6 it doesn't even mean TLS, but SSL 2.0, and there's no option to use actual TLS
2081
			 * - On PHP 5.6.0-5.6.6, >=7.2 it means negotiation with any of TLS 1.0, 1.1, 1.2
2082
			 * - On PHP 5.6.7-7.1.* it means only TLS 1.0
2083
			 *
2084
			 * We want the negotiation, so we'll force it below ...
2085
			 */
2086
			$method = is_php('5.6')
2087
				? STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
2088
				: STREAM_CRYPTO_METHOD_TLS_CLIENT;
2089
			$crypto = stream_socket_enable_crypto($this->_smtp_connect, TRUE, $method);
68 lars 2090
 
2091
			if ($crypto !== TRUE)
2092
			{
2093
				$this->_set_error_message('lang:email_smtp_error', $this->_get_smtp_data());
2094
				return FALSE;
2095
			}
2096
		}
2097
 
2098
		return $this->_send_command('hello');
2099
	}
2100
 
2101
	// --------------------------------------------------------------------
2102
 
2103
	/**
2104
	 * Send SMTP command
2105
	 *
2106
	 * @param	string
2107
	 * @param	string
1257 lars 2108
	 * @return	bool
68 lars 2109
	 */
2110
	protected function _send_command($cmd, $data = '')
2111
	{
2112
		switch ($cmd)
2113
		{
2114
			case 'hello' :
2115
 
2116
						if ($this->_smtp_auth OR $this->_get_encoding() === '8bit')
2117
						{
2118
							$this->_send_data('EHLO '.$this->_get_hostname());
2119
						}
2120
						else
2121
						{
2122
							$this->_send_data('HELO '.$this->_get_hostname());
2123
						}
2124
 
2125
						$resp = 250;
2126
			break;
2127
			case 'starttls'	:
2128
 
2129
						$this->_send_data('STARTTLS');
2130
						$resp = 220;
2131
			break;
2132
			case 'from' :
2133
 
2134
						$this->_send_data('MAIL FROM:<'.$data.'>');
2135
						$resp = 250;
2136
			break;
2137
			case 'to' :
2138
 
2139
						if ($this->dsn)
2140
						{
2141
							$this->_send_data('RCPT TO:<'.$data.'> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;'.$data);
2142
						}
2143
						else
2144
						{
2145
							$this->_send_data('RCPT TO:<'.$data.'>');
2146
						}
2147
 
2148
						$resp = 250;
2149
			break;
2150
			case 'data'	:
2151
 
2152
						$this->_send_data('DATA');
2153
						$resp = 354;
2154
			break;
2155
			case 'reset':
2156
 
2157
						$this->_send_data('RSET');
2158
						$resp = 250;
2159
			break;
2160
			case 'quit'	:
2161
 
2162
						$this->_send_data('QUIT');
2163
						$resp = 221;
2164
			break;
2165
		}
2166
 
2167
		$reply = $this->_get_smtp_data();
2168
 
2169
		$this->_debug_msg[] = '<pre>'.$cmd.': '.$reply.'</pre>';
2170
 
1257 lars 2171
		if ((int) self::substr($reply, 0, 3) !== $resp)
68 lars 2172
		{
2173
			$this->_set_error_message('lang:email_smtp_error', $reply);
2174
			return FALSE;
2175
		}
2176
 
2177
		if ($cmd === 'quit')
2178
		{
2179
			fclose($this->_smtp_connect);
2180
		}
2181
 
2182
		return TRUE;
2183
	}
2184
 
2185
	// --------------------------------------------------------------------
2186
 
2187
	/**
2188
	 * SMTP Authenticate
2189
	 *
2190
	 * @return	bool
2191
	 */
2192
	protected function _smtp_authenticate()
2193
	{
2194
		if ( ! $this->_smtp_auth)
2195
		{
2196
			return TRUE;
2197
		}
2198
 
2199
		if ($this->smtp_user === '' && $this->smtp_pass === '')
2200
		{
2201
			$this->_set_error_message('lang:email_no_smtp_unpw');
2202
			return FALSE;
2203
		}
2204
 
2205
		$this->_send_data('AUTH LOGIN');
2206
 
2207
		$reply = $this->_get_smtp_data();
2208
 
2209
		if (strpos($reply, '503') === 0)	// Already authenticated
2210
		{
2211
			return TRUE;
2212
		}
2213
		elseif (strpos($reply, '334') !== 0)
2214
		{
2215
			$this->_set_error_message('lang:email_failed_smtp_login', $reply);
2216
			return FALSE;
2217
		}
2218
 
2219
		$this->_send_data(base64_encode($this->smtp_user));
2220
 
2221
		$reply = $this->_get_smtp_data();
2222
 
2223
		if (strpos($reply, '334') !== 0)
2224
		{
2225
			$this->_set_error_message('lang:email_smtp_auth_un', $reply);
2226
			return FALSE;
2227
		}
2228
 
2229
		$this->_send_data(base64_encode($this->smtp_pass));
2230
 
2231
		$reply = $this->_get_smtp_data();
2232
 
2233
		if (strpos($reply, '235') !== 0)
2234
		{
2235
			$this->_set_error_message('lang:email_smtp_auth_pw', $reply);
2236
			return FALSE;
2237
		}
2238
 
2239
		if ($this->smtp_keepalive)
2240
		{
2241
			$this->_smtp_auth = FALSE;
2242
		}
2243
 
2244
		return TRUE;
2245
	}
2246
 
2247
	// --------------------------------------------------------------------
2248
 
2249
	/**
2250
	 * Send SMTP data
2251
	 *
2252
	 * @param	string	$data
2253
	 * @return	bool
2254
	 */
2255
	protected function _send_data($data)
2256
	{
2257
		$data .= $this->newline;
1257 lars 2258
		for ($written = $timestamp = 0, $length = self::strlen($data); $written < $length; $written += $result)
68 lars 2259
		{
1257 lars 2260
			if (($result = fwrite($this->_smtp_connect, self::substr($data, $written))) === FALSE)
68 lars 2261
			{
2262
				break;
2263
			}
2264
			// See https://bugs.php.net/bug.php?id=39598 and http://php.net/manual/en/function.fwrite.php#96951
2265
			elseif ($result === 0)
2266
			{
2267
				if ($timestamp === 0)
2268
				{
2269
					$timestamp = time();
2270
				}
2271
				elseif ($timestamp < (time() - $this->smtp_timeout))
2272
				{
2273
					$result = FALSE;
2274
					break;
2275
				}
2276
 
2277
				usleep(250000);
2278
				continue;
2279
			}
2257 lars 2280
 
2281
			$timestamp = 0;
68 lars 2282
		}
2283
 
2284
		if ($result === FALSE)
2285
		{
2286
			$this->_set_error_message('lang:email_smtp_data_failure', $data);
2287
			return FALSE;
2288
		}
2289
 
2290
		return TRUE;
2291
	}
2292
 
2293
	// --------------------------------------------------------------------
2294
 
2295
	/**
2296
	 * Get SMTP data
2297
	 *
2298
	 * @return	string
2299
	 */
2300
	protected function _get_smtp_data()
2301
	{
2302
		$data = '';
2303
 
2304
		while ($str = fgets($this->_smtp_connect, 512))
2305
		{
2306
			$data .= $str;
2307
 
2308
			if ($str[3] === ' ')
2309
			{
2310
				break;
2311
			}
2312
		}
2313
 
2314
		return $data;
2315
	}
2316
 
2317
	// --------------------------------------------------------------------
2318
 
2319
	/**
2320
	 * Get Hostname
2321
	 *
2322
	 * There are only two legal types of hostname - either a fully
2323
	 * qualified domain name (eg: "mail.example.com") or an IP literal
2324
	 * (eg: "[1.2.3.4]").
2325
	 *
2326
	 * @link	https://tools.ietf.org/html/rfc5321#section-2.3.5
2327
	 * @link	http://cbl.abuseat.org/namingproblems.html
2328
	 * @return	string
2329
	 */
2330
	protected function _get_hostname()
2331
	{
2332
		if (isset($_SERVER['SERVER_NAME']))
2333
		{
2334
			return $_SERVER['SERVER_NAME'];
2335
		}
2336
 
2337
		return isset($_SERVER['SERVER_ADDR']) ? '['.$_SERVER['SERVER_ADDR'].']' : '[127.0.0.1]';
2338
	}
2339
 
2340
	// --------------------------------------------------------------------
2341
 
2342
	/**
2343
	 * Get Debug Message
2344
	 *
2345
	 * @param	array	$include	List of raw data chunks to include in the output
2346
	 *					Valid options are: 'headers', 'subject', 'body'
2347
	 * @return	string
2348
	 */
2349
	public function print_debugger($include = array('headers', 'subject', 'body'))
2350
	{
2351
		$msg = '';
2352
 
2353
		if (count($this->_debug_msg) > 0)
2354
		{
2355
			foreach ($this->_debug_msg as $val)
2356
			{
2357
				$msg .= $val;
2358
			}
2359
		}
2360
 
2361
		// Determine which parts of our raw data needs to be printed
2362
		$raw_data = '';
2363
		is_array($include) OR $include = array($include);
2364
 
2365
		if (in_array('headers', $include, TRUE))
2366
		{
2367
			$raw_data = htmlspecialchars($this->_header_str)."\n";
2368
		}
2369
 
2370
		if (in_array('subject', $include, TRUE))
2371
		{
2372
			$raw_data .= htmlspecialchars($this->_subject)."\n";
2373
		}
2374
 
2375
		if (in_array('body', $include, TRUE))
2376
		{
2377
			$raw_data .= htmlspecialchars($this->_finalbody);
2378
		}
2379
 
2380
		return $msg.($raw_data === '' ? '' : '<pre>'.$raw_data.'</pre>');
2381
	}
2382
 
2383
	// --------------------------------------------------------------------
2384
 
2385
	/**
2386
	 * Set Message
2387
	 *
2388
	 * @param	string	$msg
2389
	 * @param	string	$val = ''
2390
	 * @return	void
2391
	 */
2392
	protected function _set_error_message($msg, $val = '')
2393
	{
2394
		$CI =& get_instance();
2395
		$CI->lang->load('email');
2396
 
2397
		if (sscanf($msg, 'lang:%s', $line) !== 1 OR FALSE === ($line = $CI->lang->line($line)))
2398
		{
2399
			$this->_debug_msg[] = str_replace('%s', $val, $msg).'<br />';
2400
		}
2401
		else
2402
		{
2403
			$this->_debug_msg[] = str_replace('%s', $val, $line).'<br />';
2404
		}
2405
	}
2406
 
2407
	// --------------------------------------------------------------------
2408
 
2409
	/**
2410
	 * Mime Types
2411
	 *
2412
	 * @param	string
2413
	 * @return	string
2414
	 */
2415
	protected function _mime_types($ext = '')
2416
	{
2417
		$ext = strtolower($ext);
2418
 
2419
		$mimes =& get_mimes();
2420
 
2421
		if (isset($mimes[$ext]))
2422
		{
2423
			return is_array($mimes[$ext])
2424
				? current($mimes[$ext])
2425
				: $mimes[$ext];
2426
		}
2427
 
2428
		return 'application/x-unknown-content-type';
2429
	}
2430
 
2431
	// --------------------------------------------------------------------
2432
 
2433
	/**
2434
	 * Destructor
2435
	 *
2436
	 * @return	void
2437
	 */
2438
	public function __destruct()
2439
	{
2440
		is_resource($this->_smtp_connect) && $this->_send_command('quit');
2441
	}
1257 lars 2442
 
2443
	// --------------------------------------------------------------------
2444
 
2445
	/**
2446
	 * Byte-safe strlen()
2447
	 *
2448
	 * @param	string	$str
2449
	 * @return	int
2450
	 */
2451
	protected static function strlen($str)
2452
	{
2107 lars 2453
		return (self::$func_overload)
1257 lars 2454
			? mb_strlen($str, '8bit')
2455
			: strlen($str);
2456
	}
2457
 
2458
	// --------------------------------------------------------------------
2459
 
2460
	/**
2461
	 * Byte-safe substr()
2462
	 *
2463
	 * @param	string	$str
2464
	 * @param	int	$start
2465
	 * @param	int	$length
2466
	 * @return	string
2467
	 */
2468
	protected static function substr($str, $start, $length = NULL)
2469
	{
2107 lars 2470
		if (self::$func_overload)
1257 lars 2471
		{
2472
			// mb_substr($str, $start, null, '8bit') returns an empty
2473
			// string on PHP 5.3
2474
			isset($length) OR $length = ($start >= 0 ? self::strlen($str) - $start : -$start);
2475
			return mb_substr($str, $start, $length, '8bit');
2476
		}
2477
 
2478
		return isset($length)
2479
			? substr($str, $start, $length)
2480
			: substr($str, $start);
2481
	}
68 lars 2482
}