Project

General

Profile

1
<?php
2
/*~ class.phpmailer.php
3
.---------------------------------------------------------------------------.
4
|  Software: PHPMailer - PHP email class                                    |
5
|   Version: 5.2                                                            |
6
|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
7
| ------------------------------------------------------------------------- |
8
|     Admin: Jim Jagielski (project admininistrator)                        |
9
|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
10
|          : Marcus Bointon (coolbru) coolbru@users.sourceforge.net         |
11
|          : Jim Jagielski (jimjag) jimjag@gmail.com                        |
12
|   Founder: Brent R. Matzelle (original founder)                           |
13
| Copyright (c) 2010-2011, Jim Jagielski. All Rights Reserved.               |
14
| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved.               |
15
| Copyright (c) 2001-2003, Brent R. Matzelle                                |
16
| ------------------------------------------------------------------------- |
17
|   License: Distributed under the Lesser General Public License (LGPL)     |
18
|            http://www.gnu.org/copyleft/lesser.html                        |
19
| This program is distributed in the hope that it will be useful - WITHOUT  |
20
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
21
| FITNESS FOR A PARTICULAR PURPOSE.                                         |
22
'---------------------------------------------------------------------------'
23
*/
24

    
25
/**
26
 * PHPMailer - PHP email transport class
27
 * NOTE: Requires PHP version 5 or later
28
 * @package PHPMailer
29
 * @author Andy Prevost
30
 * @author Marcus Bointon
31
 * @author Jim Jagielski
32
 * @copyright 2010 - 2011 Jim Jagielski
33
 * @copyright 2004 - 2009 Andy Prevost
34
 * @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $
35
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
36
 */
37

    
38
if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
39

    
40
class PHPMailer {
41

    
42
  /////////////////////////////////////////////////
43
  // PROPERTIES, PUBLIC
44
  /////////////////////////////////////////////////
45

    
46
  /**
47
   * Email priority (1 = High, 3 = Normal, 5 = low).
48
   * @var int
49
   */
50
  public $Priority          = 3;
51

    
52
  /**
53
   * Sets the CharSet of the message.
54
   * @var string
55
   */
56
  public $CharSet           = 'iso-8859-1';
57

    
58
  /**
59
   * Sets the Content-type of the message.
60
   * @var string
61
   */
62
  public $ContentType       = 'text/plain';
63

    
64
  /**
65
   * Sets the Encoding of the message. Options for this are
66
   *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
67
   * @var string
68
   */
69
  public $Encoding          = '8bit';
70

    
71
  /**
72
   * Holds the most recent mailer error message.
73
   * @var string
74
   */
75
  public $ErrorInfo         = '';
76

    
77
  /**
78
   * Sets the From email address for the message.
79
   * @var string
80
   */
81
  public $From              = 'root@localhost';
82

    
83
  /**
84
   * Sets the From name of the message.
85
   * @var string
86
   */
87
  public $FromName          = 'Root User';
88

    
89
  /**
90
   * Sets the Sender email (Return-Path) of the message.  If not empty,
91
   * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
92
   * @var string
93
   */
94
  public $Sender            = '';
95

    
96
  /**
97
   * Sets the Subject of the message.
98
   * @var string
99
   */
100
  public $Subject           = '';
101

    
102
  /**
103
   * Sets the Body of the message.  This can be either an HTML or text body.
104
   * If HTML then run IsHTML(true).
105
   * @var string
106
   */
107
  public $Body              = '';
108

    
109
  /**
110
   * Sets the text-only body of the message.  This automatically sets the
111
   * email to multipart/alternative.  This body can be read by mail
112
   * clients that do not have HTML email capability such as mutt. Clients
113
   * that can read HTML will view the normal Body.
114
   * @var string
115
   */
116
  public $AltBody           = '';
117

    
118
  /**
119
   * Stores the complete compiled MIME message body.
120
   * @var string
121
   * @access protected
122
   */
123
  protected $MIMEBody       = '';
124

    
125
  /**
126
   * Stores the complete compiled MIME message headers.
127
   * @var string
128
   * @access protected
129
   */
130
  protected $MIMEHeader     = '';
131

    
132
  /**
133
   * Sets word wrapping on the body of the message to a given number of
134
   * characters.
135
   * @var int
136
   */
137
  public $WordWrap          = 0;
138

    
139
  /**
140
   * Method to send mail: ("mail", "sendmail", or "smtp").
141
   * @var string
142
   */
143
  public $Mailer            = 'mail';
144

    
145
  /**
146
   * Sets the path of the sendmail program.
147
   * @var string
148
   */
149
  public $Sendmail          = '/usr/sbin/sendmail';
150

    
151
  /**
152
   * Path to PHPMailer plugins.  Useful if the SMTP class
153
   * is in a different directory than the PHP include path.
154
   * @var string
155
   */
156
  public $PluginDir         = '';
157

    
158
  /**
159
   * Sets the email address that a reading confirmation will be sent.
160
   * @var string
161
   */
162
  public $ConfirmReadingTo  = '';
163

    
164
  /**
165
   * Sets the hostname to use in Message-Id and Received headers
166
   * and as default HELO string. If empty, the value returned
167
   * by SERVER_NAME is used or 'localhost.localdomain'.
168
   * @var string
169
   */
170
  public $Hostname          = '';
171

    
172
  /**
173
   * Sets the message ID to be used in the Message-Id header.
174
   * If empty, a unique id will be generated.
175
   * @var string
176
   */
177
  public $MessageID         = '';
178

    
179
  /////////////////////////////////////////////////
180
  // PROPERTIES FOR SMTP
181
  /////////////////////////////////////////////////
182

    
183
  /**
184
   * Sets the SMTP hosts.  All hosts must be separated by a
185
   * semicolon.  You can also specify a different port
186
   * for each host by using this format: [hostname:port]
187
   * (e.g. "smtp1.example.com:25;smtp2.example.com").
188
   * Hosts will be tried in order.
189
   * @var string
190
   */
191
  public $Host          = 'localhost';
192

    
193
  /**
194
   * Sets the default SMTP server port.
195
   * @var int
196
   */
197
  public $Port          = 25;
198

    
199
  /**
200
   * Sets the SMTP HELO of the message (Default is $Hostname).
201
   * @var string
202
   */
203
  public $Helo          = '';
204

    
205
  /**
206
   * Sets connection prefix.
207
   * Options are "", "ssl" or "tls"
208
   * @var string
209
   */
210
  public $SMTPSecure    = '';
211

    
212
  /**
213
   * Sets SMTP authentication. Utilizes the Username and Password variables.
214
   * @var bool
215
   */
216
  public $SMTPAuth      = false;
217

    
218
  /**
219
   * Sets SMTP username.
220
   * @var string
221
   */
222
  public $Username      = '';
223

    
224
  /**
225
   * Sets SMTP password.
226
   * @var string
227
   */
228
  public $Password      = '';
229

    
230
  /**
231
   * Sets the SMTP server timeout in seconds.
232
   * This function will not work with the win32 version.
233
   * @var int
234
   */
235
  public $Timeout       = 10;
236

    
237
  /**
238
   * Sets SMTP class debugging on or off.
239
   * @var bool
240
   */
241
  public $SMTPDebug     = false;
242

    
243
  /**
244
   * Prevents the SMTP connection from being closed after each mail
245
   * sending.  If this is set to true then to close the connection
246
   * requires an explicit call to SmtpClose().
247
   * @var bool
248
   */
249
  public $SMTPKeepAlive = false;
250

    
251
  /**
252
   * Provides the ability to have the TO field process individual
253
   * emails, instead of sending to entire TO addresses
254
   * @var bool
255
   */
256
  public $SingleTo      = false;
257

    
258
   /**
259
   * If SingleTo is true, this provides the array to hold the email addresses
260
   * @var bool
261
   */
262
  public $SingleToArray = array();
263

    
264
 /**
265
   * Provides the ability to change the line ending
266
   * @var string
267
   */
268
  public $LE              = "\n";
269

    
270
  /**
271
   * Used with DKIM DNS Resource Record
272
   * @var string
273
   */
274
  public $DKIM_selector   = 'phpmailer';
275

    
276
  /**
277
   * Used with DKIM DNS Resource Record
278
   * optional, in format of email address 'you@yourdomain.com'
279
   * @var string
280
   */
281
  public $DKIM_identity   = '';
282

    
283
  /**
284
   * Used with DKIM DNS Resource Record
285
   * @var string
286
   */
287
  public $DKIM_passphrase   = '';
288

    
289
  /**
290
   * Used with DKIM DNS Resource Record
291
   * optional, in format of email address 'you@yourdomain.com'
292
   * @var string
293
   */
294
  public $DKIM_domain     = '';
295

    
296
  /**
297
   * Used with DKIM DNS Resource Record
298
   * optional, in format of email address 'you@yourdomain.com'
299
   * @var string
300
   */
301
  public $DKIM_private    = '';
302

    
303
  /**
304
   * Callback Action function name
305
   * the function that handles the result of the send email action. Parameters:
306
   *   bool    $result        result of the send action
307
   *   string  $to            email address of the recipient
308
   *   string  $cc            cc email addresses
309
   *   string  $bcc           bcc email addresses
310
   *   string  $subject       the subject
311
   *   string  $body          the email body
312
   * @var string
313
   */
314
  public $action_function = ''; //'callbackAction';
315

    
316
  /**
317
   * Sets the PHPMailer Version number
318
   * @var string
319
   */
320
  public $Version         = '5.2';
321

    
322
  /**
323
   * What to use in the X-Mailer header
324
   * @var string
325
   */
326
  public $XMailer         = '';
327

    
328
  /////////////////////////////////////////////////
329
  // PROPERTIES, PRIVATE AND PROTECTED
330
  /////////////////////////////////////////////////
331

    
332
  protected   $smtp           = NULL;
333
  protected   $to             = array();
334
  protected   $cc             = array();
335
  protected   $bcc            = array();
336
  protected   $ReplyTo        = array();
337
  protected   $all_recipients = array();
338
  protected   $attachment     = array();
339
  protected   $CustomHeader   = array();
340
  protected   $message_type   = '';
341
  protected   $boundary       = array();
342
  protected   $language       = array();
343
  protected   $error_count    = 0;
344
  protected   $sign_cert_file = '';
345
  protected   $sign_key_file  = '';
346
  protected   $sign_key_pass  = '';
347
  protected   $exceptions     = false;
348

    
349
  /////////////////////////////////////////////////
350
  // CONSTANTS
351
  /////////////////////////////////////////////////
352

    
353
  const STOP_MESSAGE  = 0; // message only, continue processing
354
  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
355
  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
356

    
357
  /////////////////////////////////////////////////
358
  // METHODS, VARIABLES
359
  /////////////////////////////////////////////////
360

    
361
  /**
362
   * Constructor
363
   * @param boolean $exceptions Should we throw external exceptions?
364
   */
365
  public function __construct($exceptions = false) {
366
    $this->exceptions = ($exceptions == true);
367
  }
368

    
369
  /**
370
   * Sets message type to HTML.
371
   * @param bool $ishtml
372
   * @return void
373
   */
374
  public function IsHTML($ishtml = true) {
375
    if ($ishtml) {
376
      $this->ContentType = 'text/html';
377
    } else {
378
      $this->ContentType = 'text/plain';
379
    }
380
  }
381

    
382
  /**
383
   * Sets Mailer to send message using SMTP.
384
   * @return void
385
   */
386
  public function IsSMTP() {
387
    $this->Mailer = 'smtp';
388
  }
389

    
390
  /**
391
   * Sets Mailer to send message using PHP mail() function.
392
   * @return void
393
   */
394
  public function IsMail() {
395
    $this->Mailer = 'mail';
396
  }
397

    
398
  /**
399
   * Sets Mailer to send message using the $Sendmail program.
400
   * @return void
401
   */
402
  public function IsSendmail() {
403
    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
404
      $this->Sendmail = '/var/qmail/bin/sendmail';
405
    }
406
    $this->Mailer = 'sendmail';
407
  }
408

    
409
  /**
410
   * Sets Mailer to send message using the qmail MTA.
411
   * @return void
412
   */
413
  public function IsQmail() {
414
    if (stristr(ini_get('sendmail_path'), 'qmail')) {
415
      $this->Sendmail = '/var/qmail/bin/sendmail';
416
    }
417
    $this->Mailer = 'sendmail';
418
  }
419

    
420
  /////////////////////////////////////////////////
421
  // METHODS, RECIPIENTS
422
  /////////////////////////////////////////////////
423

    
424
  /**
425
   * Adds a "To" address.
426
   * @param string $address
427
   * @param string $name
428
   * @return boolean true on success, false if address already used
429
   */
430
  public function AddAddress($address, $name = '') {
431
    return $this->AddAnAddress('to', $address, $name);
432
  }
433

    
434
  /**
435
   * Adds a "Cc" address.
436
   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
437
   * @param string $address
438
   * @param string $name
439
   * @return boolean true on success, false if address already used
440
   */
441
  public function AddCC($address, $name = '') {
442
    return $this->AddAnAddress('cc', $address, $name);
443
  }
444

    
445
  /**
446
   * Adds a "Bcc" address.
447
   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
448
   * @param string $address
449
   * @param string $name
450
   * @return boolean true on success, false if address already used
451
   */
452
  public function AddBCC($address, $name = '') {
453
    return $this->AddAnAddress('bcc', $address, $name);
454
  }
455

    
456
  /**
457
   * Adds a "Reply-to" address.
458
   * @param string $address
459
   * @param string $name
460
   * @return boolean
461
   */
462
  public function AddReplyTo($address, $name = '') {
463
    return $this->AddAnAddress('ReplyTo', $address, $name);
464
  }
465

    
466
  /**
467
   * Adds an address to one of the recipient arrays
468
   * Addresses that have been added already return false, but do not throw exceptions
469
   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
470
   * @param string $address The email address to send to
471
   * @param string $name
472
   * @return boolean true on success, false if address already used or invalid in some way
473
   * @access protected
474
   */
475
  protected function AddAnAddress($kind, $address, $name = '') {
476
    if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
477
      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
478
      if ($this->exceptions) {
479
        throw new phpmailerException('Invalid recipient array: ' . $kind);
480
      }
481
      echo $this->Lang('Invalid recipient array').': '.$kind;
482
      return false;
483
    }
484
    $address = trim($address);
485
    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
486
    if (!self::ValidateAddress($address)) {
487
      $this->SetError($this->Lang('invalid_address').': '. $address);
488
      if ($this->exceptions) {
489
        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
490
      }
491
      echo $this->Lang('invalid_address').': '.$address;
492
      return false;
493
    }
494
    if ($kind != 'ReplyTo') {
495
      if (!isset($this->all_recipients[strtolower($address)])) {
496
        array_push($this->$kind, array($address, $name));
497
        $this->all_recipients[strtolower($address)] = true;
498
        return true;
499
      }
500
    } else {
501
      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
502
        $this->ReplyTo[strtolower($address)] = array($address, $name);
503
      return true;
504
    }
505
  }
506
  return false;
507
}
508

    
509
/**
510
 * Set the From and FromName properties
511
 * @param string $address
512
 * @param string $name
513
 * @return boolean
514
 */
515
  public function SetFrom($address, $name = '', $auto = 1) {
516
    $address = trim($address);
517
    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
518
    if (!self::ValidateAddress($address)) {
519
      $this->SetError($this->Lang('invalid_address').': '. $address);
520
      if ($this->exceptions) {
521
        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
522
      }
523
      echo $this->Lang('invalid_address').': '.$address;
524
      return false;
525
    }
526
    $this->From = $address;
527
    $this->FromName = $name;
528
    if ($auto) {
529
      if (empty($this->ReplyTo)) {
530
        $this->AddAnAddress('ReplyTo', $address, $name);
531
      }
532
      if (empty($this->Sender)) {
533
        $this->Sender = $address;
534
      }
535
    }
536
    return true;
537
  }
538

    
539
  /**
540
   * Check that a string looks roughly like an email address should
541
   * Static so it can be used without instantiation
542
   * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
543
   * Conforms approximately to RFC2822
544
   * @link http://www.hexillion.com/samples/#Regex Original pattern found here
545
   * @param string $address The email address to check
546
   * @return boolean
547
   * @static
548
   * @access public
549
   */
550
  public static function ValidateAddress($address) {
551
    if (function_exists('filter_var')) { //Introduced in PHP 5.2
552
      if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
553
        return false;
554
      } else {
555
        return true;
556
      }
557
    } else {
558
      return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
559
    }
560
  }
561

    
562
  /////////////////////////////////////////////////
563
  // METHODS, MAIL SENDING
564
  /////////////////////////////////////////////////
565

    
566
  /**
567
   * Creates message and assigns Mailer. If the message is
568
   * not sent successfully then it returns false.  Use the ErrorInfo
569
   * variable to view description of the error.
570
   * @return bool
571
   */
572
  public function Send() {
573
    try {
574
      if(!$this->PreSend()) return false;
575
      return $this->PostSend();
576
    } catch (phpmailerException $e) {
577
      $this->SetError($e->getMessage());
578
      if ($this->exceptions) {
579
        throw $e;
580
      }
581
      return false;
582
    }
583
  }
584

    
585
  protected function PreSend() {
586
    try {
587
      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
588
        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
589
      }
590

    
591
      // Set whether the message is multipart/alternative
592
      if(!empty($this->AltBody)) {
593
        $this->ContentType = 'multipart/alternative';
594
      }
595

    
596
      $this->error_count = 0; // reset errors
597
      $this->SetMessageType();
598
      //Refuse to send an empty message
599
      if (empty($this->Body)) {
600
        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
601
      }
602

    
603
      $this->MIMEHeader = $this->CreateHeader();
604
      $this->MIMEBody = $this->CreateBody();
605

    
606

    
607
      // digitally sign with DKIM if enabled
608
      if ($this->DKIM_domain && $this->DKIM_private) {
609
        $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
610
        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
611
      }
612

    
613
      return true;
614
    } catch (phpmailerException $e) {
615
      $this->SetError($e->getMessage());
616
      if ($this->exceptions) {
617
        throw $e;
618
      }
619
      return false;
620
    }
621
  }
622

    
623
  protected function PostSend() {
624
    try {
625
      // Choose the mailer and send through it
626
      switch($this->Mailer) {
627
        case 'sendmail':
628
          return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
629
        case 'smtp':
630
          return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
631
        default:
632
          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
633
      }
634

    
635
    } catch (phpmailerException $e) {
636
      $this->SetError($e->getMessage());
637
      if ($this->exceptions) {
638
        throw $e;
639
      }
640
      echo $e->getMessage()."\n";
641
      return false;
642
    }
643
  }
644

    
645
  /**
646
   * Sends mail using the $Sendmail program.
647
   * @param string $header The message headers
648
   * @param string $body The message body
649
   * @access protected
650
   * @return bool
651
   */
652
  protected function SendmailSend($header, $body) {
653
    if ($this->Sender != '') {
654
      $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
655
    } else {
656
      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
657
    }
658
    if ($this->SingleTo === true) {
659
      foreach ($this->SingleToArray as $key => $val) {
660
        if(!@$mail = popen($sendmail, 'w')) {
661
          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
662
        }
663
        fputs($mail, "To: " . $val . "\n");
664
        fputs($mail, $header);
665
        fputs($mail, $body);
666
        $result = pclose($mail);
667
        // implement call back function if it exists
668
        $isSent = ($result == 0) ? 1 : 0;
669
        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
670
        if($result != 0) {
671
          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
672
        }
673
      }
674
    } else {
675
      if(!@$mail = popen($sendmail, 'w')) {
676
        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
677
      }
678
      fputs($mail, $header);
679
      fputs($mail, $body);
680
      $result = pclose($mail);
681
      // implement call back function if it exists
682
      $isSent = ($result == 0) ? 1 : 0;
683
      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
684
      if($result != 0) {
685
        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
686
      }
687
    }
688
    return true;
689
  }
690

    
691
  /**
692
   * Sends mail using the PHP mail() function.
693
   * @param string $header The message headers
694
   * @param string $body The message body
695
   * @access protected
696
   * @return bool
697
   */
698
  protected function MailSend($header, $body) {
699
    $toArr = array();
700
    foreach($this->to as $t) {
701
      $toArr[] = $this->AddrFormat($t);
702
    }
703
    $to = implode(', ', $toArr);
704

    
705
    if (empty($this->Sender)) {
706
      $params = "-oi -f %s";
707
    } else {
708
      $params = sprintf("-oi -f %s", $this->Sender);
709
    }
710
    if ($this->Sender != '' and !ini_get('safe_mode')) {
711
      $old_from = ini_get('sendmail_from');
712
      ini_set('sendmail_from', $this->Sender);
713
      if ($this->SingleTo === true && count($toArr) > 1) {
714
        foreach ($toArr as $key => $val) {
715
          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
716
          // implement call back function if it exists
717
          $isSent = ($rt == 1) ? 1 : 0;
718
          $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
719
        }
720
      } else {
721
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
722
        // implement call back function if it exists
723
        $isSent = ($rt == 1) ? 1 : 0;
724
        $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
725
      }
726
    } else {
727
      if ($this->SingleTo === true && count($toArr) > 1) {
728
        foreach ($toArr as $key => $val) {
729
          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
730
          // implement call back function if it exists
731
          $isSent = ($rt == 1) ? 1 : 0;
732
          $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
733
        }
734
      } else {
735
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
736
        // implement call back function if it exists
737
        $isSent = ($rt == 1) ? 1 : 0;
738
        $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
739
      }
740
    }
741
    if (isset($old_from)) {
742
      ini_set('sendmail_from', $old_from);
743
    }
744
    if(!$rt) {
745
      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
746
    }
747
    return true;
748
  }
749

    
750
  /**
751
   * Sends mail via SMTP using PhpSMTP
752
   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
753
   * @param string $header The message headers
754
   * @param string $body The message body
755
   * @uses SMTP
756
   * @access protected
757
   * @return bool
758
   */
759
  protected function SmtpSend($header, $body) {
760
    require_once $this->PluginDir . 'class.smtp.php';
761
    $bad_rcpt = array();
762

    
763
    if(!$this->SmtpConnect()) {
764
      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
765
    }
766
    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
767
    if(!$this->smtp->Mail($smtp_from)) {
768
      throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
769
    }
770

    
771
    // Attempt to send attach all recipients
772
    foreach($this->to as $to) {
773
      if (!$this->smtp->Recipient($to[0])) {
774
        $bad_rcpt[] = $to[0];
775
        // implement call back function if it exists
776
        $isSent = 0;
777
        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
778
      } else {
779
        // implement call back function if it exists
780
        $isSent = 1;
781
        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
782
      }
783
    }
784
    foreach($this->cc as $cc) {
785
      if (!$this->smtp->Recipient($cc[0])) {
786
        $bad_rcpt[] = $cc[0];
787
        // implement call back function if it exists
788
        $isSent = 0;
789
        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
790
      } else {
791
        // implement call back function if it exists
792
        $isSent = 1;
793
        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
794
      }
795
    }
796
    foreach($this->bcc as $bcc) {
797
      if (!$this->smtp->Recipient($bcc[0])) {
798
        $bad_rcpt[] = $bcc[0];
799
        // implement call back function if it exists
800
        $isSent = 0;
801
        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
802
      } else {
803
        // implement call back function if it exists
804
        $isSent = 1;
805
        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
806
      }
807
    }
808

    
809

    
810
    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
811
      $badaddresses = implode(', ', $bad_rcpt);
812
      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
813
    }
814
    if(!$this->smtp->Data($header . $body)) {
815
      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
816
    }
817
    if($this->SMTPKeepAlive == true) {
818
      $this->smtp->Reset();
819
    }
820
    return true;
821
  }
822

    
823
  /**
824
   * Initiates a connection to an SMTP server.
825
   * Returns false if the operation failed.
826
   * @uses SMTP
827
   * @access public
828
   * @return bool
829
   */
830
  public function SmtpConnect() {
831
    if(is_null($this->smtp)) {
832
      $this->smtp = new SMTP();
833
    }
834

    
835
    $this->smtp->do_debug = $this->SMTPDebug;
836
    $hosts = explode(';', $this->Host);
837
    $index = 0;
838
    $connection = $this->smtp->Connected();
839

    
840
    // Retry while there is no connection
841
    try {
842
      while($index < count($hosts) && !$connection) {
843
        $hostinfo = array();
844
        if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
845
          $host = $hostinfo[1];
846
          $port = $hostinfo[2];
847
        } else {
848
          $host = $hosts[$index];
849
          $port = $this->Port;
850
        }
851

    
852
        $tls = ($this->SMTPSecure == 'tls');
853
        $ssl = ($this->SMTPSecure == 'ssl');
854

    
855
        if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
856

    
857
          $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
858
          $this->smtp->Hello($hello);
859

    
860
          if ($tls) {
861
            if (!$this->smtp->StartTLS()) {
862
              throw new phpmailerException($this->Lang('tls'));
863
            }
864

    
865
            //We must resend HELO after tls negotiation
866
            $this->smtp->Hello($hello);
867
          }
868

    
869
          $connection = true;
870
          if ($this->SMTPAuth) {
871
            if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
872
              throw new phpmailerException($this->Lang('authenticate'));
873
            }
874
          }
875
        }
876
        $index++;
877
        if (!$connection) {
878
          throw new phpmailerException($this->Lang('connect_host'));
879
        }
880
      }
881
    } catch (phpmailerException $e) {
882
      $this->smtp->Reset();
883
      throw $e;
884
    }
885
    return true;
886
  }
887

    
888
  /**
889
   * Closes the active SMTP session if one exists.
890
   * @return void
891
   */
892
  public function SmtpClose() {
893
    if(!is_null($this->smtp)) {
894
      if($this->smtp->Connected()) {
895
        $this->smtp->Quit();
896
        $this->smtp->Close();
897
      }
898
    }
899
  }
900

    
901
  /**
902
  * Sets the language for all class error messages.
903
  * Returns false if it cannot load the language file.  The default language is English.
904
  * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
905
  * @param string $lang_path Path to the language file directory
906
  * @access public
907
  */
908
  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
909
    //Define full set of translatable strings
910
    $PHPMAILER_LANG = array(
911
      'provide_address' => 'You must provide at least one recipient email address.',
912
      'mailer_not_supported' => ' mailer is not supported.',
913
      'execute' => 'Could not execute: ',
914
      'instantiate' => 'Could not instantiate mail function.',
915
      'authenticate' => 'SMTP Error: Could not authenticate.',
916
      'from_failed' => 'The following From address failed: ',
917
      'recipients_failed' => 'SMTP Error: The following recipients failed: ',
918
      'data_not_accepted' => 'SMTP Error: Data not accepted.',
919
      'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
920
      'file_access' => 'Could not access file: ',
921
      'file_open' => 'File Error: Could not open file: ',
922
      'encoding' => 'Unknown encoding: ',
923
      'signing' => 'Signing Error: ',
924
      'smtp_error' => 'SMTP server error: ',
925
      'empty_message' => 'Message body empty',
926
      'invalid_address' => 'Invalid address',
927
      'variable_set' => 'Cannot set or reset variable: '
928
    );
929
    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
930
    $l = true;
931
    if ($langcode != 'en') { //There is no English translation file
932
      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
933
    }
934
    $this->language = $PHPMAILER_LANG;
935
    return ($l == true); //Returns false if language not found
936
  }
937

    
938
  /**
939
  * Return the current array of language strings
940
  * @return array
941
  */
942
  public function GetTranslations() {
943
    return $this->language;
944
  }
945

    
946
  /////////////////////////////////////////////////
947
  // METHODS, MESSAGE CREATION
948
  /////////////////////////////////////////////////
949

    
950
  /**
951
   * Creates recipient headers.
952
   * @access public
953
   * @return string
954
   */
955
  public function AddrAppend($type, $addr) {
956
    $addr_str = $type . ': ';
957
    $addresses = array();
958
    foreach ($addr as $a) {
959
      $addresses[] = $this->AddrFormat($a);
960
    }
961
    $addr_str .= implode(', ', $addresses);
962
    $addr_str .= $this->LE;
963

    
964
    return $addr_str;
965
  }
966

    
967
  /**
968
   * Formats an address correctly.
969
   * @access public
970
   * @return string
971
   */
972
  public function AddrFormat($addr) {
973
    if (empty($addr[1])) {
974
      return $this->SecureHeader($addr[0]);
975
    } else {
976
      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
977
    }
978
  }
979

    
980
  /**
981
   * Wraps message for use with mailers that do not
982
   * automatically perform wrapping and for quoted-printable.
983
   * Original written by philippe.
984
   * @param string $message The message to wrap
985
   * @param integer $length The line length to wrap to
986
   * @param boolean $qp_mode Whether to run in Quoted-Printable mode
987
   * @access public
988
   * @return string
989
   */
990
  public function WrapText($message, $length, $qp_mode = false) {
991
    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
992
    // If utf-8 encoding is used, we will need to make sure we don't
993
    // split multibyte characters when we wrap
994
    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
995

    
996
    $message = $this->FixEOL($message);
997
    if (substr($message, -1) == $this->LE) {
998
      $message = substr($message, 0, -1);
999
    }
1000

    
1001
    $line = explode($this->LE, $message);
1002
    $message = '';
1003
    for ($i = 0 ;$i < count($line); $i++) {
1004
      $line_part = explode(' ', $line[$i]);
1005
      $buf = '';
1006
      for ($e = 0; $e<count($line_part); $e++) {
1007
        $word = $line_part[$e];
1008
        if ($qp_mode and (strlen($word) > $length)) {
1009
          $space_left = $length - strlen($buf) - 1;
1010
          if ($e != 0) {
1011
            if ($space_left > 20) {
1012
              $len = $space_left;
1013
              if ($is_utf8) {
1014
                $len = $this->UTF8CharBoundary($word, $len);
1015
              } elseif (substr($word, $len - 1, 1) == "=") {
1016
                $len--;
1017
              } elseif (substr($word, $len - 2, 1) == "=") {
1018
                $len -= 2;
1019
              }
1020
              $part = substr($word, 0, $len);
1021
              $word = substr($word, $len);
1022
              $buf .= ' ' . $part;
1023
              $message .= $buf . sprintf("=%s", $this->LE);
1024
            } else {
1025
              $message .= $buf . $soft_break;
1026
            }
1027
            $buf = '';
1028
          }
1029
          while (strlen($word) > 0) {
1030
            $len = $length;
1031
            if ($is_utf8) {
1032
              $len = $this->UTF8CharBoundary($word, $len);
1033
            } elseif (substr($word, $len - 1, 1) == "=") {
1034
              $len--;
1035
            } elseif (substr($word, $len - 2, 1) == "=") {
1036
              $len -= 2;
1037
            }
1038
            $part = substr($word, 0, $len);
1039
            $word = substr($word, $len);
1040

    
1041
            if (strlen($word) > 0) {
1042
              $message .= $part . sprintf("=%s", $this->LE);
1043
            } else {
1044
              $buf = $part;
1045
            }
1046
          }
1047
        } else {
1048
          $buf_o = $buf;
1049
          $buf .= ($e == 0) ? $word : (' ' . $word);
1050

    
1051
          if (strlen($buf) > $length and $buf_o != '') {
1052
            $message .= $buf_o . $soft_break;
1053
            $buf = $word;
1054
          }
1055
        }
1056
      }
1057
      $message .= $buf . $this->LE;
1058
    }
1059

    
1060
    return $message;
1061
  }
1062

    
1063
  /**
1064
   * Finds last character boundary prior to maxLength in a utf-8
1065
   * quoted (printable) encoded string.
1066
   * Original written by Colin Brown.
1067
   * @access public
1068
   * @param string $encodedText utf-8 QP text
1069
   * @param int    $maxLength   find last character boundary prior to this length
1070
   * @return int
1071
   */
1072
  public function UTF8CharBoundary($encodedText, $maxLength) {
1073
    $foundSplitPos = false;
1074
    $lookBack = 3;
1075
    while (!$foundSplitPos) {
1076
      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1077
      $encodedCharPos = strpos($lastChunk, "=");
1078
      if ($encodedCharPos !== false) {
1079
        // Found start of encoded character byte within $lookBack block.
1080
        // Check the encoded byte value (the 2 chars after the '=')
1081
        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1082
        $dec = hexdec($hex);
1083
        if ($dec < 128) { // Single byte character.
1084
          // If the encoded char was found at pos 0, it will fit
1085
          // otherwise reduce maxLength to start of the encoded char
1086
          $maxLength = ($encodedCharPos == 0) ? $maxLength :
1087
          $maxLength - ($lookBack - $encodedCharPos);
1088
          $foundSplitPos = true;
1089
        } elseif ($dec >= 192) { // First byte of a multi byte character
1090
          // Reduce maxLength to split at start of character
1091
          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1092
          $foundSplitPos = true;
1093
        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
1094
          $lookBack += 3;
1095
        }
1096
      } else {
1097
        // No encoded character found
1098
        $foundSplitPos = true;
1099
      }
1100
    }
1101
    return $maxLength;
1102
  }
1103

    
1104

    
1105
  /**
1106
   * Set the body wrapping.
1107
   * @access public
1108
   * @return void
1109
   */
1110
  public function SetWordWrap() {
1111
    if($this->WordWrap < 1) {
1112
      return;
1113
    }
1114

    
1115
    switch($this->message_type) {
1116
      case 'alt':
1117
      case 'alt_inline':
1118
      case 'alt_attach':
1119
      case 'alt_inline_attach':
1120
        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
1121
        break;
1122
      default:
1123
        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
1124
        break;
1125
    }
1126
  }
1127

    
1128
  /**
1129
   * Assembles message header.
1130
   * @access public
1131
   * @return string The assembled header
1132
   */
1133
  public function CreateHeader() {
1134
    $result = '';
1135

    
1136
    // Set the boundaries
1137
    $uniq_id = md5(uniqid(time()));
1138
    $this->boundary[1] = 'b1_' . $uniq_id;
1139
    $this->boundary[2] = 'b2_' . $uniq_id;
1140
    $this->boundary[3] = 'b3_' . $uniq_id;
1141

    
1142
    $result .= $this->HeaderLine('Date', self::RFCDate());
1143
    if($this->Sender == '') {
1144
      $result .= $this->HeaderLine('Return-Path', trim($this->From));
1145
    } else {
1146
      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
1147
    }
1148

    
1149
    // To be created automatically by mail()
1150
    if($this->Mailer != 'mail') {
1151
      if ($this->SingleTo === true) {
1152
        foreach($this->to as $t) {
1153
          $this->SingleToArray[] = $this->AddrFormat($t);
1154
        }
1155
      } else {
1156
        if(count($this->to) > 0) {
1157
          $result .= $this->AddrAppend('To', $this->to);
1158
        } elseif (count($this->cc) == 0) {
1159
          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
1160
        }
1161
      }
1162
    }
1163

    
1164
    $from = array();
1165
    $from[0][0] = trim($this->From);
1166
    $from[0][1] = $this->FromName;
1167
    $result .= $this->AddrAppend('From', $from);
1168

    
1169
    // sendmail and mail() extract Cc from the header before sending
1170
    if(count($this->cc) > 0) {
1171
      $result .= $this->AddrAppend('Cc', $this->cc);
1172
    }
1173

    
1174
    // sendmail and mail() extract Bcc from the header before sending
1175
    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
1176
      $result .= $this->AddrAppend('Bcc', $this->bcc);
1177
    }
1178

    
1179
    if(count($this->ReplyTo) > 0) {
1180
      $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
1181
    }
1182

    
1183
    // mail() sets the subject itself
1184
    if($this->Mailer != 'mail') {
1185
      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
1186
    }
1187

    
1188
    if($this->MessageID != '') {
1189
      $result .= $this->HeaderLine('Message-ID', $this->MessageID);
1190
    } else {
1191
      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1192
    }
1193
    $result .= $this->HeaderLine('X-Priority', $this->Priority);
1194
    if($this->XMailer) {
1195
      $result .= $this->HeaderLine('X-Mailer', $this->XMailer);
1196
    } else {
1197
      $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
1198
    }
1199

    
1200
    if($this->ConfirmReadingTo != '') {
1201
      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1202
    }
1203

    
1204
    // Add custom headers
1205
    for($index = 0; $index < count($this->CustomHeader); $index++) {
1206
      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1207
    }
1208
    if (!$this->sign_key_file) {
1209
      $result .= $this->HeaderLine('MIME-Version', '1.0');
1210
      $result .= $this->GetMailMIME();
1211
    }
1212

    
1213
    return $result;
1214
  }
1215

    
1216
  /**
1217
   * Returns the message MIME.
1218
   * @access public
1219
   * @return string
1220
   */
1221
  public function GetMailMIME() {
1222
    $result = '';
1223
    switch($this->message_type) {
1224
      case 'plain':
1225
        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
1226
        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"');
1227
        break;
1228
      case 'inline':
1229
        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
1230
        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1231
        break;
1232
      case 'attach':
1233
      case 'inline_attach':
1234
      case 'alt_attach':
1235
      case 'alt_inline_attach':
1236
        $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
1237
        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1238
        break;
1239
      case 'alt':
1240
      case 'alt_inline':
1241
        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1242
        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1243
        break;
1244
    }
1245

    
1246
    if($this->Mailer != 'mail') {
1247
      $result .= $this->LE.$this->LE;
1248
    }
1249

    
1250
    return $result;
1251
  }
1252

    
1253
  /**
1254
   * Assembles the message body.  Returns an empty string on failure.
1255
   * @access public
1256
   * @return string The assembled message body
1257
   */
1258
  public function CreateBody() {
1259
    $body = '';
1260

    
1261
    if ($this->sign_key_file) {
1262
      $body .= $this->GetMailMIME();
1263
    }
1264

    
1265
    $this->SetWordWrap();
1266

    
1267
    switch($this->message_type) {
1268
      case 'plain':
1269
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1270
        break;
1271
      case 'inline':
1272
        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1273
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1274
        $body .= $this->LE.$this->LE;
1275
        $body .= $this->AttachAll("inline", $this->boundary[1]);
1276
        break;
1277
      case 'attach':
1278
        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1279
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1280
        $body .= $this->LE.$this->LE;
1281
        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1282
        break;
1283
      case 'inline_attach':
1284
        $body .= $this->TextLine("--" . $this->boundary[1]);
1285
        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1286
        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1287
        $body .= $this->LE;
1288
        $body .= $this->GetBoundary($this->boundary[2], '', '', '');
1289
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1290
        $body .= $this->LE.$this->LE;
1291
        $body .= $this->AttachAll("inline", $this->boundary[2]);
1292
        $body .= $this->LE;
1293
        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1294
        break;
1295
      case 'alt':
1296
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1297
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1298
        $body .= $this->LE.$this->LE;
1299
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
1300
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1301
        $body .= $this->LE.$this->LE;
1302
        $body .= $this->EndBoundary($this->boundary[1]);
1303
        break;
1304
      case 'alt_inline':
1305
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1306
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1307
        $body .= $this->LE.$this->LE;
1308
        $body .= $this->TextLine("--" . $this->boundary[1]);
1309
        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1310
        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1311
        $body .= $this->LE;
1312
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
1313
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1314
        $body .= $this->LE.$this->LE;
1315
        $body .= $this->AttachAll("inline", $this->boundary[2]);
1316
        $body .= $this->LE;
1317
        $body .= $this->EndBoundary($this->boundary[1]);
1318
        break;
1319
      case 'alt_attach':
1320
        $body .= $this->TextLine("--" . $this->boundary[1]);
1321
        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1322
        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1323
        $body .= $this->LE;
1324
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
1325
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1326
        $body .= $this->LE.$this->LE;
1327
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
1328
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1329
        $body .= $this->LE.$this->LE;
1330
        $body .= $this->EndBoundary($this->boundary[2]);
1331
        $body .= $this->LE;
1332
        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1333
        break;
1334
      case 'alt_inline_attach':
1335
        $body .= $this->TextLine("--" . $this->boundary[1]);
1336
        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1337
        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1338
        $body .= $this->LE;
1339
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
1340
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1341
        $body .= $this->LE.$this->LE;
1342
        $body .= $this->TextLine("--" . $this->boundary[2]);
1343
        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1344
        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
1345
        $body .= $this->LE;
1346
        $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
1347
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1348
        $body .= $this->LE.$this->LE;
1349
        $body .= $this->AttachAll("inline", $this->boundary[3]);
1350
        $body .= $this->LE;
1351
        $body .= $this->EndBoundary($this->boundary[2]);
1352
        $body .= $this->LE;
1353
        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1354
        break;
1355
    }
1356

    
1357
    if ($this->IsError()) {
1358
      $body = '';
1359
    } elseif ($this->sign_key_file) {
1360
      try {
1361
        $file = tempnam('', 'mail');
1362
        file_put_contents($file, $body); //TODO check this worked
1363
        $signed = tempnam("", "signed");
1364
        if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
1365
          @unlink($file);
1366
          @unlink($signed);
1367
          $body = file_get_contents($signed);
1368
        } else {
1369
          @unlink($file);
1370
          @unlink($signed);
1371
          throw new phpmailerException($this->Lang("signing").openssl_error_string());
1372
        }
1373
      } catch (phpmailerException $e) {
1374
        $body = '';
1375
        if ($this->exceptions) {
1376
          throw $e;
1377
        }
1378
      }
1379
    }
1380

    
1381
    return $body;
1382
  }
1383

    
1384
  /**
1385
   * Returns the start of a message boundary.
1386
   * @access protected
1387
   * @return string
1388
   */
1389
  protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1390
    $result = '';
1391
    if($charSet == '') {
1392
      $charSet = $this->CharSet;
1393
    }
1394
    if($contentType == '') {
1395
      $contentType = $this->ContentType;
1396
    }
1397
    if($encoding == '') {
1398
      $encoding = $this->Encoding;
1399
    }
1400
    $result .= $this->TextLine('--' . $boundary);
1401
    $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet);
1402
    $result .= $this->LE;
1403
    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
1404
    $result .= $this->LE;
1405

    
1406
    return $result;
1407
  }
1408

    
1409
  /**
1410
   * Returns the end of a message boundary.
1411
   * @access protected
1412
   * @return string
1413
   */
1414
  protected function EndBoundary($boundary) {
1415
    return $this->LE . '--' . $boundary . '--' . $this->LE;
1416
  }
1417

    
1418
  /**
1419
   * Sets the message type.
1420
   * @access protected
1421
   * @return void
1422
   */
1423
  protected function SetMessageType() {
1424
    $this->message_type = array();
1425
    if($this->AlternativeExists()) $this->message_type[] = "alt";
1426
    if($this->InlineImageExists()) $this->message_type[] = "inline";
1427
    if($this->AttachmentExists()) $this->message_type[] = "attach";
1428
    $this->message_type = implode("_", $this->message_type);
1429
    if($this->message_type == "") $this->message_type = "plain";
1430
  }
1431

    
1432
  /**
1433
   *  Returns a formatted header line.
1434
   * @access public
1435
   * @return string
1436
   */
1437
  public function HeaderLine($name, $value) {
1438
    return $name . ': ' . $value . $this->LE;
1439
  }
1440

    
1441
  /**
1442
   * Returns a formatted mail line.
1443
   * @access public
1444
   * @return string
1445
   */
1446
  public function TextLine($value) {
1447
    return $value . $this->LE;
1448
  }
1449

    
1450
  /////////////////////////////////////////////////
1451
  // CLASS METHODS, ATTACHMENTS
1452
  /////////////////////////////////////////////////
1453

    
1454
  /**
1455
   * Adds an attachment from a path on the filesystem.
1456
   * Returns false if the file could not be found
1457
   * or accessed.
1458
   * @param string $path Path to the attachment.
1459
   * @param string $name Overrides the attachment name.
1460
   * @param string $encoding File encoding (see $Encoding).
1461
   * @param string $type File extension (MIME) type.
1462
   * @return bool
1463
   */
1464
  public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1465
    try {
1466
      if ( !@is_file($path) ) {
1467
        throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
1468
      }
1469
      $filename = basename($path);
1470
      if ( $name == '' ) {
1471
        $name = $filename;
1472
      }
1473

    
1474
      $this->attachment[] = array(
1475
        0 => $path,
1476
        1 => $filename,
1477
        2 => $name,
1478
        3 => $encoding,
1479
        4 => $type,
1480
        5 => false,  // isStringAttachment
1481
        6 => 'attachment',
1482
        7 => 0
1483
      );
1484

    
1485
    } catch (phpmailerException $e) {
1486
      $this->SetError($e->getMessage());
1487
      if ($this->exceptions) {
1488
        throw $e;
1489
      }
1490
      echo $e->getMessage()."\n";
1491
      if ( $e->getCode() == self::STOP_CRITICAL ) {
1492
        return false;
1493
      }
1494
    }
1495
    return true;
1496
  }
1497

    
1498
  /**
1499
  * Return the current array of attachments
1500
  * @return array
1501
  */
1502
  public function GetAttachments() {
1503
    return $this->attachment;
1504
  }
1505

    
1506
  /**
1507
   * Attaches all fs, string, and binary attachments to the message.
1508
   * Returns an empty string on failure.
1509
   * @access protected
1510
   * @return string
1511
   */
1512
  protected function AttachAll($disposition_type, $boundary) {
1513
    // Return text of body
1514
    $mime = array();
1515
    $cidUniq = array();
1516
    $incl = array();
1517

    
1518
    // Add all attachments
1519
    foreach ($this->attachment as $attachment) {
1520
      // CHECK IF IT IS A VALID DISPOSITION_FILTER
1521
      if($attachment[6] == $disposition_type) {
1522
        // Check for string attachment
1523
        $bString = $attachment[5];
1524
        if ($bString) {
1525
          $string = $attachment[0];
1526
        } else {
1527
          $path = $attachment[0];
1528
        }
1529

    
1530
        $inclhash = md5(serialize($attachment));
1531
        if (in_array($inclhash, $incl)) { continue; }
1532
        $incl[]      = $inclhash;
1533
        $filename    = $attachment[1];
1534
        $name        = $attachment[2];
1535
        $encoding    = $attachment[3];
1536
        $type        = $attachment[4];
1537
        $disposition = $attachment[6];
1538
        $cid         = $attachment[7];
1539
        if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
1540
        $cidUniq[$cid] = true;
1541

    
1542
        $mime[] = sprintf("--%s%s", $boundary, $this->LE);
1543
        $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
1544
        $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1545

    
1546
        if($disposition == 'inline') {
1547
          $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1548
        }
1549

    
1550
        $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
1551

    
1552
        // Encode as string attachment
1553
        if($bString) {
1554
          $mime[] = $this->EncodeString($string, $encoding);
1555
          if($this->IsError()) {
1556
            return '';
1557
          }
1558
          $mime[] = $this->LE.$this->LE;
1559
        } else {
1560
          $mime[] = $this->EncodeFile($path, $encoding);
1561
          if($this->IsError()) {
1562
            return '';
1563
          }
1564
          $mime[] = $this->LE.$this->LE;
1565
        }
1566
      }
1567
    }
1568

    
1569
    $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
1570

    
1571
    return implode("", $mime);
1572
  }
1573

    
1574
  /**
1575
   * Encodes attachment in requested format.
1576
   * Returns an empty string on failure.
1577
   * @param string $path The full path to the file
1578
   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1579
   * @see EncodeFile()
1580
   * @access protected
1581
   * @return string
1582
   */
1583
  protected function EncodeFile($path, $encoding = 'base64') {
1584
    try {
1585
      if (!is_readable($path)) {
1586
        throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
1587
      }
1588
      if (function_exists('get_magic_quotes')) {
1589
        function get_magic_quotes() {
1590
          return false;
1591
        }
1592
      }
1593
      if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1594
        $magic_quotes = get_magic_quotes_runtime();
1595
        set_magic_quotes_runtime(0);
1596
      }
1597
      $file_buffer  = file_get_contents($path);
1598
      $file_buffer  = $this->EncodeString($file_buffer, $encoding);
1599
      if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1600
        set_magic_quotes_runtime($magic_quotes);
1601
      }
1602
      return $file_buffer;
1603
    } catch (Exception $e) {
1604
      $this->SetError($e->getMessage());
1605
      return '';
1606
    }
1607
  }
1608

    
1609
  /**
1610
   * Encodes string to requested format.
1611
   * Returns an empty string on failure.
1612
   * @param string $str The text to encode
1613
   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1614
   * @access public
1615
   * @return string
1616
   */
1617
  public function EncodeString($str, $encoding = 'base64') {
1618
    $encoded = '';
1619
    switch(strtolower($encoding)) {
1620
      case 'base64':
1621
        $encoded = chunk_split(base64_encode($str), 76, $this->LE);
1622
        break;
1623
      case '7bit':
1624
      case '8bit':
1625
        $encoded = $this->FixEOL($str);
1626
        //Make sure it ends with a line break
1627
        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1628
          $encoded .= $this->LE;
1629
        break;
1630
      case 'binary':
1631
        $encoded = $str;
1632
        break;
1633
      case 'quoted-printable':
1634
        $encoded = $this->EncodeQP($str);
1635
        break;
1636
      default:
1637
        $this->SetError($this->Lang('encoding') . $encoding);
1638
        break;
1639
    }
1640
    return $encoded;
1641
  }
1642

    
1643
  /**
1644
   * Encode a header string to best (shortest) of Q, B, quoted or none.
1645
   * @access public
1646
   * @return string
1647
   */
1648
  public function EncodeHeader($str, $position = 'text') {
1649
    $x = 0;
1650

    
1651
    switch (strtolower($position)) {
1652
      case 'phrase':
1653
        if (!preg_match('/[\200-\377]/', $str)) {
1654
          // Can't use addslashes as we don't know what value has magic_quotes_sybase
1655
          $encoded = addcslashes($str, "\0..\37\177\\\"");
1656
          if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
1657
            return ($encoded);
1658
          } else {
1659
            return ("\"$encoded\"");
1660
          }
1661
        }
1662
        $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1663
        break;
1664
      case 'comment':
1665
        $x = preg_match_all('/[()"]/', $str, $matches);
1666
        // Fall-through
1667
      case 'text':
1668
      default:
1669
        $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1670
        break;
1671
    }
1672

    
1673
    if ($x == 0) {
1674
      return ($str);
1675
    }
1676

    
1677
    $maxlen = 75 - 7 - strlen($this->CharSet);
1678
    // Try to select the encoding which should produce the shortest output
1679
    if (strlen($str)/3 < $x) {
1680
      $encoding = 'B';
1681
      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
1682
        // Use a custom function which correctly encodes and wraps long
1683
        // multibyte strings without breaking lines within a character
1684
        $encoded = $this->Base64EncodeWrapMB($str);
1685
      } else {
1686
        $encoded = base64_encode($str);
1687
        $maxlen -= $maxlen % 4;
1688
        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1689
      }
1690
    } else {
1691
      $encoding = 'Q';
1692
      $encoded = $this->EncodeQ($str, $position);
1693
      $encoded = $this->WrapText($encoded, $maxlen, true);
1694
      $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
1695
    }
1696

    
1697
    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1698
    $encoded = trim(str_replace("\n", $this->LE, $encoded));
1699

    
1700
    return $encoded;
1701
  }
1702

    
1703
  /**
1704
   * Checks if a string contains multibyte characters.
1705
   * @access public
1706
   * @param string $str multi-byte text to wrap encode
1707
   * @return bool
1708
   */
1709
  public function HasMultiBytes($str) {
1710
    if (function_exists('mb_strlen')) {
1711
      return (strlen($str) > mb_strlen($str, $this->CharSet));
1712
    } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
1713
      return false;
1714
    }
1715
  }
1716

    
1717
  /**
1718
   * Correctly encodes and wraps long multibyte strings for mail headers
1719
   * without breaking lines within a character.
1720
   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
1721
   * @access public
1722
   * @param string $str multi-byte text to wrap encode
1723
   * @return string
1724
   */
1725
  public function Base64EncodeWrapMB($str) {
1726
    $start = "=?".$this->CharSet."?B?";
1727
    $end = "?=";
1728
    $encoded = "";
1729

    
1730
    $mb_length = mb_strlen($str, $this->CharSet);
1731
    // Each line must have length <= 75, including $start and $end
1732
    $length = 75 - strlen($start) - strlen($end);
1733
    // Average multi-byte ratio
1734
    $ratio = $mb_length / strlen($str);
1735
    // Base64 has a 4:3 ratio
1736
    $offset = $avgLength = floor($length * $ratio * .75);
1737

    
1738
    for ($i = 0; $i < $mb_length; $i += $offset) {
1739
      $lookBack = 0;
1740

    
1741
      do {
1742
        $offset = $avgLength - $lookBack;
1743
        $chunk = mb_substr($str, $i, $offset, $this->CharSet);
1744
        $chunk = base64_encode($chunk);
1745
        $lookBack++;
1746
      }
1747
      while (strlen($chunk) > $length);
1748

    
1749
      $encoded .= $chunk . $this->LE;
1750
    }
1751

    
1752
    // Chomp the last linefeed
1753
    $encoded = substr($encoded, 0, -strlen($this->LE));
1754
    return $encoded;
1755
  }
1756

    
1757
  /**
1758
  * Encode string to quoted-printable.
1759
  * Only uses standard PHP, slow, but will always work
1760
  * @access public
1761
  * @param string $string the text to encode
1762
  * @param integer $line_max Number of chars allowed on a line before wrapping
1763
  * @return string
1764
  */
1765
  public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
1766
    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
1767
    $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
1768
    $eol = "\r\n";
1769
    $escape = '=';
1770
    $output = '';
1771
    while( list(, $line) = each($lines) ) {
1772
      $linlen = strlen($line);
1773
      $newline = '';
1774
      for($i = 0; $i < $linlen; $i++) {
1775
        $c = substr( $line, $i, 1 );
1776
        $dec = ord( $c );
1777
        if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
1778
          $c = '=2E';
1779
        }
1780
        if ( $dec == 32 ) {
1781
          if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
1782
            $c = '=20';
1783
          } else if ( $space_conv ) {
1784
            $c = '=20';
1785
          }
1786
        } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
1787
          $h2 = floor($dec/16);
1788
          $h1 = floor($dec%16);
1789
          $c = $escape.$hex[$h2].$hex[$h1];
1790
        }
1791
        if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
1792
          $output .= $newline.$escape.$eol; //  soft line break; " =\r\n" is okay
1793
          $newline = '';
1794
          // check if newline first character will be point or not
1795
          if ( $dec == 46 ) {
1796
            $c = '=2E';
1797
          }
1798
        }
1799
        $newline .= $c;
1800
      } // end of for
1801
      $output .= $newline.$eol;
1802
    } // end of while
1803
    return $output;
1804
  }
1805

    
1806
  /**
1807
  * Encode string to RFC2045 (6.7) quoted-printable format
1808
  * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
1809
  * Also results in same content as you started with after decoding
1810
  * @see EncodeQPphp()
1811
  * @access public
1812
  * @param string $string the text to encode
1813
  * @param integer $line_max Number of chars allowed on a line before wrapping
1814
  * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
1815
  * @return string
1816
  * @author Marcus Bointon
1817
  */
1818
  public function EncodeQP($string, $line_max = 76, $space_conv = false) {
1819
    if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
1820
      return quoted_printable_encode($string);
1821
    }
1822
    $filters = stream_get_filters();
1823
    if (!in_array('convert.*', $filters)) { //Got convert stream filter?
1824
      return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
1825
    }
1826
    $fp = fopen('php://temp/', 'r+');
1827
    $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
1828
    $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
1829
    $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
1830
    fputs($fp, $string);
1831
    rewind($fp);
1832
    $out = stream_get_contents($fp);
1833
    stream_filter_remove($s);
1834
    $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
1835
    fclose($fp);
1836
    return $out;
1837
  }
1838

    
1839
  /**
1840
   * Encode string to q encoding.
1841
   * @link http://tools.ietf.org/html/rfc2047
1842
   * @param string $str the text to encode
1843
   * @param string $position Where the text is going to be used, see the RFC for what that means
1844
   * @access public
1845
   * @return string
1846
   */
1847
  public function EncodeQ($str, $position = 'text') {
1848
    // There should not be any EOL in the string
1849
    $encoded = preg_replace('/[\r\n]*/', '', $str);
1850

    
1851
    switch (strtolower($position)) {
1852
      case 'phrase':
1853
        $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1854
        break;
1855
      case 'comment':
1856
        $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1857
      case 'text':
1858
      default:
1859
        // Replace every high ascii, control =, ? and _ characters
1860
        //TODO using /e (equivalent to eval()) is probably not a good idea
1861
        $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1862
                                "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded);
1863
        break;
1864
    }
1865

    
1866
    // Replace every spaces to _ (more readable than =20)
1867
    $encoded = str_replace(' ', '_', $encoded);
1868

    
1869
    return $encoded;
1870
  }
1871

    
1872
  /**
1873
   * Adds a string or binary attachment (non-filesystem) to the list.
1874
   * This method can be used to attach ascii or binary data,
1875
   * such as a BLOB record from a database.
1876
   * @param string $string String attachment data.
1877
   * @param string $filename Name of the attachment.
1878
   * @param string $encoding File encoding (see $Encoding).
1879
   * @param string $type File extension (MIME) type.
1880
   * @return void
1881
   */
1882
  public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
1883
    // Append to $attachment array
1884
    $this->attachment[] = array(
1885
      0 => $string,
1886
      1 => $filename,
1887
      2 => basename($filename),
1888
      3 => $encoding,
1889
      4 => $type,
1890
      5 => true,  // isStringAttachment
1891
      6 => 'attachment',
1892
      7 => 0
1893
    );
1894
  }
1895

    
1896
  /**
1897
   * Adds an embedded attachment.  This can include images, sounds, and
1898
   * just about any other document.  Make sure to set the $type to an
1899
   * image type.  For JPEG images use "image/jpeg" and for GIF images
1900
   * use "image/gif".
1901
   * @param string $path Path to the attachment.
1902
   * @param string $cid Content ID of the attachment.  Use this to identify
1903
   *        the Id for accessing the image in an HTML form.
1904
   * @param string $name Overrides the attachment name.
1905
   * @param string $encoding File encoding (see $Encoding).
1906
   * @param string $type File extension (MIME) type.
1907
   * @return bool
1908
   */
1909
  public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1910

    
1911
    if ( !@is_file($path) ) {
1912
      $this->SetError($this->Lang('file_access') . $path);
1913
      return false;
1914
    }
1915

    
1916
    $filename = basename($path);
1917
    if ( $name == '' ) {
1918
      $name = $filename;
1919
    }
1920

    
1921
    // Append to $attachment array
1922
    $this->attachment[] = array(
1923
      0 => $path,
1924
      1 => $filename,
1925
      2 => $name,
1926
      3 => $encoding,
1927
      4 => $type,
1928
      5 => false,  // isStringAttachment
1929
      6 => 'inline',
1930
      7 => $cid
1931
    );
1932

    
1933
    return true;
1934
  }
1935

    
1936
  public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') {
1937
    // Append to $attachment array
1938
    $this->attachment[] = array(
1939
      0 => $string,
1940
      1 => $filename,
1941
      2 => basename($filename),
1942
      3 => $encoding,
1943
      4 => $type,
1944
      5 => true,  // isStringAttachment
1945
      6 => 'inline',
1946
      7 => $cid
1947
    );
1948
  }
1949

    
1950
  /**
1951
   * Returns true if an inline attachment is present.
1952
   * @access public
1953
   * @return bool
1954
   */
1955
  public function InlineImageExists() {
1956
    foreach($this->attachment as $attachment) {
1957
      if ($attachment[6] == 'inline') {
1958
        return true;
1959
      }
1960
    }
1961
    return false;
1962
  }
1963

    
1964
  public function AttachmentExists() {
1965
    foreach($this->attachment as $attachment) {
1966
      if ($attachment[6] == 'attachment') {
1967
        return true;
1968
      }
1969
    }
1970
    return false;
1971
  }
1972

    
1973
  public function AlternativeExists() {
1974
    return strlen($this->AltBody)>0;
1975
  }
1976

    
1977
  /////////////////////////////////////////////////
1978
  // CLASS METHODS, MESSAGE RESET
1979
  /////////////////////////////////////////////////
1980

    
1981
  /**
1982
   * Clears all recipients assigned in the TO array.  Returns void.
1983
   * @return void
1984
   */
1985
  public function ClearAddresses() {
1986
    foreach($this->to as $to) {
1987
      unset($this->all_recipients[strtolower($to[0])]);
1988
    }
1989
    $this->to = array();
1990
  }
1991

    
1992
  /**
1993
   * Clears all recipients assigned in the CC array.  Returns void.
1994
   * @return void
1995
   */
1996
  public function ClearCCs() {
1997
    foreach($this->cc as $cc) {
1998
      unset($this->all_recipients[strtolower($cc[0])]);
1999
    }
2000
    $this->cc = array();
2001
  }
2002

    
2003
  /**
2004
   * Clears all recipients assigned in the BCC array.  Returns void.
2005
   * @return void
2006
   */
2007
  public function ClearBCCs() {
2008
    foreach($this->bcc as $bcc) {
2009
      unset($this->all_recipients[strtolower($bcc[0])]);
2010
    }
2011
    $this->bcc = array();
2012
  }
2013

    
2014
  /**
2015
   * Clears all recipients assigned in the ReplyTo array.  Returns void.
2016
   * @return void
2017
   */
2018
  public function ClearReplyTos() {
2019
    $this->ReplyTo = array();
2020
  }
2021

    
2022
  /**
2023
   * Clears all recipients assigned in the TO, CC and BCC
2024
   * array.  Returns void.
2025
   * @return void
2026
   */
2027
  public function ClearAllRecipients() {
2028
    $this->to = array();
2029
    $this->cc = array();
2030
    $this->bcc = array();
2031
    $this->all_recipients = array();
2032
  }
2033

    
2034
  /**
2035
   * Clears all previously set filesystem, string, and binary
2036
   * attachments.  Returns void.
2037
   * @return void
2038
   */
2039
  public function ClearAttachments() {
2040
    $this->attachment = array();
2041
  }
2042

    
2043
  /**
2044
   * Clears all custom headers.  Returns void.
2045
   * @return void
2046
   */
2047
  public function ClearCustomHeaders() {
2048
    $this->CustomHeader = array();
2049
  }
2050

    
2051
  /////////////////////////////////////////////////
2052
  // CLASS METHODS, MISCELLANEOUS
2053
  /////////////////////////////////////////////////
2054

    
2055
  /**
2056
   * Adds the error message to the error container.
2057
   * @access protected
2058
   * @return void
2059
   */
2060
  protected function SetError($msg) {
2061
    $this->error_count++;
2062
    if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
2063
      $lasterror = $this->smtp->getError();
2064
      if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
2065
        $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
2066
      }
2067
    }
2068
    $this->ErrorInfo = $msg;
2069
  }
2070

    
2071
  /**
2072
   * Returns the proper RFC 822 formatted date.
2073
   * @access public
2074
   * @return string
2075
   * @static
2076
   */
2077
  public static function RFCDate() {
2078
    $tz = date('Z');
2079
    $tzs = ($tz < 0) ? '-' : '+';
2080
    $tz = abs($tz);
2081
    $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
2082
    $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
2083

    
2084
    return $result;
2085
  }
2086

    
2087
  /**
2088
   * Returns the server hostname or 'localhost.localdomain' if unknown.
2089
   * @access protected
2090
   * @return string
2091
   */
2092
  protected function ServerHostname() {
2093
    if (!empty($this->Hostname)) {
2094
      $result = $this->Hostname;
2095
    } elseif (isset($_SERVER['SERVER_NAME'])) {
2096
      $result = $_SERVER['SERVER_NAME'];
2097
    } else {
2098
      $result = 'localhost.localdomain';
2099
    }
2100

    
2101
    return $result;
2102
  }
2103

    
2104
  /**
2105
   * Returns a message in the appropriate language.
2106
   * @access protected
2107
   * @return string
2108
   */
2109
  protected function Lang($key) {
2110
    if(count($this->language) < 1) {
2111
      $this->SetLanguage('en'); // set the default language
2112
    }
2113

    
2114
    if(isset($this->language[$key])) {
2115
      return $this->language[$key];
2116
    } else {
2117
      return 'Language string failed to load: ' . $key;
2118
    }
2119
  }
2120

    
2121
  /**
2122
   * Returns true if an error occurred.
2123
   * @access public
2124
   * @return bool
2125
   */
2126
  public function IsError() {
2127
    return ($this->error_count > 0);
2128
  }
2129

    
2130
  /**
2131
   * Changes every end of line from CR or LF to CRLF.
2132
   * @access public
2133
   * @return string
2134
   */
2135
  public function FixEOL($str) {
2136
    $str = str_replace("\r\n", "\n", $str);
2137
    $str = str_replace("\r", "\n", $str);
2138
    $str = str_replace("\n", $this->LE, $str);
2139
    return $str;
2140
  }
2141

    
2142
  /**
2143
   * Adds a custom header.
2144
   * @access public
2145
   * @return void
2146
   */
2147
  public function AddCustomHeader($custom_header) {
2148
    $this->CustomHeader[] = explode(':', $custom_header, 2);
2149
  }
2150

    
2151
  /**
2152
   * Evaluates the message and returns modifications for inline images and backgrounds
2153
   * @access public
2154
   * @return $message
2155
   */
2156
  public function MsgHTML($message, $basedir = '') {
2157
    preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
2158
    if(isset($images[2])) {
2159
      foreach($images[2] as $i => $url) {
2160
        // do not change urls for absolute images (thanks to corvuscorax)
2161
        if (!preg_match('#^[A-z]+://#', $url)) {
2162
          $filename = basename($url);
2163
          $directory = dirname($url);
2164
          ($directory == '.') ? $directory='': '';
2165
          $cid = 'cid:' . md5($filename);
2166
          $ext = pathinfo($filename, PATHINFO_EXTENSION);
2167
          $mimeType  = self::_mime_types($ext);
2168
          if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; }
2169
          if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
2170
          if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) {
2171
            $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
2172
          }
2173
        }
2174
      }
2175
    }
2176
    $this->IsHTML(true);
2177
    $this->Body = $message;
2178
    $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
2179
    if (!empty($textMsg) && empty($this->AltBody)) {
2180
      $this->AltBody = html_entity_decode($textMsg);
2181
    }
2182
    if (empty($this->AltBody)) {
2183
      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
2184
    }
2185
  }
2186

    
2187
  /**
2188
   * Gets the MIME type of the embedded or inline image
2189
   * @param string File extension
2190
   * @access public
2191
   * @return string MIME type of ext
2192
   * @static
2193
   */
2194
  public static function _mime_types($ext = '') {
2195
    $mimes = array(
2196
      'hqx'   =>  'application/mac-binhex40',
2197
      'cpt'   =>  'application/mac-compactpro',
2198
      'doc'   =>  'application/msword',
2199
      'bin'   =>  'application/macbinary',
2200
      'dms'   =>  'application/octet-stream',
2201
      'lha'   =>  'application/octet-stream',
2202
      'lzh'   =>  'application/octet-stream',
2203
      'exe'   =>  'application/octet-stream',
2204
      'class' =>  'application/octet-stream',
2205
      'psd'   =>  'application/octet-stream',
2206
      'so'    =>  'application/octet-stream',
2207
      'sea'   =>  'application/octet-stream',
2208
      'dll'   =>  'application/octet-stream',
2209
      'oda'   =>  'application/oda',
2210
      'pdf'   =>  'application/pdf',
2211
      'ai'    =>  'application/postscript',
2212
      'eps'   =>  'application/postscript',
2213
      'ps'    =>  'application/postscript',
2214
      'smi'   =>  'application/smil',
2215
      'smil'  =>  'application/smil',
2216
      'mif'   =>  'application/vnd.mif',
2217
      'xls'   =>  'application/vnd.ms-excel',
2218
      'ppt'   =>  'application/vnd.ms-powerpoint',
2219
      'wbxml' =>  'application/vnd.wap.wbxml',
2220
      'wmlc'  =>  'application/vnd.wap.wmlc',
2221
      'dcr'   =>  'application/x-director',
2222
      'dir'   =>  'application/x-director',
2223
      'dxr'   =>  'application/x-director',
2224
      'dvi'   =>  'application/x-dvi',
2225
      'gtar'  =>  'application/x-gtar',
2226
      'php'   =>  'application/x-httpd-php',
2227
      'php4'  =>  'application/x-httpd-php',
2228
      'php3'  =>  'application/x-httpd-php',
2229
      'phtml' =>  'application/x-httpd-php',
2230
      'phps'  =>  'application/x-httpd-php-source',
2231
      'js'    =>  'application/x-javascript',
2232
      'swf'   =>  'application/x-shockwave-flash',
2233
      'sit'   =>  'application/x-stuffit',
2234
      'tar'   =>  'application/x-tar',
2235
      'tgz'   =>  'application/x-tar',
2236
      'xhtml' =>  'application/xhtml+xml',
2237
      'xht'   =>  'application/xhtml+xml',
2238
      'zip'   =>  'application/zip',
2239
      'mid'   =>  'audio/midi',
2240
      'midi'  =>  'audio/midi',
2241
      'mpga'  =>  'audio/mpeg',
2242
      'mp2'   =>  'audio/mpeg',
2243
      'mp3'   =>  'audio/mpeg',
2244
      'aif'   =>  'audio/x-aiff',
2245
      'aiff'  =>  'audio/x-aiff',
2246
      'aifc'  =>  'audio/x-aiff',
2247
      'ram'   =>  'audio/x-pn-realaudio',
2248
      'rm'    =>  'audio/x-pn-realaudio',
2249
      'rpm'   =>  'audio/x-pn-realaudio-plugin',
2250
      'ra'    =>  'audio/x-realaudio',
2251
      'rv'    =>  'video/vnd.rn-realvideo',
2252
      'wav'   =>  'audio/x-wav',
2253
      'bmp'   =>  'image/bmp',
2254
      'gif'   =>  'image/gif',
2255
      'jpeg'  =>  'image/jpeg',
2256
      'jpg'   =>  'image/jpeg',
2257
      'jpe'   =>  'image/jpeg',
2258
      'png'   =>  'image/png',
2259
      'tiff'  =>  'image/tiff',
2260
      'tif'   =>  'image/tiff',
2261
      'css'   =>  'text/css',
2262
      'html'  =>  'text/html',
2263
      'htm'   =>  'text/html',
2264
      'shtml' =>  'text/html',
2265
      'txt'   =>  'text/plain',
2266
      'text'  =>  'text/plain',
2267
      'log'   =>  'text/plain',
2268
      'rtx'   =>  'text/richtext',
2269
      'rtf'   =>  'text/rtf',
2270
      'xml'   =>  'text/xml',
2271
      'xsl'   =>  'text/xml',
2272
      'mpeg'  =>  'video/mpeg',
2273
      'mpg'   =>  'video/mpeg',
2274
      'mpe'   =>  'video/mpeg',
2275
      'qt'    =>  'video/quicktime',
2276
      'mov'   =>  'video/quicktime',
2277
      'avi'   =>  'video/x-msvideo',
2278
      'movie' =>  'video/x-sgi-movie',
2279
      'doc'   =>  'application/msword',
2280
      'word'  =>  'application/msword',
2281
      'xl'    =>  'application/excel',
2282
      'eml'   =>  'message/rfc822'
2283
    );
2284
    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
2285
  }
2286

    
2287
  /**
2288
  * Set (or reset) Class Objects (variables)
2289
  *
2290
  * Usage Example:
2291
  * $page->set('X-Priority', '3');
2292
  *
2293
  * @access public
2294
  * @param string $name Parameter Name
2295
  * @param mixed $value Parameter Value
2296
  * NOTE: will not work with arrays, there are no arrays to set/reset
2297
  * @todo Should this not be using __set() magic function?
2298
  */
2299
  public function set($name, $value = '') {
2300
    try {
2301
      if (isset($this->$name) ) {
2302
        $this->$name = $value;
2303
      } else {
2304
        throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
2305
      }
2306
    } catch (Exception $e) {
2307
      $this->SetError($e->getMessage());
2308
      if ($e->getCode() == self::STOP_CRITICAL) {
2309
        return false;
2310
      }
2311
    }
2312
    return true;
2313
  }
2314

    
2315
  /**
2316
   * Strips newlines to prevent header injection.
2317
   * @access public
2318
   * @param string $str String
2319
   * @return string
2320
   */
2321
  public function SecureHeader($str) {
2322
    $str = str_replace("\r", '', $str);
2323
    $str = str_replace("\n", '', $str);
2324
    return trim($str);
2325
  }
2326

    
2327
  /**
2328
   * Set the private key file and password to sign the message.
2329
   *
2330
   * @access public
2331
   * @param string $key_filename Parameter File Name
2332
   * @param string $key_pass Password for private key
2333
   */
2334
  public function Sign($cert_filename, $key_filename, $key_pass) {
2335
    $this->sign_cert_file = $cert_filename;
2336
    $this->sign_key_file = $key_filename;
2337
    $this->sign_key_pass = $key_pass;
2338
  }
2339

    
2340
  /**
2341
   * Set the private key file and password to sign the message.
2342
   *
2343
   * @access public
2344
   * @param string $key_filename Parameter File Name
2345
   * @param string $key_pass Password for private key
2346
   */
2347
  public function DKIM_QP($txt) {
2348
    $tmp = '';
2349
    $line = '';
2350
    for ($i = 0; $i < strlen($txt); $i++) {
2351
      $ord = ord($txt[$i]);
2352
      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
2353
        $line .= $txt[$i];
2354
      } else {
2355
        $line .= "=".sprintf("%02X", $ord);
2356
      }
2357
    }
2358
    return $line;
2359
  }
2360

    
2361
  /**
2362
   * Generate DKIM signature
2363
   *
2364
   * @access public
2365
   * @param string $s Header
2366
   */
2367
  public function DKIM_Sign($s) {
2368
    $privKeyStr = file_get_contents($this->DKIM_private);
2369
    if ($this->DKIM_passphrase != '') {
2370
      $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
2371
    } else {
2372
      $privKey = $privKeyStr;
2373
    }
2374
    if (openssl_sign($s, $signature, $privKey)) {
2375
      return base64_encode($signature);
2376
    }
2377
  }
2378

    
2379
  /**
2380
   * Generate DKIM Canonicalization Header
2381
   *
2382
   * @access public
2383
   * @param string $s Header
2384
   */
2385
  public function DKIM_HeaderC($s) {
2386
    $s = preg_replace("/\r\n\s+/", " ", $s);
2387
    $lines = explode("\r\n", $s);
2388
    foreach ($lines as $key => $line) {
2389
      list($heading, $value) = explode(":", $line, 2);
2390
      $heading = strtolower($heading);
2391
      $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
2392
      $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
2393
    }
2394
    $s = implode("\r\n", $lines);
2395
    return $s;
2396
  }
2397

    
2398
  /**
2399
   * Generate DKIM Canonicalization Body
2400
   *
2401
   * @access public
2402
   * @param string $body Message Body
2403
   */
2404
  public function DKIM_BodyC($body) {
2405
    if ($body == '') return "\r\n";
2406
    // stabilize line endings
2407
    $body = str_replace("\r\n", "\n", $body);
2408
    $body = str_replace("\n", "\r\n", $body);
2409
    // END stabilize line endings
2410
    while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
2411
      $body = substr($body, 0, strlen($body) - 2);
2412
    }
2413
    return $body;
2414
  }
2415

    
2416
  /**
2417
   * Create the DKIM header, body, as new header
2418
   *
2419
   * @access public
2420
   * @param string $headers_line Header lines
2421
   * @param string $subject Subject
2422
   * @param string $body Body
2423
   */
2424
  public function DKIM_Add($headers_line, $subject, $body) {
2425
    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
2426
    $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
2427
    $DKIMquery            = 'dns/txt'; // Query method
2428
    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
2429
    $subject_header       = "Subject: $subject";
2430
    $headers              = explode($this->LE, $headers_line);
2431
    foreach($headers as $header) {
2432
      if (strpos($header, 'From:') === 0) {
2433
        $from_header = $header;
2434
      } elseif (strpos($header, 'To:') === 0) {
2435
        $to_header = $header;
2436
      }
2437
    }
2438
    $from     = str_replace('|', '=7C', $this->DKIM_QP($from_header));
2439
    $to       = str_replace('|', '=7C', $this->DKIM_QP($to_header));
2440
    $subject  = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
2441
    $body     = $this->DKIM_BodyC($body);
2442
    $DKIMlen  = strlen($body) ; // Length of body
2443
    $DKIMb64  = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
2444
    $ident    = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
2445
    $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
2446
                "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
2447
                "\th=From:To:Subject;\r\n".
2448
                "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
2449
                "\tz=$from\r\n".
2450
                "\t|$to\r\n".
2451
                "\t|$subject;\r\n".
2452
                "\tbh=" . $DKIMb64 . ";\r\n".
2453
                "\tb=";
2454
    $toSign   = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
2455
    $signed   = $this->DKIM_Sign($toSign);
2456
    return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
2457
  }
2458

    
2459
  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) {
2460
    if (!empty($this->action_function) && function_exists($this->action_function)) {
2461
      $params = array($isSent, $to, $cc, $bcc, $subject, $body);
2462
      call_user_func_array($this->action_function, $params);
2463
    }
2464
  }
2465
}
2466

    
2467
class phpmailerException extends Exception {
2468
  public function errorMessage() {
2469
    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
2470
    return $errorMsg;
2471
  }
2472
}
2473
?>
(4-4/7)