PageRenderTime 19ms CodeModel.GetById 5ms app.highlight 42ms RepoModel.GetById 1ms app.codeStats 1ms

/greenhouse/wp-includes/class-phpmailer.php

https://github.com/sahlal/Ubiquitous-Computing-Project-4
PHP | 3265 lines | 2008 code | 212 blank | 1045 comment | 294 complexity | 4271124f375797d87661ee9f98693463 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * PHPMailer - PHP email creation and transport class.
   4 * PHP Version 5.0.0
   5 * Version 5.2.7
   6 * @package PHPMailer
   7 * @link https://github.com/PHPMailer/PHPMailer/
   8 * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
   9 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  10 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  11 * @author Brent R. Matzelle (original founder)
  12 * @copyright 2013 Marcus Bointon
  13 * @copyright 2010 - 2012 Jim Jagielski
  14 * @copyright 2004 - 2009 Andy Prevost
  15 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  16 * @note This program is distributed in the hope that it will be useful - WITHOUT
  17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  18 * FITNESS FOR A PARTICULAR PURPOSE.
  19 */
  20
  21if (version_compare(PHP_VERSION, '5.0.0', '<')) {
  22    exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n");
  23}
  24
  25/**
  26 * PHPMailer - PHP email creation and transport class.
  27 * PHP Version 5.0.0
  28 * @package PHPMailer
  29 * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
  30 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  31 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  32 * @author Brent R. Matzelle (original founder)
  33 * @copyright 2013 Marcus Bointon
  34 * @copyright 2010 - 2012 Jim Jagielski
  35 * @copyright 2004 - 2009 Andy Prevost
  36 */
  37class PHPMailer
  38{
  39    /**
  40     * The PHPMailer Version number.
  41     * @type string
  42     */
  43    public $Version = '5.2.7';
  44
  45    /**
  46     * Email priority.
  47     * Options: 1 = High, 3 = Normal, 5 = low.
  48     * @type int
  49     */
  50    public $Priority = 3;
  51
  52    /**
  53     * The character set of the message.
  54     * @type string
  55     */
  56    public $CharSet = 'iso-8859-1';
  57
  58    /**
  59     * The MIME Content-type of the message.
  60     * @type string
  61     */
  62    public $ContentType = 'text/plain';
  63
  64    /**
  65     * The message encoding.
  66     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  67     * @type string
  68     */
  69    public $Encoding = '8bit';
  70
  71    /**
  72     * Holds the most recent mailer error message.
  73     * @type string
  74     */
  75    public $ErrorInfo = '';
  76
  77    /**
  78     * The From email address for the message.
  79     * @type string
  80     */
  81    public $From = 'root@localhost';
  82
  83    /**
  84     * The From name of the message.
  85     * @type string
  86     */
  87    public $FromName = 'Root User';
  88
  89    /**
  90     * The Sender email (Return-Path) of the message.
  91     * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  92     * @type string
  93     */
  94    public $Sender = '';
  95
  96    /**
  97     * The Return-Path of the message.
  98     * If empty, it will be set to either From or Sender.
  99     * @type string
 100     */
 101    public $ReturnPath = '';
 102
 103    /**
 104     * The Subject of the message.
 105     * @type string
 106     */
 107    public $Subject = '';
 108
 109    /**
 110     * An HTML or plain text message body.
 111     * If HTML then call isHTML(true).
 112     * @type string
 113     */
 114    public $Body = '';
 115
 116    /**
 117     * The plain-text message body.
 118     * This body can be read by mail clients that do not have HTML email
 119     * capability such as mutt & Eudora.
 120     * Clients that can read HTML will view the normal Body.
 121     * @type string
 122     */
 123    public $AltBody = '';
 124
 125    /**
 126     * An iCal message part body.
 127     * Only supported in simple alt or alt_inline message types
 128     * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
 129     * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
 130     * @link http://kigkonsult.se/iCalcreator/
 131     * @type string
 132     */
 133    public $Ical = '';
 134
 135    /**
 136     * The complete compiled MIME message body.
 137     * @access protected
 138     * @type string
 139     */
 140    protected $MIMEBody = '';
 141
 142    /**
 143     * The complete compiled MIME message headers.
 144     * @type string
 145     * @access protected
 146     */
 147    protected $MIMEHeader = '';
 148
 149    /**
 150     * Extra headers that createHeader() doesn't fold in.
 151     * @type string
 152     * @access protected
 153     */
 154    protected $mailHeader = '';
 155
 156    /**
 157     * Word-wrap the message body to this number of chars.
 158     * @type int
 159     */
 160    public $WordWrap = 0;
 161
 162    /**
 163     * Which method to use to send mail.
 164     * Options: "mail", "sendmail", or "smtp".
 165     * @type string
 166     */
 167    public $Mailer = 'mail';
 168
 169    /**
 170     * The path to the sendmail program.
 171     * @type string
 172     */
 173    public $Sendmail = '/usr/sbin/sendmail';
 174
 175    /**
 176     * Whether mail() uses a fully sendmail-compatible MTA.
 177     * One which supports sendmail's "-oi -f" options.
 178     * @type bool
 179     */
 180    public $UseSendmailOptions = true;
 181
 182    /**
 183     * Path to PHPMailer plugins.
 184     * Useful if the SMTP class is not in the PHP include path.
 185     * @type string
 186     * @deprecated Should not be needed now there is an autoloader.
 187     */
 188    public $PluginDir = '';
 189
 190    /**
 191     * The email address that a reading confirmation should be sent to.
 192     * @type string
 193     */
 194    public $ConfirmReadingTo = '';
 195
 196    /**
 197     * The hostname to use in Message-Id and Received headers
 198     * and as default HELO string.
 199     * If empty, the value returned
 200     * by SERVER_NAME is used or 'localhost.localdomain'.
 201     * @type string
 202     */
 203    public $Hostname = '';
 204
 205    /**
 206     * An ID to be used in the Message-Id header.
 207     * If empty, a unique id will be generated.
 208     * @type string
 209     */
 210    public $MessageID = '';
 211
 212    /**
 213     * The message Date to be used in the Date header.
 214     * If empty, the current date will be added.
 215     * @type string
 216     */
 217    public $MessageDate = '';
 218
 219    /**
 220     * SMTP hosts.
 221     * Either a single hostname or multiple semicolon-delimited hostnames.
 222     * You can also specify a different port
 223     * for each host by using this format: [hostname:port]
 224     * (e.g. "smtp1.example.com:25;smtp2.example.com").
 225     * Hosts will be tried in order.
 226     * @type string
 227     */
 228    public $Host = 'localhost';
 229
 230    /**
 231     * The default SMTP server port.
 232     * @type int
 233     * @Todo Why is this needed when the SMTP class takes care of it?
 234     */
 235    public $Port = 25;
 236
 237    /**
 238     * The SMTP HELO of the message.
 239     * Default is $Hostname.
 240     * @type string
 241     * @see PHPMailer::$Hostname
 242     */
 243    public $Helo = '';
 244
 245    /**
 246     * The secure connection prefix.
 247     * Options: "", "ssl" or "tls"
 248     * @type string
 249     */
 250    public $SMTPSecure = '';
 251
 252    /**
 253     * Whether to use SMTP authentication.
 254     * Uses the Username and Password properties.
 255     * @type bool
 256     * @see PHPMailer::$Username
 257     * @see PHPMailer::$Password
 258     */
 259    public $SMTPAuth = false;
 260
 261    /**
 262     * SMTP username.
 263     * @type string
 264     */
 265    public $Username = '';
 266
 267    /**
 268     * SMTP password.
 269     * @type string
 270     */
 271    public $Password = '';
 272
 273    /**
 274     * SMTP auth type.
 275     * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
 276     * @type string
 277     */
 278    public $AuthType = '';
 279
 280    /**
 281     * SMTP realm.
 282     * Used for NTLM auth
 283     * @type string
 284     */
 285    public $Realm = '';
 286
 287    /**
 288     * SMTP workstation.
 289     * Used for NTLM auth
 290     * @type string
 291     */
 292    public $Workstation = '';
 293
 294    /**
 295     * The SMTP server timeout in seconds.
 296     * @type int
 297     */
 298    public $Timeout = 10;
 299
 300    /**
 301     * SMTP class debug output mode.
 302     * Options: 0 = off, 1 = commands, 2 = commands and data
 303     * @type int
 304     * @see SMTP::$do_debug
 305     */
 306    public $SMTPDebug = 0;
 307
 308    /**
 309     * The function/method to use for debugging output.
 310     * Options: "echo" or "error_log"
 311     * @type string
 312     * @see SMTP::$Debugoutput
 313     */
 314    public $Debugoutput = "echo";
 315
 316    /**
 317     * Whether to keep SMTP connection open after each message.
 318     * If this is set to true then to close the connection
 319     * requires an explicit call to smtpClose().
 320     * @type bool
 321     */
 322    public $SMTPKeepAlive = false;
 323
 324    /**
 325     * Whether to split multiple to addresses into multiple messages
 326     * or send them all in one message.
 327     * @type bool
 328     */
 329    public $SingleTo = false;
 330
 331    /**
 332     * Storage for addresses when SingleTo is enabled.
 333     * @type array
 334     * @todo This should really not be public
 335     */
 336    public $SingleToArray = array();
 337
 338    /**
 339     * Whether to generate VERP addresses on send.
 340     * Only applicable when sending via SMTP.
 341     * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
 342     * @type bool
 343     */
 344    public $do_verp = false;
 345
 346    /**
 347     * Whether to allow sending messages with an empty body.
 348     * @type bool
 349     */
 350    public $AllowEmpty = false;
 351
 352    /**
 353     * The default line ending.
 354     * @note The default remains "\n". We force CRLF where we know
 355     *        it must be used via self::CRLF.
 356     * @type string
 357     */
 358    public $LE = "\n";
 359
 360    /**
 361     * DKIM selector.
 362     * @type string
 363     */
 364    public $DKIM_selector = '';
 365
 366    /**
 367     * DKIM Identity.
 368     * Usually the email address used as the source of the email
 369     * @type string
 370     */
 371    public $DKIM_identity = '';
 372
 373    /**
 374     * DKIM passphrase.
 375     * Used if your key is encrypted.
 376     * @type string
 377     */
 378    public $DKIM_passphrase = '';
 379
 380    /**
 381     * DKIM signing domain name.
 382     * @example 'example.com'
 383     * @type string
 384     */
 385    public $DKIM_domain = '';
 386
 387    /**
 388     * DKIM private key file path.
 389     * @type string
 390     */
 391    public $DKIM_private = '';
 392
 393    /**
 394     * Callback Action function name.
 395     *
 396     * The function that handles the result of the send email action.
 397     * It is called out by send() for each email sent.
 398     *
 399     * Value can be:
 400     * - 'function_name' for function names
 401     * - 'Class::Method' for static method calls
 402     * - array($object, 'Method') for calling methods on $object
 403     * See http://php.net/is_callable manual page for more details.
 404     *
 405     * Parameters:
 406     *   bool    $result        result of the send action
 407     *   string  $to            email address of the recipient
 408     *   string  $cc            cc email addresses
 409     *   string  $bcc           bcc email addresses
 410     *   string  $subject       the subject
 411     *   string  $body          the email body
 412     *   string  $from          email address of sender
 413     * 
 414     * @type string
 415     */
 416    public $action_function = '';
 417
 418    /**
 419     * What to use in the X-Mailer header.
 420     * Options: null for default, whitespace for none, or a string to use
 421     * @type string
 422     */
 423    public $XMailer = '';
 424
 425    /**
 426     * An instance of the SMTP sender class.
 427     * @type SMTP
 428     * @access protected
 429     */
 430    protected $smtp = null;
 431
 432    /**
 433     * The array of 'to' addresses.
 434     * @type array
 435     * @access protected
 436     */
 437    protected $to = array();
 438
 439    /**
 440     * The array of 'cc' addresses.
 441     * @type array
 442     * @access protected
 443     */
 444    protected $cc = array();
 445
 446    /**
 447     * The array of 'bcc' addresses.
 448     * @type array
 449     * @access protected
 450     */
 451    protected $bcc = array();
 452
 453    /**
 454     * The array of reply-to names and addresses.
 455     * @type array
 456     * @access protected
 457     */
 458    protected $ReplyTo = array();
 459
 460    /**
 461     * An array of all kinds of addresses.
 462     * Includes all of $to, $cc, $bcc, $replyto
 463     * @type array
 464     * @access protected
 465     */
 466    protected $all_recipients = array();
 467
 468    /**
 469     * The array of attachments.
 470     * @type array
 471     * @access protected
 472     */
 473    protected $attachment = array();
 474
 475    /**
 476     * The array of custom headers.
 477     * @type array
 478     * @access protected
 479     */
 480    protected $CustomHeader = array();
 481
 482    /**
 483     * The most recent Message-ID (including angular brackets).
 484     * @type string
 485     * @access protected
 486     */
 487    protected $lastMessageID = '';
 488
 489    /**
 490     * The message's MIME type.
 491     * @type string
 492     * @access protected
 493     */
 494    protected $message_type = '';
 495
 496    /**
 497     * The array of MIME boundary strings.
 498     * @type array
 499     * @access protected
 500     */
 501    protected $boundary = array();
 502
 503    /**
 504     * The array of available languages.
 505     * @type array
 506     * @access protected
 507     */
 508    protected $language = array();
 509
 510    /**
 511     * The number of errors encountered.
 512     * @type integer
 513     * @access protected
 514     */
 515    protected $error_count = 0;
 516
 517    /**
 518     * The S/MIME certificate file path.
 519     * @type string
 520     * @access protected
 521     */
 522    protected $sign_cert_file = '';
 523
 524    /**
 525     * The S/MIME key file path.
 526     * @type string
 527     * @access protected
 528     */
 529    protected $sign_key_file = '';
 530
 531    /**
 532     * The S/MIME password for the key.
 533     * Used only if the key is encrypted.
 534     * @type string
 535     * @access protected
 536     */
 537    protected $sign_key_pass = '';
 538
 539    /**
 540     * Whether to throw exceptions for errors.
 541     * @type bool
 542     * @access protected
 543     */
 544    protected $exceptions = false;
 545
 546    /**
 547     * Error severity: message only, continue processing
 548     */
 549    const STOP_MESSAGE = 0;
 550
 551    /**
 552     * Error severity: message, likely ok to continue processing
 553     */
 554    const STOP_CONTINUE = 1;
 555
 556    /**
 557     * Error severity: message, plus full stop, critical error reached
 558     */
 559    const STOP_CRITICAL = 2;
 560
 561    /**
 562     * SMTP RFC standard line ending
 563     */
 564    const CRLF = "\r\n";
 565
 566    /**
 567     * Constructor
 568     * @param bool $exceptions Should we throw external exceptions?
 569     */
 570    public function __construct($exceptions = false)
 571    {
 572        $this->exceptions = ($exceptions == true);
 573    }
 574
 575    /**
 576     * Destructor.
 577     */
 578    public function __destruct()
 579    {
 580        if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely
 581            $this->smtpClose();
 582        }
 583    }
 584
 585    /**
 586     * Call mail() in a safe_mode-aware fashion.
 587     * Also, unless sendmail_path points to sendmail (or something that
 588     * claims to be sendmail), don't pass params (not a perfect fix,
 589     * but it will do)
 590     * @param string $to To
 591     * @param string $subject Subject
 592     * @param string $body Message Body
 593     * @param string $header Additional Header(s)
 594     * @param string $params Params
 595     * @access private
 596     * @return bool
 597     */
 598    private function mailPassthru($to, $subject, $body, $header, $params)
 599    {
 600        if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
 601            $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header);
 602        } else {
 603            $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header, $params);
 604        }
 605        return $rt;
 606    }
 607
 608    /**
 609     * Output debugging info via user-defined method.
 610     * Only if debug output is enabled.
 611     * @see PHPMailer::$Debugoutput
 612     * @see PHPMailer::$SMTPDebug
 613     * @param string $str
 614     */
 615    protected function edebug($str)
 616    {
 617        if (!$this->SMTPDebug) {
 618            return;
 619        }
 620        switch ($this->Debugoutput) {
 621            case 'error_log':
 622                error_log($str);
 623                break;
 624            case 'html':
 625                //Cleans up output a bit for a better looking display that's HTML-safe
 626                echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet) . "<br>\n";
 627                break;
 628            case 'echo':
 629            default:
 630                //Just echoes exactly what was received
 631                echo $str;
 632        }
 633    }
 634
 635    /**
 636     * Sets message type to HTML or plain.
 637     * @param bool $ishtml True for HTML mode.
 638     * @return void
 639     */
 640    public function isHTML($ishtml = true)
 641    {
 642        if ($ishtml) {
 643            $this->ContentType = 'text/html';
 644        } else {
 645            $this->ContentType = 'text/plain';
 646        }
 647    }
 648
 649    /**
 650     * Send messages using SMTP.
 651     * @return void
 652     */
 653    public function isSMTP()
 654    {
 655        $this->Mailer = 'smtp';
 656    }
 657
 658    /**
 659     * Send messages using PHP's mail() function.
 660     * @return void
 661     */
 662    public function isMail()
 663    {
 664        $this->Mailer = 'mail';
 665    }
 666
 667    /**
 668     * Send messages using $Sendmail.
 669     * @return void
 670     */
 671    public function isSendmail()
 672    {
 673        if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
 674            $this->Sendmail = '/var/qmail/bin/sendmail';
 675        }
 676        $this->Mailer = 'sendmail';
 677    }
 678
 679    /**
 680     * Send messages using qmail.
 681     * @return void
 682     */
 683    public function isQmail()
 684    {
 685        if (stristr(ini_get('sendmail_path'), 'qmail')) {
 686            $this->Sendmail = '/var/qmail/bin/sendmail';
 687        }
 688        $this->Mailer = 'sendmail';
 689    }
 690
 691    /**
 692     * Add a "To" address.
 693     * @param string $address
 694     * @param string $name
 695     * @return bool true on success, false if address already used
 696     */
 697    public function addAddress($address, $name = '')
 698    {
 699        return $this->addAnAddress('to', $address, $name);
 700    }
 701
 702    /**
 703     * Add a "CC" address.
 704     * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
 705     * @param string $address
 706     * @param string $name
 707     * @return bool true on success, false if address already used
 708     */
 709    public function addCC($address, $name = '')
 710    {
 711        return $this->addAnAddress('cc', $address, $name);
 712    }
 713
 714    /**
 715     * Add a "BCC" address.
 716     * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
 717     * @param string $address
 718     * @param string $name
 719     * @return bool true on success, false if address already used
 720     */
 721    public function addBCC($address, $name = '')
 722    {
 723        return $this->addAnAddress('bcc', $address, $name);
 724    }
 725
 726    /**
 727     * Add a "Reply-to" address.
 728     * @param string $address
 729     * @param string $name
 730     * @return bool
 731     */
 732    public function addReplyTo($address, $name = '')
 733    {
 734        return $this->addAnAddress('Reply-To', $address, $name);
 735    }
 736
 737    /**
 738     * Add an address to one of the recipient arrays.
 739     * Addresses that have been added already return false, but do not throw exceptions
 740     * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
 741     * @param string $address The email address to send to
 742     * @param string $name
 743     * @throws phpmailerException
 744     * @return bool true on success, false if address already used or invalid in some way
 745     * @access protected
 746     */
 747    protected function addAnAddress($kind, $address, $name = '')
 748    {
 749        if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
 750            $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
 751            if ($this->exceptions) {
 752                throw new phpmailerException('Invalid recipient array: ' . $kind);
 753            }
 754            $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
 755            return false;
 756        }
 757        $address = trim($address);
 758        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 759        if (!$this->validateAddress($address)) {
 760            $this->setError($this->lang('invalid_address') . ': ' . $address);
 761            if ($this->exceptions) {
 762                throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
 763            }
 764            $this->edebug($this->lang('invalid_address') . ': ' . $address);
 765            return false;
 766        }
 767        if ($kind != 'Reply-To') {
 768            if (!isset($this->all_recipients[strtolower($address)])) {
 769                array_push($this->$kind, array($address, $name));
 770                $this->all_recipients[strtolower($address)] = true;
 771                return true;
 772            }
 773        } else {
 774            if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
 775                $this->ReplyTo[strtolower($address)] = array($address, $name);
 776                return true;
 777            }
 778        }
 779        return false;
 780    }
 781
 782    /**
 783     * Set the From and FromName properties.
 784     * @param string $address
 785     * @param string $name
 786     * @param bool $auto Whether to also set the Sender address, defaults to true
 787     * @throws phpmailerException
 788     * @return bool
 789     */
 790    public function setFrom($address, $name = '', $auto = true)
 791    {
 792        $address = trim($address);
 793        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 794        if (!$this->validateAddress($address)) {
 795            $this->setError($this->lang('invalid_address') . ': ' . $address);
 796            if ($this->exceptions) {
 797                throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
 798            }
 799            $this->edebug($this->lang('invalid_address') . ': ' . $address);
 800            return false;
 801        }
 802        $this->From = $address;
 803        $this->FromName = $name;
 804        if ($auto) {
 805            if (empty($this->Sender)) {
 806                $this->Sender = $address;
 807            }
 808        }
 809        return true;
 810    }
 811
 812    /**
 813     * Return the Message-ID header of the last email.
 814     * Technically this is the value from the last time the headers were created,
 815     * but it's also the message ID of the last sent message except in
 816     * pathological cases.
 817     * @return string
 818     */
 819    public function getLastMessageID()
 820    {
 821        return $this->lastMessageID;
 822    }
 823
 824    /**
 825     * Check that a string looks like an email address.
 826     * @param string $address The email address to check
 827     * @param string $patternselect A selector for the validation pattern to use :
 828     *   'auto' - pick best one automatically;
 829     *   'pcre8' - use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
 830     *   'pcre' - use old PCRE implementation;
 831     *   'php' - use PHP built-in FILTER_VALIDATE_EMAIL; faster, less thorough;
 832     *   'noregex' - super fast, really dumb.
 833     * @return bool
 834     * @static
 835     * @access public
 836     */
 837    public static function validateAddress($address, $patternselect = 'auto')
 838    {
 839        if ($patternselect == 'auto') {
 840            if (defined(
 841                'PCRE_VERSION'
 842            )
 843            ) { //Check this instead of extension_loaded so it works when that function is disabled
 844                if (version_compare(PCRE_VERSION, '8.0') >= 0) {
 845                    $patternselect = 'pcre8';
 846                } else {
 847                    $patternselect = 'pcre';
 848                }
 849            } else {
 850                //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
 851                if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
 852                    $patternselect = 'php';
 853                } else {
 854                    $patternselect = 'noregex';
 855                }
 856            }
 857        }
 858        switch ($patternselect) {
 859            case 'pcre8':
 860                /**
 861                 * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
 862                 * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
 863                 * not allow a@b type valid addresses :(
 864                 * @link http://squiloople.com/2009/12/20/email-address-validation/
 865                 * @copyright 2009-2010 Michael Rushton
 866                 * Feel free to use and redistribute this code. But please keep this copyright notice.
 867                 */
 868                return (bool)preg_match(
 869                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
 870                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
 871                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
 872                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
 873                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
 874                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
 875                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
 876                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
 877                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
 878                    $address
 879                );
 880                break;
 881            case 'pcre':
 882                //An older regex that doesn't need a recent PCRE
 883                return (bool)preg_match(
 884                    '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
 885                    '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
 886                    '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
 887                    '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
 888                    '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
 889                    '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
 890                    '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
 891                    '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
 892                    '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
 893                    '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
 894                    $address
 895                );
 896                break;
 897            case 'php':
 898            default:
 899                return (bool)filter_var($address, FILTER_VALIDATE_EMAIL);
 900                break;
 901            case 'noregex':
 902                //No PCRE! Do something _very_ approximate!
 903                //Check the address is 3 chars or longer and contains an @ that's not the first or last char
 904                return (strlen($address) >= 3
 905                    and strpos($address, '@') >= 1
 906                    and strpos($address, '@') != strlen($address) - 1);
 907                break;
 908        }
 909    }
 910
 911    /**
 912     * Create a message and send it.
 913     * Uses the sending method specified by $Mailer.
 914     * Returns false on error - Use the ErrorInfo variable to view description of the error.
 915     * @throws phpmailerException
 916     * @return bool
 917     */
 918    public function send()
 919    {
 920        try {
 921            if (!$this->preSend()) {
 922                return false;
 923            }
 924            return $this->postSend();
 925        } catch (phpmailerException $e) {
 926            $this->mailHeader = '';
 927            $this->setError($e->getMessage());
 928            if ($this->exceptions) {
 929                throw $e;
 930            }
 931            return false;
 932        }
 933    }
 934
 935    /**
 936     * Prepare a message for sending.
 937     * @throws phpmailerException
 938     * @return bool
 939     */
 940    public function preSend()
 941    {
 942        try {
 943            $this->mailHeader = "";
 944            if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
 945                throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
 946            }
 947
 948            // Set whether the message is multipart/alternative
 949            if (!empty($this->AltBody)) {
 950                $this->ContentType = 'multipart/alternative';
 951            }
 952
 953            $this->error_count = 0; // reset errors
 954            $this->setMessageType();
 955            // Refuse to send an empty message unless we are specifically allowing it
 956            if (!$this->AllowEmpty and empty($this->Body)) {
 957                throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
 958            }
 959
 960            $this->MIMEHeader = $this->createHeader();
 961            $this->MIMEBody = $this->createBody();
 962
 963            // To capture the complete message when using mail(), create
 964            // an extra header list which createHeader() doesn't fold in
 965            if ($this->Mailer == 'mail') {
 966                if (count($this->to) > 0) {
 967                    $this->mailHeader .= $this->addrAppend("To", $this->to);
 968                } else {
 969                    $this->mailHeader .= $this->headerLine("To", "undisclosed-recipients:;");
 970                }
 971                $this->mailHeader .= $this->headerLine(
 972                    'Subject',
 973                    $this->encodeHeader($this->secureHeader(trim($this->Subject)))
 974                );
 975            }
 976
 977            // Sign with DKIM if enabled
 978            if (!empty($this->DKIM_domain)
 979                && !empty($this->DKIM_private)
 980                && !empty($this->DKIM_selector)
 981                && !empty($this->DKIM_domain)
 982                && file_exists($this->DKIM_private)) {
 983                $header_dkim = $this->DKIM_Add(
 984                    $this->MIMEHeader . $this->mailHeader,
 985                    $this->encodeHeader($this->secureHeader($this->Subject)),
 986                    $this->MIMEBody
 987                );
 988                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
 989                    str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
 990            }
 991            return true;
 992
 993        } catch (phpmailerException $e) {
 994            $this->setError($e->getMessage());
 995            if ($this->exceptions) {
 996                throw $e;
 997            }
 998            return false;
 999        }
1000    }
1001
1002    /**
1003     * Actually send a message.
1004     * Send the email via the selected mechanism
1005     * @throws phpmailerException
1006     * @return bool
1007     */
1008    public function postSend()
1009    {
1010        try {
1011            // Choose the mailer and send through it
1012            switch ($this->Mailer) {
1013                case 'sendmail':
1014                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1015                case 'smtp':
1016                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1017                case 'mail':
1018                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1019                default:
1020                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1021            }
1022        } catch (phpmailerException $e) {
1023            $this->setError($e->getMessage());
1024            if ($this->exceptions) {
1025                throw $e;
1026            }
1027            $this->edebug($e->getMessage() . "\n");
1028        }
1029        return false;
1030    }
1031
1032    /**
1033     * Send mail using the $Sendmail program.
1034     * @param string $header The message headers
1035     * @param string $body The message body
1036     * @see PHPMailer::$Sendmail
1037     * @throws phpmailerException
1038     * @access protected
1039     * @return bool
1040     */
1041    protected function sendmailSend($header, $body)
1042    {
1043        if ($this->Sender != '') {
1044            $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1045        } else {
1046            $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
1047        }
1048        if ($this->SingleTo === true) {
1049            foreach ($this->SingleToArray as $val) {
1050                if (!@$mail = popen($sendmail, 'w')) {
1051                    throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1052                }
1053                fputs($mail, "To: " . $val . "\n");
1054                fputs($mail, $header);
1055                fputs($mail, $body);
1056                $result = pclose($mail);
1057                // implement call back function if it exists
1058                $isSent = ($result == 0) ? 1 : 0;
1059                $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1060                if ($result != 0) {
1061                    throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1062                }
1063            }
1064        } else {
1065            if (!@$mail = popen($sendmail, 'w')) {
1066                throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1067            }
1068            fputs($mail, $header);
1069            fputs($mail, $body);
1070            $result = pclose($mail);
1071            // implement call back function if it exists
1072            $isSent = ($result == 0) ? 1 : 0;
1073            $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1074            if ($result != 0) {
1075                throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1076            }
1077        }
1078        return true;
1079    }
1080
1081    /**
1082     * Send mail using the PHP mail() function.
1083     * @param string $header The message headers
1084     * @param string $body The message body
1085     * @link http://www.php.net/manual/en/book.mail.php
1086     * @throws phpmailerException
1087     * @access protected
1088     * @return bool
1089     */
1090    protected function mailSend($header, $body)
1091    {
1092        $toArr = array();
1093        foreach ($this->to as $t) {
1094            $toArr[] = $this->addrFormat($t);
1095        }
1096        $to = implode(', ', $toArr);
1097
1098        if (empty($this->Sender)) {
1099            $params = " ";
1100        } else {
1101            $params = sprintf("-f%s", $this->Sender);
1102        }
1103        if ($this->Sender != '' and !ini_get('safe_mode')) {
1104            $old_from = ini_get('sendmail_from');
1105            ini_set('sendmail_from', $this->Sender);
1106        }
1107        $rt = false;
1108        if ($this->SingleTo === true && count($toArr) > 1) {
1109            foreach ($toArr as $val) {
1110                $rt = $this->mailPassthru($val, $this->Subject, $body, $header, $params);
1111                // implement call back function if it exists
1112                $isSent = ($rt == 1) ? 1 : 0;
1113                $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1114            }
1115        } else {
1116            $rt = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1117            // implement call back function if it exists
1118            $isSent = ($rt == 1) ? 1 : 0;
1119            $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1120        }
1121        if (isset($old_from)) {
1122            ini_set('sendmail_from', $old_from);
1123        }
1124        if (!$rt) {
1125            throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
1126        }
1127        return true;
1128    }
1129
1130    /**
1131     * Get an instance to use for SMTP operations.
1132     * Override this function to load your own SMTP implementation
1133     * @return SMTP
1134     */
1135    public function getSMTPInstance()
1136    {
1137        if (!is_object($this->smtp)) {
1138            require_once 'class-smtp.php';
1139            $this->smtp = new SMTP;
1140        }
1141        return $this->smtp;
1142    }
1143
1144    /**
1145     * Send mail via SMTP.
1146     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1147     * Uses the PHPMailerSMTP class by default.
1148     * @see PHPMailer::getSMTPInstance() to use a different class.
1149     * @param string $header The message headers
1150     * @param string $body The message body
1151     * @throws phpmailerException
1152     * @uses SMTP
1153     * @access protected
1154     * @return bool
1155     */
1156    protected function smtpSend($header, $body)
1157    {
1158        $bad_rcpt = array();
1159
1160        if (!$this->smtpConnect()) {
1161            throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1162        }
1163        $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
1164        if (!$this->smtp->mail($smtp_from)) {
1165            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1166            throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1167        }
1168
1169        // Attempt to send attach all recipients
1170        foreach ($this->to as $to) {
1171            if (!$this->smtp->recipient($to[0])) {
1172                $bad_rcpt[] = $to[0];
1173                $isSent = 0;
1174            } else {
1175                $isSent = 1;
1176            }
1177            $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body, $this->From);
1178        }
1179        foreach ($this->cc as $cc) {
1180            if (!$this->smtp->recipient($cc[0])) {
1181                $bad_rcpt[] = $cc[0];
1182                $isSent = 0;
1183            } else {
1184                $isSent = 1;
1185            }
1186            $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body, $this->From);
1187        }
1188        foreach ($this->bcc as $bcc) {
1189            if (!$this->smtp->recipient($bcc[0])) {
1190                $bad_rcpt[] = $bcc[0];
1191                $isSent = 0;
1192            } else {
1193                $isSent = 1;
1194            }
1195            $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body, $this->From);
1196        }
1197
1198        if (count($bad_rcpt) > 0) { //Create error message for any bad addresses
1199            throw new phpmailerException($this->lang('recipients_failed') . implode(', ', $bad_rcpt));
1200        }
1201        if (!$this->smtp->data($header . $body)) {
1202            throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1203        }
1204        if ($this->SMTPKeepAlive == true) {
1205            $this->smtp->reset();
1206        } else {
1207            $this->smtp->quit();
1208            $this->smtp->close();
1209        }
1210        return true;
1211    }
1212
1213    /**
1214     * Initiate a connection to an SMTP server.
1215     * Returns false if the operation failed.
1216     * @param array $options An array of options compatible with stream_context_create()
1217     * @uses SMTP
1218     * @access public
1219     * @throws phpmailerException
1220     * @return bool
1221     */
1222    public function smtpConnect($options = array())
1223    {
1224        if (is_null($this->smtp)) {
1225            $this->smtp = $this->getSMTPInstance();
1226        }
1227
1228        //Already connected?
1229        if ($this->smtp->connected()) {
1230            return true;
1231        }
1232
1233        $this->smtp->setTimeout($this->Timeout);
1234        $this->smtp->setDebugLevel($this->SMTPDebug);
1235        $this->smtp->setDebugOutput($this->Debugoutput);
1236        $this->smtp->setVerp($this->do_verp);
1237        $tls = ($this->SMTPSecure == 'tls');
1238        $ssl = ($this->SMTPSecure == 'ssl');
1239        $hosts = explode(';', $this->Host);
1240        $lastexception = null;
1241
1242        foreach ($hosts as $hostentry) {
1243            $hostinfo = array();
1244            $host = $hostentry;
1245            $port = $this->Port;
1246            if (preg_match(
1247                '/^(.+):([0-9]+)$/',
1248                $hostentry,
1249                $hostinfo
1250            )
1251            ) { //If $hostentry contains 'address:port', override default
1252                $host = $hostinfo[1];
1253                $port = $hostinfo[2];
1254            }
1255            if ($this->smtp->connect(($ssl ? 'ssl://' : '') . $host, $port, $this->Timeout, $options)) {
1256                try {
1257                    if ($this->Helo) {
1258                        $hello = $this->Helo;
1259                    } else {
1260                        $hello = $this->serverHostname();
1261                    }
1262                    $this->smtp->hello($hello);
1263
1264                    if ($tls) {
1265                        if (!$this->smtp->startTLS()) {
1266                            throw new phpmailerException($this->lang('connect_host'));
1267                        }
1268                        //We must resend HELO after tls negotiation
1269                        $this->smtp->hello($hello);
1270                    }
1271                    if ($this->SMTPAuth) {
1272                        if (!$this->smtp->authenticate(
1273                            $this->Username,
1274                            $this->Password,
1275                            $this->AuthType,
1276                            $this->Realm,
1277                            $this->Workstation
1278                        )
1279                        ) {
1280                            throw new phpmailerException($this->lang('authenticate'));
1281                        }
1282                    }
1283                    return true;
1284                } catch (phpmailerException $e) {
1285                    $lastexception = $e;
1286                    //We must have connected, but then failed TLS or Auth, so close connection nicely
1287                    $this->smtp->quit();
1288                }
1289            }
1290        }
1291        //If we get here, all connection attempts have failed, so close connection hard
1292        $this->smtp->close();
1293        //As we've caught all exceptions, just report whatever the last one was
1294        if ($this->exceptions and !is_null($lastexception)) {
1295            throw $lastexception;
1296        }
1297        return false;
1298    }
1299
1300    /**
1301     * Close the active SMTP session if one exists.
1302     * @return void
1303     */
1304    public function smtpClose()
1305    {
1306        if ($this->smtp !== null) {
1307            if ($this->smtp->connected()) {
1308                $this->smtp->quit();
1309                $this->smtp->close();
1310            }
1311        }
1312    }
1313
1314    /**
1315     * Set the language for error messages.
1316     * Returns false if it cannot load the language file.
1317     * The default language is English.
1318     * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1319     * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1320     * @return bool
1321     * @access public
1322     */
1323    public function setLanguage($langcode = 'en', $lang_path = 'language/')
1324    {
1325        //Define full set of translatable strings
1326        $PHPMAILER_LANG = array(
1327            'authenticate' => 'SMTP Error: Could not authenticate.',
1328            'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1329            'data_not_accepted' => 'SMTP Error: data not accepted.',
1330            'empty_message' => 'Message body empty',
1331            'encoding' => 'Unknown encoding: ',
1332            'execute' => 'Could not execute: ',
1333            'file_access' => 'Could not access file: ',
1334            'file_open' => 'File Error: Could not open file: ',
1335            'from_failed' => 'The following From address failed: ',
1336            'instantiate' => 'Could not instantiate mail function.',
1337            'invalid_address' => 'Invalid address',
1338            'mailer_not_supported' => ' mailer is not supported.',
1339            'provide_address' => 'You must provide at least one recipient email address.',
1340            'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1341            'signing' => 'Signing Error: ',
1342            'smtp_connect_failed' => 'SMTP connect() failed.',
1343            'smtp_error' => 'SMTP server error: ',
1344            'variable_set' => 'Cannot set or reset variable: '
1345        );
1346        //Overwrite language-specific strings.
1347        //This way we'll never have missing translations - no more "language string failed to load"!
1348        $l = true;
1349        if ($langcode != 'en') { //There is no English translation file
1350            $l = @include $lang_path . 'phpmailer.lang-' . $langcode . '.php';
1351        }
1352        $this->language = $PHPMAILER_LANG;
1353        return ($l == true); //Returns false if language not found
1354    }
1355
1356    /**
1357     * Get the array of strings for the current language.
1358     * @return array
1359     */
1360    public function getTranslations()
1361    {
1362        return $this->language;
1363    }
1364
1365    /**
1366     * Create recipient headers.
1367     * @access public
1368     * @param string $type
1369     * @param array $addr An array of recipient,
1370     * where each recipient is a 2-element indexed array with element 0 containing an address
1371     * and element 1 containing a name, like:
1372     * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
1373     * @return string
1374     */
1375    public function addrAppend($type, $addr)
1376    {
1377        $addresses = array();
1378        foreach ($addr as $a) {
1379            $addresses[] = $this->addrFormat($a);
1380        }
1381        return $type . ': ' . implode(', ', $addresses) . $this->LE;
1382    }
1383
1384    /**
1385     * Format an address for use in a message header.
1386     * @access public
1387     * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
1388     *      like array('joe@example.com', 'Joe User')
1389     * @return string
1390     */
1391    public function addrFormat($addr)
1392    {
1393        if (empty($addr[1])) { // No name provided
1394            return $this->secureHeader($addr[0]);
1395        } else {
1396            return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . " <" . $this->secureHeader(
1397                $addr[0]
1398            ) . ">";
1399        }
1400    }
1401
1402    /**
1403     * Word-wrap message.
1404     * For use with mailers that do not automatically perform wrapping
1405     * and for quoted-printable encoded messages.
1406     * Original written by philippe.
1407     * @param string $message The message to wrap
1408     * @param integer $length The line length to wrap to
1409     * @param bool $qp_mode Whether to run in Quoted-Printable mode
1410     * @access public
1411     * @return string
1412     */
1413    public function wrapText($message, $length, $qp_mode = false)
1414    {
1415        $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
1416        // If utf-8 encoding is used, we will need to make sure we don't
1417        // split multibyte characters when we wrap
1418        $is_utf8 = (strtolower($this->CharSet) == "utf-8");
1419        $lelen = strlen($this->LE);
1420        $crlflen = strlen(self::CRLF);
1421
1422        $message = $this->fixEOL($message);
1423        if (substr($message, -$lelen) == $this->LE) {
1424            $message = substr($message, 0, -$lelen);
1425        }
1426
1427        $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE
1428        $message = '';
1429        for ($i = 0; $i < count($line); $i++) {
1430            $line_part = explode(' ', $line[$i]);
1431            $buf = '';
1432            for ($e = 0; $e < count($line_part); $e++) {
1433                $word = $line_part[$e];
1434                if ($qp_mode and (strlen($word) > $length)) {
1435                    $space_left = $length - strlen($buf) - $crlflen;
1436                    if ($e != 0) {
1437                        if ($space_left > 20) {
1438                            $len = $space_left;
1439                            if ($is_utf8) {
1440                                $len = $this->utf8CharBoundary($word, $len);
1441                            } elseif (substr($word, $len - 1, 1) == "=") {
1442                                $len--;
1443                            } elseif (substr($word, $len - 2, 1) == "=") {
1444                                $len -= 2;
1445                            }
1446                            $part = substr($word, 0, $len);
1447                            $word = substr($word, $len);
1448                            $buf .= ' ' . $part;
1449                            $message .= $buf . sprintf("=%s", self::CRLF);
1450                        } else {
1451                            $message .= $buf . $soft_break;
1452                        }
1453                        $buf = '';
1454                    }
1455                    while (strlen($word) > 0) {
1456                        if ($length <= 0) {
1457                            break;
1458                        }
1459                        $len = $length;
1460                        if ($is_utf8) {
1461                            $len = $this->utf8CharBoundary($word, $len);
1462                        } elseif (substr($word, $len - 1, 1) == "=") {
1463                            $len--;
1464                        } elseif (substr($word, $len - 2, 1) == "=") {
1465                            $len -= 2;
1466                        }
1467                        $part = substr($word, 0, $len);
1468                        $word = substr($word, $len);
1469
1470                        if (strlen($word) > 0) {
1471                            $message .= $part . sprintf("=%s", self::CRLF);
1472                        } else {
1473                            $buf = $part;
1474                        }
1475                    }
1476                } else {
1477                    $buf_o = $buf;
1478                    $buf .= ($e == 0) ? $word : (' ' . $word);
1479
1480                    if (strlen($buf) > $length and $buf_o != '') {
1481                        $message .= $buf_o . $soft_break;
1482                        $buf = $word;
1483                    }
1484                }
1485            }
1486            $message .= $buf . self::CRLF;
1487        }
1488
1489        return $message;
1490    }
1491
1492    /**
1493     * Find the last character boundary prior to $maxLength in a utf-8
1494     * quoted (printable) encoded string.
1495     * Original written by Colin Brown.
1496     * @access public
1497     * @param string $encodedText utf-8 QP text
1498     * @param int $maxLength   find last character boundary prior to this length
1499     * @return int
1500     */
1501    public function utf8CharBoundary($encodedText, $maxLength)
1502    {
1503        $foundSplitPos = false;
1504        $lookBack = 3;
1505        while (!$foundSplitPos) {
1506            $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1507            $encodedCharPos = strpos($lastChunk, "=");
1508            if ($encodedCharPos !== false) {
1509                // Found start of encoded character byte within $lookBack block.
1510                // Check the encoded byte value (the 2 chars after the '=')
1511                $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1512                $dec = hexdec($hex);
1513                if ($dec < 128) { // Single byte character.
1514                    // If the encoded char was found at pos 0, it will fit
1515                    // otherwise reduce maxLength to start of the encoded char
1516                    $maxLength = ($encodedCharPos == 0) ? $maxLength :
1517                        $maxLength - ($lookBack - $encodedCharPos);
1518                    $foundSplitPos = true;
1519                } elseif ($dec >= 192) { // First byte of a multi byte character
1520                    // Reduce maxLength to split at start of character
1521                    $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1522                    $foundSplitPos = true;
1523                } elseif ($dec < 192) { // Middle byte of a multi byte character, look further …

Large files files are truncated, but you can click here to view the full file