Project

General

Profile

1 1463 Luisehahne
<?php
2
/*~ class.phpmailer.php
3
.---------------------------------------------------------------------------.
4
|  Software: PHPMailer - PHP email class                                    |
5 1550 Luisehahne
|   Version: 5.2                                                            |
6
|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
7 1463 Luisehahne
| ------------------------------------------------------------------------- |
8 1550 Luisehahne
|     Admin: Jim Jagielski (project admininistrator)                        |
9 1539 Luisehahne
|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
10
|          : Marcus Bointon (coolbru) coolbru@users.sourceforge.net         |
11 1550 Luisehahne
|          : Jim Jagielski (jimjag) jimjag@gmail.com                        |
12 1539 Luisehahne
|   Founder: Brent R. Matzelle (original founder)                           |
13 1550 Luisehahne
| Copyright (c) 2010-2011, Jim Jagielski. All Rights Reserved.               |
14 1539 Luisehahne
| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved.               |
15 1463 Luisehahne
| 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 1539 Luisehahne
 * NOTE: Requires PHP version 5 or later
28 1463 Luisehahne
 * @package PHPMailer
29
 * @author Andy Prevost
30 1539 Luisehahne
 * @author Marcus Bointon
31 1550 Luisehahne
 * @author Jim Jagielski
32
 * @copyright 2010 - 2011 Jim Jagielski
33 1463 Luisehahne
 * @copyright 2004 - 2009 Andy Prevost
34 1550 Luisehahne
 * @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $
35 1539 Luisehahne
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
36 1463 Luisehahne
 */
37
38 1539 Luisehahne
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 1463 Luisehahne
class PHPMailer {
41
42
  /////////////////////////////////////////////////
43
  // PROPERTIES, PUBLIC
44
  /////////////////////////////////////////////////
45
46
  /**
47
   * Email priority (1 = High, 3 = Normal, 5 = low).
48 1539 Luisehahne
   * @var int
49 1463 Luisehahne
   */
50 1539 Luisehahne
  public $Priority          = 3;
51 1463 Luisehahne
52
  /**
53
   * Sets the CharSet of the message.
54 1539 Luisehahne
   * @var string
55 1463 Luisehahne
   */
56 1539 Luisehahne
  public $CharSet           = 'iso-8859-1';
57 1463 Luisehahne
58
  /**
59
   * Sets the Content-type of the message.
60 1539 Luisehahne
   * @var string
61 1463 Luisehahne
   */
62 1539 Luisehahne
  public $ContentType       = 'text/plain';
63 1463 Luisehahne
64
  /**
65 1539 Luisehahne
   * Sets the Encoding of the message. Options for this are
66
   *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
67
   * @var string
68 1463 Luisehahne
   */
69 1539 Luisehahne
  public $Encoding          = '8bit';
70 1463 Luisehahne
71
  /**
72
   * Holds the most recent mailer error message.
73 1539 Luisehahne
   * @var string
74 1463 Luisehahne
   */
75 1539 Luisehahne
  public $ErrorInfo         = '';
76 1463 Luisehahne
77
  /**
78
   * Sets the From email address for the message.
79 1539 Luisehahne
   * @var string
80 1463 Luisehahne
   */
81 1539 Luisehahne
  public $From              = 'root@localhost';
82 1463 Luisehahne
83
  /**
84
   * Sets the From name of the message.
85 1539 Luisehahne
   * @var string
86 1463 Luisehahne
   */
87 1539 Luisehahne
  public $FromName          = 'Root User';
88 1463 Luisehahne
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 1539 Luisehahne
   * @var string
93 1463 Luisehahne
   */
94 1539 Luisehahne
  public $Sender            = '';
95 1463 Luisehahne
96
  /**
97
   * Sets the Subject of the message.
98 1539 Luisehahne
   * @var string
99 1463 Luisehahne
   */
100 1539 Luisehahne
  public $Subject           = '';
101 1463 Luisehahne
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 1539 Luisehahne
   * @var string
106 1463 Luisehahne
   */
107 1539 Luisehahne
  public $Body              = '';
108 1463 Luisehahne
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 1539 Luisehahne
   * @var string
115 1463 Luisehahne
   */
116 1539 Luisehahne
  public $AltBody           = '';
117 1463 Luisehahne
118
  /**
119 1550 Luisehahne
   * 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 1463 Luisehahne
   * Sets word wrapping on the body of the message to a given number of
134
   * characters.
135 1539 Luisehahne
   * @var int
136 1463 Luisehahne
   */
137 1539 Luisehahne
  public $WordWrap          = 0;
138 1463 Luisehahne
139
  /**
140
   * Method to send mail: ("mail", "sendmail", or "smtp").
141 1539 Luisehahne
   * @var string
142 1463 Luisehahne
   */
143 1539 Luisehahne
  public $Mailer            = 'mail';
144 1463 Luisehahne
145
  /**
146
   * Sets the path of the sendmail program.
147 1539 Luisehahne
   * @var string
148 1463 Luisehahne
   */
149 1539 Luisehahne
  public $Sendmail          = '/usr/sbin/sendmail';
150 1463 Luisehahne
151
  /**
152 1539 Luisehahne
   * Path to PHPMailer plugins.  Useful if the SMTP class
153 1463 Luisehahne
   * is in a different directory than the PHP include path.
154 1539 Luisehahne
   * @var string
155 1463 Luisehahne
   */
156 1539 Luisehahne
  public $PluginDir         = '';
157 1463 Luisehahne
158
  /**
159
   * Sets the email address that a reading confirmation will be sent.
160 1539 Luisehahne
   * @var string
161 1463 Luisehahne
   */
162 1539 Luisehahne
  public $ConfirmReadingTo  = '';
163 1463 Luisehahne
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 1539 Luisehahne
   * @var string
169 1463 Luisehahne
   */
170 1539 Luisehahne
  public $Hostname          = '';
171 1463 Luisehahne
172
  /**
173
   * Sets the message ID to be used in the Message-Id header.
174
   * If empty, a unique id will be generated.
175 1539 Luisehahne
   * @var string
176 1463 Luisehahne
   */
177 1539 Luisehahne
  public $MessageID         = '';
178 1463 Luisehahne
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 1539 Luisehahne
   * @var string
190 1463 Luisehahne
   */
191 1539 Luisehahne
  public $Host          = 'localhost';
192 1463 Luisehahne
193
  /**
194
   * Sets the default SMTP server port.
195 1539 Luisehahne
   * @var int
196 1463 Luisehahne
   */
197 1539 Luisehahne
  public $Port          = 25;
198 1463 Luisehahne
199
  /**
200
   * Sets the SMTP HELO of the message (Default is $Hostname).
201 1539 Luisehahne
   * @var string
202 1463 Luisehahne
   */
203 1539 Luisehahne
  public $Helo          = '';
204 1463 Luisehahne
205
  /**
206
   * Sets connection prefix.
207
   * Options are "", "ssl" or "tls"
208 1539 Luisehahne
   * @var string
209 1463 Luisehahne
   */
210 1539 Luisehahne
  public $SMTPSecure    = '';
211 1463 Luisehahne
212
  /**
213
   * Sets SMTP authentication. Utilizes the Username and Password variables.
214 1539 Luisehahne
   * @var bool
215 1463 Luisehahne
   */
216 1539 Luisehahne
  public $SMTPAuth      = false;
217 1463 Luisehahne
218
  /**
219
   * Sets SMTP username.
220 1539 Luisehahne
   * @var string
221 1463 Luisehahne
   */
222 1539 Luisehahne
  public $Username      = '';
223 1463 Luisehahne
224
  /**
225
   * Sets SMTP password.
226 1539 Luisehahne
   * @var string
227 1463 Luisehahne
   */
228 1539 Luisehahne
  public $Password      = '';
229 1463 Luisehahne
230
  /**
231 1539 Luisehahne
   * Sets the SMTP server timeout in seconds.
232
   * This function will not work with the win32 version.
233
   * @var int
234 1463 Luisehahne
   */
235 1539 Luisehahne
  public $Timeout       = 10;
236 1463 Luisehahne
237
  /**
238
   * Sets SMTP class debugging on or off.
239 1539 Luisehahne
   * @var bool
240 1463 Luisehahne
   */
241 1539 Luisehahne
  public $SMTPDebug     = false;
242 1463 Luisehahne
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 1539 Luisehahne
   * @var bool
248 1463 Luisehahne
   */
249 1539 Luisehahne
  public $SMTPKeepAlive = false;
250 1463 Luisehahne
251
  /**
252
   * Provides the ability to have the TO field process individual
253
   * emails, instead of sending to entire TO addresses
254 1539 Luisehahne
   * @var bool
255 1463 Luisehahne
   */
256 1539 Luisehahne
  public $SingleTo      = false;
257 1463 Luisehahne
258 1539 Luisehahne
   /**
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 1550 Luisehahne
   * @var string
286
   */
287
  public $DKIM_passphrase   = '';
288
289
  /**
290
   * Used with DKIM DNS Resource Record
291 1539 Luisehahne
   * 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 1550 Luisehahne
  public $Version         = '5.2';
321 1539 Luisehahne
322 1550 Luisehahne
  /**
323
   * What to use in the X-Mailer header
324
   * @var string
325
   */
326
  public $XMailer         = '';
327
328 1463 Luisehahne
  /////////////////////////////////////////////////
329 1539 Luisehahne
  // PROPERTIES, PRIVATE AND PROTECTED
330 1463 Luisehahne
  /////////////////////////////////////////////////
331
332 1550 Luisehahne
  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 1463 Luisehahne
349
  /////////////////////////////////////////////////
350 1539 Luisehahne
  // 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 1463 Luisehahne
  // METHODS, VARIABLES
359
  /////////////////////////////////////////////////
360
361
  /**
362 1539 Luisehahne
   * 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 1463 Luisehahne
   * Sets message type to HTML.
371 1539 Luisehahne
   * @param bool $ishtml
372
   * @return void
373 1463 Luisehahne
   */
374 1539 Luisehahne
  public function IsHTML($ishtml = true) {
375
    if ($ishtml) {
376 1463 Luisehahne
      $this->ContentType = 'text/html';
377
    } else {
378
      $this->ContentType = 'text/plain';
379
    }
380
  }
381
382
  /**
383
   * Sets Mailer to send message using SMTP.
384 1539 Luisehahne
   * @return void
385 1463 Luisehahne
   */
386 1539 Luisehahne
  public function IsSMTP() {
387 1463 Luisehahne
    $this->Mailer = 'smtp';
388
  }
389
390
  /**
391
   * Sets Mailer to send message using PHP mail() function.
392 1539 Luisehahne
   * @return void
393 1463 Luisehahne
   */
394 1539 Luisehahne
  public function IsMail() {
395 1463 Luisehahne
    $this->Mailer = 'mail';
396
  }
397
398
  /**
399
   * Sets Mailer to send message using the $Sendmail program.
400 1539 Luisehahne
   * @return void
401 1463 Luisehahne
   */
402 1539 Luisehahne
  public function IsSendmail() {
403
    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
404
      $this->Sendmail = '/var/qmail/bin/sendmail';
405
    }
406 1463 Luisehahne
    $this->Mailer = 'sendmail';
407
  }
408
409
  /**
410
   * Sets Mailer to send message using the qmail MTA.
411 1539 Luisehahne
   * @return void
412 1463 Luisehahne
   */
413 1539 Luisehahne
  public function IsQmail() {
414
    if (stristr(ini_get('sendmail_path'), 'qmail')) {
415
      $this->Sendmail = '/var/qmail/bin/sendmail';
416
    }
417 1463 Luisehahne
    $this->Mailer = 'sendmail';
418
  }
419
420
  /////////////////////////////////////////////////
421
  // METHODS, RECIPIENTS
422
  /////////////////////////////////////////////////
423
424
  /**
425
   * Adds a "To" address.
426 1539 Luisehahne
   * @param string $address
427
   * @param string $name
428
   * @return boolean true on success, false if address already used
429 1463 Luisehahne
   */
430 1539 Luisehahne
  public function AddAddress($address, $name = '') {
431
    return $this->AddAnAddress('to', $address, $name);
432 1463 Luisehahne
  }
433
434
  /**
435 1539 Luisehahne
   * 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 1463 Luisehahne
   */
441 1539 Luisehahne
  public function AddCC($address, $name = '') {
442
    return $this->AddAnAddress('cc', $address, $name);
443 1463 Luisehahne
  }
444
445
  /**
446 1539 Luisehahne
   * 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 1463 Luisehahne
   */
452 1539 Luisehahne
  public function AddBCC($address, $name = '') {
453
    return $this->AddAnAddress('bcc', $address, $name);
454 1463 Luisehahne
  }
455
456
  /**
457 1539 Luisehahne
   * Adds a "Reply-to" address.
458
   * @param string $address
459
   * @param string $name
460
   * @return boolean
461 1463 Luisehahne
   */
462 1539 Luisehahne
  public function AddReplyTo($address, $name = '') {
463
    return $this->AddAnAddress('ReplyTo', $address, $name);
464 1463 Luisehahne
  }
465
466 1539 Luisehahne
  /**
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 1550 Luisehahne
   * @access protected
474 1539 Luisehahne
   */
475 1550 Luisehahne
  protected function AddAnAddress($kind, $address, $name = '') {
476 1539 Luisehahne
    if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
477 1550 Luisehahne
      $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 1539 Luisehahne
      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 1550 Luisehahne
  public function SetFrom($address, $name = '', $auto = 1) {
516 1539 Luisehahne
    $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 1463 Luisehahne
  /////////////////////////////////////////////////
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 1539 Luisehahne
   * @return bool
571 1463 Luisehahne
   */
572 1539 Luisehahne
  public function Send() {
573
    try {
574 1550 Luisehahne
      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 1539 Luisehahne
      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
588
        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
589
      }
590 1463 Luisehahne
591 1539 Luisehahne
      // Set whether the message is multipart/alternative
592
      if(!empty($this->AltBody)) {
593
        $this->ContentType = 'multipart/alternative';
594
      }
595 1463 Luisehahne
596 1539 Luisehahne
      $this->error_count = 0; // reset errors
597
      $this->SetMessageType();
598 1550 Luisehahne
      //Refuse to send an empty message
599 1539 Luisehahne
      if (empty($this->Body)) {
600
        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
601
      }
602 1463 Luisehahne
603 1550 Luisehahne
      $this->MIMEHeader = $this->CreateHeader();
604
      $this->MIMEBody = $this->CreateBody();
605
606
607 1539 Luisehahne
      // digitally sign with DKIM if enabled
608
      if ($this->DKIM_domain && $this->DKIM_private) {
609 1550 Luisehahne
        $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 1539 Luisehahne
      }
612
613 1550 Luisehahne
      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 1539 Luisehahne
      // Choose the mailer and send through it
626
      switch($this->Mailer) {
627
        case 'sendmail':
628 1550 Luisehahne
          return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
629 1539 Luisehahne
        case 'smtp':
630 1550 Luisehahne
          return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
631 1539 Luisehahne
        default:
632 1550 Luisehahne
          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
633 1539 Luisehahne
      }
634
635
    } catch (phpmailerException $e) {
636
      $this->SetError($e->getMessage());
637
      if ($this->exceptions) {
638
        throw $e;
639
      }
640
      echo $e->getMessage()."\n";
641 1463 Luisehahne
      return false;
642
    }
643
  }
644
645
  /**
646
   * Sends mail using the $Sendmail program.
647 1539 Luisehahne
   * @param string $header The message headers
648
   * @param string $body The message body
649
   * @access protected
650
   * @return bool
651 1463 Luisehahne
   */
652 1539 Luisehahne
  protected function SendmailSend($header, $body) {
653 1463 Luisehahne
    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 1539 Luisehahne
    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 1550 Luisehahne
        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
670 1539 Luisehahne
        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 1550 Luisehahne
      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
684 1539 Luisehahne
      if($result != 0) {
685
        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
686
      }
687 1463 Luisehahne
    }
688
    return true;
689
  }
690
691
  /**
692
   * Sends mail using the PHP mail() function.
693 1539 Luisehahne
   * @param string $header The message headers
694
   * @param string $body The message body
695
   * @access protected
696
   * @return bool
697 1463 Luisehahne
   */
698 1539 Luisehahne
  protected function MailSend($header, $body) {
699
    $toArr = array();
700
    foreach($this->to as $t) {
701
      $toArr[] = $this->AddrFormat($t);
702 1463 Luisehahne
    }
703 1539 Luisehahne
    $to = implode(', ', $toArr);
704 1463 Luisehahne
705 1550 Luisehahne
    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 1463 Luisehahne
      $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 1539 Luisehahne
          // implement call back function if it exists
717
          $isSent = ($rt == 1) ? 1 : 0;
718 1550 Luisehahne
          $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
719 1463 Luisehahne
        }
720
      } else {
721
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
722 1539 Luisehahne
        // implement call back function if it exists
723
        $isSent = ($rt == 1) ? 1 : 0;
724 1550 Luisehahne
        $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
725 1463 Luisehahne
      }
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 1539 Luisehahne
          // implement call back function if it exists
731
          $isSent = ($rt == 1) ? 1 : 0;
732 1550 Luisehahne
          $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
733 1463 Luisehahne
        }
734
      } else {
735
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
736 1539 Luisehahne
        // implement call back function if it exists
737
        $isSent = ($rt == 1) ? 1 : 0;
738 1550 Luisehahne
        $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
739 1463 Luisehahne
      }
740
    }
741
    if (isset($old_from)) {
742
      ini_set('sendmail_from', $old_from);
743
    }
744
    if(!$rt) {
745 1539 Luisehahne
      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
746 1463 Luisehahne
    }
747
    return true;
748
  }
749
750
  /**
751 1539 Luisehahne
   * 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 1463 Luisehahne
   */
759 1539 Luisehahne
  protected function SmtpSend($header, $body) {
760
    require_once $this->PluginDir . 'class.smtp.php';
761 1463 Luisehahne
    $bad_rcpt = array();
762
763
    if(!$this->SmtpConnect()) {
764 1539 Luisehahne
      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
765 1463 Luisehahne
    }
766
    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
767
    if(!$this->smtp->Mail($smtp_from)) {
768 1539 Luisehahne
      throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
769 1463 Luisehahne
    }
770
771 1539 Luisehahne
    // 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 1550 Luisehahne
        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
778 1539 Luisehahne
      } else {
779
        // implement call back function if it exists
780
        $isSent = 1;
781 1550 Luisehahne
        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
782 1463 Luisehahne
      }
783
    }
784 1539 Luisehahne
    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 1550 Luisehahne
        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
790 1539 Luisehahne
      } else {
791
        // implement call back function if it exists
792
        $isSent = 1;
793 1550 Luisehahne
        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
794 1463 Luisehahne
      }
795
    }
796 1539 Luisehahne
    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 1550 Luisehahne
        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
802 1539 Luisehahne
      } else {
803
        // implement call back function if it exists
804
        $isSent = 1;
805 1550 Luisehahne
        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
806 1463 Luisehahne
      }
807
    }
808
809 1539 Luisehahne
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 1463 Luisehahne
    }
814
    if(!$this->smtp->Data($header . $body)) {
815 1539 Luisehahne
      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
816 1463 Luisehahne
    }
817
    if($this->SMTPKeepAlive == true) {
818
      $this->smtp->Reset();
819
    }
820
    return true;
821
  }
822
823
  /**
824 1539 Luisehahne
   * Initiates a connection to an SMTP server.
825
   * Returns false if the operation failed.
826
   * @uses SMTP
827
   * @access public
828
   * @return bool
829 1463 Luisehahne
   */
830 1539 Luisehahne
  public function SmtpConnect() {
831
    if(is_null($this->smtp)) {
832 1463 Luisehahne
      $this->smtp = new SMTP();
833
    }
834
835
    $this->smtp->do_debug = $this->SMTPDebug;
836
    $hosts = explode(';', $this->Host);
837
    $index = 0;
838 1539 Luisehahne
    $connection = $this->smtp->Connected();
839 1463 Luisehahne
840 1539 Luisehahne
    // 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 1463 Luisehahne
        } else {
848 1539 Luisehahne
          $host = $hosts[$index];
849
          $port = $this->Port;
850 1463 Luisehahne
        }
851
852 1539 Luisehahne
        $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 1463 Luisehahne
          }
868 1539 Luisehahne
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 1463 Luisehahne
        }
876 1539 Luisehahne
        $index++;
877
        if (!$connection) {
878
          throw new phpmailerException($this->Lang('connect_host'));
879
        }
880 1463 Luisehahne
      }
881 1539 Luisehahne
    } catch (phpmailerException $e) {
882
      $this->smtp->Reset();
883
      throw $e;
884 1463 Luisehahne
    }
885 1539 Luisehahne
    return true;
886 1463 Luisehahne
  }
887
888
  /**
889
   * Closes the active SMTP session if one exists.
890 1539 Luisehahne
   * @return void
891 1463 Luisehahne
   */
892 1539 Luisehahne
  public function SmtpClose() {
893
    if(!is_null($this->smtp)) {
894 1463 Luisehahne
      if($this->smtp->Connected()) {
895
        $this->smtp->Quit();
896
        $this->smtp->Close();
897
      }
898
    }
899
  }
900
901
  /**
902 1539 Luisehahne
  * 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 1463 Luisehahne
  * @param string $lang_path Path to the language file directory
906
  * @access public
907 1539 Luisehahne
  */
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 1463 Luisehahne
    }
934
    $this->language = $PHPMAILER_LANG;
935 1539 Luisehahne
    return ($l == true); //Returns false if language not found
936
  }
937 1463 Luisehahne
938 1539 Luisehahne
  /**
939
  * Return the current array of language strings
940
  * @return array
941
  */
942
  public function GetTranslations() {
943
    return $this->language;
944 1463 Luisehahne
  }
945
946
  /////////////////////////////////////////////////
947
  // METHODS, MESSAGE CREATION
948
  /////////////////////////////////////////////////
949
950
  /**
951
   * Creates recipient headers.
952 1539 Luisehahne
   * @access public
953
   * @return string
954 1463 Luisehahne
   */
955 1539 Luisehahne
  public function AddrAppend($type, $addr) {
956 1463 Luisehahne
    $addr_str = $type . ': ';
957 1539 Luisehahne
    $addresses = array();
958
    foreach ($addr as $a) {
959
      $addresses[] = $this->AddrFormat($a);
960 1463 Luisehahne
    }
961 1539 Luisehahne
    $addr_str .= implode(', ', $addresses);
962 1463 Luisehahne
    $addr_str .= $this->LE;
963
964
    return $addr_str;
965
  }
966
967
  /**
968
   * Formats an address correctly.
969 1539 Luisehahne
   * @access public
970
   * @return string
971 1463 Luisehahne
   */
972 1539 Luisehahne
  public function AddrFormat($addr) {
973
    if (empty($addr[1])) {
974
      return $this->SecureHeader($addr[0]);
975 1463 Luisehahne
    } else {
976 1539 Luisehahne
      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
977 1463 Luisehahne
    }
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 1539 Luisehahne
   * @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 1463 Luisehahne
   */
990 1539 Luisehahne
  public function WrapText($message, $length, $qp_mode = false) {
991 1463 Luisehahne
    $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 1550 Luisehahne
    for ($i = 0 ;$i < count($line); $i++) {
1004 1463 Luisehahne
      $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 1539 Luisehahne
   * @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 1463 Luisehahne
   */
1072 1539 Luisehahne
  public function UTF8CharBoundary($encodedText, $maxLength) {
1073 1463 Luisehahne
    $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 1539 Luisehahne
1105 1463 Luisehahne
  /**
1106
   * Set the body wrapping.
1107 1539 Luisehahne
   * @access public
1108
   * @return void
1109 1463 Luisehahne
   */
1110 1539 Luisehahne
  public function SetWordWrap() {
1111 1463 Luisehahne
    if($this->WordWrap < 1) {
1112
      return;
1113
    }
1114
1115
    switch($this->message_type) {
1116
      case 'alt':
1117 1550 Luisehahne
      case 'alt_inline':
1118
      case 'alt_attach':
1119
      case 'alt_inline_attach':
1120 1463 Luisehahne
        $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 1539 Luisehahne
   * @access public
1131
   * @return string The assembled header
1132 1463 Luisehahne
   */
1133 1539 Luisehahne
  public function CreateHeader() {
1134 1463 Luisehahne
    $result = '';
1135
1136 1539 Luisehahne
    // Set the boundaries
1137 1463 Luisehahne
    $uniq_id = md5(uniqid(time()));
1138
    $this->boundary[1] = 'b1_' . $uniq_id;
1139
    $this->boundary[2] = 'b2_' . $uniq_id;
1140 1550 Luisehahne
    $this->boundary[3] = 'b3_' . $uniq_id;
1141 1463 Luisehahne
1142 1539 Luisehahne
    $result .= $this->HeaderLine('Date', self::RFCDate());
1143 1463 Luisehahne
    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 1539 Luisehahne
    // To be created automatically by mail()
1150 1463 Luisehahne
    if($this->Mailer != 'mail') {
1151 1539 Luisehahne
      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 1463 Luisehahne
      }
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 1539 Luisehahne
    // sendmail and mail() extract Cc from the header before sending
1170
    if(count($this->cc) > 0) {
1171 1463 Luisehahne
      $result .= $this->AddrAppend('Cc', $this->cc);
1172
    }
1173
1174 1539 Luisehahne
    // sendmail and mail() extract Bcc from the header before sending
1175 1463 Luisehahne
    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 1539 Luisehahne
      $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
1181 1463 Luisehahne
    }
1182
1183 1539 Luisehahne
    // mail() sets the subject itself
1184 1463 Luisehahne
    if($this->Mailer != 'mail') {
1185
      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
1186
    }
1187
1188
    if($this->MessageID != '') {
1189 1550 Luisehahne
      $result .= $this->HeaderLine('Message-ID', $this->MessageID);
1190 1463 Luisehahne
    } 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 1550 Luisehahne
    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 1463 Luisehahne
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 1539 Luisehahne
   * @access public
1219
   * @return string
1220 1463 Luisehahne
   */
1221 1539 Luisehahne
  public function GetMailMIME() {
1222 1463 Luisehahne
    $result = '';
1223
    switch($this->message_type) {
1224
      case 'plain':
1225
        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
1226 1550 Luisehahne
        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"');
1227 1463 Luisehahne
        break;
1228 1550 Luisehahne
      case 'inline':
1229
        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
1230
        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1231 1463 Luisehahne
        break;
1232 1550 Luisehahne
      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 1463 Luisehahne
      case 'alt':
1240 1550 Luisehahne
      case 'alt_inline':
1241 1463 Luisehahne
        $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 1539 Luisehahne
   * @access public
1256
   * @return string The assembled message body
1257 1463 Luisehahne
   */
1258 1539 Luisehahne
  public function CreateBody() {
1259
    $body = '';
1260
1261 1463 Luisehahne
    if ($this->sign_key_file) {
1262 1539 Luisehahne
      $body .= $this->GetMailMIME();
1263 1463 Luisehahne
    }
1264
1265
    $this->SetWordWrap();
1266
1267
    switch($this->message_type) {
1268 1550 Luisehahne
      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 1463 Luisehahne
      case 'alt':
1296 1539 Luisehahne
        $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 1463 Luisehahne
        break;
1304 1550 Luisehahne
      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 1539 Luisehahne
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1314 1550 Luisehahne
        $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 1463 Luisehahne
        break;
1319 1550 Luisehahne
      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 1539 Luisehahne
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1329 1550 Luisehahne
        $body .= $this->LE.$this->LE;
1330
        $body .= $this->EndBoundary($this->boundary[2]);
1331 1539 Luisehahne
        $body .= $this->LE;
1332 1550 Luisehahne
        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1333 1463 Luisehahne
        break;
1334 1550 Luisehahne
      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 1539 Luisehahne
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1341
        $body .= $this->LE.$this->LE;
1342 1550 Luisehahne
        $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 1539 Luisehahne
        $body .= $this->EncodeString($this->Body, $this->Encoding);
1348
        $body .= $this->LE.$this->LE;
1349 1550 Luisehahne
        $body .= $this->AttachAll("inline", $this->boundary[3]);
1350
        $body .= $this->LE;
1351 1539 Luisehahne
        $body .= $this->EndBoundary($this->boundary[2]);
1352 1550 Luisehahne
        $body .= $this->LE;
1353
        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1354 1463 Luisehahne
        break;
1355
    }
1356
1357 1539 Luisehahne
    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 1463 Luisehahne
        }
1373 1539 Luisehahne
      } catch (phpmailerException $e) {
1374
        $body = '';
1375
        if ($this->exceptions) {
1376
          throw $e;
1377
        }
1378 1463 Luisehahne
      }
1379
    }
1380
1381 1539 Luisehahne
    return $body;
1382 1463 Luisehahne
  }
1383
1384
  /**
1385
   * Returns the start of a message boundary.
1386 1550 Luisehahne
   * @access protected
1387
   * @return string
1388 1463 Luisehahne
   */
1389 1550 Luisehahne
  protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1390 1463 Luisehahne
    $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 1550 Luisehahne
    $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet);
1402 1463 Luisehahne
    $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 1550 Luisehahne
   * @access protected
1412
   * @return string
1413 1463 Luisehahne
   */
1414 1550 Luisehahne
  protected function EndBoundary($boundary) {
1415 1463 Luisehahne
    return $this->LE . '--' . $boundary . '--' . $this->LE;
1416
  }
1417
1418
  /**
1419
   * Sets the message type.
1420 1550 Luisehahne
   * @access protected
1421 1539 Luisehahne
   * @return void
1422 1463 Luisehahne
   */
1423 1550 Luisehahne
  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 1463 Luisehahne
  }
1431
1432 1539 Luisehahne
  /**
1433
   *  Returns a formatted header line.
1434
   * @access public
1435
   * @return string
1436 1463 Luisehahne
   */
1437 1539 Luisehahne
  public function HeaderLine($name, $value) {
1438 1463 Luisehahne
    return $name . ': ' . $value . $this->LE;
1439
  }
1440
1441
  /**
1442
   * Returns a formatted mail line.
1443 1539 Luisehahne
   * @access public
1444
   * @return string
1445 1463 Luisehahne
   */
1446 1539 Luisehahne
  public function TextLine($value) {
1447 1463 Luisehahne
    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 1539 Luisehahne
   * @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 1463 Luisehahne
   */
1464 1539 Luisehahne
  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 1463 Luisehahne
1474 1539 Luisehahne
      $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 1463 Luisehahne
    }
1495
    return true;
1496
  }
1497
1498
  /**
1499 1539 Luisehahne
  * Return the current array of attachments
1500
  * @return array
1501
  */
1502
  public function GetAttachments() {
1503
    return $this->attachment;
1504
  }
1505
1506
  /**
1507 1463 Luisehahne
   * Attaches all fs, string, and binary attachments to the message.
1508
   * Returns an empty string on failure.
1509 1550 Luisehahne
   * @access protected
1510 1539 Luisehahne
   * @return string
1511 1463 Luisehahne
   */
1512 1550 Luisehahne
  protected function AttachAll($disposition_type, $boundary) {
1513 1539 Luisehahne
    // Return text of body
1514 1463 Luisehahne
    $mime = array();
1515 1539 Luisehahne
    $cidUniq = array();
1516
    $incl = array();
1517 1463 Luisehahne
1518 1539 Luisehahne
    // Add all attachments
1519
    foreach ($this->attachment as $attachment) {
1520 1550 Luisehahne
      // 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 1463 Luisehahne
1530 1550 Luisehahne
        $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 1463 Luisehahne
1542 1550 Luisehahne
        $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 1463 Luisehahne
1546 1550 Luisehahne
        if($disposition == 'inline') {
1547
          $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1548
        }
1549 1463 Luisehahne
1550 1550 Luisehahne
        $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
1551 1463 Luisehahne
1552 1550 Luisehahne
        // 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 1463 Luisehahne
        }
1566
      }
1567
    }
1568
1569 1550 Luisehahne
    $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
1570 1463 Luisehahne
1571 1550 Luisehahne
    return implode("", $mime);
1572 1463 Luisehahne
  }
1573
1574
  /**
1575 1539 Luisehahne
   * 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 1550 Luisehahne
   * @access protected
1581 1539 Luisehahne
   * @return string
1582 1463 Luisehahne
   */
1583 1550 Luisehahne
  protected function EncodeFile($path, $encoding = 'base64') {
1584 1539 Luisehahne
    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 1550 Luisehahne
      if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1594 1539 Luisehahne
        $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 1550 Luisehahne
      if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1600
        set_magic_quotes_runtime($magic_quotes);
1601
      }
1602 1539 Luisehahne
      return $file_buffer;
1603
    } catch (Exception $e) {
1604
      $this->SetError($e->getMessage());
1605 1463 Luisehahne
      return '';
1606
    }
1607
  }
1608
1609
  /**
1610 1539 Luisehahne
   * 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 1463 Luisehahne
   */
1617 1550 Luisehahne
  public function EncodeString($str, $encoding = 'base64') {
1618 1463 Luisehahne
    $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 1539 Luisehahne
        //Make sure it ends with a line break
1627 1463 Luisehahne
        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 1539 Luisehahne
   * Encode a header string to best (shortest) of Q, B, quoted or none.
1645
   * @access public
1646
   * @return string
1647 1463 Luisehahne
   */
1648 1539 Luisehahne
  public function EncodeHeader($str, $position = 'text') {
1649 1463 Luisehahne
    $x = 0;
1650
1651
    switch (strtolower($position)) {
1652
      case 'phrase':
1653
        if (!preg_match('/[\200-\377]/', $str)) {
1654 1539 Luisehahne
          // Can't use addslashes as we don't know what value has magic_quotes_sybase
1655 1463 Luisehahne
          $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 1539 Luisehahne
        // Fall-through
1667 1463 Luisehahne
      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 1539 Luisehahne
    // Try to select the encoding which should produce the shortest output
1679 1463 Luisehahne
    if (strlen($str)/3 < $x) {
1680
      $encoding = 'B';
1681
      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
1682 1539 Luisehahne
        // Use a custom function which correctly encodes and wraps long
1683
        // multibyte strings without breaking lines within a character
1684 1463 Luisehahne
        $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 1539 Luisehahne
   * @access public
1706
   * @param string $str multi-byte text to wrap encode
1707
   * @return bool
1708 1463 Luisehahne
   */
1709 1539 Luisehahne
  public function HasMultiBytes($str) {
1710 1463 Luisehahne
    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 1539 Luisehahne
      return false;
1714 1463 Luisehahne
    }
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 1539 Luisehahne
   * @access public
1722
   * @param string $str multi-byte text to wrap encode
1723
   * @return string
1724 1463 Luisehahne
   */
1725 1539 Luisehahne
  public function Base64EncodeWrapMB($str) {
1726 1463 Luisehahne
    $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 1539 Luisehahne
  * 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 1463 Luisehahne
  * @return string
1764 1539 Luisehahne
  */
1765
  public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
1766 1550 Luisehahne
    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
1767 1463 Luisehahne
    $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 1539 Luisehahne
  * 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 1463 Luisehahne
   * Encode string to q encoding.
1841 1539 Luisehahne
   * @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 1463 Luisehahne
   */
1847 1550 Luisehahne
  public function EncodeQ($str, $position = 'text') {
1848 1539 Luisehahne
    // There should not be any EOL in the string
1849
    $encoded = preg_replace('/[\r\n]*/', '', $str);
1850 1463 Luisehahne
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 1539 Luisehahne
        // Replace every high ascii, control =, ? and _ characters
1860
        //TODO using /e (equivalent to eval()) is probably not a good idea
1861 1463 Luisehahne
        $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1862 1550 Luisehahne
                                "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded);
1863 1463 Luisehahne
        break;
1864
    }
1865
1866 1539 Luisehahne
    // Replace every spaces to _ (more readable than =20)
1867 1463 Luisehahne
    $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 1539 Luisehahne
   * @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 1463 Luisehahne
   */
1882 1539 Luisehahne
  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 1463 Luisehahne
  }
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 1539 Luisehahne
   * @param string $path Path to the attachment.
1902
   * @param string $cid Content ID of the attachment.  Use this to identify
1903 1463 Luisehahne
   *        the Id for accessing the image in an HTML form.
1904 1539 Luisehahne
   * @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 1463 Luisehahne
   */
1909 1539 Luisehahne
  public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1910 1463 Luisehahne
1911 1539 Luisehahne
    if ( !@is_file($path) ) {
1912 1463 Luisehahne
      $this->SetError($this->Lang('file_access') . $path);
1913
      return false;
1914
    }
1915
1916
    $filename = basename($path);
1917 1539 Luisehahne
    if ( $name == '' ) {
1918 1463 Luisehahne
      $name = $filename;
1919
    }
1920
1921 1539 Luisehahne
    // 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 1463 Luisehahne
1933
    return true;
1934
  }
1935
1936 1550 Luisehahne
  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 1463 Luisehahne
  /**
1951
   * Returns true if an inline attachment is present.
1952 1539 Luisehahne
   * @access public
1953
   * @return bool
1954 1463 Luisehahne
   */
1955 1539 Luisehahne
  public function InlineImageExists() {
1956
    foreach($this->attachment as $attachment) {
1957
      if ($attachment[6] == 'inline') {
1958
        return true;
1959 1463 Luisehahne
      }
1960
    }
1961 1539 Luisehahne
    return false;
1962 1463 Luisehahne
  }
1963
1964 1550 Luisehahne
  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 1463 Luisehahne
  /////////////////////////////////////////////////
1978
  // CLASS METHODS, MESSAGE RESET
1979
  /////////////////////////////////////////////////
1980
1981
  /**
1982
   * Clears all recipients assigned in the TO array.  Returns void.
1983 1539 Luisehahne
   * @return void
1984 1463 Luisehahne
   */
1985 1539 Luisehahne
  public function ClearAddresses() {
1986
    foreach($this->to as $to) {
1987
      unset($this->all_recipients[strtolower($to[0])]);
1988
    }
1989 1463 Luisehahne
    $this->to = array();
1990
  }
1991
1992
  /**
1993
   * Clears all recipients assigned in the CC array.  Returns void.
1994 1539 Luisehahne
   * @return void
1995 1463 Luisehahne
   */
1996 1539 Luisehahne
  public function ClearCCs() {
1997
    foreach($this->cc as $cc) {
1998
      unset($this->all_recipients[strtolower($cc[0])]);
1999
    }
2000 1463 Luisehahne
    $this->cc = array();
2001
  }
2002
2003
  /**
2004
   * Clears all recipients assigned in the BCC array.  Returns void.
2005 1539 Luisehahne
   * @return void
2006 1463 Luisehahne
   */
2007 1539 Luisehahne
  public function ClearBCCs() {
2008
    foreach($this->bcc as $bcc) {
2009
      unset($this->all_recipients[strtolower($bcc[0])]);
2010
    }
2011 1463 Luisehahne
    $this->bcc = array();
2012
  }
2013
2014
  /**
2015
   * Clears all recipients assigned in the ReplyTo array.  Returns void.
2016 1539 Luisehahne
   * @return void
2017 1463 Luisehahne
   */
2018 1539 Luisehahne
  public function ClearReplyTos() {
2019 1463 Luisehahne
    $this->ReplyTo = array();
2020
  }
2021
2022
  /**
2023
   * Clears all recipients assigned in the TO, CC and BCC
2024
   * array.  Returns void.
2025 1539 Luisehahne
   * @return void
2026 1463 Luisehahne
   */
2027 1539 Luisehahne
  public function ClearAllRecipients() {
2028 1463 Luisehahne
    $this->to = array();
2029
    $this->cc = array();
2030
    $this->bcc = array();
2031 1539 Luisehahne
    $this->all_recipients = array();
2032 1463 Luisehahne
  }
2033
2034
  /**
2035
   * Clears all previously set filesystem, string, and binary
2036
   * attachments.  Returns void.
2037 1539 Luisehahne
   * @return void
2038 1463 Luisehahne
   */
2039 1539 Luisehahne
  public function ClearAttachments() {
2040 1463 Luisehahne
    $this->attachment = array();
2041
  }
2042
2043
  /**
2044
   * Clears all custom headers.  Returns void.
2045 1539 Luisehahne
   * @return void
2046 1463 Luisehahne
   */
2047 1539 Luisehahne
  public function ClearCustomHeaders() {
2048 1463 Luisehahne
    $this->CustomHeader = array();
2049
  }
2050
2051
  /////////////////////////////////////////////////
2052
  // CLASS METHODS, MISCELLANEOUS
2053
  /////////////////////////////////////////////////
2054
2055
  /**
2056
   * Adds the error message to the error container.
2057 1539 Luisehahne
   * @access protected
2058
   * @return void
2059 1463 Luisehahne
   */
2060 1539 Luisehahne
  protected function SetError($msg) {
2061 1463 Luisehahne
    $this->error_count++;
2062 1539 Luisehahne
    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 1463 Luisehahne
    $this->ErrorInfo = $msg;
2069
  }
2070
2071
  /**
2072
   * Returns the proper RFC 822 formatted date.
2073 1539 Luisehahne
   * @access public
2074
   * @return string
2075
   * @static
2076 1463 Luisehahne
   */
2077 1539 Luisehahne
  public static function RFCDate() {
2078 1463 Luisehahne
    $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 1550 Luisehahne
   * @access protected
2090 1539 Luisehahne
   * @return string
2091 1463 Luisehahne
   */
2092 1550 Luisehahne
  protected function ServerHostname() {
2093 1539 Luisehahne
    if (!empty($this->Hostname)) {
2094 1463 Luisehahne
      $result = $this->Hostname;
2095 1539 Luisehahne
    } elseif (isset($_SERVER['SERVER_NAME'])) {
2096
      $result = $_SERVER['SERVER_NAME'];
2097 1463 Luisehahne
    } else {
2098
      $result = 'localhost.localdomain';
2099
    }
2100
2101
    return $result;
2102
  }
2103
2104
  /**
2105
   * Returns a message in the appropriate language.
2106 1550 Luisehahne
   * @access protected
2107 1539 Luisehahne
   * @return string
2108 1463 Luisehahne
   */
2109 1550 Luisehahne
  protected function Lang($key) {
2110 1463 Luisehahne
    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 1539 Luisehahne
   * @access public
2124
   * @return bool
2125 1463 Luisehahne
   */
2126 1539 Luisehahne
  public function IsError() {
2127 1463 Luisehahne
    return ($this->error_count > 0);
2128
  }
2129
2130
  /**
2131
   * Changes every end of line from CR or LF to CRLF.
2132 1550 Luisehahne
   * @access public
2133 1539 Luisehahne
   * @return string
2134 1463 Luisehahne
   */
2135 1550 Luisehahne
  public function FixEOL($str) {
2136 1463 Luisehahne
    $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 1539 Luisehahne
   * @access public
2145
   * @return void
2146 1463 Luisehahne
   */
2147 1539 Luisehahne
  public function AddCustomHeader($custom_header) {
2148 1463 Luisehahne
    $this->CustomHeader[] = explode(':', $custom_header, 2);
2149
  }
2150
2151
  /**
2152
   * Evaluates the message and returns modifications for inline images and backgrounds
2153 1539 Luisehahne
   * @access public
2154
   * @return $message
2155 1463 Luisehahne
   */
2156 1539 Luisehahne
  public function MsgHTML($message, $basedir = '') {
2157 1463 Luisehahne
    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 1550 Luisehahne
        if (!preg_match('#^[A-z]+://#', $url)) {
2162 1463 Luisehahne
          $filename = basename($url);
2163
          $directory = dirname($url);
2164 1550 Luisehahne
          ($directory == '.') ? $directory='': '';
2165 1463 Luisehahne
          $cid = 'cid:' . md5($filename);
2166 1539 Luisehahne
          $ext = pathinfo($filename, PATHINFO_EXTENSION);
2167
          $mimeType  = self::_mime_types($ext);
2168 1550 Luisehahne
          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 1463 Luisehahne
            $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 1550 Luisehahne
    $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
2179 1539 Luisehahne
    if (!empty($textMsg) && empty($this->AltBody)) {
2180 1463 Luisehahne
      $this->AltBody = html_entity_decode($textMsg);
2181
    }
2182 1539 Luisehahne
    if (empty($this->AltBody)) {
2183
      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
2184 1463 Luisehahne
    }
2185
  }
2186
2187
  /**
2188 1539 Luisehahne
   * 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 1463 Luisehahne
   */
2194 1539 Luisehahne
  public static function _mime_types($ext = '') {
2195 1463 Luisehahne
    $mimes = array(
2196 1539 Luisehahne
      'hqx'   =>  'application/mac-binhex40',
2197
      'cpt'   =>  'application/mac-compactpro',
2198
      'doc'   =>  'application/msword',
2199 1463 Luisehahne
      'bin'   =>  'application/macbinary',
2200 1539 Luisehahne
      'dms'   =>  'application/octet-stream',
2201
      'lha'   =>  'application/octet-stream',
2202
      'lzh'   =>  'application/octet-stream',
2203
      'exe'   =>  'application/octet-stream',
2204 1463 Luisehahne
      'class' =>  'application/octet-stream',
2205 1539 Luisehahne
      '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 1463 Luisehahne
      'dcr'   =>  'application/x-director',
2222
      'dir'   =>  'application/x-director',
2223 1539 Luisehahne
      'dxr'   =>  'application/x-director',
2224 1463 Luisehahne
      'dvi'   =>  'application/x-dvi',
2225
      'gtar'  =>  'application/x-gtar',
2226 1539 Luisehahne
      '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 1463 Luisehahne
      'js'    =>  'application/x-javascript',
2232 1539 Luisehahne
      '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 1463 Luisehahne
      'mid'   =>  'audio/midi',
2240
      'midi'  =>  'audio/midi',
2241 1539 Luisehahne
      'mpga'  =>  'audio/mpeg',
2242 1463 Luisehahne
      'mp2'   =>  'audio/mpeg',
2243
      'mp3'   =>  'audio/mpeg',
2244 1539 Luisehahne
      'aif'   =>  'audio/x-aiff',
2245
      'aiff'  =>  'audio/x-aiff',
2246
      'aifc'  =>  'audio/x-aiff',
2247 1463 Luisehahne
      'ram'   =>  'audio/x-pn-realaudio',
2248
      'rm'    =>  'audio/x-pn-realaudio',
2249
      'rpm'   =>  'audio/x-pn-realaudio-plugin',
2250 1539 Luisehahne
      'ra'    =>  'audio/x-realaudio',
2251 1463 Luisehahne
      'rv'    =>  'video/vnd.rn-realvideo',
2252 1539 Luisehahne
      '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 1463 Luisehahne
      'shtml' =>  'text/html',
2265 1539 Luisehahne
      'txt'   =>  'text/plain',
2266 1463 Luisehahne
      'text'  =>  'text/plain',
2267 1539 Luisehahne
      '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 1463 Luisehahne
      'word'  =>  'application/msword',
2281
      'xl'    =>  'application/excel',
2282 1539 Luisehahne
      'eml'   =>  'message/rfc822'
2283 1463 Luisehahne
    );
2284 1539 Luisehahne
    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
2285 1463 Luisehahne
  }
2286
2287
  /**
2288 1539 Luisehahne
  * Set (or reset) Class Objects (variables)
2289
  *
2290
  * Usage Example:
2291
  * $page->set('X-Priority', '3');
2292
  *
2293 1463 Luisehahne
  * @access public
2294
  * @param string $name Parameter Name
2295
  * @param mixed $value Parameter Value
2296 1539 Luisehahne
  * 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 1463 Luisehahne
   */
2321 1539 Luisehahne
  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 1550 Luisehahne
    $tmp = '';
2349
    $line = '';
2350
    for ($i = 0; $i < strlen($txt); $i++) {
2351
      $ord = ord($txt[$i]);
2352 1539 Luisehahne
      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
2353 1550 Luisehahne
        $line .= $txt[$i];
2354 1539 Luisehahne
      } else {
2355 1550 Luisehahne
        $line .= "=".sprintf("%02X", $ord);
2356 1539 Luisehahne
      }
2357 1463 Luisehahne
    }
2358 1539 Luisehahne
    return $line;
2359 1463 Luisehahne
  }
2360
2361
  /**
2362 1539 Luisehahne
   * Generate DKIM signature
2363 1463 Luisehahne
   *
2364 1539 Luisehahne
   * @access public
2365
   * @param string $s Header
2366 1463 Luisehahne
   */
2367 1539 Luisehahne
  public function DKIM_Sign($s) {
2368
    $privKeyStr = file_get_contents($this->DKIM_private);
2369 1550 Luisehahne
    if ($this->DKIM_passphrase != '') {
2370
      $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
2371 1463 Luisehahne
    } else {
2372 1539 Luisehahne
      $privKey = $privKeyStr;
2373 1463 Luisehahne
    }
2374 1539 Luisehahne
    if (openssl_sign($s, $signature, $privKey)) {
2375
      return base64_encode($signature);
2376
    }
2377 1463 Luisehahne
  }
2378
2379
  /**
2380 1539 Luisehahne
   * Generate DKIM Canonicalization Header
2381
   *
2382
   * @access public
2383
   * @param string $s Header
2384 1463 Luisehahne
   */
2385 1539 Luisehahne
  public function DKIM_HeaderC($s) {
2386 1550 Luisehahne
    $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 1539 Luisehahne
    }
2394 1550 Luisehahne
    $s = implode("\r\n", $lines);
2395 1539 Luisehahne
    return $s;
2396 1463 Luisehahne
  }
2397
2398
  /**
2399 1539 Luisehahne
   * Generate DKIM Canonicalization Body
2400 1463 Luisehahne
   *
2401 1539 Luisehahne
   * @access public
2402
   * @param string $body Message Body
2403 1463 Luisehahne
   */
2404 1539 Luisehahne
  public function DKIM_BodyC($body) {
2405
    if ($body == '') return "\r\n";
2406
    // stabilize line endings
2407 1550 Luisehahne
    $body = str_replace("\r\n", "\n", $body);
2408
    $body = str_replace("\n", "\r\n", $body);
2409 1539 Luisehahne
    // END stabilize line endings
2410 1550 Luisehahne
    while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
2411
      $body = substr($body, 0, strlen($body) - 2);
2412 1539 Luisehahne
    }
2413
    return $body;
2414 1463 Luisehahne
  }
2415
2416 1539 Luisehahne
  /**
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 1550 Luisehahne
  public function DKIM_Add($headers_line, $subject, $body) {
2425 1539 Luisehahne
    $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 1550 Luisehahne
    $headers              = explode($this->LE, $headers_line);
2431 1539 Luisehahne
    foreach($headers as $header) {
2432 1550 Luisehahne
      if (strpos($header, 'From:') === 0) {
2433
        $from_header = $header;
2434
      } elseif (strpos($header, 'To:') === 0) {
2435
        $to_header = $header;
2436 1539 Luisehahne
      }
2437
    }
2438 1550 Luisehahne
    $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 1539 Luisehahne
    $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 1550 Luisehahne
  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) {
2460 1539 Luisehahne
    if (!empty($this->action_function) && function_exists($this->action_function)) {
2461 1550 Luisehahne
      $params = array($isSent, $to, $cc, $bcc, $subject, $body);
2462
      call_user_func_array($this->action_function, $params);
2463 1539 Luisehahne
    }
2464
  }
2465 1463 Luisehahne
}
2466
2467 1539 Luisehahne
class phpmailerException extends Exception {
2468
  public function errorMessage() {
2469
    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
2470
    return $errorMsg;
2471
  }
2472
}
2473 1550 Luisehahne
?>