diff --git a/include/class.mailer.php b/include/class.mailer.php
index a469d5528f6598489a8a8ecd63b795594f5db322..8f22c6431f35f93fe4cdb20c504bf66e2d6f6234 100644
--- a/include/class.mailer.php
+++ b/include/class.mailer.php
@@ -65,8 +65,8 @@ class Mailer {
 
     function getFromAddress() {
 
-        if(!$this->ht['from'] && $this->getEmail())
-            $this->ht['from'] =$this->getEmail()->getAddress();
+        if(!$this->ht['from'] && ($email=$this->getEmail()))
+            $this->ht['from'] =sprintf('"%s" <%s>', ($email->getName()?$email->getName():$email->getEmail()), $email->getEmail());
 
         return $this->ht['from'];
     }
@@ -134,7 +134,7 @@ class Mailer {
         //encode the body
         $body = $mime->get($encodings);
         //encode the headers.
-        $headers = $mime->headers($headers);
+        $headers = $mime->headers($headers, true);
         if(($smtp=$this->getSMTPInfo())) { //Send via SMTP
             $mail = mail::factory('smtp',
                     array ('host' => $smtp['host'],
@@ -142,7 +142,7 @@ class Mailer {
                            'auth' => $smtp['auth'],
                            'username' => $smtp['username'],
                            'password' => $smtp['password'],
-                           'timeout'  =>20,
+                           'timeout'  => 20,
                            'debug' => false,
                            ));
 
diff --git a/include/pear/Auth/SASL.php b/include/pear/Auth/SASL.php
index 45a3f713d2e2444ed1718d7a40f2591c081209d4..5bd6eb09610106ed1d6315d83c0589754ebef6ac 100644
--- a/include/pear/Auth/SASL.php
+++ b/include/pear/Auth/SASL.php
@@ -1,99 +1,125 @@
-<?php
-// +-----------------------------------------------------------------------+ 
-// | Copyright (c) 2002-2003 Richard Heyes                                 | 
-// | All rights reserved.                                                  | 
-// |                                                                       | 
-// | Redistribution and use in source and binary forms, with or without    | 
-// | modification, are permitted provided that the following conditions    | 
-// | are met:                                                              | 
-// |                                                                       | 
-// | o Redistributions of source code must retain the above copyright      | 
-// |   notice, this list of conditions and the following disclaimer.       | 
-// | o Redistributions in binary form must reproduce the above copyright   | 
-// |   notice, this list of conditions and the following disclaimer in the | 
-// |   documentation and/or other materials provided with the distribution.| 
-// | o The names of the authors may not be used to endorse or promote      | 
-// |   products derived from this software without specific prior written  | 
-// |   permission.                                                         | 
-// |                                                                       | 
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
-// |                                                                       | 
-// +-----------------------------------------------------------------------+ 
-// | Author: Richard Heyes <richard@php.net>                               | 
-// +-----------------------------------------------------------------------+ 
-// 
-// $Id: SASL.php,v 1.5 2006/03/22 05:20:11 amistry Exp $
-
-/**
-* Client implementation of various SASL mechanisms 
-*
-* @author  Richard Heyes <richard@php.net>
-* @access  public
-* @version 1.0
-* @package Auth_SASL
-*/
-
-require_once('PEAR.php');
-
-class Auth_SASL
-{
-    /**
-    * Factory class. Returns an object of the request
-    * type.
-    *
-    * @param string $type One of: Anonymous
-    *                             Plain
-    *                             CramMD5
-    *                             DigestMD5
-    *                     Types are not case sensitive
-    */
-    function &factory($type)
-    {
-        switch (strtolower($type)) {
-            case 'anonymous':
-                $filename  = 'Auth/SASL/Anonymous.php';
-                $classname = 'Auth_SASL_Anonymous';
-                break;
-
-            case 'login':
-                $filename  = 'Auth/SASL/Login.php';
-                $classname = 'Auth_SASL_Login';
-                break;
-
-            case 'plain':
-                $filename  = 'Auth/SASL/Plain.php';
-                $classname = 'Auth_SASL_Plain';
-                break;
-
-            case 'crammd5':
-                $filename  = 'Auth/SASL/CramMD5.php';
-                $classname = 'Auth_SASL_CramMD5';
-                break;
-
-            case 'digestmd5':
-                $filename  = 'Auth/SASL/DigestMD5.php';
-                $classname = 'Auth_SASL_DigestMD5';
-                break;
-
-            default:
-                return PEAR::raiseError('Invalid SASL mechanism type');
-                break;
-        }
-
-        require_once($filename);
-        $obj = new $classname();
-        return $obj;
-    }
-}
-
-?>
\ No newline at end of file
+<?php
+// +-----------------------------------------------------------------------+
+// | Copyright (c) 2002-2003 Richard Heyes                                 |
+// | All rights reserved.                                                  |
+// |                                                                       |
+// | Redistribution and use in source and binary forms, with or without    |
+// | modification, are permitted provided that the following conditions    |
+// | are met:                                                              |
+// |                                                                       |
+// | o Redistributions of source code must retain the above copyright      |
+// |   notice, this list of conditions and the following disclaimer.       |
+// | o Redistributions in binary form must reproduce the above copyright   |
+// |   notice, this list of conditions and the following disclaimer in the |
+// |   documentation and/or other materials provided with the distribution.|
+// | o The names of the authors may not be used to endorse or promote      |
+// |   products derived from this software without specific prior written  |
+// |   permission.                                                         |
+// |                                                                       |
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
+// |                                                                       |
+// +-----------------------------------------------------------------------+
+// | Author: Richard Heyes <richard@php.net>                               |
+// +-----------------------------------------------------------------------+
+//
+// $Id$
+
+/**
+* Client implementation of various SASL mechanisms
+*
+* @author  Richard Heyes <richard@php.net>
+* @access  public
+* @version 1.0
+* @package Auth_SASL
+*/
+
+require_once('PEAR.php');
+
+class Auth_SASL
+{
+    /**
+    * Factory class. Returns an object of the request
+    * type.
+    *
+    * @param string $type One of: Anonymous
+    *                             Plain
+    *                             CramMD5
+    *                             DigestMD5
+    *                             SCRAM-* (any mechanism of the SCRAM family)
+    *                     Types are not case sensitive
+    */
+    function &factory($type)
+    {
+        switch (strtolower($type)) {
+            case 'anonymous':
+                $filename  = 'Auth/SASL/Anonymous.php';
+                $classname = 'Auth_SASL_Anonymous';
+                break;
+
+            case 'login':
+                $filename  = 'Auth/SASL/Login.php';
+                $classname = 'Auth_SASL_Login';
+                break;
+
+            case 'plain':
+                $filename  = 'Auth/SASL/Plain.php';
+                $classname = 'Auth_SASL_Plain';
+                break;
+
+            case 'external':
+                $filename  = 'Auth/SASL/External.php';
+                $classname = 'Auth_SASL_External';
+                break;
+
+            case 'crammd5':
+                // $msg = 'Deprecated mechanism name. Use IANA-registered name: CRAM-MD5.';
+                // trigger_error($msg, E_USER_DEPRECATED);
+            case 'cram-md5':
+                $filename  = 'Auth/SASL/CramMD5.php';
+                $classname = 'Auth_SASL_CramMD5';
+                break;
+
+            case 'digestmd5':
+                // $msg = 'Deprecated mechanism name. Use IANA-registered name: DIGEST-MD5.';
+                // trigger_error($msg, E_USER_DEPRECATED);
+            case 'digest-md5':
+                // $msg = 'DIGEST-MD5 is a deprecated SASL mechanism as per RFC-6331. Using it could be a security risk.';
+                // trigger_error($msg, E_USER_NOTICE);
+                $filename  = 'Auth/SASL/DigestMD5.php';
+                $classname = 'Auth_SASL_DigestMD5';
+                break;
+
+            default:
+                $scram = '/^SCRAM-(.{1,9})$/i';
+                if (preg_match($scram, $type, $matches))
+                {
+                    $hash = $matches[1];
+                    $filename = dirname(__FILE__) .'/SASL/SCRAM.php';
+                    $classname = 'Auth_SASL_SCRAM';
+                    $parameter = $hash;
+                    break;
+                }
+                return PEAR::raiseError('Invalid SASL mechanism type');
+                break;
+        }
+
+        require_once($filename);
+        if (isset($parameter))
+            $obj = new $classname($parameter);
+        else
+            $obj = new $classname();
+        return $obj;
+    }
+}
+
+?>
diff --git a/include/pear/Auth/SASL/Anonymous.php b/include/pear/Auth/SASL/Anonymous.php
index dc6511c1af248645664d969b0868f02e93b8bda3..08119093643e0468c23b00b551372ee9c2d251dd 100644
--- a/include/pear/Auth/SASL/Anonymous.php
+++ b/include/pear/Auth/SASL/Anonymous.php
@@ -1,71 +1,71 @@
-<?php
-// +-----------------------------------------------------------------------+ 
-// | Copyright (c) 2002-2003 Richard Heyes                                 | 
-// | All rights reserved.                                                  | 
-// |                                                                       | 
-// | Redistribution and use in source and binary forms, with or without    | 
-// | modification, are permitted provided that the following conditions    | 
-// | are met:                                                              | 
-// |                                                                       | 
-// | o Redistributions of source code must retain the above copyright      | 
-// |   notice, this list of conditions and the following disclaimer.       | 
-// | o Redistributions in binary form must reproduce the above copyright   | 
-// |   notice, this list of conditions and the following disclaimer in the | 
-// |   documentation and/or other materials provided with the distribution.| 
-// | o The names of the authors may not be used to endorse or promote      | 
-// |   products derived from this software without specific prior written  | 
-// |   permission.                                                         | 
-// |                                                                       | 
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
-// |                                                                       | 
-// +-----------------------------------------------------------------------+ 
-// | Author: Richard Heyes <richard@php.net>                               | 
-// +-----------------------------------------------------------------------+ 
-// 
-// $Id: Anonymous.php,v 1.4 2003/02/21 16:07:17 mj Exp $
-
-/**
-* Implmentation of ANONYMOUS SASL mechanism
-*
-* @author  Richard Heyes <richard@php.net>
-* @access  public
-* @version 1.0
-* @package Auth_SASL
-*/
-
-require_once('Auth/SASL/Common.php');
-
-class Auth_SASL_Anonymous extends Auth_SASL_Common
-{
-    /**
-    * Not much to do here except return the token supplied.
-    * No encoding, hashing or encryption takes place for this
-    * mechanism, simply one of:
-    *  o An email address
-    *  o An opaque string not containing "@" that can be interpreted
-    *    by the sysadmin
-    *  o Nothing
-    *
-    * We could have some logic here for the second option, but this
-    * would by no means create something interpretable.
-    *
-    * @param  string $token Optional email address or string to provide
-    *                       as trace information.
-    * @return string        The unaltered input token
-    */
-    function getResponse($token = '')
-    {
-        return $token;
-    }
-}
+<?php
+// +-----------------------------------------------------------------------+ 
+// | Copyright (c) 2002-2003 Richard Heyes                                 | 
+// | All rights reserved.                                                  | 
+// |                                                                       | 
+// | Redistribution and use in source and binary forms, with or without    | 
+// | modification, are permitted provided that the following conditions    | 
+// | are met:                                                              | 
+// |                                                                       | 
+// | o Redistributions of source code must retain the above copyright      | 
+// |   notice, this list of conditions and the following disclaimer.       | 
+// | o Redistributions in binary form must reproduce the above copyright   | 
+// |   notice, this list of conditions and the following disclaimer in the | 
+// |   documentation and/or other materials provided with the distribution.| 
+// | o The names of the authors may not be used to endorse or promote      | 
+// |   products derived from this software without specific prior written  | 
+// |   permission.                                                         | 
+// |                                                                       | 
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
+// |                                                                       | 
+// +-----------------------------------------------------------------------+ 
+// | Author: Richard Heyes <richard@php.net>                               | 
+// +-----------------------------------------------------------------------+ 
+// 
+// $Id$
+
+/**
+* Implmentation of ANONYMOUS SASL mechanism
+*
+* @author  Richard Heyes <richard@php.net>
+* @access  public
+* @version 1.0
+* @package Auth_SASL
+*/
+
+require_once('Auth/SASL/Common.php');
+
+class Auth_SASL_Anonymous extends Auth_SASL_Common
+{
+    /**
+    * Not much to do here except return the token supplied.
+    * No encoding, hashing or encryption takes place for this
+    * mechanism, simply one of:
+    *  o An email address
+    *  o An opaque string not containing "@" that can be interpreted
+    *    by the sysadmin
+    *  o Nothing
+    *
+    * We could have some logic here for the second option, but this
+    * would by no means create something interpretable.
+    *
+    * @param  string $token Optional email address or string to provide
+    *                       as trace information.
+    * @return string        The unaltered input token
+    */
+    function getResponse($token = '')
+    {
+        return $token;
+    }
+}
 ?>
\ No newline at end of file
diff --git a/include/pear/Auth/SASL/Common.php b/include/pear/Auth/SASL/Common.php
index f21c8cc1ce55ea7548e2a88ce96efb446ea715f7..d8c5610d1658eaafb0bcdcab018fabb96b99a307 100644
--- a/include/pear/Auth/SASL/Common.php
+++ b/include/pear/Auth/SASL/Common.php
@@ -1,38 +1,38 @@
 <?php
-// +-----------------------------------------------------------------------+ 
-// | Copyright (c) 2002-2003 Richard Heyes                                 | 
-// | All rights reserved.                                                  | 
-// |                                                                       | 
-// | Redistribution and use in source and binary forms, with or without    | 
-// | modification, are permitted provided that the following conditions    | 
-// | are met:                                                              | 
-// |                                                                       | 
-// | o Redistributions of source code must retain the above copyright      | 
-// |   notice, this list of conditions and the following disclaimer.       | 
-// | o Redistributions in binary form must reproduce the above copyright   | 
-// |   notice, this list of conditions and the following disclaimer in the | 
-// |   documentation and/or other materials provided with the distribution.| 
-// | o The names of the authors may not be used to endorse or promote      | 
-// |   products derived from this software without specific prior written  | 
-// |   permission.                                                         | 
-// |                                                                       | 
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
-// |                                                                       | 
-// +-----------------------------------------------------------------------+ 
-// | Author: Richard Heyes <richard@php.net>                               | 
-// +-----------------------------------------------------------------------+ 
-// 
-// $Id: Common.php,v 1.6 2003/02/21 16:07:17 mj Exp $
+// +-----------------------------------------------------------------------+
+// | Copyright (c) 2002-2003 Richard Heyes                                 |
+// | All rights reserved.                                                  |
+// |                                                                       |
+// | Redistribution and use in source and binary forms, with or without    |
+// | modification, are permitted provided that the following conditions    |
+// | are met:                                                              |
+// |                                                                       |
+// | o Redistributions of source code must retain the above copyright      |
+// |   notice, this list of conditions and the following disclaimer.       |
+// | o Redistributions in binary form must reproduce the above copyright   |
+// |   notice, this list of conditions and the following disclaimer in the |
+// |   documentation and/or other materials provided with the distribution.|
+// | o The names of the authors may not be used to endorse or promote      |
+// |   products derived from this software without specific prior written  |
+// |   permission.                                                         |
+// |                                                                       |
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
+// |                                                                       |
+// +-----------------------------------------------------------------------+
+// | Author: Richard Heyes <richard@php.net>                               |
+// +-----------------------------------------------------------------------+
+//
+// $Id$
 
 /**
 * Common functionality to SASL mechanisms
@@ -49,10 +49,12 @@ class Auth_SASL_Common
     * Function which implements HMAC MD5 digest
     *
     * @param  string $key  The secret key
-    * @param  string $data The data to protect
-    * @return string       The HMAC MD5 digest
+    * @param  string $data The data to hash
+    * @param  bool $raw_output Whether the digest is returned in binary or hexadecimal format.
+    *
+    * @return string       The HMAC-MD5 digest
     */
-    function _HMAC_MD5($key, $data)
+    function _HMAC_MD5($key, $data, $raw_output = FALSE)
     {
         if (strlen($key) > 64) {
             $key = pack('H32', md5($key));
@@ -66,9 +68,38 @@ class Auth_SASL_Common
         $k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);
 
         $inner  = pack('H32', md5($k_ipad . $data));
-        $digest = md5($k_opad . $inner);
+        $digest = md5($k_opad . $inner, $raw_output);
 
         return $digest;
     }
+
+    /**
+    * Function which implements HMAC-SHA-1 digest
+    *
+    * @param  string $key  The secret key
+    * @param  string $data The data to hash
+    * @param  bool $raw_output Whether the digest is returned in binary or hexadecimal format.
+    * @return string       The HMAC-SHA-1 digest
+    * @author Jehan <jehan.marmottard@gmail.com>
+    * @access protected
+    */
+    protected function _HMAC_SHA1($key, $data, $raw_output = FALSE)
+    {
+        if (strlen($key) > 64) {
+            $key = sha1($key, TRUE);
+        }
+
+        if (strlen($key) < 64) {
+            $key = str_pad($key, 64, chr(0));
+        }
+
+        $k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64);
+        $k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);
+
+        $inner  = pack('H40', sha1($k_ipad . $data));
+        $digest = sha1($k_opad . $inner, $raw_output);
+
+         return $digest;
+     }
 }
 ?>
diff --git a/include/pear/Auth/SASL/CramMD5.php b/include/pear/Auth/SASL/CramMD5.php
index 086248fee8b6d6f63d1df55d7a44d308500bb1cd..d3fbf179b2b974295d97fb4bd4ba80cda52119f5 100644
--- a/include/pear/Auth/SASL/CramMD5.php
+++ b/include/pear/Auth/SASL/CramMD5.php
@@ -1,68 +1,68 @@
-<?php
-// +-----------------------------------------------------------------------+ 
-// | Copyright (c) 2002-2003 Richard Heyes                                 | 
-// | All rights reserved.                                                  | 
-// |                                                                       | 
-// | Redistribution and use in source and binary forms, with or without    | 
-// | modification, are permitted provided that the following conditions    | 
-// | are met:                                                              | 
-// |                                                                       | 
-// | o Redistributions of source code must retain the above copyright      | 
-// |   notice, this list of conditions and the following disclaimer.       | 
-// | o Redistributions in binary form must reproduce the above copyright   | 
-// |   notice, this list of conditions and the following disclaimer in the | 
-// |   documentation and/or other materials provided with the distribution.| 
-// | o The names of the authors may not be used to endorse or promote      | 
-// |   products derived from this software without specific prior written  | 
-// |   permission.                                                         | 
-// |                                                                       | 
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
-// |                                                                       | 
-// +-----------------------------------------------------------------------+ 
-// | Author: Richard Heyes <richard@php.net>                               | 
-// +-----------------------------------------------------------------------+ 
-// 
-// $Id: CramMD5.php,v 1.4 2003/02/21 16:07:17 mj Exp $
-
-/**
-* Implmentation of CRAM-MD5 SASL mechanism
-*
-* @author  Richard Heyes <richard@php.net>
-* @access  public
-* @version 1.0
-* @package Auth_SASL
-*/
-
-require_once('Auth/SASL/Common.php');
-
-class Auth_SASL_CramMD5 extends Auth_SASL_Common
-{
-    /**
-    * Implements the CRAM-MD5 SASL mechanism
-    * This DOES NOT base64 encode the return value,
-    * you will need to do that yourself.
-    *
-    * @param string $user      Username
-    * @param string $pass      Password
-    * @param string $challenge The challenge supplied by the server.
-    *                          this should be already base64_decoded.
-    *
-    * @return string The string to pass back to the server, of the form
-    *                "<user> <digest>". This is NOT base64_encoded.
-    */
-    function getResponse($user, $pass, $challenge)
-    {
-        return $user . ' ' . $this->_HMAC_MD5($pass, $challenge);
-    }
-}
+<?php
+// +-----------------------------------------------------------------------+ 
+// | Copyright (c) 2002-2003 Richard Heyes                                 | 
+// | All rights reserved.                                                  | 
+// |                                                                       | 
+// | Redistribution and use in source and binary forms, with or without    | 
+// | modification, are permitted provided that the following conditions    | 
+// | are met:                                                              | 
+// |                                                                       | 
+// | o Redistributions of source code must retain the above copyright      | 
+// |   notice, this list of conditions and the following disclaimer.       | 
+// | o Redistributions in binary form must reproduce the above copyright   | 
+// |   notice, this list of conditions and the following disclaimer in the | 
+// |   documentation and/or other materials provided with the distribution.| 
+// | o The names of the authors may not be used to endorse or promote      | 
+// |   products derived from this software without specific prior written  | 
+// |   permission.                                                         | 
+// |                                                                       | 
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
+// |                                                                       | 
+// +-----------------------------------------------------------------------+ 
+// | Author: Richard Heyes <richard@php.net>                               | 
+// +-----------------------------------------------------------------------+ 
+// 
+// $Id$
+
+/**
+* Implmentation of CRAM-MD5 SASL mechanism
+*
+* @author  Richard Heyes <richard@php.net>
+* @access  public
+* @version 1.0
+* @package Auth_SASL
+*/
+
+require_once('Auth/SASL/Common.php');
+
+class Auth_SASL_CramMD5 extends Auth_SASL_Common
+{
+    /**
+    * Implements the CRAM-MD5 SASL mechanism
+    * This DOES NOT base64 encode the return value,
+    * you will need to do that yourself.
+    *
+    * @param string $user      Username
+    * @param string $pass      Password
+    * @param string $challenge The challenge supplied by the server.
+    *                          this should be already base64_decoded.
+    *
+    * @return string The string to pass back to the server, of the form
+    *                "<user> <digest>". This is NOT base64_encoded.
+    */
+    function getResponse($user, $pass, $challenge)
+    {
+        return $user . ' ' . $this->_HMAC_MD5($pass, $challenge);
+    }
+}
 ?>
\ No newline at end of file
diff --git a/include/pear/Auth/SASL/DigestMD5.php b/include/pear/Auth/SASL/DigestMD5.php
index e97e15daba0c01f2cc361ecffec3cd177fdb7ee0..07007b7c91f336eac1e5853dba1bae77904e99a8 100644
--- a/include/pear/Auth/SASL/DigestMD5.php
+++ b/include/pear/Auth/SASL/DigestMD5.php
@@ -32,7 +32,7 @@
 // | Author: Richard Heyes <richard@php.net>                               | 
 // +-----------------------------------------------------------------------+ 
 // 
-// $Id: DigestMD5.php,v 1.8 2006/03/22 05:20:11 amistry Exp $
+// $Id$
 
 /**
 * Implmentation of DIGEST-MD5 SASL mechanism
@@ -186,7 +186,6 @@ class Auth_SASL_DigestMD5 extends Auth_SASL_Common
 
         } else {
             $str = '';
-            mt_srand((double)microtime()*10000000);
             for ($i=0; $i<32; $i++) {
                 $str .= chr(mt_rand(0, 255));
             }
diff --git a/include/pear/Auth/SASL/External.php b/include/pear/Auth/SASL/External.php
new file mode 100644
index 0000000000000000000000000000000000000000..c5ae25e75d584a93248bb219a57c214bfcf5af80
--- /dev/null
+++ b/include/pear/Auth/SASL/External.php
@@ -0,0 +1,63 @@
+<?php
+// +-----------------------------------------------------------------------+ 
+// | Copyright (c) 2008 Christoph Schulz                                   | 
+// | All rights reserved.                                                  | 
+// |                                                                       | 
+// | Redistribution and use in source and binary forms, with or without    | 
+// | modification, are permitted provided that the following conditions    | 
+// | are met:                                                              | 
+// |                                                                       | 
+// | o Redistributions of source code must retain the above copyright      | 
+// |   notice, this list of conditions and the following disclaimer.       | 
+// | o Redistributions in binary form must reproduce the above copyright   | 
+// |   notice, this list of conditions and the following disclaimer in the | 
+// |   documentation and/or other materials provided with the distribution.| 
+// | o The names of the authors may not be used to endorse or promote      | 
+// |   products derived from this software without specific prior written  | 
+// |   permission.                                                         | 
+// |                                                                       | 
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
+// |                                                                       | 
+// +-----------------------------------------------------------------------+ 
+// | Author: Christoph Schulz <develop@kristov.de>                         | 
+// +-----------------------------------------------------------------------+ 
+// 
+// $Id$
+
+/**
+* Implmentation of EXTERNAL SASL mechanism
+*
+* @author  Christoph Schulz <develop@kristov.de>
+* @access  public
+* @version 1.0.3
+* @package Auth_SASL
+*/
+
+require_once('Auth/SASL/Common.php');
+
+class Auth_SASL_External extends Auth_SASL_Common
+{
+    /**
+    * Returns EXTERNAL response
+    *
+    * @param  string $authcid   Authentication id (username)
+    * @param  string $pass      Password
+    * @param  string $authzid   Autorization id
+    * @return string            EXTERNAL Response
+    */
+    function getResponse($authcid, $pass, $authzid = '')
+    {
+        return $authzid;
+    }
+}
+?>
diff --git a/include/pear/Auth/SASL/Login.php b/include/pear/Auth/SASL/Login.php
index bad9ab98c3d10e5869f50826f0463bc80fa428a6..918daeedd14bc380653ea0247e05dbbb8e427d37 100644
--- a/include/pear/Auth/SASL/Login.php
+++ b/include/pear/Auth/SASL/Login.php
@@ -1,65 +1,65 @@
-<?php
-// +-----------------------------------------------------------------------+ 
-// | Copyright (c) 2002-2003 Richard Heyes                                 | 
-// | All rights reserved.                                                  | 
-// |                                                                       | 
-// | Redistribution and use in source and binary forms, with or without    | 
-// | modification, are permitted provided that the following conditions    | 
-// | are met:                                                              | 
-// |                                                                       | 
-// | o Redistributions of source code must retain the above copyright      | 
-// |   notice, this list of conditions and the following disclaimer.       | 
-// | o Redistributions in binary form must reproduce the above copyright   | 
-// |   notice, this list of conditions and the following disclaimer in the | 
-// |   documentation and/or other materials provided with the distribution.| 
-// | o The names of the authors may not be used to endorse or promote      | 
-// |   products derived from this software without specific prior written  | 
-// |   permission.                                                         | 
-// |                                                                       | 
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
-// |                                                                       | 
-// +-----------------------------------------------------------------------+ 
-// | Author: Richard Heyes <richard@php.net>                               | 
-// +-----------------------------------------------------------------------+ 
-// 
-// $Id: Login.php,v 1.4 2003/02/21 16:07:17 mj Exp $
-
-/**
-* This is technically not a SASL mechanism, however
-* it's used by Net_Sieve, Net_Cyrus and potentially
-* other protocols , so here is a good place to abstract
-* it.
-*
-* @author  Richard Heyes <richard@php.net>
-* @access  public
-* @version 1.0
-* @package Auth_SASL
-*/
-
-require_once('Auth/SASL/Common.php');
-
-class Auth_SASL_Login extends Auth_SASL_Common
-{
-    /**
-    * Pseudo SASL LOGIN mechanism
-    *
-    * @param  string $user Username
-    * @param  string $pass Password
-    * @return string       LOGIN string
-    */
-    function getResponse($user, $pass)
-    {
-        return sprintf('LOGIN %s %s', $user, $pass);
-    }
-}
+<?php
+// +-----------------------------------------------------------------------+ 
+// | Copyright (c) 2002-2003 Richard Heyes                                 | 
+// | All rights reserved.                                                  | 
+// |                                                                       | 
+// | Redistribution and use in source and binary forms, with or without    | 
+// | modification, are permitted provided that the following conditions    | 
+// | are met:                                                              | 
+// |                                                                       | 
+// | o Redistributions of source code must retain the above copyright      | 
+// |   notice, this list of conditions and the following disclaimer.       | 
+// | o Redistributions in binary form must reproduce the above copyright   | 
+// |   notice, this list of conditions and the following disclaimer in the | 
+// |   documentation and/or other materials provided with the distribution.| 
+// | o The names of the authors may not be used to endorse or promote      | 
+// |   products derived from this software without specific prior written  | 
+// |   permission.                                                         | 
+// |                                                                       | 
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
+// |                                                                       | 
+// +-----------------------------------------------------------------------+ 
+// | Author: Richard Heyes <richard@php.net>                               | 
+// +-----------------------------------------------------------------------+ 
+// 
+// $Id$
+
+/**
+* This is technically not a SASL mechanism, however
+* it's used by Net_Sieve, Net_Cyrus and potentially
+* other protocols , so here is a good place to abstract
+* it.
+*
+* @author  Richard Heyes <richard@php.net>
+* @access  public
+* @version 1.0
+* @package Auth_SASL
+*/
+
+require_once('Auth/SASL/Common.php');
+
+class Auth_SASL_Login extends Auth_SASL_Common
+{
+    /**
+    * Pseudo SASL LOGIN mechanism
+    *
+    * @param  string $user Username
+    * @param  string $pass Password
+    * @return string       LOGIN string
+    */
+    function getResponse($user, $pass)
+    {
+        return sprintf('LOGIN %s %s', $user, $pass);
+    }
+}
 ?>
\ No newline at end of file
diff --git a/include/pear/Auth/SASL/Plain.php b/include/pear/Auth/SASL/Plain.php
index e4662ff700269d6eff59f509118a4f0b34c7130b..57894d04209494853e303158bfb050235f211b93 100644
--- a/include/pear/Auth/SASL/Plain.php
+++ b/include/pear/Auth/SASL/Plain.php
@@ -1,63 +1,63 @@
-<?php
-// +-----------------------------------------------------------------------+ 
-// | Copyright (c) 2002-2003 Richard Heyes                                 | 
-// | All rights reserved.                                                  | 
-// |                                                                       | 
-// | Redistribution and use in source and binary forms, with or without    | 
-// | modification, are permitted provided that the following conditions    | 
-// | are met:                                                              | 
-// |                                                                       | 
-// | o Redistributions of source code must retain the above copyright      | 
-// |   notice, this list of conditions and the following disclaimer.       | 
-// | o Redistributions in binary form must reproduce the above copyright   | 
-// |   notice, this list of conditions and the following disclaimer in the | 
-// |   documentation and/or other materials provided with the distribution.| 
-// | o The names of the authors may not be used to endorse or promote      | 
-// |   products derived from this software without specific prior written  | 
-// |   permission.                                                         | 
-// |                                                                       | 
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
-// |                                                                       | 
-// +-----------------------------------------------------------------------+ 
-// | Author: Richard Heyes <richard@php.net>                               | 
-// +-----------------------------------------------------------------------+ 
-// 
-// $Id: Plain.php,v 1.6 2003/09/11 18:53:56 mbretter Exp $
-
-/**
-* Implmentation of PLAIN SASL mechanism
-*
-* @author  Richard Heyes <richard@php.net>
-* @access  public
-* @version 1.0
-* @package Auth_SASL
-*/
-
-require_once('Auth/SASL/Common.php');
-
-class Auth_SASL_Plain extends Auth_SASL_Common
-{
-    /**
-    * Returns PLAIN response
-    *
-    * @param  string $authcid   Authentication id (username)
-    * @param  string $pass      Password
-    * @param  string $authzid   Autorization id
-    * @return string            PLAIN Response
-    */
-    function getResponse($authcid, $pass, $authzid = '')
-    {
-        return $authzid . chr(0) . $authcid . chr(0) . $pass;
-    }
-}
-?>
+<?php
+// +-----------------------------------------------------------------------+ 
+// | Copyright (c) 2002-2003 Richard Heyes                                 | 
+// | All rights reserved.                                                  | 
+// |                                                                       | 
+// | Redistribution and use in source and binary forms, with or without    | 
+// | modification, are permitted provided that the following conditions    | 
+// | are met:                                                              | 
+// |                                                                       | 
+// | o Redistributions of source code must retain the above copyright      | 
+// |   notice, this list of conditions and the following disclaimer.       | 
+// | o Redistributions in binary form must reproduce the above copyright   | 
+// |   notice, this list of conditions and the following disclaimer in the | 
+// |   documentation and/or other materials provided with the distribution.| 
+// | o The names of the authors may not be used to endorse or promote      | 
+// |   products derived from this software without specific prior written  | 
+// |   permission.                                                         | 
+// |                                                                       | 
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   | 
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     | 
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | 
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  | 
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | 
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      | 
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | 
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | 
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   | 
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | 
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  | 
+// |                                                                       | 
+// +-----------------------------------------------------------------------+ 
+// | Author: Richard Heyes <richard@php.net>                               | 
+// +-----------------------------------------------------------------------+ 
+// 
+// $Id$
+
+/**
+* Implmentation of PLAIN SASL mechanism
+*
+* @author  Richard Heyes <richard@php.net>
+* @access  public
+* @version 1.0
+* @package Auth_SASL
+*/
+
+require_once('Auth/SASL/Common.php');
+
+class Auth_SASL_Plain extends Auth_SASL_Common
+{
+    /**
+    * Returns PLAIN response
+    *
+    * @param  string $authcid   Authentication id (username)
+    * @param  string $pass      Password
+    * @param  string $authzid   Autorization id
+    * @return string            PLAIN Response
+    */
+    function getResponse($authcid, $pass, $authzid = '')
+    {
+        return $authzid . chr(0) . $authcid . chr(0) . $pass;
+    }
+}
+?>
diff --git a/include/pear/Auth/SASL/SCRAM.php b/include/pear/Auth/SASL/SCRAM.php
new file mode 100644
index 0000000000000000000000000000000000000000..cbca500e47fcb522f8929265971c84af0b3b64f2
--- /dev/null
+++ b/include/pear/Auth/SASL/SCRAM.php
@@ -0,0 +1,306 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Copyright (c) 2011 Jehan                                              |
+// | All rights reserved.                                                  |
+// |                                                                       |
+// | Redistribution and use in source and binary forms, with or without    |
+// | modification, are permitted provided that the following conditions    |
+// | are met:                                                              |
+// |                                                                       |
+// | o Redistributions of source code must retain the above copyright      |
+// |   notice, this list of conditions and the following disclaimer.       |
+// | o Redistributions in binary form must reproduce the above copyright   |
+// |   notice, this list of conditions and the following disclaimer in the |
+// |   documentation and/or other materials provided with the distribution.|
+// | o The names of the authors may not be used to endorse or promote      |
+// |   products derived from this software without specific prior written  |
+// |   permission.                                                         |
+// |                                                                       |
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
+// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
+// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
+// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
+// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
+// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
+// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
+// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
+// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
+// |                                                                       |
+// +-----------------------------------------------------------------------+
+// | Author: Jehan <jehan.marmottard@gmail.com                             |
+// +-----------------------------------------------------------------------+
+//
+// $Id$
+
+/**
+* Implementation of SCRAM-* SASL mechanisms.
+* SCRAM mechanisms have 3 main steps (initial response, response to the server challenge, then server signature
+* verification) which keep state-awareness. Therefore a single class instanciation must be done and reused for the whole
+* authentication process.
+*
+* @author  Jehan <jehan.marmottard@gmail.com>
+* @access  public
+* @version 1.0
+* @package Auth_SASL
+*/
+
+require_once('Auth/SASL/Common.php');
+
+class Auth_SASL_SCRAM extends Auth_SASL_Common
+{
+    /**
+    * Construct a SCRAM-H client where 'H' is a cryptographic hash function.
+    *
+    * @param string $hash The name cryptographic hash function 'H' as registered by IANA in the "Hash Function Textual
+    * Names" registry.
+    * @link http://www.iana.org/assignments/hash-function-text-names/hash-function-text-names.xml "Hash Function Textual
+    * Names"
+    * format of core PHP hash function.
+    * @access public
+    */
+    function __construct($hash)
+    {
+        // Though I could be strict, I will actually also accept the naming used in the PHP core hash framework.
+        // For instance "sha1" is accepted, while the registered hash name should be "SHA-1".
+        $hash = strtolower($hash);
+        $hashes = array('md2' => 'md2',
+            'md5' => 'md5',
+            'sha-1' => 'sha1',
+            'sha1' => 'sha1',
+            'sha-224' > 'sha224',
+            'sha224' > 'sha224',
+            'sha-256' => 'sha256',
+            'sha256' => 'sha256',
+            'sha-384' => 'sha384',
+            'sha384' => 'sha384',
+            'sha-512' => 'sha512',
+            'sha512' => 'sha512');
+        if (function_exists('hash_hmac') && isset($hashes[$hash]))
+        {
+            $this->hash = create_function('$data', 'return hash("' . $hashes[$hash] . '", $data, TRUE);');
+            $this->hmac = create_function('$key,$str,$raw', 'return hash_hmac("' . $hashes[$hash] . '", $str, $key, $raw);');
+        }
+        elseif ($hash == 'md5')
+        {
+            $this->hash = create_function('$data', 'return md5($data, true);');
+            $this->hmac = array($this, '_HMAC_MD5');
+        }
+        elseif (in_array($hash, array('sha1', 'sha-1')))
+        {
+            $this->hash = create_function('$data', 'return sha1($data, true);');
+            $this->hmac = array($this, '_HMAC_SHA1');
+        }
+        else
+            return PEAR::raiseError('Invalid SASL mechanism type');
+    }
+
+    /**
+    * Provides the (main) client response for SCRAM-H.
+    *
+    * @param  string $authcid   Authentication id (username)
+    * @param  string $pass      Password
+    * @param  string $challenge The challenge sent by the server.
+    * If the challenge is NULL or an empty string, the result will be the "initial response".
+    * @param  string $authzid   Authorization id (username to proxy as)
+    * @return string|false      The response (binary, NOT base64 encoded)
+    * @access public
+    */
+    public function getResponse($authcid, $pass, $challenge = NULL, $authzid = NULL)
+    {
+        $authcid = $this->_formatName($authcid);
+        if (empty($authcid))
+        {
+            return false;
+        }
+        if (!empty($authzid))
+        {
+            $authzid = $this->_formatName($authzid);
+            if (empty($authzid))
+            {
+                return false;
+            }
+        }
+
+        if (empty($challenge))
+        {
+            return $this->_generateInitialResponse($authcid, $authzid);
+        }
+        else
+        {
+            return $this->_generateResponse($challenge, $pass);
+        }
+
+    }
+
+    /**
+    * Prepare a name for inclusion in a SCRAM response.
+    *
+    * @param string $username a name to be prepared.
+    * @return string the reformated name.
+    * @access private
+    */
+    private function _formatName($username)
+    {
+        // TODO: prepare through the SASLprep profile of the stringprep algorithm.
+        // See RFC-4013.
+
+        $username = str_replace('=', '=3D', $username);
+        $username = str_replace(',', '=2C', $username);
+        return $username;
+    }
+
+    /**
+    * Generate the initial response which can be either sent directly in the first message or as a response to an empty
+    * server challenge.
+    *
+    * @param string $authcid Prepared authentication identity.
+    * @param string $authzid Prepared authorization identity.
+    * @return string The SCRAM response to send.
+    * @access private
+    */
+    private function _generateInitialResponse($authcid, $authzid)
+    {
+        $init_rep = '';
+        $gs2_cbind_flag = 'n,'; // TODO: support channel binding.
+        $this->gs2_header = $gs2_cbind_flag . (!empty($authzid)? 'a=' . $authzid : '') . ',';
+
+        // I must generate a client nonce and "save" it for later comparison on second response.
+        $this->cnonce = $this->_getCnonce();
+        // XXX: in the future, when mandatory and/or optional extensions are defined in any updated RFC,
+        // this message can be updated.
+        $this->first_message_bare = 'n=' . $authcid . ',r=' . $this->cnonce;
+        return $this->gs2_header . $this->first_message_bare;
+    }
+
+    /**
+    * Parses and verifies a non-empty SCRAM challenge.
+    *
+    * @param  string $challenge The SCRAM challenge
+    * @return string|false      The response to send; false in case of wrong challenge or if an initial response has not
+    * been generated first.
+    * @access private
+    */
+    private function _generateResponse($challenge, $password)
+    {
+        // XXX: as I don't support mandatory extension, I would fail on them.
+        // And I simply ignore any optional extension.
+        $server_message_regexp = "#^r=([\x21-\x2B\x2D-\x7E]+),s=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9]{3}=|[A-Xa-z0-9]{2}==)?),i=([0-9]*)(,[A-Za-z]=[^,])*$#";
+        if (!isset($this->cnonce, $this->gs2_header)
+            || !preg_match($server_message_regexp, $challenge, $matches))
+        {
+            return false;
+        }
+        $nonce = $matches[1];
+        $salt = base64_decode($matches[2]);
+        if (!$salt)
+        {
+            // Invalid Base64.
+            return false;
+        }
+        $i = intval($matches[3]);
+
+        $cnonce = substr($nonce, 0, strlen($this->cnonce));
+        if ($cnonce <> $this->cnonce)
+        {
+            // Invalid challenge! Are we under attack?
+            return false;
+        }
+
+        $channel_binding = 'c=' . base64_encode($this->gs2_header); // TODO: support channel binding.
+        $final_message = $channel_binding . ',r=' . $nonce; // XXX: no extension.
+
+        // TODO: $password = $this->normalize($password); // SASLprep profile of stringprep.
+        $saltedPassword = $this->hi($password, $salt, $i);
+        $this->saltedPassword = $saltedPassword;
+        $clientKey = call_user_func($this->hmac, $saltedPassword, "Client Key", TRUE);
+        $storedKey = call_user_func($this->hash, $clientKey, TRUE);
+        $authMessage = $this->first_message_bare . ',' . $challenge . ',' . $final_message;
+        $this->authMessage = $authMessage;
+        $clientSignature = call_user_func($this->hmac, $storedKey, $authMessage, TRUE);
+        $clientProof = $clientKey ^ $clientSignature;
+        $proof = ',p=' . base64_encode($clientProof);
+
+        return $final_message . $proof;
+    }
+
+    /**
+    * SCRAM has also a server verification step. On a successful outcome, it will send additional data which must
+    * absolutely be checked against this function. If this fails, the entity which we are communicating with is probably
+    * not the server as it has not access to your ServerKey.
+    *
+    * @param string $data The additional data sent along a successful outcome.
+    * @return bool Whether the server has been authenticated.
+    * If false, the client must close the connection and consider to be under a MITM attack.
+    * @access public
+    */
+    public function processOutcome($data)
+    {
+        $verifier_regexp = '#^v=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9]{3}=|[A-Xa-z0-9]{2}==)?)$#';
+        if (!isset($this->saltedPassword, $this->authMessage)
+            || !preg_match($verifier_regexp, $data, $matches))
+        {
+            // This cannot be an outcome, you never sent the challenge's response.
+            return false;
+        }
+
+        $verifier = $matches[1];
+        $proposed_serverSignature = base64_decode($verifier);
+        $serverKey = call_user_func($this->hmac, $this->saltedPassword, "Server Key", true);
+        $serverSignature = call_user_func($this->hmac, $serverKey, $this->authMessage, TRUE);
+        return ($proposed_serverSignature === $serverSignature);
+    }
+
+    /**
+    * Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
+    *
+    * @param string $str The string to hash.
+    * @param string $hash The hash value.
+    * @param int $i The iteration count.
+    * @access private
+    */
+    private function hi($str, $salt, $i)
+    {
+        $int1 = "\0\0\0\1";
+        $ui = call_user_func($this->hmac, $str, $salt . $int1, true);
+        $result = $ui;
+        for ($k = 1; $k < $i; $k++)
+        {
+            $ui = call_user_func($this->hmac, $str, $ui, true);
+            $result = $result ^ $ui;
+        }
+        return $result;
+    }
+
+
+    /**
+    * Creates the client nonce for the response
+    *
+    * @return string  The cnonce value
+    * @access private
+    * @author  Richard Heyes <richard@php.net>
+    */
+    private function _getCnonce()
+    {
+        // TODO: I reused the nonce function from the DigestMD5 class.
+        // I should probably make this a protected function in Common.
+        if (@file_exists('/dev/urandom') && $fd = @fopen('/dev/urandom', 'r')) {
+            return base64_encode(fread($fd, 32));
+
+        } elseif (@file_exists('/dev/random') && $fd = @fopen('/dev/random', 'r')) {
+            return base64_encode(fread($fd, 32));
+
+        } else {
+            $str = '';
+            for ($i=0; $i<32; $i++) {
+                $str .= chr(mt_rand(0, 255));
+            }
+
+            return base64_encode($str);
+        }
+    }
+
+}
+
+?>
diff --git a/include/pear/BUNDLE b/include/pear/BUNDLE
new file mode 100644
index 0000000000000000000000000000000000000000..22917abc2caad7086de5ea447757c18f2cd44321
--- /dev/null
+++ b/include/pear/BUNDLE
@@ -0,0 +1,13 @@
+Log of pear packages bundled with osTicket
+
+* osTicket v1.7.*
+===========================================================
+ PEAR-1.9.4 - core class
+ Mail-1.2.0
+ Mail_Mime-1.8.5 
+ Net_SMTP-1.6.1
+ Net_Socket-1.0.10
+ Auth_SASL-1.0.6
+
+-------- Changes ----------
+* Add connect() function to Mail/smtp.php
diff --git a/include/pear/Mail.php b/include/pear/Mail.php
index 7a3c70f82190e89749f7651b8d3b8b4fc4748681..75132ac2a6c3e9d99bd1784feb41154f0cd71d3d 100644
--- a/include/pear/Mail.php
+++ b/include/pear/Mail.php
@@ -1,245 +1,270 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org>                            |
-// +----------------------------------------------------------------------+
-//
-// $Id: Mail.php,v 1.20 2007/10/06 17:00:00 chagenbu Exp $
-
-require_once 'PEAR.php';
-
-/**
- * PEAR's Mail:: interface. Defines the interface for implementing
- * mailers under the PEAR hierarchy, and provides supporting functions
- * useful in multiple mailer backends.
- *
- * @access public
- * @version $Revision: 1.20 $
- * @package Mail
- */
-class Mail
-{
-    /**
-     * Line terminator used for separating header lines.
-     * @var string
-     */
-    var $sep = "\r\n";
-
-    /**
-     * Provides an interface for generating Mail:: objects of various
-     * types
-     *
-     * @param string $driver The kind of Mail:: object to instantiate.
-     * @param array  $params The parameters to pass to the Mail:: object.
-     * @return object Mail a instance of the driver class or if fails a PEAR Error
-     * @access public
-     */
-    function &factory($driver, $params = array())
-    {
-        $driver = strtolower($driver);
-        include_once 'Mail/' . $driver . '.php';
-        $class = 'Mail_' . $driver;
-        if (class_exists($class)) {
-            $mailer = new $class($params);
-            return $mailer;
-        } else {
-            return PEAR::raiseError('Unable to find class for driver ' . $driver);
-        }
-    }
-
-    /**
-     * Implements Mail::send() function using php's built-in mail()
-     * command.
-     *
-     * @param mixed $recipients Either a comma-seperated list of recipients
-     *              (RFC822 compliant), or an array of recipients,
-     *              each RFC822 valid. This may contain recipients not
-     *              specified in the headers, for Bcc:, resending
-     *              messages, etc.
-     *
-     * @param array $headers The array of headers to send with the mail, in an
-     *              associative array, where the array key is the
-     *              header name (ie, 'Subject'), and the array value
-     *              is the header value (ie, 'test'). The header
-     *              produced from those values would be 'Subject:
-     *              test'.
-     *
-     * @param string $body The full text of the message body, including any
-     *               Mime parts, etc.
-     *
-     * @return mixed Returns true on success, or a PEAR_Error
-     *               containing a descriptive error message on
-     *               failure.
-     *
-     * @access public
-     * @deprecated use Mail_mail::send instead
-     */
-    function send($recipients, $headers, $body)
-    {
-        if (!is_array($headers)) {
-            return PEAR::raiseError('$headers must be an array');
-        }
-
-        $result = $this->_sanitizeHeaders($headers);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        // if we're passed an array of recipients, implode it.
-        if (is_array($recipients)) {
-            $recipients = implode(', ', $recipients);
-        }
-
-        // get the Subject out of the headers array so that we can
-        // pass it as a seperate argument to mail().
-        $subject = '';
-        if (isset($headers['Subject'])) {
-            $subject = $headers['Subject'];
-            unset($headers['Subject']);
-        }
-
-        // flatten the headers out.
-        list(, $text_headers) = Mail::prepareHeaders($headers);
-
-        return mail($recipients, $subject, $body, $text_headers);
-    }
-
-    /**
-     * Sanitize an array of mail headers by removing any additional header
-     * strings present in a legitimate header's value.  The goal of this
-     * filter is to prevent mail injection attacks.
-     *
-     * @param array $headers The associative array of headers to sanitize.
-     *
-     * @access private
-     */
-    function _sanitizeHeaders(&$headers)
-    {
-        foreach ($headers as $key => $value) {
-            $headers[$key] =
-                preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i',
-                             null, $value);
-        }
-    }
-
-    /**
-     * Take an array of mail headers and return a string containing
-     * text usable in sending a message.
-     *
-     * @param array $headers The array of headers to prepare, in an associative
-     *              array, where the array key is the header name (ie,
-     *              'Subject'), and the array value is the header
-     *              value (ie, 'test'). The header produced from those
-     *              values would be 'Subject: test'.
-     *
-     * @return mixed Returns false if it encounters a bad address,
-     *               otherwise returns an array containing two
-     *               elements: Any From: address found in the headers,
-     *               and the plain text version of the headers.
-     * @access private
-     */
-    function prepareHeaders($headers)
-    {
-        $lines = array();
-        $from = null;
-
-        foreach ($headers as $key => $value) {
-            if (strcasecmp($key, 'From') === 0) {
-                include_once 'Mail/RFC822.php';
-                $parser = new Mail_RFC822();
-                $addresses = $parser->parseAddressList($value, 'localhost', false);
-                if (is_a($addresses, 'PEAR_Error')) {
-                    return $addresses;
-                }
-
-                $from = $addresses[0]->mailbox . '@' . $addresses[0]->host;
-
-                // Reject envelope From: addresses with spaces.
-                if (strstr($from, ' ')) {
-                    return false;
-                }
-
-                $lines[] = $key . ': ' . $value;
-            } elseif (strcasecmp($key, 'Received') === 0) {
-                $received = array();
-                if (is_array($value)) {
-                    foreach ($value as $line) {
-                        $received[] = $key . ': ' . $line;
-                    }
-                }
-                else {
-                    $received[] = $key . ': ' . $value;
-                }
-                // Put Received: headers at the top.  Spam detectors often
-                // flag messages with Received: headers after the Subject:
-                // as spam.
-                $lines = array_merge($received, $lines);
-            } else {
-                // If $value is an array (i.e., a list of addresses), convert
-                // it to a comma-delimited string of its elements (addresses).
-                if (is_array($value)) {
-                    $value = implode(', ', $value);
-                }
-                $lines[] = $key . ': ' . $value;
-            }
-        }
-
-        return array($from, join($this->sep, $lines));
-    }
-
-    /**
-     * Take a set of recipients and parse them, returning an array of
-     * bare addresses (forward paths) that can be passed to sendmail
-     * or an smtp server with the rcpt to: command.
-     *
-     * @param mixed Either a comma-seperated list of recipients
-     *              (RFC822 compliant), or an array of recipients,
-     *              each RFC822 valid.
-     *
-     * @return mixed An array of forward paths (bare addresses) or a PEAR_Error
-     *               object if the address list could not be parsed.
-     * @access private
-     */
-    function parseRecipients($recipients)
-    {
-        include_once 'Mail/RFC822.php';
-
-        // if we're passed an array, assume addresses are valid and
-        // implode them before parsing.
-        if (is_array($recipients)) {
-            $recipients = implode(', ', $recipients);
-        }
-
-        // Parse recipients, leaving out all personal info. This is
-        // for smtp recipients, etc. All relevant personal information
-        // should already be in the headers.
-        $addresses = Mail_RFC822::parseAddressList($recipients, 'localhost', false);
-
-        // If parseAddressList() returned a PEAR_Error object, just return it.
-        if (is_a($addresses, 'PEAR_Error')) {
-            return $addresses;
-        }
-
-        $recipients = array();
-        if (is_array($addresses)) {
-            foreach ($addresses as $ob) {
-                $recipients[] = $ob->mailbox . '@' . $ob->host;
-            }
-        }
-
-        return $recipients;
-    }
-
-}
+<?php
+/**
+ *  PEAR's Mail:: interface.
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2002-2007, Richard Heyes
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category    Mail
+ * @package     Mail
+ * @author      Chuck Hagenbuch <chuck@horde.org>
+ * @copyright   1997-2010 Chuck Hagenbuch
+ * @license     http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version     CVS: $Id: Mail.php 294747 2010-02-08 08:18:33Z clockwerx $
+ * @link        http://pear.php.net/package/Mail/
+ */
+
+require_once 'PEAR.php';
+
+/**
+ * PEAR's Mail:: interface. Defines the interface for implementing
+ * mailers under the PEAR hierarchy, and provides supporting functions
+ * useful in multiple mailer backends.
+ *
+ * @access public
+ * @version $Revision: 294747 $
+ * @package Mail
+ */
+class Mail
+{
+    /**
+     * Line terminator used for separating header lines.
+     * @var string
+     */
+    var $sep = "\r\n";
+
+    /**
+     * Provides an interface for generating Mail:: objects of various
+     * types
+     *
+     * @param string $driver The kind of Mail:: object to instantiate.
+     * @param array  $params The parameters to pass to the Mail:: object.
+     * @return object Mail a instance of the driver class or if fails a PEAR Error
+     * @access public
+     */
+    function &factory($driver, $params = array())
+    {
+        $driver = strtolower($driver);
+        @include_once 'Mail/' . $driver . '.php';
+        $class = 'Mail_' . $driver;
+        if (class_exists($class)) {
+            $mailer = new $class($params);
+            return $mailer;
+        } else {
+            return PEAR::raiseError('Unable to find class for driver ' . $driver);
+        }
+    }
+
+    /**
+     * Implements Mail::send() function using php's built-in mail()
+     * command.
+     *
+     * @param mixed $recipients Either a comma-seperated list of recipients
+     *              (RFC822 compliant), or an array of recipients,
+     *              each RFC822 valid. This may contain recipients not
+     *              specified in the headers, for Bcc:, resending
+     *              messages, etc.
+     *
+     * @param array $headers The array of headers to send with the mail, in an
+     *              associative array, where the array key is the
+     *              header name (ie, 'Subject'), and the array value
+     *              is the header value (ie, 'test'). The header
+     *              produced from those values would be 'Subject:
+     *              test'.
+     *
+     * @param string $body The full text of the message body, including any
+     *               Mime parts, etc.
+     *
+     * @return mixed Returns true on success, or a PEAR_Error
+     *               containing a descriptive error message on
+     *               failure.
+     *
+     * @access public
+     * @deprecated use Mail_mail::send instead
+     */
+    function send($recipients, $headers, $body)
+    {
+        if (!is_array($headers)) {
+            return PEAR::raiseError('$headers must be an array');
+        }
+
+        $result = $this->_sanitizeHeaders($headers);
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+
+        // if we're passed an array of recipients, implode it.
+        if (is_array($recipients)) {
+            $recipients = implode(', ', $recipients);
+        }
+
+        // get the Subject out of the headers array so that we can
+        // pass it as a seperate argument to mail().
+        $subject = '';
+        if (isset($headers['Subject'])) {
+            $subject = $headers['Subject'];
+            unset($headers['Subject']);
+        }
+
+        // flatten the headers out.
+        list(, $text_headers) = Mail::prepareHeaders($headers);
+
+        return mail($recipients, $subject, $body, $text_headers);
+    }
+
+    /**
+     * Sanitize an array of mail headers by removing any additional header
+     * strings present in a legitimate header's value.  The goal of this
+     * filter is to prevent mail injection attacks.
+     *
+     * @param array $headers The associative array of headers to sanitize.
+     *
+     * @access private
+     */
+    function _sanitizeHeaders(&$headers)
+    {
+        foreach ($headers as $key => $value) {
+            $headers[$key] =
+                preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i',
+                             null, $value);
+        }
+    }
+
+    /**
+     * Take an array of mail headers and return a string containing
+     * text usable in sending a message.
+     *
+     * @param array $headers The array of headers to prepare, in an associative
+     *              array, where the array key is the header name (ie,
+     *              'Subject'), and the array value is the header
+     *              value (ie, 'test'). The header produced from those
+     *              values would be 'Subject: test'.
+     *
+     * @return mixed Returns false if it encounters a bad address,
+     *               otherwise returns an array containing two
+     *               elements: Any From: address found in the headers,
+     *               and the plain text version of the headers.
+     * @access private
+     */
+    function prepareHeaders($headers)
+    {
+        $lines = array();
+        $from = null;
+
+        foreach ($headers as $key => $value) {
+            if (strcasecmp($key, 'From') === 0) {
+                include_once 'Mail/RFC822.php';
+                $parser = new Mail_RFC822();
+                $addresses = $parser->parseAddressList($value, 'localhost', false);
+                if (is_a($addresses, 'PEAR_Error')) {
+                    return $addresses;
+                }
+
+                $from = $addresses[0]->mailbox . '@' . $addresses[0]->host;
+
+                // Reject envelope From: addresses with spaces.
+                if (strstr($from, ' ')) {
+                    return false;
+                }
+
+                $lines[] = $key . ': ' . $value;
+            } elseif (strcasecmp($key, 'Received') === 0) {
+                $received = array();
+                if (is_array($value)) {
+                    foreach ($value as $line) {
+                        $received[] = $key . ': ' . $line;
+                    }
+                }
+                else {
+                    $received[] = $key . ': ' . $value;
+                }
+                // Put Received: headers at the top.  Spam detectors often
+                // flag messages with Received: headers after the Subject:
+                // as spam.
+                $lines = array_merge($received, $lines);
+            } else {
+                // If $value is an array (i.e., a list of addresses), convert
+                // it to a comma-delimited string of its elements (addresses).
+                if (is_array($value)) {
+                    $value = implode(', ', $value);
+                }
+                $lines[] = $key . ': ' . $value;
+            }
+        }
+
+        return array($from, join($this->sep, $lines));
+    }
+
+    /**
+     * Take a set of recipients and parse them, returning an array of
+     * bare addresses (forward paths) that can be passed to sendmail
+     * or an smtp server with the rcpt to: command.
+     *
+     * @param mixed Either a comma-seperated list of recipients
+     *              (RFC822 compliant), or an array of recipients,
+     *              each RFC822 valid.
+     *
+     * @return mixed An array of forward paths (bare addresses) or a PEAR_Error
+     *               object if the address list could not be parsed.
+     * @access private
+     */
+    function parseRecipients($recipients)
+    {
+        include_once 'Mail/RFC822.php';
+
+        // if we're passed an array, assume addresses are valid and
+        // implode them before parsing.
+        if (is_array($recipients)) {
+            $recipients = implode(', ', $recipients);
+        }
+
+        // Parse recipients, leaving out all personal info. This is
+        // for smtp recipients, etc. All relevant personal information
+        // should already be in the headers.
+        $addresses = Mail_RFC822::parseAddressList($recipients, 'localhost', false);
+
+        // If parseAddressList() returned a PEAR_Error object, just return it.
+        if (is_a($addresses, 'PEAR_Error')) {
+            return $addresses;
+        }
+
+        $recipients = array();
+        if (is_array($addresses)) {
+            foreach ($addresses as $ob) {
+                $recipients[] = $ob->mailbox . '@' . $ob->host;
+            }
+        }
+
+        return $recipients;
+    }
+
+}
diff --git a/include/pear/Mail/RFC822.php b/include/pear/Mail/RFC822.php
index 866638268dad6d6254280b301d9057056cbffc62..58d36465cba21779887651cec4204f222f9271ec 100644
--- a/include/pear/Mail/RFC822.php
+++ b/include/pear/Mail/RFC822.php
@@ -1,940 +1,951 @@
-<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2001-2002, Richard Heyes                                |
-// | All rights reserved.                                                  |
-// |                                                                       |
-// | Redistribution and use in source and binary forms, with or without    |
-// | modification, are permitted provided that the following conditions    |
-// | are met:                                                              |
-// |                                                                       |
-// | o Redistributions of source code must retain the above copyright      |
-// |   notice, this list of conditions and the following disclaimer.       |
-// | o Redistributions in binary form must reproduce the above copyright   |
-// |   notice, this list of conditions and the following disclaimer in the |
-// |   documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote      |
-// |   products derived from this software without specific prior written  |
-// |   permission.                                                         |
-// |                                                                       |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
-// |                                                                       |
-// +-----------------------------------------------------------------------+
-// | Authors: Richard Heyes <richard@phpguru.org>                          |
-// |          Chuck Hagenbuch <chuck@horde.org>                            |
-// +-----------------------------------------------------------------------+
-
-/**
- * RFC 822 Email address list validation Utility
- *
- * What is it?
- *
- * This class will take an address string, and parse it into it's consituent
- * parts, be that either addresses, groups, or combinations. Nested groups
- * are not supported. The structure it returns is pretty straight forward,
- * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
- * print_r() to view the structure.
- *
- * How do I use it?
- *
- * $address_string = 'My Group: "Richard" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
- * $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', true)
- * print_r($structure);
- *
- * @author  Richard Heyes <richard@phpguru.org>
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @version $Revision: 1.24 $
- * @license BSD
- * @package Mail
- */
-class Mail_RFC822 {
-
-    /**
-     * The address being parsed by the RFC822 object.
-     * @var string $address
-     */
-    var $address = '';
-
-    /**
-     * The default domain to use for unqualified addresses.
-     * @var string $default_domain
-     */
-    var $default_domain = 'localhost';
-
-    /**
-     * Should we return a nested array showing groups, or flatten everything?
-     * @var boolean $nestGroups
-     */
-    var $nestGroups = true;
-
-    /**
-     * Whether or not to validate atoms for non-ascii characters.
-     * @var boolean $validate
-     */
-    var $validate = true;
-
-    /**
-     * The array of raw addresses built up as we parse.
-     * @var array $addresses
-     */
-    var $addresses = array();
-
-    /**
-     * The final array of parsed address information that we build up.
-     * @var array $structure
-     */
-    var $structure = array();
-
-    /**
-     * The current error message, if any.
-     * @var string $error
-     */
-    var $error = null;
-
-    /**
-     * An internal counter/pointer.
-     * @var integer $index
-     */
-    var $index = null;
-
-    /**
-     * The number of groups that have been found in the address list.
-     * @var integer $num_groups
-     * @access public
-     */
-    var $num_groups = 0;
-
-    /**
-     * A variable so that we can tell whether or not we're inside a
-     * Mail_RFC822 object.
-     * @var boolean $mailRFC822
-     */
-    var $mailRFC822 = true;
-
-    /**
-    * A limit after which processing stops
-    * @var int $limit
-    */
-    var $limit = null;
-
-    /**
-     * Sets up the object. The address must either be set here or when
-     * calling parseAddressList(). One or the other.
-     *
-     * @access public
-     * @param string  $address         The address(es) to validate.
-     * @param string  $default_domain  Default domain/host etc. If not supplied, will be set to localhost.
-     * @param boolean $nest_groups     Whether to return the structure with groups nested for easier viewing.
-     * @param boolean $validate        Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
-     *
-     * @return object Mail_RFC822 A new Mail_RFC822 object.
-     */
-    function Mail_RFC822($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
-    {
-        if (isset($address))        $this->address        = $address;
-        if (isset($default_domain)) $this->default_domain = $default_domain;
-        if (isset($nest_groups))    $this->nestGroups     = $nest_groups;
-        if (isset($validate))       $this->validate       = $validate;
-        if (isset($limit))          $this->limit          = $limit;
-    }
-
-    /**
-     * Starts the whole process. The address must either be set here
-     * or when creating the object. One or the other.
-     *
-     * @access public
-     * @param string  $address         The address(es) to validate.
-     * @param string  $default_domain  Default domain/host etc.
-     * @param boolean $nest_groups     Whether to return the structure with groups nested for easier viewing.
-     * @param boolean $validate        Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
-     *
-     * @return array A structured array of addresses.
-     */
-    function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
-    {
-        if (!isset($this) || !isset($this->mailRFC822)) {
-            $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
-            return $obj->parseAddressList();
-        }
-
-        if (isset($address))        $this->address        = $address;
-        if (isset($default_domain)) $this->default_domain = $default_domain;
-        if (isset($nest_groups))    $this->nestGroups     = $nest_groups;
-        if (isset($validate))       $this->validate       = $validate;
-        if (isset($limit))          $this->limit          = $limit;
-
-        $this->structure  = array();
-        $this->addresses  = array();
-        $this->error      = null;
-        $this->index      = null;
-
-        // Unfold any long lines in $this->address.
-        $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
-        $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
-
-        while ($this->address = $this->_splitAddresses($this->address));
-
-        if ($this->address === false || isset($this->error)) {
-            require_once 'PEAR.php';
-            return PEAR::raiseError($this->error);
-        }
-
-        // Validate each address individually.  If we encounter an invalid
-        // address, stop iterating and return an error immediately.
-        foreach ($this->addresses as $address) {
-            $valid = $this->_validateAddress($address);
-
-            if ($valid === false || isset($this->error)) {
-                require_once 'PEAR.php';
-                return PEAR::raiseError($this->error);
-            }
-
-            if (!$this->nestGroups) {
-                $this->structure = array_merge($this->structure, $valid);
-            } else {
-                $this->structure[] = $valid;
-            }
-        }
-
-        return $this->structure;
-    }
-
-    /**
-     * Splits an address into separate addresses.
-     *
-     * @access private
-     * @param string $address The addresses to split.
-     * @return boolean Success or failure.
-     */
-    function _splitAddresses($address)
-    {
-        if (!empty($this->limit) && count($this->addresses) == $this->limit) {
-            return '';
-        }
-
-        if ($this->_isGroup($address) && !isset($this->error)) {
-            $split_char = ';';
-            $is_group   = true;
-        } elseif (!isset($this->error)) {
-            $split_char = ',';
-            $is_group   = false;
-        } elseif (isset($this->error)) {
-            return false;
-        }
-
-        // Split the string based on the above ten or so lines.
-        $parts  = explode($split_char, $address);
-        $string = $this->_splitCheck($parts, $split_char);
-
-        // If a group...
-        if ($is_group) {
-            // If $string does not contain a colon outside of
-            // brackets/quotes etc then something's fubar.
-
-            // First check there's a colon at all:
-            if (strpos($string, ':') === false) {
-                $this->error = 'Invalid address: ' . $string;
-                return false;
-            }
-
-            // Now check it's outside of brackets/quotes:
-            if (!$this->_splitCheck(explode(':', $string), ':')) {
-                return false;
-            }
-
-            // We must have a group at this point, so increase the counter:
-            $this->num_groups++;
-        }
-
-        // $string now contains the first full address/group.
-        // Add to the addresses array.
-        $this->addresses[] = array(
-                                   'address' => trim($string),
-                                   'group'   => $is_group
-                                   );
-
-        // Remove the now stored address from the initial line, the +1
-        // is to account for the explode character.
-        $address = trim(substr($address, strlen($string) + 1));
-
-        // If the next char is a comma and this was a group, then
-        // there are more addresses, otherwise, if there are any more
-        // chars, then there is another address.
-        if ($is_group && substr($address, 0, 1) == ','){
-            $address = trim(substr($address, 1));
-            return $address;
-
-        } elseif (strlen($address) > 0) {
-            return $address;
-
-        } else {
-            return '';
-        }
-
-        // If you got here then something's off
-        return false;
-    }
-
-    /**
-     * Checks for a group at the start of the string.
-     *
-     * @access private
-     * @param string $address The address to check.
-     * @return boolean Whether or not there is a group at the start of the string.
-     */
-    function _isGroup($address)
-    {
-        // First comma not in quotes, angles or escaped:
-        $parts  = explode(',', $address);
-        $string = $this->_splitCheck($parts, ',');
-
-        // Now we have the first address, we can reliably check for a
-        // group by searching for a colon that's not escaped or in
-        // quotes or angle brackets.
-        if (count($parts = explode(':', $string)) > 1) {
-            $string2 = $this->_splitCheck($parts, ':');
-            return ($string2 !== $string);
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * A common function that will check an exploded string.
-     *
-     * @access private
-     * @param array $parts The exloded string.
-     * @param string $char  The char that was exploded on.
-     * @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
-     */
-    function _splitCheck($parts, $char)
-    {
-        $string = $parts[0];
-
-        for ($i = 0; $i < count($parts); $i++) {
-            if ($this->_hasUnclosedQuotes($string)
-                || $this->_hasUnclosedBrackets($string, '<>')
-                || $this->_hasUnclosedBrackets($string, '[]')
-                || $this->_hasUnclosedBrackets($string, '()')
-                || substr($string, -1) == '\\') {
-                if (isset($parts[$i + 1])) {
-                    $string = $string . $char . $parts[$i + 1];
-                } else {
-                    $this->error = 'Invalid address spec. Unclosed bracket or quotes';
-                    return false;
-                }
-            } else {
-                $this->index = $i;
-                break;
-            }
-        }
-
-        return $string;
-    }
-
-    /**
-     * Checks if a string has unclosed quotes or not.
-     *
-     * @access private
-     * @param string $string  The string to check.
-     * @return boolean  True if there are unclosed quotes inside the string,
-     *                  false otherwise.
-     */
-    function _hasUnclosedQuotes($string)
-    {
-        $string = trim($string);
-        $iMax = strlen($string);
-        $in_quote = false;
-        $i = $slashes = 0;
-
-        for (; $i < $iMax; ++$i) {
-            switch ($string[$i]) {
-            case '\\':
-                ++$slashes;
-                break;
-
-            case '"':
-                if ($slashes % 2 == 0) {
-                    $in_quote = !$in_quote;
-                }
-                // Fall through to default action below.
-
-            default:
-                $slashes = 0;
-                break;
-            }
-        }
-
-        return $in_quote;
-    }
-
-    /**
-     * Checks if a string has an unclosed brackets or not. IMPORTANT:
-     * This function handles both angle brackets and square brackets;
-     *
-     * @access private
-     * @param string $string The string to check.
-     * @param string $chars  The characters to check for.
-     * @return boolean True if there are unclosed brackets inside the string, false otherwise.
-     */
-    function _hasUnclosedBrackets($string, $chars)
-    {
-        $num_angle_start = substr_count($string, $chars[0]);
-        $num_angle_end   = substr_count($string, $chars[1]);
-
-        $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
-        $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
-
-        if ($num_angle_start < $num_angle_end) {
-            $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
-            return false;
-        } else {
-            return ($num_angle_start > $num_angle_end);
-        }
-    }
-
-    /**
-     * Sub function that is used only by hasUnclosedBrackets().
-     *
-     * @access private
-     * @param string $string The string to check.
-     * @param integer &$num    The number of occurences.
-     * @param string $char   The character to count.
-     * @return integer The number of occurences of $char in $string, adjusted for backslashes.
-     */
-    function _hasUnclosedBracketsSub($string, &$num, $char)
-    {
-        $parts = explode($char, $string);
-        for ($i = 0; $i < count($parts); $i++){
-            if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
-                $num--;
-            if (isset($parts[$i + 1]))
-                $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
-        }
-
-        return $num;
-    }
-
-    /**
-     * Function to begin checking the address.
-     *
-     * @access private
-     * @param string $address The address to validate.
-     * @return mixed False on failure, or a structured array of address information on success.
-     */
-    function _validateAddress($address)
-    {
-        $is_group = false;
-        $addresses = array();
-
-        if ($address['group']) {
-            $is_group = true;
-
-            // Get the group part of the name
-            $parts     = explode(':', $address['address']);
-            $groupname = $this->_splitCheck($parts, ':');
-            $structure = array();
-
-            // And validate the group part of the name.
-            if (!$this->_validatePhrase($groupname)){
-                $this->error = 'Group name did not validate.';
-                return false;
-            } else {
-                // Don't include groups if we are not nesting
-                // them. This avoids returning invalid addresses.
-                if ($this->nestGroups) {
-                    $structure = new stdClass;
-                    $structure->groupname = $groupname;
-                }
-            }
-
-            $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
-        }
-
-        // If a group then split on comma and put into an array.
-        // Otherwise, Just put the whole address in an array.
-        if ($is_group) {
-            while (strlen($address['address']) > 0) {
-                $parts       = explode(',', $address['address']);
-                $addresses[] = $this->_splitCheck($parts, ',');
-                $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
-            }
-        } else {
-            $addresses[] = $address['address'];
-        }
-
-        // Check that $addresses is set, if address like this:
-        // Groupname:;
-        // Then errors were appearing.
-        if (!count($addresses)){
-            $this->error = 'Empty group.';
-            return false;
-        }
-
-        // Trim the whitespace from all of the address strings.
-        array_map('trim', $addresses);
-
-        // Validate each mailbox.
-        // Format could be one of: name <geezer@domain.com>
-        //                         geezer@domain.com
-        //                         geezer
-        // ... or any other format valid by RFC 822.
-        for ($i = 0; $i < count($addresses); $i++) {
-            if (!$this->validateMailbox($addresses[$i])) {
-                if (empty($this->error)) {
-                    $this->error = 'Validation failed for: ' . $addresses[$i];
-                }
-                return false;
-            }
-        }
-
-        // Nested format
-        if ($this->nestGroups) {
-            if ($is_group) {
-                $structure->addresses = $addresses;
-            } else {
-                $structure = $addresses[0];
-            }
-
-        // Flat format
-        } else {
-            if ($is_group) {
-                $structure = array_merge($structure, $addresses);
-            } else {
-                $structure = $addresses;
-            }
-        }
-
-        return $structure;
-    }
-
-    /**
-     * Function to validate a phrase.
-     *
-     * @access private
-     * @param string $phrase The phrase to check.
-     * @return boolean Success or failure.
-     */
-    function _validatePhrase($phrase)
-    {
-        // Splits on one or more Tab or space.
-        $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
-
-        $phrase_parts = array();
-        while (count($parts) > 0){
-            $phrase_parts[] = $this->_splitCheck($parts, ' ');
-            for ($i = 0; $i < $this->index + 1; $i++)
-                array_shift($parts);
-        }
-
-        foreach ($phrase_parts as $part) {
-            // If quoted string:
-            if (substr($part, 0, 1) == '"') {
-                if (!$this->_validateQuotedString($part)) {
-                    return false;
-                }
-                continue;
-            }
-
-            // Otherwise it's an atom:
-            if (!$this->_validateAtom($part)) return false;
-        }
-
-        return true;
-    }
-
-    /**
-     * Function to validate an atom which from rfc822 is:
-     * atom = 1*<any CHAR except specials, SPACE and CTLs>
-     *
-     * If validation ($this->validate) has been turned off, then
-     * validateAtom() doesn't actually check anything. This is so that you
-     * can split a list of addresses up before encoding personal names
-     * (umlauts, etc.), for example.
-     *
-     * @access private
-     * @param string $atom The string to check.
-     * @return boolean Success or failure.
-     */
-    function _validateAtom($atom)
-    {
-        if (!$this->validate) {
-            // Validation has been turned off; assume the atom is okay.
-            return true;
-        }
-
-        // Check for any char from ASCII 0 - ASCII 127
-        if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
-            return false;
-        }
-
-        // Check for specials:
-        if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
-            return false;
-        }
-
-        // Check for control characters (ASCII 0-31):
-        if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
-            return false;
-        }
-
-        return true;
-    }
-
-    /**
-     * Function to validate quoted string, which is:
-     * quoted-string = <"> *(qtext/quoted-pair) <">
-     *
-     * @access private
-     * @param string $qstring The string to check
-     * @return boolean Success or failure.
-     */
-    function _validateQuotedString($qstring)
-    {
-        // Leading and trailing "
-        $qstring = substr($qstring, 1, -1);
-
-        // Perform check, removing quoted characters first.
-        return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
-    }
-
-    /**
-     * Function to validate a mailbox, which is:
-     * mailbox =   addr-spec         ; simple address
-     *           / phrase route-addr ; name and route-addr
-     *
-     * @access public
-     * @param string &$mailbox The string to check.
-     * @return boolean Success or failure.
-     */
-    function validateMailbox(&$mailbox)
-    {
-        // A couple of defaults.
-        $phrase  = '';
-        $comment = '';
-        $comments = array();
-
-        // Catch any RFC822 comments and store them separately.
-        $_mailbox = $mailbox;
-        while (strlen(trim($_mailbox)) > 0) {
-            $parts = explode('(', $_mailbox);
-            $before_comment = $this->_splitCheck($parts, '(');
-            if ($before_comment != $_mailbox) {
-                // First char should be a (.
-                $comment    = substr(str_replace($before_comment, '', $_mailbox), 1);
-                $parts      = explode(')', $comment);
-                $comment    = $this->_splitCheck($parts, ')');
-                $comments[] = $comment;
-
-                // +1 is for the trailing )
-                $_mailbox   = substr($_mailbox, strpos($_mailbox, $comment)+strlen($comment)+1);
-            } else {
-                break;
-            }
-        }
-
-        foreach ($comments as $comment) {
-            $mailbox = str_replace("($comment)", '', $mailbox);
-        }
-
-        $mailbox = trim($mailbox);
-
-        // Check for name + route-addr
-        if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
-            $parts  = explode('<', $mailbox);
-            $name   = $this->_splitCheck($parts, '<');
-
-            $phrase     = trim($name);
-            $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
-
-            if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
-                return false;
-            }
-
-        // Only got addr-spec
-        } else {
-            // First snip angle brackets if present.
-            if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
-                $addr_spec = substr($mailbox, 1, -1);
-            } else {
-                $addr_spec = $mailbox;
-            }
-
-            if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
-                return false;
-            }
-        }
-
-        // Construct the object that will be returned.
-        $mbox = new stdClass();
-
-        // Add the phrase (even if empty) and comments
-        $mbox->personal = $phrase;
-        $mbox->comment  = isset($comments) ? $comments : array();
-
-        if (isset($route_addr)) {
-            $mbox->mailbox = $route_addr['local_part'];
-            $mbox->host    = $route_addr['domain'];
-            $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
-        } else {
-            $mbox->mailbox = $addr_spec['local_part'];
-            $mbox->host    = $addr_spec['domain'];
-        }
-
-        $mailbox = $mbox;
-        return true;
-    }
-
-    /**
-     * This function validates a route-addr which is:
-     * route-addr = "<" [route] addr-spec ">"
-     *
-     * Angle brackets have already been removed at the point of
-     * getting to this function.
-     *
-     * @access private
-     * @param string $route_addr The string to check.
-     * @return mixed False on failure, or an array containing validated address/route information on success.
-     */
-    function _validateRouteAddr($route_addr)
-    {
-        // Check for colon.
-        if (strpos($route_addr, ':') !== false) {
-            $parts = explode(':', $route_addr);
-            $route = $this->_splitCheck($parts, ':');
-        } else {
-            $route = $route_addr;
-        }
-
-        // If $route is same as $route_addr then the colon was in
-        // quotes or brackets or, of course, non existent.
-        if ($route === $route_addr){
-            unset($route);
-            $addr_spec = $route_addr;
-            if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
-                return false;
-            }
-        } else {
-            // Validate route part.
-            if (($route = $this->_validateRoute($route)) === false) {
-                return false;
-            }
-
-            $addr_spec = substr($route_addr, strlen($route . ':'));
-
-            // Validate addr-spec part.
-            if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
-                return false;
-            }
-        }
-
-        if (isset($route)) {
-            $return['adl'] = $route;
-        } else {
-            $return['adl'] = '';
-        }
-
-        $return = array_merge($return, $addr_spec);
-        return $return;
-    }
-
-    /**
-     * Function to validate a route, which is:
-     * route = 1#("@" domain) ":"
-     *
-     * @access private
-     * @param string $route The string to check.
-     * @return mixed False on failure, or the validated $route on success.
-     */
-    function _validateRoute($route)
-    {
-        // Split on comma.
-        $domains = explode(',', trim($route));
-
-        foreach ($domains as $domain) {
-            $domain = str_replace('@', '', trim($domain));
-            if (!$this->_validateDomain($domain)) return false;
-        }
-
-        return $route;
-    }
-
-    /**
-     * Function to validate a domain, though this is not quite what
-     * you expect of a strict internet domain.
-     *
-     * domain = sub-domain *("." sub-domain)
-     *
-     * @access private
-     * @param string $domain The string to check.
-     * @return mixed False on failure, or the validated domain on success.
-     */
-    function _validateDomain($domain)
-    {
-        // Note the different use of $subdomains and $sub_domains
-        $subdomains = explode('.', $domain);
-
-        while (count($subdomains) > 0) {
-            $sub_domains[] = $this->_splitCheck($subdomains, '.');
-            for ($i = 0; $i < $this->index + 1; $i++)
-                array_shift($subdomains);
-        }
-
-        foreach ($sub_domains as $sub_domain) {
-            if (!$this->_validateSubdomain(trim($sub_domain)))
-                return false;
-        }
-
-        // Managed to get here, so return input.
-        return $domain;
-    }
-
-    /**
-     * Function to validate a subdomain:
-     *   subdomain = domain-ref / domain-literal
-     *
-     * @access private
-     * @param string $subdomain The string to check.
-     * @return boolean Success or failure.
-     */
-    function _validateSubdomain($subdomain)
-    {
-        if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
-            if (!$this->_validateDliteral($arr[1])) return false;
-        } else {
-            if (!$this->_validateAtom($subdomain)) return false;
-        }
-
-        // Got here, so return successful.
-        return true;
-    }
-
-    /**
-     * Function to validate a domain literal:
-     *   domain-literal =  "[" *(dtext / quoted-pair) "]"
-     *
-     * @access private
-     * @param string $dliteral The string to check.
-     * @return boolean Success or failure.
-     */
-    function _validateDliteral($dliteral)
-    {
-        return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
-    }
-
-    /**
-     * Function to validate an addr-spec.
-     *
-     * addr-spec = local-part "@" domain
-     *
-     * @access private
-     * @param string $addr_spec The string to check.
-     * @return mixed False on failure, or the validated addr-spec on success.
-     */
-    function _validateAddrSpec($addr_spec)
-    {
-        $addr_spec = trim($addr_spec);
-
-        // Split on @ sign if there is one.
-        if (strpos($addr_spec, '@') !== false) {
-            $parts      = explode('@', $addr_spec);
-            $local_part = $this->_splitCheck($parts, '@');
-            $domain     = substr($addr_spec, strlen($local_part . '@'));
-
-        // No @ sign so assume the default domain.
-        } else {
-            $local_part = $addr_spec;
-            $domain     = $this->default_domain;
-        }
-
-        if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
-        if (($domain     = $this->_validateDomain($domain)) === false) return false;
-
-        // Got here so return successful.
-        return array('local_part' => $local_part, 'domain' => $domain);
-    }
-
-    /**
-     * Function to validate the local part of an address:
-     *   local-part = word *("." word)
-     *
-     * @access private
-     * @param string $local_part
-     * @return mixed False on failure, or the validated local part on success.
-     */
-    function _validateLocalPart($local_part)
-    {
-        $parts = explode('.', $local_part);
-        $words = array();
-
-        // Split the local_part into words.
-        while (count($parts) > 0){
-            $words[] = $this->_splitCheck($parts, '.');
-            for ($i = 0; $i < $this->index + 1; $i++) {
-                array_shift($parts);
-            }
-        }
-
-        // Validate each word.
-        foreach ($words as $word) {
-            // If this word contains an unquoted space, it is invalid. (6.2.4)
-            if (strpos($word, ' ') && $word[0] !== '"')
-            {
-                return false;
-            }
-
-            if ($this->_validatePhrase(trim($word)) === false) return false;
-        }
-
-        // Managed to get here, so return the input.
-        return $local_part;
-    }
-
-    /**
-     * Returns an approximate count of how many addresses are in the
-     * given string. This is APPROXIMATE as it only splits based on a
-     * comma which has no preceding backslash. Could be useful as
-     * large amounts of addresses will end up producing *large*
-     * structures when used with parseAddressList().
-     *
-     * @param  string $data Addresses to count
-     * @return int          Approximate count
-     */
-    function approximateCount($data)
-    {
-        return count(preg_split('/(?<!\\\\),/', $data));
-    }
-
-    /**
-     * This is a email validating function separate to the rest of the
-     * class. It simply validates whether an email is of the common
-     * internet form: <user>@<domain>. This can be sufficient for most
-     * people. Optional stricter mode can be utilised which restricts
-     * mailbox characters allowed to alphanumeric, full stop, hyphen
-     * and underscore.
-     *
-     * @param  string  $data   Address to check
-     * @param  boolean $strict Optional stricter mode
-     * @return mixed           False if it fails, an indexed array
-     *                         username/domain if it matches
-     */
-    function isValidInetAddress($data, $strict = false)
-    {
-        $regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
-        if (preg_match($regex, trim($data), $matches)) {
-            return array($matches[1], $matches[2]);
-        } else {
-            return false;
-        }
-    }
-
-}
+<?php
+/**
+ * RFC 822 Email address list validation Utility
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2001-2010, Richard Heyes
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category    Mail
+ * @package     Mail
+ * @author      Richard Heyes <richard@phpguru.org>
+ * @author      Chuck Hagenbuch <chuck@horde.org
+ * @copyright   2001-2010 Richard Heyes
+ * @license     http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version     CVS: $Id: RFC822.php 294749 2010-02-08 08:22:25Z clockwerx $
+ * @link        http://pear.php.net/package/Mail/
+ */
+
+/**
+ * RFC 822 Email address list validation Utility
+ *
+ * What is it?
+ *
+ * This class will take an address string, and parse it into it's consituent
+ * parts, be that either addresses, groups, or combinations. Nested groups
+ * are not supported. The structure it returns is pretty straight forward,
+ * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
+ * print_r() to view the structure.
+ *
+ * How do I use it?
+ *
+ * $address_string = 'My Group: "Richard" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
+ * $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', true)
+ * print_r($structure);
+ *
+ * @author  Richard Heyes <richard@phpguru.org>
+ * @author  Chuck Hagenbuch <chuck@horde.org>
+ * @version $Revision: 294749 $
+ * @license BSD
+ * @package Mail
+ */
+class Mail_RFC822 {
+
+    /**
+     * The address being parsed by the RFC822 object.
+     * @var string $address
+     */
+    var $address = '';
+
+    /**
+     * The default domain to use for unqualified addresses.
+     * @var string $default_domain
+     */
+    var $default_domain = 'localhost';
+
+    /**
+     * Should we return a nested array showing groups, or flatten everything?
+     * @var boolean $nestGroups
+     */
+    var $nestGroups = true;
+
+    /**
+     * Whether or not to validate atoms for non-ascii characters.
+     * @var boolean $validate
+     */
+    var $validate = true;
+
+    /**
+     * The array of raw addresses built up as we parse.
+     * @var array $addresses
+     */
+    var $addresses = array();
+
+    /**
+     * The final array of parsed address information that we build up.
+     * @var array $structure
+     */
+    var $structure = array();
+
+    /**
+     * The current error message, if any.
+     * @var string $error
+     */
+    var $error = null;
+
+    /**
+     * An internal counter/pointer.
+     * @var integer $index
+     */
+    var $index = null;
+
+    /**
+     * The number of groups that have been found in the address list.
+     * @var integer $num_groups
+     * @access public
+     */
+    var $num_groups = 0;
+
+    /**
+     * A variable so that we can tell whether or not we're inside a
+     * Mail_RFC822 object.
+     * @var boolean $mailRFC822
+     */
+    var $mailRFC822 = true;
+
+    /**
+    * A limit after which processing stops
+    * @var int $limit
+    */
+    var $limit = null;
+
+    /**
+     * Sets up the object. The address must either be set here or when
+     * calling parseAddressList(). One or the other.
+     *
+     * @access public
+     * @param string  $address         The address(es) to validate.
+     * @param string  $default_domain  Default domain/host etc. If not supplied, will be set to localhost.
+     * @param boolean $nest_groups     Whether to return the structure with groups nested for easier viewing.
+     * @param boolean $validate        Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
+     *
+     * @return object Mail_RFC822 A new Mail_RFC822 object.
+     */
+    function Mail_RFC822($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
+    {
+        if (isset($address))        $this->address        = $address;
+        if (isset($default_domain)) $this->default_domain = $default_domain;
+        if (isset($nest_groups))    $this->nestGroups     = $nest_groups;
+        if (isset($validate))       $this->validate       = $validate;
+        if (isset($limit))          $this->limit          = $limit;
+    }
+
+    /**
+     * Starts the whole process. The address must either be set here
+     * or when creating the object. One or the other.
+     *
+     * @access public
+     * @param string  $address         The address(es) to validate.
+     * @param string  $default_domain  Default domain/host etc.
+     * @param boolean $nest_groups     Whether to return the structure with groups nested for easier viewing.
+     * @param boolean $validate        Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
+     *
+     * @return array A structured array of addresses.
+     */
+    function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
+    {
+        if (!isset($this) || !isset($this->mailRFC822)) {
+            $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
+            return $obj->parseAddressList();
+        }
+
+        if (isset($address))        $this->address        = $address;
+        if (isset($default_domain)) $this->default_domain = $default_domain;
+        if (isset($nest_groups))    $this->nestGroups     = $nest_groups;
+        if (isset($validate))       $this->validate       = $validate;
+        if (isset($limit))          $this->limit          = $limit;
+
+        $this->structure  = array();
+        $this->addresses  = array();
+        $this->error      = null;
+        $this->index      = null;
+
+        // Unfold any long lines in $this->address.
+        $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
+        $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
+
+        while ($this->address = $this->_splitAddresses($this->address));
+
+        if ($this->address === false || isset($this->error)) {
+            require_once 'PEAR.php';
+            return PEAR::raiseError($this->error);
+        }
+
+        // Validate each address individually.  If we encounter an invalid
+        // address, stop iterating and return an error immediately.
+        foreach ($this->addresses as $address) {
+            $valid = $this->_validateAddress($address);
+
+            if ($valid === false || isset($this->error)) {
+                require_once 'PEAR.php';
+                return PEAR::raiseError($this->error);
+            }
+
+            if (!$this->nestGroups) {
+                $this->structure = array_merge($this->structure, $valid);
+            } else {
+                $this->structure[] = $valid;
+            }
+        }
+
+        return $this->structure;
+    }
+
+    /**
+     * Splits an address into separate addresses.
+     *
+     * @access private
+     * @param string $address The addresses to split.
+     * @return boolean Success or failure.
+     */
+    function _splitAddresses($address)
+    {
+        if (!empty($this->limit) && count($this->addresses) == $this->limit) {
+            return '';
+        }
+
+        if ($this->_isGroup($address) && !isset($this->error)) {
+            $split_char = ';';
+            $is_group   = true;
+        } elseif (!isset($this->error)) {
+            $split_char = ',';
+            $is_group   = false;
+        } elseif (isset($this->error)) {
+            return false;
+        }
+
+        // Split the string based on the above ten or so lines.
+        $parts  = explode($split_char, $address);
+        $string = $this->_splitCheck($parts, $split_char);
+
+        // If a group...
+        if ($is_group) {
+            // If $string does not contain a colon outside of
+            // brackets/quotes etc then something's fubar.
+
+            // First check there's a colon at all:
+            if (strpos($string, ':') === false) {
+                $this->error = 'Invalid address: ' . $string;
+                return false;
+            }
+
+            // Now check it's outside of brackets/quotes:
+            if (!$this->_splitCheck(explode(':', $string), ':')) {
+                return false;
+            }
+
+            // We must have a group at this point, so increase the counter:
+            $this->num_groups++;
+        }
+
+        // $string now contains the first full address/group.
+        // Add to the addresses array.
+        $this->addresses[] = array(
+                                   'address' => trim($string),
+                                   'group'   => $is_group
+                                   );
+
+        // Remove the now stored address from the initial line, the +1
+        // is to account for the explode character.
+        $address = trim(substr($address, strlen($string) + 1));
+
+        // If the next char is a comma and this was a group, then
+        // there are more addresses, otherwise, if there are any more
+        // chars, then there is another address.
+        if ($is_group && substr($address, 0, 1) == ','){
+            $address = trim(substr($address, 1));
+            return $address;
+
+        } elseif (strlen($address) > 0) {
+            return $address;
+
+        } else {
+            return '';
+        }
+
+        // If you got here then something's off
+        return false;
+    }
+
+    /**
+     * Checks for a group at the start of the string.
+     *
+     * @access private
+     * @param string $address The address to check.
+     * @return boolean Whether or not there is a group at the start of the string.
+     */
+    function _isGroup($address)
+    {
+        // First comma not in quotes, angles or escaped:
+        $parts  = explode(',', $address);
+        $string = $this->_splitCheck($parts, ',');
+
+        // Now we have the first address, we can reliably check for a
+        // group by searching for a colon that's not escaped or in
+        // quotes or angle brackets.
+        if (count($parts = explode(':', $string)) > 1) {
+            $string2 = $this->_splitCheck($parts, ':');
+            return ($string2 !== $string);
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * A common function that will check an exploded string.
+     *
+     * @access private
+     * @param array $parts The exloded string.
+     * @param string $char  The char that was exploded on.
+     * @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
+     */
+    function _splitCheck($parts, $char)
+    {
+        $string = $parts[0];
+
+        for ($i = 0; $i < count($parts); $i++) {
+            if ($this->_hasUnclosedQuotes($string)
+                || $this->_hasUnclosedBrackets($string, '<>')
+                || $this->_hasUnclosedBrackets($string, '[]')
+                || $this->_hasUnclosedBrackets($string, '()')
+                || substr($string, -1) == '\\') {
+                if (isset($parts[$i + 1])) {
+                    $string = $string . $char . $parts[$i + 1];
+                } else {
+                    $this->error = 'Invalid address spec. Unclosed bracket or quotes';
+                    return false;
+                }
+            } else {
+                $this->index = $i;
+                break;
+            }
+        }
+
+        return $string;
+    }
+
+    /**
+     * Checks if a string has unclosed quotes or not.
+     *
+     * @access private
+     * @param string $string  The string to check.
+     * @return boolean  True if there are unclosed quotes inside the string,
+     *                  false otherwise.
+     */
+    function _hasUnclosedQuotes($string)
+    {
+        $string = trim($string);
+        $iMax = strlen($string);
+        $in_quote = false;
+        $i = $slashes = 0;
+
+        for (; $i < $iMax; ++$i) {
+            switch ($string[$i]) {
+            case '\\':
+                ++$slashes;
+                break;
+
+            case '"':
+                if ($slashes % 2 == 0) {
+                    $in_quote = !$in_quote;
+                }
+                // Fall through to default action below.
+
+            default:
+                $slashes = 0;
+                break;
+            }
+        }
+
+        return $in_quote;
+    }
+
+    /**
+     * Checks if a string has an unclosed brackets or not. IMPORTANT:
+     * This function handles both angle brackets and square brackets;
+     *
+     * @access private
+     * @param string $string The string to check.
+     * @param string $chars  The characters to check for.
+     * @return boolean True if there are unclosed brackets inside the string, false otherwise.
+     */
+    function _hasUnclosedBrackets($string, $chars)
+    {
+        $num_angle_start = substr_count($string, $chars[0]);
+        $num_angle_end   = substr_count($string, $chars[1]);
+
+        $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
+        $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
+
+        if ($num_angle_start < $num_angle_end) {
+            $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
+            return false;
+        } else {
+            return ($num_angle_start > $num_angle_end);
+        }
+    }
+
+    /**
+     * Sub function that is used only by hasUnclosedBrackets().
+     *
+     * @access private
+     * @param string $string The string to check.
+     * @param integer &$num    The number of occurences.
+     * @param string $char   The character to count.
+     * @return integer The number of occurences of $char in $string, adjusted for backslashes.
+     */
+    function _hasUnclosedBracketsSub($string, &$num, $char)
+    {
+        $parts = explode($char, $string);
+        for ($i = 0; $i < count($parts); $i++){
+            if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
+                $num--;
+            if (isset($parts[$i + 1]))
+                $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
+        }
+
+        return $num;
+    }
+
+    /**
+     * Function to begin checking the address.
+     *
+     * @access private
+     * @param string $address The address to validate.
+     * @return mixed False on failure, or a structured array of address information on success.
+     */
+    function _validateAddress($address)
+    {
+        $is_group = false;
+        $addresses = array();
+
+        if ($address['group']) {
+            $is_group = true;
+
+            // Get the group part of the name
+            $parts     = explode(':', $address['address']);
+            $groupname = $this->_splitCheck($parts, ':');
+            $structure = array();
+
+            // And validate the group part of the name.
+            if (!$this->_validatePhrase($groupname)){
+                $this->error = 'Group name did not validate.';
+                return false;
+            } else {
+                // Don't include groups if we are not nesting
+                // them. This avoids returning invalid addresses.
+                if ($this->nestGroups) {
+                    $structure = new stdClass;
+                    $structure->groupname = $groupname;
+                }
+            }
+
+            $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
+        }
+
+        // If a group then split on comma and put into an array.
+        // Otherwise, Just put the whole address in an array.
+        if ($is_group) {
+            while (strlen($address['address']) > 0) {
+                $parts       = explode(',', $address['address']);
+                $addresses[] = $this->_splitCheck($parts, ',');
+                $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
+            }
+        } else {
+            $addresses[] = $address['address'];
+        }
+
+        // Check that $addresses is set, if address like this:
+        // Groupname:;
+        // Then errors were appearing.
+        if (!count($addresses)){
+            $this->error = 'Empty group.';
+            return false;
+        }
+
+        // Trim the whitespace from all of the address strings.
+        array_map('trim', $addresses);
+
+        // Validate each mailbox.
+        // Format could be one of: name <geezer@domain.com>
+        //                         geezer@domain.com
+        //                         geezer
+        // ... or any other format valid by RFC 822.
+        for ($i = 0; $i < count($addresses); $i++) {
+            if (!$this->validateMailbox($addresses[$i])) {
+                if (empty($this->error)) {
+                    $this->error = 'Validation failed for: ' . $addresses[$i];
+                }
+                return false;
+            }
+        }
+
+        // Nested format
+        if ($this->nestGroups) {
+            if ($is_group) {
+                $structure->addresses = $addresses;
+            } else {
+                $structure = $addresses[0];
+            }
+
+        // Flat format
+        } else {
+            if ($is_group) {
+                $structure = array_merge($structure, $addresses);
+            } else {
+                $structure = $addresses;
+            }
+        }
+
+        return $structure;
+    }
+
+    /**
+     * Function to validate a phrase.
+     *
+     * @access private
+     * @param string $phrase The phrase to check.
+     * @return boolean Success or failure.
+     */
+    function _validatePhrase($phrase)
+    {
+        // Splits on one or more Tab or space.
+        $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
+
+        $phrase_parts = array();
+        while (count($parts) > 0){
+            $phrase_parts[] = $this->_splitCheck($parts, ' ');
+            for ($i = 0; $i < $this->index + 1; $i++)
+                array_shift($parts);
+        }
+
+        foreach ($phrase_parts as $part) {
+            // If quoted string:
+            if (substr($part, 0, 1) == '"') {
+                if (!$this->_validateQuotedString($part)) {
+                    return false;
+                }
+                continue;
+            }
+
+            // Otherwise it's an atom:
+            if (!$this->_validateAtom($part)) return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Function to validate an atom which from rfc822 is:
+     * atom = 1*<any CHAR except specials, SPACE and CTLs>
+     *
+     * If validation ($this->validate) has been turned off, then
+     * validateAtom() doesn't actually check anything. This is so that you
+     * can split a list of addresses up before encoding personal names
+     * (umlauts, etc.), for example.
+     *
+     * @access private
+     * @param string $atom The string to check.
+     * @return boolean Success or failure.
+     */
+    function _validateAtom($atom)
+    {
+        if (!$this->validate) {
+            // Validation has been turned off; assume the atom is okay.
+            return true;
+        }
+
+        // Check for any char from ASCII 0 - ASCII 127
+        if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
+            return false;
+        }
+
+        // Check for specials:
+        if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
+            return false;
+        }
+
+        // Check for control characters (ASCII 0-31):
+        if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Function to validate quoted string, which is:
+     * quoted-string = <"> *(qtext/quoted-pair) <">
+     *
+     * @access private
+     * @param string $qstring The string to check
+     * @return boolean Success or failure.
+     */
+    function _validateQuotedString($qstring)
+    {
+        // Leading and trailing "
+        $qstring = substr($qstring, 1, -1);
+
+        // Perform check, removing quoted characters first.
+        return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
+    }
+
+    /**
+     * Function to validate a mailbox, which is:
+     * mailbox =   addr-spec         ; simple address
+     *           / phrase route-addr ; name and route-addr
+     *
+     * @access public
+     * @param string &$mailbox The string to check.
+     * @return boolean Success or failure.
+     */
+    function validateMailbox(&$mailbox)
+    {
+        // A couple of defaults.
+        $phrase  = '';
+        $comment = '';
+        $comments = array();
+
+        // Catch any RFC822 comments and store them separately.
+        $_mailbox = $mailbox;
+        while (strlen(trim($_mailbox)) > 0) {
+            $parts = explode('(', $_mailbox);
+            $before_comment = $this->_splitCheck($parts, '(');
+            if ($before_comment != $_mailbox) {
+                // First char should be a (.
+                $comment    = substr(str_replace($before_comment, '', $_mailbox), 1);
+                $parts      = explode(')', $comment);
+                $comment    = $this->_splitCheck($parts, ')');
+                $comments[] = $comment;
+
+                // +2 is for the brackets
+                $_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
+            } else {
+                break;
+            }
+        }
+
+        foreach ($comments as $comment) {
+            $mailbox = str_replace("($comment)", '', $mailbox);
+        }
+
+        $mailbox = trim($mailbox);
+
+        // Check for name + route-addr
+        if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
+            $parts  = explode('<', $mailbox);
+            $name   = $this->_splitCheck($parts, '<');
+
+            $phrase     = trim($name);
+            $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
+
+            if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
+                return false;
+            }
+
+        // Only got addr-spec
+        } else {
+            // First snip angle brackets if present.
+            if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
+                $addr_spec = substr($mailbox, 1, -1);
+            } else {
+                $addr_spec = $mailbox;
+            }
+
+            if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
+                return false;
+            }
+        }
+
+        // Construct the object that will be returned.
+        $mbox = new stdClass();
+
+        // Add the phrase (even if empty) and comments
+        $mbox->personal = $phrase;
+        $mbox->comment  = isset($comments) ? $comments : array();
+
+        if (isset($route_addr)) {
+            $mbox->mailbox = $route_addr['local_part'];
+            $mbox->host    = $route_addr['domain'];
+            $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
+        } else {
+            $mbox->mailbox = $addr_spec['local_part'];
+            $mbox->host    = $addr_spec['domain'];
+        }
+
+        $mailbox = $mbox;
+        return true;
+    }
+
+    /**
+     * This function validates a route-addr which is:
+     * route-addr = "<" [route] addr-spec ">"
+     *
+     * Angle brackets have already been removed at the point of
+     * getting to this function.
+     *
+     * @access private
+     * @param string $route_addr The string to check.
+     * @return mixed False on failure, or an array containing validated address/route information on success.
+     */
+    function _validateRouteAddr($route_addr)
+    {
+        // Check for colon.
+        if (strpos($route_addr, ':') !== false) {
+            $parts = explode(':', $route_addr);
+            $route = $this->_splitCheck($parts, ':');
+        } else {
+            $route = $route_addr;
+        }
+
+        // If $route is same as $route_addr then the colon was in
+        // quotes or brackets or, of course, non existent.
+        if ($route === $route_addr){
+            unset($route);
+            $addr_spec = $route_addr;
+            if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
+                return false;
+            }
+        } else {
+            // Validate route part.
+            if (($route = $this->_validateRoute($route)) === false) {
+                return false;
+            }
+
+            $addr_spec = substr($route_addr, strlen($route . ':'));
+
+            // Validate addr-spec part.
+            if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
+                return false;
+            }
+        }
+
+        if (isset($route)) {
+            $return['adl'] = $route;
+        } else {
+            $return['adl'] = '';
+        }
+
+        $return = array_merge($return, $addr_spec);
+        return $return;
+    }
+
+    /**
+     * Function to validate a route, which is:
+     * route = 1#("@" domain) ":"
+     *
+     * @access private
+     * @param string $route The string to check.
+     * @return mixed False on failure, or the validated $route on success.
+     */
+    function _validateRoute($route)
+    {
+        // Split on comma.
+        $domains = explode(',', trim($route));
+
+        foreach ($domains as $domain) {
+            $domain = str_replace('@', '', trim($domain));
+            if (!$this->_validateDomain($domain)) return false;
+        }
+
+        return $route;
+    }
+
+    /**
+     * Function to validate a domain, though this is not quite what
+     * you expect of a strict internet domain.
+     *
+     * domain = sub-domain *("." sub-domain)
+     *
+     * @access private
+     * @param string $domain The string to check.
+     * @return mixed False on failure, or the validated domain on success.
+     */
+    function _validateDomain($domain)
+    {
+        // Note the different use of $subdomains and $sub_domains
+        $subdomains = explode('.', $domain);
+
+        while (count($subdomains) > 0) {
+            $sub_domains[] = $this->_splitCheck($subdomains, '.');
+            for ($i = 0; $i < $this->index + 1; $i++)
+                array_shift($subdomains);
+        }
+
+        foreach ($sub_domains as $sub_domain) {
+            if (!$this->_validateSubdomain(trim($sub_domain)))
+                return false;
+        }
+
+        // Managed to get here, so return input.
+        return $domain;
+    }
+
+    /**
+     * Function to validate a subdomain:
+     *   subdomain = domain-ref / domain-literal
+     *
+     * @access private
+     * @param string $subdomain The string to check.
+     * @return boolean Success or failure.
+     */
+    function _validateSubdomain($subdomain)
+    {
+        if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
+            if (!$this->_validateDliteral($arr[1])) return false;
+        } else {
+            if (!$this->_validateAtom($subdomain)) return false;
+        }
+
+        // Got here, so return successful.
+        return true;
+    }
+
+    /**
+     * Function to validate a domain literal:
+     *   domain-literal =  "[" *(dtext / quoted-pair) "]"
+     *
+     * @access private
+     * @param string $dliteral The string to check.
+     * @return boolean Success or failure.
+     */
+    function _validateDliteral($dliteral)
+    {
+        return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
+    }
+
+    /**
+     * Function to validate an addr-spec.
+     *
+     * addr-spec = local-part "@" domain
+     *
+     * @access private
+     * @param string $addr_spec The string to check.
+     * @return mixed False on failure, or the validated addr-spec on success.
+     */
+    function _validateAddrSpec($addr_spec)
+    {
+        $addr_spec = trim($addr_spec);
+
+        // Split on @ sign if there is one.
+        if (strpos($addr_spec, '@') !== false) {
+            $parts      = explode('@', $addr_spec);
+            $local_part = $this->_splitCheck($parts, '@');
+            $domain     = substr($addr_spec, strlen($local_part . '@'));
+
+        // No @ sign so assume the default domain.
+        } else {
+            $local_part = $addr_spec;
+            $domain     = $this->default_domain;
+        }
+
+        if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
+        if (($domain     = $this->_validateDomain($domain)) === false) return false;
+
+        // Got here so return successful.
+        return array('local_part' => $local_part, 'domain' => $domain);
+    }
+
+    /**
+     * Function to validate the local part of an address:
+     *   local-part = word *("." word)
+     *
+     * @access private
+     * @param string $local_part
+     * @return mixed False on failure, or the validated local part on success.
+     */
+    function _validateLocalPart($local_part)
+    {
+        $parts = explode('.', $local_part);
+        $words = array();
+
+        // Split the local_part into words.
+        while (count($parts) > 0){
+            $words[] = $this->_splitCheck($parts, '.');
+            for ($i = 0; $i < $this->index + 1; $i++) {
+                array_shift($parts);
+            }
+        }
+
+        // Validate each word.
+        foreach ($words as $word) {
+            // If this word contains an unquoted space, it is invalid. (6.2.4)
+            if (strpos($word, ' ') && $word[0] !== '"')
+            {
+                return false;
+            }
+
+            if ($this->_validatePhrase(trim($word)) === false) return false;
+        }
+
+        // Managed to get here, so return the input.
+        return $local_part;
+    }
+
+    /**
+     * Returns an approximate count of how many addresses are in the
+     * given string. This is APPROXIMATE as it only splits based on a
+     * comma which has no preceding backslash. Could be useful as
+     * large amounts of addresses will end up producing *large*
+     * structures when used with parseAddressList().
+     *
+     * @param  string $data Addresses to count
+     * @return int          Approximate count
+     */
+    function approximateCount($data)
+    {
+        return count(preg_split('/(?<!\\\\),/', $data));
+    }
+
+    /**
+     * This is a email validating function separate to the rest of the
+     * class. It simply validates whether an email is of the common
+     * internet form: <user>@<domain>. This can be sufficient for most
+     * people. Optional stricter mode can be utilised which restricts
+     * mailbox characters allowed to alphanumeric, full stop, hyphen
+     * and underscore.
+     *
+     * @param  string  $data   Address to check
+     * @param  boolean $strict Optional stricter mode
+     * @return mixed           False if it fails, an indexed array
+     *                         username/domain if it matches
+     */
+    function isValidInetAddress($data, $strict = false)
+    {
+        $regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
+        if (preg_match($regex, trim($data), $matches)) {
+            return array($matches[1], $matches[2]);
+        } else {
+            return false;
+        }
+    }
+
+}
diff --git a/include/pear/Mail/mail.php b/include/pear/Mail/mail.php
index b48d2697fa9acbad7b835ef8989dcb7fd9291297..a8b4b5dbeef6c0b194fa9a2036af40c2feb5869a 100644
--- a/include/pear/Mail/mail.php
+++ b/include/pear/Mail/mail.php
@@ -1,143 +1,168 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org>                            |
-// +----------------------------------------------------------------------+
-//
-// $Id: mail.php,v 1.20 2007/10/06 17:00:00 chagenbu Exp $
-
-/**
- * internal PHP-mail() implementation of the PEAR Mail:: interface.
- * @package Mail
- * @version $Revision: 1.20 $
- */
-class Mail_mail extends Mail {
-
-    /**
-     * Any arguments to pass to the mail() function.
-     * @var string
-     */
-    var $_params = '';
-
-    /**
-     * Constructor.
-     *
-     * Instantiates a new Mail_mail:: object based on the parameters
-     * passed in.
-     *
-     * @param array $params Extra arguments for the mail() function.
-     */
-    function Mail_mail($params = null)
-    {
-        // The other mail implementations accept parameters as arrays.
-        // In the interest of being consistent, explode an array into
-        // a string of parameter arguments.
-        if (is_array($params)) {
-            $this->_params = join(' ', $params);
-        } else {
-            $this->_params = $params;
-        }
-
-        /* Because the mail() function may pass headers as command
-         * line arguments, we can't guarantee the use of the standard
-         * "\r\n" separator.  Instead, we use the system's native line
-         * separator. */
-        if (defined('PHP_EOL')) {
-            $this->sep = PHP_EOL;
-        } else {
-            $this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
-        }
-    }
-
-    /**
-     * Implements Mail_mail::send() function using php's built-in mail()
-     * command.
-     *
-     * @param mixed $recipients Either a comma-seperated list of recipients
-     *              (RFC822 compliant), or an array of recipients,
-     *              each RFC822 valid. This may contain recipients not
-     *              specified in the headers, for Bcc:, resending
-     *              messages, etc.
-     *
-     * @param array $headers The array of headers to send with the mail, in an
-     *              associative array, where the array key is the
-     *              header name (ie, 'Subject'), and the array value
-     *              is the header value (ie, 'test'). The header
-     *              produced from those values would be 'Subject:
-     *              test'.
-     *
-     * @param string $body The full text of the message body, including any
-     *               Mime parts, etc.
-     *
-     * @return mixed Returns true on success, or a PEAR_Error
-     *               containing a descriptive error message on
-     *               failure.
-     *
-     * @access public
-     */
-    function send($recipients, $headers, $body)
-    {
-        if (!is_array($headers)) {
-            return PEAR::raiseError('$headers must be an array');
-        }
-
-        $result = $this->_sanitizeHeaders($headers);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        // If we're passed an array of recipients, implode it.
-        if (is_array($recipients)) {
-            $recipients = implode(', ', $recipients);
-        }
-
-        // Get the Subject out of the headers array so that we can
-        // pass it as a seperate argument to mail().
-        $subject = '';
-        if (isset($headers['Subject'])) {
-            $subject = $headers['Subject'];
-            unset($headers['Subject']);
-        }
-
-        // Also remove the To: header.  The mail() function will add its own
-        // To: header based on the contents of $recipients.
-        unset($headers['To']);
-
-        // Flatten the headers out.
-        $headerElements = $this->prepareHeaders($headers);
-        if (is_a($headerElements, 'PEAR_Error')) {
-            return $headerElements;
-        }
-        list(, $text_headers) = $headerElements;
-
-        // We only use mail()'s optional fifth parameter if the additional
-        // parameters have been provided and we're not running in safe mode.
-        if (empty($this->_params) || ini_get('safe_mode')) {
-            $result = mail($recipients, $subject, $body, $text_headers);
-        } else {
-            $result = mail($recipients, $subject, $body, $text_headers,
-                           $this->_params);
-        }
-
-        // If the mail() function returned failure, we need to create a
-        // PEAR_Error object and return it instead of the boolean result.
-        if ($result === false) {
-            $result = PEAR::raiseError('mail() returned failure');
-        }
-
-        return $result;
-    }
-
-}
+<?php
+/**
+ * internal PHP-mail() implementation of the PEAR Mail:: interface.
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2010 Chuck Hagenbuch
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category    Mail
+ * @package     Mail
+ * @author      Chuck Hagenbuch <chuck@horde.org> 
+ * @copyright   2010 Chuck Hagenbuch
+ * @license     http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version     CVS: $Id: mail.php 294747 2010-02-08 08:18:33Z clockwerx $
+ * @link        http://pear.php.net/package/Mail/
+ */
+
+/**
+ * internal PHP-mail() implementation of the PEAR Mail:: interface.
+ * @package Mail
+ * @version $Revision: 294747 $
+ */
+class Mail_mail extends Mail {
+
+    /**
+     * Any arguments to pass to the mail() function.
+     * @var string
+     */
+    var $_params = '';
+
+    /**
+     * Constructor.
+     *
+     * Instantiates a new Mail_mail:: object based on the parameters
+     * passed in.
+     *
+     * @param array $params Extra arguments for the mail() function.
+     */
+    function Mail_mail($params = null)
+    {
+        // The other mail implementations accept parameters as arrays.
+        // In the interest of being consistent, explode an array into
+        // a string of parameter arguments.
+        if (is_array($params)) {
+            $this->_params = join(' ', $params);
+        } else {
+            $this->_params = $params;
+        }
+
+        /* Because the mail() function may pass headers as command
+         * line arguments, we can't guarantee the use of the standard
+         * "\r\n" separator.  Instead, we use the system's native line
+         * separator. */
+        if (defined('PHP_EOL')) {
+            $this->sep = PHP_EOL;
+        } else {
+            $this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
+        }
+    }
+
+    /**
+     * Implements Mail_mail::send() function using php's built-in mail()
+     * command.
+     *
+     * @param mixed $recipients Either a comma-seperated list of recipients
+     *              (RFC822 compliant), or an array of recipients,
+     *              each RFC822 valid. This may contain recipients not
+     *              specified in the headers, for Bcc:, resending
+     *              messages, etc.
+     *
+     * @param array $headers The array of headers to send with the mail, in an
+     *              associative array, where the array key is the
+     *              header name (ie, 'Subject'), and the array value
+     *              is the header value (ie, 'test'). The header
+     *              produced from those values would be 'Subject:
+     *              test'.
+     *
+     * @param string $body The full text of the message body, including any
+     *               Mime parts, etc.
+     *
+     * @return mixed Returns true on success, or a PEAR_Error
+     *               containing a descriptive error message on
+     *               failure.
+     *
+     * @access public
+     */
+    function send($recipients, $headers, $body)
+    {
+        if (!is_array($headers)) {
+            return PEAR::raiseError('$headers must be an array');
+        }
+
+        $result = $this->_sanitizeHeaders($headers);
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+
+        // If we're passed an array of recipients, implode it.
+        if (is_array($recipients)) {
+            $recipients = implode(', ', $recipients);
+        }
+
+        // Get the Subject out of the headers array so that we can
+        // pass it as a seperate argument to mail().
+        $subject = '';
+        if (isset($headers['Subject'])) {
+            $subject = $headers['Subject'];
+            unset($headers['Subject']);
+        }
+
+        // Also remove the To: header.  The mail() function will add its own
+        // To: header based on the contents of $recipients.
+        unset($headers['To']);
+
+        // Flatten the headers out.
+        $headerElements = $this->prepareHeaders($headers);
+        if (is_a($headerElements, 'PEAR_Error')) {
+            return $headerElements;
+        }
+        list(, $text_headers) = $headerElements;
+
+        // We only use mail()'s optional fifth parameter if the additional
+        // parameters have been provided and we're not running in safe mode.
+        if (empty($this->_params) || ini_get('safe_mode')) {
+            $result = mail($recipients, $subject, $body, $text_headers);
+        } else {
+            $result = mail($recipients, $subject, $body, $text_headers,
+                           $this->_params);
+        }
+
+        // If the mail() function returned failure, we need to create a
+        // PEAR_Error object and return it instead of the boolean result.
+        if ($result === false) {
+            $result = PEAR::raiseError('mail() returned failure');
+        }
+
+        return $result;
+    }
+
+}
diff --git a/include/pear/Mail/mime.php b/include/pear/Mail/mime.php
index 2286920d76625b5fa1f9eb9537cd22bb4d8c5019..4522e20cd2eab289a3be6b39126c3aafc81e18a3 100644
--- a/include/pear/Mail/mime.php
+++ b/include/pear/Mail/mime.php
@@ -45,9 +45,10 @@
  * @author    Tomas V.V. Cox <cox@idecnet.com>
  * @author    Cipriano Groenendal <cipri@php.net>
  * @author    Sean Coates <sean@php.net>
+ * @author    Aleksander Machniak <alec@php.net>
  * @copyright 2003-2006 PEAR <pear-group@php.net>
  * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version   CVS: $Id: mime.php,v 1.81 2007/06/21 19:08:28 cipri Exp $
+ * @version   CVS: $Id$
  * @link      http://pear.php.net/package/Mail_mime
  *
  *            This class is based on HTML Mime Mail class from
@@ -109,22 +110,6 @@ class Mail_mime
      */
     var $_htmlbody;
 
-    /**
-     * contains the mime encoded text
-     *
-     * @var string
-     * @access private
-     */
-    var $_mime;
-
-    /**
-     * contains the multipart content
-     *
-     * @var string
-     * @access private
-     */
-    var $_multipart;
-
     /**
      * list of the attached images
      *
@@ -142,66 +127,97 @@ class Mail_mime
     var $_parts = array();
 
     /**
-     * Build parameters
+     * Headers for the mail
      *
      * @var array
      * @access private
      */
-    var $_build_params = array();
+    var $_headers = array();
 
     /**
-     * Headers for the mail
+     * Build parameters
      *
      * @var array
      * @access private
      */
-    var $_headers = array();
+    var $_build_params = array(
+        // What encoding to use for the headers
+        // Options: quoted-printable or base64
+        'head_encoding' => 'quoted-printable',
+        // What encoding to use for plain text
+        // Options: 7bit, 8bit, base64, or quoted-printable
+        'text_encoding' => 'quoted-printable',
+        // What encoding to use for html
+        // Options: 7bit, 8bit, base64, or quoted-printable
+        'html_encoding' => 'quoted-printable',
+        // The character set to use for html
+        'html_charset'  => 'ISO-8859-1',
+        // The character set to use for text
+        'text_charset'  => 'ISO-8859-1',
+        // The character set to use for headers
+        'head_charset'  => 'ISO-8859-1',
+        // End-of-line sequence
+        'eol'           => "\r\n",
+        // Delay attachment files IO until building the message
+        'delay_file_io' => false
+    );
 
     /**
-     * End Of Line sequence (for serialize)
+     * Constructor function
      *
-     * @var string
-     * @access private
+     * @param mixed $params Build parameters that change the way the email
+     *                      is built. Should be an associative array.
+     *                      See $_build_params.
+     *
+     * @return void
+     * @access public
      */
-    var $_eol;
+    function Mail_mime($params = array())
+    {
+        // Backward-compatible EOL setting
+        if (is_string($params)) {
+            $this->_build_params['eol'] = $params;
+        } else if (defined('MAIL_MIME_CRLF') && !isset($params['eol'])) {
+            $this->_build_params['eol'] = MAIL_MIME_CRLF;
+        }
 
+        // Update build parameters
+        if (!empty($params) && is_array($params)) {
+            while (list($key, $value) = each($params)) {
+                $this->_build_params[$key] = $value;
+            }
+        }
+    }
 
     /**
-     * Constructor function.
+     * Set build parameter value
      *
-     * @param string $crlf what type of linebreak to use.
-     *                     Defaults to "\r\n"
+     * @param string $name  Parameter name
+     * @param string $value Parameter value
      *
      * @return void
-     *
      * @access public
+     * @since 1.6.0
      */
-    function Mail_mime($crlf = "\r\n")
+    function setParam($name, $value)
     {
-        $this->_setEOL($crlf);
-        $this->_build_params = array(
-                                     'head_encoding' => 'quoted-printable',
-                                     'text_encoding' => '7bit',
-                                     'html_encoding' => 'quoted-printable',
-                                     '7bit_wrap'     => 998,
-                                     'html_charset'  => 'ISO-8859-1',
-                                     'text_charset'  => 'ISO-8859-1',
-                                     'head_charset'  => 'ISO-8859-1'
-                                    );
+        $this->_build_params[$name] = $value;
     }
 
     /**
-     * wakeup function called by unserialize. It re-sets the EOL constant
+     * Get build parameter value
      *
-     * @access private
-     * @return void
+     * @param string $name Parameter name
+     *
+     * @return mixed Parameter value
+     * @access public
+     * @since 1.6.0
      */
-    function __wakeup()
+    function getParam($name)
     {
-        $this->_setEOL($this->_eol);
+        return isset($this->_build_params[$name]) ? $this->_build_params[$name] : null;
     }
 
-
     /**
      * Accessor function to set the body text. Body text is used if
      * it's not an html mail being sent or else is used to fill the
@@ -209,14 +225,14 @@ class Mail_mime
      * html should show.
      *
      * @param string $data   Either a string or
-     *                        the file name with the contents
+     *                       the file name with the contents
      * @param bool   $isfile If true the first param should be treated
-     *                        as a file name, else as a string (default)
+     *                       as a file name, else as a string (default)
      * @param bool   $append If true the text or file is appended to
-     *                        the existing body, else the old body is
-     *                        overwritten
+     *                       the existing body, else the old body is
+     *                       overwritten
      *
-     * @return mixed   true on success or PEAR_Error object
+     * @return mixed         True on success or PEAR_Error object
      * @access public
      */
     function setTXTBody($data, $isfile = false, $append = false)
@@ -241,15 +257,27 @@ class Mail_mime
         return true;
     }
 
+    /**
+     * Get message text body
+     *
+     * @return string Text body
+     * @access public
+     * @since 1.6.0
+     */
+    function getTXTBody()
+    {
+        return $this->_txtbody;
+    }
+
     /**
      * Adds a html part to the mail.
      *
-     * @param string $data   either a string or the file name with the
-     *                        contents
-     * @param bool   $isfile a flag that determines whether $data is a
-     *                        filename, or a string(false, default)
+     * @param string $data   Either a string or the file name with the
+     *                       contents
+     * @param bool   $isfile A flag that determines whether $data is a
+     *                       filename, or a string(false, default)
      *
-     * @return bool    true on success
+     * @return bool          True on success
      * @access public
      */
     function setHTMLBody($data, $isfile = false)
@@ -267,38 +295,69 @@ class Mail_mime
         return true;
     }
 
+    /**
+     * Get message HTML body
+     *
+     * @return string HTML body
+     * @access public
+     * @since 1.6.0
+     */
+    function getHTMLBody()
+    {
+        return $this->_htmlbody;
+    }
+
     /**
      * Adds an image to the list of embedded images.
      *
-     * @param string $file   the image file name OR image data itself
-     * @param string $c_type the content type
-     * @param string $name   the filename of the image.
-     *                        Only used if $file is the image data.
-     * @param bool   $isfile whether $file is a filename or not.
-     *                        Defaults to true
+     * @param string $file       The image file name OR image data itself
+     * @param string $c_type     The content type
+     * @param string $name       The filename of the image.
+     *                           Only used if $file is the image data.
+     * @param bool   $isfile     Whether $file is a filename or not.
+     *                           Defaults to true
+     * @param string $content_id Desired Content-ID of MIME part
+     *                           Defaults to generated unique ID
      *
-     * @return bool          true on success
+     * @return bool          True on success
      * @access public
      */
-    function addHTMLImage($file, $c_type='application/octet-stream',
-                          $name = '', $isfile = true)
-    {
-        $filedata = ($isfile === true) ? $this->_file2str($file)
-                                           : $file;
-        if ($isfile === true) {
-            $filename = ($name == '' ? $file : $name);
+    function addHTMLImage($file,
+        $c_type='application/octet-stream',
+        $name = '',
+        $isfile = true,
+        $content_id = null
+    ) {
+        $bodyfile = null;
+
+        if ($isfile) {
+            // Don't load file into memory
+            if ($this->_build_params['delay_file_io']) {
+                $filedata = null;
+                $bodyfile = $file;
+            } else {
+                if (PEAR::isError($filedata = $this->_file2str($file))) {
+                    return $filedata;
+                }
+            }
+            $filename = ($name ? $name : $file);
         } else {
+            $filedata = $file;
             $filename = $name;
         }
-        if (PEAR::isError($filedata)) {
-            return $filedata;
+
+        if (!$content_id) {
+            $content_id = md5(uniqid(time()));
         }
+
         $this->_html_images[] = array(
-                                      'body'   => $filedata,
-                                      'name'   => $filename,
-                                      'c_type' => $c_type,
-                                      'cid'    => md5(uniqid(time()))
-                                     );
+            'body'      => $filedata,
+            'body_file' => $bodyfile,
+            'name'      => $filename,
+            'c_type'    => $c_type,
+            'cid'       => $content_id
+        );
+
         return true;
     }
 
@@ -306,99 +365,128 @@ class Mail_mime
      * Adds a file to the list of attachments.
      *
      * @param string $file        The file name of the file to attach
-     *                             OR the file contents itself
+     *                            or the file contents itself
      * @param string $c_type      The content type
      * @param string $name        The filename of the attachment
-     *                             Only use if $file is the contents
-     * @param bool   $isfile      Whether $file is a filename or not
-     *                             Defaults to true
-     * @param string $encoding    The type of encoding to use.
-     *                             Defaults to base64.
-     *                             Possible values: 7bit, 8bit, base64, 
-     *                             or quoted-printable.
+     *                            Only use if $file is the contents
+     * @param bool   $isfile      Whether $file is a filename or not. Defaults to true
+     * @param string $encoding    The type of encoding to use. Defaults to base64.
+     *                            Possible values: 7bit, 8bit, base64 or quoted-printable.
      * @param string $disposition The content-disposition of this file
-     *                             Defaults to attachment.
-     *                             Possible values: attachment, inline.
-     * @param string $charset     The character set used in the filename
-     *                             of this attachment.
+     *                            Defaults to attachment.
+     *                            Possible values: attachment, inline.
+     * @param string $charset     The character set of attachment's content.
      * @param string $language    The language of the attachment
      * @param string $location    The RFC 2557.4 location of the attachment
+     * @param string $n_encoding  Encoding of the attachment's name in Content-Type
+     *                            By default filenames are encoded using RFC2231 method
+     *                            Here you can set RFC2047 encoding (quoted-printable
+     *                            or base64) instead
+     * @param string $f_encoding  Encoding of the attachment's filename
+     *                            in Content-Disposition header.
+     * @param string $description Content-Description header
+     * @param string $h_charset   The character set of the headers e.g. filename
+     *                            If not specified, $charset will be used
+     * @param array  $add_headers Additional part headers. Array keys can be in form
+     *                            of <header_name>:<parameter_name>
      *
-     * @return mixed true on success or PEAR_Error object
+     * @return mixed              True on success or PEAR_Error object
      * @access public
      */
     function addAttachment($file,
-                           $c_type      = 'application/octet-stream',
-                           $name        = '',
-                            $isfile     = true,
-                           $encoding    = 'base64',
-                           $disposition = 'attachment',
-                           $charset     = '',
-                            $language   = '',
-                           $location    = '')
-    {
-        $filedata = ($isfile === true) ? $this->_file2str($file)
-                                           : $file;
-        if ($isfile === true) {
+        $c_type      = 'application/octet-stream',
+        $name        = '',
+        $isfile      = true,
+        $encoding    = 'base64',
+        $disposition = 'attachment',
+        $charset     = '',
+        $language    = '',
+        $location    = '',
+        $n_encoding  = null,
+        $f_encoding  = null,
+        $description = '',
+        $h_charset   = null,
+        $add_headers = array()
+    ) {
+        $bodyfile = null;
+
+        if ($isfile) {
+            // Don't load file into memory
+            if ($this->_build_params['delay_file_io']) {
+                $filedata = null;
+                $bodyfile = $file;
+            } else {
+                if (PEAR::isError($filedata = $this->_file2str($file))) {
+                    return $filedata;
+                }
+            }
             // Force the name the user supplied, otherwise use $file
-            $filename = (strlen($name)) ? $name : $file;
+            $filename = ($name ? $name : $file);
         } else {
+            $filedata = $file;
             $filename = $name;
         }
+
         if (!strlen($filename)) {
             $msg = "The supplied filename for the attachment can't be empty";
             $err = PEAR::raiseError($msg);
             return $err;
         }
-        $filename = basename($filename);
-        if (PEAR::isError($filedata)) {
-            return $filedata;
-        }
+        $filename = $this->_basename($filename);
 
         $this->_parts[] = array(
-                                'body'        => $filedata,
-                                'name'        => $filename,
-                                'c_type'      => $c_type,
-                                'encoding'    => $encoding,
-                                'charset'     => $charset,
-                                'language'    => $language,
-                                'location'    => $location,
-                                'disposition' => $disposition
-                               );
+            'body'        => $filedata,
+            'body_file'   => $bodyfile,
+            'name'        => $filename,
+            'c_type'      => $c_type,
+            'charset'     => $charset,
+            'encoding'    => $encoding,
+            'language'    => $language,
+            'location'    => $location,
+            'disposition' => $disposition,
+            'description' => $description,
+            'add_headers' => $add_headers,
+            'name_encoding'     => $n_encoding,
+            'filename_encoding' => $f_encoding,
+            'headers_charset'   => $h_charset,
+        );
+
         return true;
     }
 
     /**
      * Get the contents of the given file name as string
      *
-     * @param string $file_name path of file to process
+     * @param string $file_name Path of file to process
      *
-     * @return string  contents of $file_name
+     * @return string           Contents of $file_name
      * @access private
      */
     function &_file2str($file_name)
     {
-        if (!is_readable($file_name)) {
-            $err = PEAR::raiseError('File is not readable ' . $file_name);
+        // Check state of file and raise an error properly
+        if (!file_exists($file_name)) {
+            $err = PEAR::raiseError('File not found: ' . $file_name);
             return $err;
         }
-        if (!$fd = fopen($file_name, 'rb')) {
-            $err = PEAR::raiseError('Could not open ' . $file_name);
+        if (!is_file($file_name)) {
+            $err = PEAR::raiseError('Not a regular file: ' . $file_name);
             return $err;
         }
-        $filesize = filesize($file_name);
-        if ($filesize == 0) {
-            $cont =  "";
-        } else {
-            if ($magic_quote_setting = get_magic_quotes_runtime()) {
-                set_magic_quotes_runtime(0);
-            }
-            $cont = fread($fd, $filesize);
-            if ($magic_quote_setting) {
-                set_magic_quotes_runtime($magic_quote_setting);
-            }
+        if (!is_readable($file_name)) {
+            $err = PEAR::raiseError('File is not readable: ' . $file_name);
+            return $err;
+        }
+
+        // Temporarily reset magic_quotes_runtime and read file contents
+        if ($magic_quote_setting = get_magic_quotes_runtime()) {
+            @ini_set('magic_quotes_runtime', 0);
+        }
+        $cont = file_get_contents($file_name);
+        if ($magic_quote_setting) {
+            @ini_set('magic_quotes_runtime', $magic_quote_setting);
         }
-        fclose($fd);
+
         return $cont;
     }
 
@@ -407,10 +495,10 @@ class Mail_mime
      * returns it during the build process.
      *
      * @param mixed  &$obj The object to add the part to, or
-     *                      null if a new object is to be created.
+     *                     null if a new object is to be created.
      * @param string $text The text to add.
      *
-     * @return object  The text mimePart object
+     * @return object      The text mimePart object
      * @access private
      */
     function &_addTextPart(&$obj, $text)
@@ -418,6 +506,8 @@ class Mail_mime
         $params['content_type'] = 'text/plain';
         $params['encoding']     = $this->_build_params['text_encoding'];
         $params['charset']      = $this->_build_params['text_charset'];
+        $params['eol']          = $this->_build_params['eol'];
+
         if (is_object($obj)) {
             $ret = $obj->addSubpart($text, $params);
             return $ret;
@@ -432,9 +522,9 @@ class Mail_mime
      * returns it during the build process.
      *
      * @param mixed &$obj The object to add the part to, or
-     *                     null if a new object is to be created.
+     *                    null if a new object is to be created.
      *
-     * @return object The html mimePart object
+     * @return object     The html mimePart object
      * @access private
      */
     function &_addHtmlPart(&$obj)
@@ -442,6 +532,8 @@ class Mail_mime
         $params['content_type'] = 'text/html';
         $params['encoding']     = $this->_build_params['html_encoding'];
         $params['charset']      = $this->_build_params['html_charset'];
+        $params['eol']          = $this->_build_params['eol'];
+
         if (is_object($obj)) {
             $ret = $obj->addSubpart($this->_htmlbody, $params);
             return $ret;
@@ -463,8 +555,9 @@ class Mail_mime
     {
         $params                 = array();
         $params['content_type'] = 'multipart/mixed';
-        
-        //Create empty multipart/mixed Mail_mimePart object to return
+        $params['eol']          = $this->_build_params['eol'];
+
+        // Create empty multipart/mixed Mail_mimePart object to return
         $ret = new Mail_mimePart('', $params);
         return $ret;
     }
@@ -475,14 +568,16 @@ class Mail_mime
      * the build process.
      *
      * @param mixed &$obj The object to add the part to, or
-     *                     null if a new object is to be created.
+     *                    null if a new object is to be created.
      *
-     * @return object  The multipart/mixed mimePart object
+     * @return object     The multipart/mixed mimePart object
      * @access private
      */
     function &_addAlternativePart(&$obj)
     {
         $params['content_type'] = 'multipart/alternative';
+        $params['eol']          = $this->_build_params['eol'];
+
         if (is_object($obj)) {
             return $obj->addSubpart('', $params);
         } else {
@@ -497,14 +592,16 @@ class Mail_mime
      * the build process.
      *
      * @param mixed &$obj The object to add the part to, or
-     *                     null if a new object is to be created
+     *                    null if a new object is to be created
      *
-     * @return object  The multipart/mixed mimePart object
+     * @return object     The multipart/mixed mimePart object
      * @access private
      */
     function &_addRelatedPart(&$obj)
     {
         $params['content_type'] = 'multipart/related';
+        $params['eol']          = $this->_build_params['eol'];
+
         if (is_object($obj)) {
             return $obj->addSubpart('', $params);
         } else {
@@ -520,7 +617,7 @@ class Mail_mime
      * @param object &$obj  The mimePart to add the image to
      * @param array  $value The image information
      *
-     * @return object  The image mimePart object
+     * @return object       The image mimePart object
      * @access private
      */
     function &_addHtmlImagePart(&$obj, $value)
@@ -528,12 +625,20 @@ class Mail_mime
         $params['content_type'] = $value['c_type'];
         $params['encoding']     = 'base64';
         $params['disposition']  = 'inline';
-        $params['dfilename']    = $value['name'];
+        $params['filename']     = $value['name'];
         $params['cid']          = $value['cid'];
-        
+        $params['body_file']    = $value['body_file'];
+        $params['eol']          = $this->_build_params['eol'];
+
+        if (!empty($value['name_encoding'])) {
+            $params['name_encoding'] = $value['name_encoding'];
+        }
+        if (!empty($value['filename_encoding'])) {
+            $params['filename_encoding'] = $value['filename_encoding'];
+        }
+
         $ret = $obj->addSubpart($value['body'], $params);
         return $ret;
-    
     }
 
     /**
@@ -543,25 +648,46 @@ class Mail_mime
      * @param object &$obj  The mimePart to add the image to
      * @param array  $value The attachment information
      *
-     * @return object  The image mimePart object
+     * @return object       The image mimePart object
      * @access private
      */
     function &_addAttachmentPart(&$obj, $value)
     {
-        $params['dfilename'] = $value['name'];
-        $params['encoding']  = $value['encoding'];
-        if ($value['charset']) {
+        $params['eol']          = $this->_build_params['eol'];
+        $params['filename']     = $value['name'];
+        $params['encoding']     = $value['encoding'];
+        $params['content_type'] = $value['c_type'];
+        $params['body_file']    = $value['body_file'];
+        $params['disposition']  = isset($value['disposition']) ? 
+                                  $value['disposition'] : 'attachment';
+
+        // content charset
+        if (!empty($value['charset'])) {
             $params['charset'] = $value['charset'];
         }
-        if ($value['language']) {
+        // headers charset (filename, description)
+        if (!empty($value['headers_charset'])) {
+            $params['headers_charset'] = $value['headers_charset'];
+        }
+        if (!empty($value['language'])) {
             $params['language'] = $value['language'];
         }
-        if ($value['location']) {
+        if (!empty($value['location'])) {
             $params['location'] = $value['location'];
         }
-        $params['content_type'] = $value['c_type'];
-        $params['disposition']  = isset($value['disposition']) ? 
-                                  $value['disposition'] : 'attachment';
+        if (!empty($value['name_encoding'])) {
+            $params['name_encoding'] = $value['name_encoding'];
+        }
+        if (!empty($value['filename_encoding'])) {
+            $params['filename_encoding'] = $value['filename_encoding'];
+        }
+        if (!empty($value['description'])) {
+            $params['description'] = $value['description'];
+        }
+        if (is_array($value['add_headers'])) {
+            $params['headers'] = $value['add_headers'];
+        }
+
         $ret = $obj->addSubpart($value['body'], $params);
         return $ret;
     }
@@ -571,85 +697,178 @@ class Mail_mime
      * mail delivery method. Note that only the mailpart that is made
      * with Mail_Mime is created. This means that,
      * YOU WILL HAVE NO TO: HEADERS UNLESS YOU SET IT YOURSELF 
-     * using the $xtra_headers parameter!
+     * using the $headers parameter!
      * 
-     * @param string $separation   The separation etween these two parts.
-     * @param array  $build_params The Build parameters passed to the
-     *                             &get() function. See &get for more info.
-     * @param array  $xtra_headers The extra headers that should be passed
-     *                             to the &headers() function.
-     *                             See that function for more info.
-     * @param bool   $overwrite    Overwrite the existing headers with new.
-     *
-     * @return string The complete e-mail.
+     * @param string $separation The separation between these two parts.
+     * @param array  $params     The Build parameters passed to the
+     *                           &get() function. See &get for more info.
+     * @param array  $headers    The extra headers that should be passed
+     *                           to the &headers() function.
+     *                           See that function for more info.
+     * @param bool   $overwrite  Overwrite the existing headers with new.
+     *
+     * @return mixed The complete e-mail or PEAR error object
      * @access public
      */
-    function getMessage(
-                        $separation   = null, 
-                        $build_params = null, 
-                        $xtra_headers = null, 
-                        $overwrite    = false
-                       )
-    {
+    function getMessage($separation = null, $params = null, $headers = null,
+        $overwrite = false
+    ) {
         if ($separation === null) {
-            $separation = MAIL_MIME_CRLF;
+            $separation = $this->_build_params['eol'];
         }
-        $body = $this->get($build_params);
-        $head = $this->txtHeaders($xtra_headers, $overwrite);
+
+        $body = $this->get($params);
+
+        if (PEAR::isError($body)) {
+            return $body;
+        }
+
+        $head = $this->txtHeaders($headers, $overwrite);
         $mail = $head . $separation . $body;
         return $mail;
     }
 
+    /**
+     * Returns the complete e-mail body, ready to send using an alternative
+     * mail delivery method.
+     * 
+     * @param array $params The Build parameters passed to the
+     *                      &get() function. See &get for more info.
+     *
+     * @return mixed The e-mail body or PEAR error object
+     * @access public
+     * @since 1.6.0
+     */
+    function getMessageBody($params = null)
+    {
+        return $this->get($params, null, true);
+    }
+
+    /**
+     * Writes (appends) the complete e-mail into file.
+     * 
+     * @param string $filename  Output file location
+     * @param array  $params    The Build parameters passed to the
+     *                          &get() function. See &get for more info.
+     * @param array  $headers   The extra headers that should be passed
+     *                          to the &headers() function.
+     *                          See that function for more info.
+     * @param bool   $overwrite Overwrite the existing headers with new.
+     *
+     * @return mixed True or PEAR error object
+     * @access public
+     * @since 1.6.0
+     */
+    function saveMessage($filename, $params = null, $headers = null, $overwrite = false)
+    {
+        // Check state of file and raise an error properly
+        if (file_exists($filename) && !is_writable($filename)) {
+            $err = PEAR::raiseError('File is not writable: ' . $filename);
+            return $err;
+        }
+
+        // Temporarily reset magic_quotes_runtime and read file contents
+        if ($magic_quote_setting = get_magic_quotes_runtime()) {
+            @ini_set('magic_quotes_runtime', 0);
+        }
+
+        if (!($fh = fopen($filename, 'ab'))) {
+            $err = PEAR::raiseError('Unable to open file: ' . $filename);
+            return $err;
+        }
+
+        // Write message headers into file (skipping Content-* headers)
+        $head = $this->txtHeaders($headers, $overwrite, true);
+        if (fwrite($fh, $head) === false) {
+            $err = PEAR::raiseError('Error writing to file: ' . $filename);
+            return $err;
+        }
+
+        fclose($fh);
+
+        if ($magic_quote_setting) {
+            @ini_set('magic_quotes_runtime', $magic_quote_setting);
+        }
+
+        // Write the rest of the message into file
+        $res = $this->get($params, $filename);
+
+        return $res ? $res : true;
+    }
+
+    /**
+     * Writes (appends) the complete e-mail body into file.
+     * 
+     * @param string $filename Output file location
+     * @param array  $params   The Build parameters passed to the
+     *                         &get() function. See &get for more info.
+     *
+     * @return mixed True or PEAR error object
+     * @access public
+     * @since 1.6.0
+     */
+    function saveMessageBody($filename, $params = null)
+    {
+        // Check state of file and raise an error properly
+        if (file_exists($filename) && !is_writable($filename)) {
+            $err = PEAR::raiseError('File is not writable: ' . $filename);
+            return $err;
+        }
+
+        // Temporarily reset magic_quotes_runtime and read file contents
+        if ($magic_quote_setting = get_magic_quotes_runtime()) {
+            @ini_set('magic_quotes_runtime', 0);
+        }
+
+        if (!($fh = fopen($filename, 'ab'))) {
+            $err = PEAR::raiseError('Unable to open file: ' . $filename);
+            return $err;
+        }
+
+        // Write the rest of the message into file
+        $res = $this->get($params, $filename, true);
+
+        return $res ? $res : true;
+    }
 
     /**
      * Builds the multipart message from the list ($this->_parts) and
      * returns the mime content.
      *
-     * @param array $build_params Build parameters that change the way the email
-     *                             is built. Should be associative. Can contain:
-     *                head_encoding  -  What encoding to use for the headers. 
-     *                                  Options: quoted-printable or base64
-     *                                  Default is quoted-printable
-     *                text_encoding  -  What encoding to use for plain text
-     *                                  Options: 7bit, 8bit,
-     *                                  base64, or quoted-printable
-     *                                  Default is 7bit
-     *                html_encoding  -  What encoding to use for html
-     *                                  Options: 7bit, 8bit,
-     *                                  base64, or quoted-printable
-     *                                  Default is quoted-printable
-     *                7bit_wrap      -  Number of characters before text is
-     *                                  wrapped in 7bit encoding
-     *                                  Default is 998
-     *                html_charset   -  The character set to use for html.
-     *                                  Default is iso-8859-1
-     *                text_charset   -  The character set to use for text.
-     *                                  Default is iso-8859-1
-     *                head_charset   -  The character set to use for headers.
-     *                                  Default is iso-8859-1
-     *
-     * @return string The mime content
+     * @param array    $params    Build parameters that change the way the email
+     *                            is built. Should be associative. See $_build_params.
+     * @param resource $filename  Output file where to save the message instead of
+     *                            returning it
+     * @param boolean  $skip_head True if you want to return/save only the message
+     *                            without headers
+     *
+     * @return mixed The MIME message content string, null or PEAR error object
      * @access public
      */
-    function &get($build_params = null)
+    function &get($params = null, $filename = null, $skip_head = false)
     {
-        if (isset($build_params)) {
-            while (list($key, $value) = each($build_params)) {
+        if (isset($params)) {
+            while (list($key, $value) = each($params)) {
                 $this->_build_params[$key] = $value;
             }
         }
-        
-        if (isset($this->_headers['From'])){
-            $domain = @strstr($this->_headers['From'],'@');
-            //Bug #11381: Illegal characters in domain ID
-            $domain = str_replace(array("<", ">", "&", "(", ")", " ", "\"", "'"), "", $domain);
-            $domain = urlencode($domain);
-            foreach($this->_html_images as $i => $img){
-                $this->_html_images[$i]['cid'] = $this->_html_images[$i]['cid'] . $domain;
+
+        if (isset($this->_headers['From'])) {
+            // Bug #11381: Illegal characters in domain ID
+            if (preg_match('#(@[0-9a-zA-Z\-\.]+)#', $this->_headers['From'], $matches)) {
+                $domainID = $matches[1];
+            } else {
+                $domainID = '@localhost';
+            }
+            foreach ($this->_html_images as $i => $img) {
+                $cid = $this->_html_images[$i]['cid']; 
+                if (!preg_match('#'.preg_quote($domainID).'$#', $cid)) {
+                    $this->_html_images[$i]['cid'] = $cid . $domainID;
+                }
             }
         }
-        
-        if (count($this->_html_images) AND isset($this->_htmlbody)) {
+
+        if (count($this->_html_images) && isset($this->_htmlbody)) {
             foreach ($this->_html_images as $key => $value) {
                 $regex   = array();
                 $regex[] = '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' .
@@ -659,33 +878,35 @@ class Mail_mime
 
                 $rep   = array();
                 $rep[] = '\1\2=\3cid:' . $value['cid'] .'\3';
-                $rep[] = 'url(\1cid:' . $value['cid'] . '\2)';
+                $rep[] = 'url(\1cid:' . $value['cid'] . '\1)';
 
                 $this->_htmlbody = preg_replace($regex, $rep, $this->_htmlbody);
-                $this->_html_images[$key]['name'] = 
-                    basename($this->_html_images[$key]['name']);
+                $this->_html_images[$key]['name']
+                    = $this->_basename($this->_html_images[$key]['name']);
             }
         }
 
+        $this->_checkParams();
+
         $null        = null;
         $attachments = count($this->_parts)                 ? true : false;
         $html_images = count($this->_html_images)           ? true : false;
         $html        = strlen($this->_htmlbody)             ? true : false;
-        $text        = (!$html AND strlen($this->_txtbody)) ? true : false;
+        $text        = (!$html && strlen($this->_txtbody))  ? true : false;
 
         switch (true) {
-        case $text AND !$attachments:
+        case $text && !$attachments:
             $message =& $this->_addTextPart($null, $this->_txtbody);
             break;
 
-        case !$text AND !$html AND $attachments:
+        case !$text && !$html && $attachments:
             $message =& $this->_addMixedPart();
             for ($i = 0; $i < count($this->_parts); $i++) {
                 $this->_addAttachmentPart($message, $this->_parts[$i]);
             }
             break;
 
-        case $text AND $attachments:
+        case $text && $attachments:
             $message =& $this->_addMixedPart();
             $this->_addTextPart($message, $this->_txtbody);
             for ($i = 0; $i < count($this->_parts); $i++) {
@@ -693,7 +914,7 @@ class Mail_mime
             }
             break;
 
-        case $html AND !$attachments AND !$html_images:
+        case $html && !$attachments && !$html_images:
             if (isset($this->_txtbody)) {
                 $message =& $this->_addAlternativePart($null);
                 $this->_addTextPart($message, $this->_txtbody);
@@ -703,7 +924,38 @@ class Mail_mime
             }
             break;
 
-        case $html AND !$attachments AND $html_images:
+        case $html && !$attachments && $html_images:
+            // * Content-Type: multipart/alternative;
+            //    * text
+            //    * Content-Type: multipart/related;
+            //       * html
+            //       * image...
+            if (isset($this->_txtbody)) {
+                $message =& $this->_addAlternativePart($null);
+                $this->_addTextPart($message, $this->_txtbody);
+
+                $ht =& $this->_addRelatedPart($message);
+                $this->_addHtmlPart($ht);
+                for ($i = 0; $i < count($this->_html_images); $i++) {
+                    $this->_addHtmlImagePart($ht, $this->_html_images[$i]);
+                }
+            } else {
+                // * Content-Type: multipart/related;
+                //    * html
+                //    * image...
+                $message =& $this->_addRelatedPart($null);
+                $this->_addHtmlPart($message);
+                for ($i = 0; $i < count($this->_html_images); $i++) {
+                    $this->_addHtmlImagePart($message, $this->_html_images[$i]);
+                }
+            }
+            /*
+            // #13444, #9725: the code below was a non-RFC compliant hack
+            // * Content-Type: multipart/related;
+            //    * Content-Type: multipart/alternative;
+            //        * text
+            //        * html
+            //    * image...
             $message =& $this->_addRelatedPart($null);
             if (isset($this->_txtbody)) {
                 $alt =& $this->_addAlternativePart($message);
@@ -715,9 +967,10 @@ class Mail_mime
             for ($i = 0; $i < count($this->_html_images); $i++) {
                 $this->_addHtmlImagePart($message, $this->_html_images[$i]);
             }
+            */
             break;
 
-        case $html AND $attachments AND !$html_images:
+        case $html && $attachments && !$html_images:
             $message =& $this->_addMixedPart();
             if (isset($this->_txtbody)) {
                 $alt =& $this->_addAlternativePart($message);
@@ -731,7 +984,7 @@ class Mail_mime
             }
             break;
 
-        case $html AND $attachments AND $html_images:
+        case $html && $attachments && $html_images:
             $message =& $this->_addMixedPart();
             if (isset($this->_txtbody)) {
                 $alt =& $this->_addAlternativePart($message);
@@ -751,17 +1004,36 @@ class Mail_mime
 
         }
 
-        if (isset($message)) {
-            $output = $message->encode();
-            
-            $this->_headers = array_merge($this->_headers,
-                                          $output['headers']);
-            $body = $output['body'];
-            return $body;
+        if (!isset($message)) {
+            $ret = null;
+            return $ret;
+        }
 
+        // Use saved boundary
+        if (!empty($this->_build_params['boundary'])) {
+            $boundary = $this->_build_params['boundary'];
         } else {
-            $ret = false;
+            $boundary = null;
+        }
+
+        // Write output to file
+        if ($filename) {
+            // Append mimePart message headers and body into file
+            $headers = $message->encodeToFile($filename, $boundary, $skip_head);
+            if (PEAR::isError($headers)) {
+                return $headers;
+            }
+            $this->_headers = array_merge($this->_headers, $headers);
+            $ret = null;
             return $ret;
+        } else {
+            $output = $message->encode($boundary, $skip_head);
+            if (PEAR::isError($output)) {
+                return $output;
+            }
+            $this->_headers = array_merge($this->_headers, $output['headers']);
+            $body = $output['body'];
+            return $body;
         }
     }
 
@@ -770,28 +1042,49 @@ class Mail_mime
      * (MIME-Version and Content-Type). Format of argument is:
      * $array['header-name'] = 'header-value';
      *
-     * @param array $xtra_headers Assoc array with any extra headers.
-     *                             Optional.
+     * @param array $xtra_headers Assoc array with any extra headers (optional)
+     *                            (Don't set Content-Type for multipart messages here!)
      * @param bool  $overwrite    Overwrite already existing headers.
+     * @param bool  $skip_content Don't return content headers: Content-Type,
+     *                            Content-Disposition and Content-Transfer-Encoding
      * 
-     * @return array Assoc array with the mime headers
+     * @return array              Assoc array with the mime headers
      * @access public
      */
-    function &headers($xtra_headers = null, $overwrite = false)
+    function &headers($xtra_headers = null, $overwrite = false, $skip_content = false)
     {
-        // Content-Type header should already be present,
-        // So just add mime version header
+        // Add mime version header
         $headers['MIME-Version'] = '1.0';
-        if (isset($xtra_headers)) {
+
+        // Content-Type and Content-Transfer-Encoding headers should already
+        // be present if get() was called, but we'll re-set them to make sure
+        // we got them when called before get() or something in the message
+        // has been changed after get() [#14780]
+        if (!$skip_content) {
+            $headers += $this->_contentHeaders();
+        }
+
+        if (!empty($xtra_headers)) {
             $headers = array_merge($headers, $xtra_headers);
         }
+
         if ($overwrite) {
             $this->_headers = array_merge($this->_headers, $headers);
         } else {
             $this->_headers = array_merge($headers, $this->_headers);
         }
 
-        $encodedHeaders = $this->_encodeHeaders($this->_headers);
+        $headers = $this->_headers;
+
+        if ($skip_content) {
+            unset($headers['Content-Type']);
+            unset($headers['Content-Transfer-Encoding']);
+            unset($headers['Content-Disposition']);
+        } else if (!empty($this->_build_params['ctype'])) {
+            $headers['Content-Type'] = $this->_build_params['ctype'];
+        }
+
+        $encodedHeaders = $this->_encodeHeaders($headers);
         return $encodedHeaders;
     }
 
@@ -799,24 +1092,91 @@ class Mail_mime
      * Get the text version of the headers
      * (usefull if you want to use the PHP mail() function)
      *
-     * @param array $xtra_headers Assoc array with any extra headers.
-     *                             Optional.
-     * @param bool  $overwrite    Overwrite the existing heaers with new.
+     * @param array $xtra_headers Assoc array with any extra headers (optional)
+     *                            (Don't set Content-Type for multipart messages here!)
+     * @param bool  $overwrite    Overwrite the existing headers with new.
+     * @param bool  $skip_content Don't return content headers: Content-Type,
+     *                            Content-Disposition and Content-Transfer-Encoding
      *
-     * @return string  Plain text headers
+     * @return string             Plain text headers
      * @access public
      */
-    function txtHeaders($xtra_headers = null, $overwrite = false)
+    function txtHeaders($xtra_headers = null, $overwrite = false, $skip_content = false)
     {
-        $headers = $this->headers($xtra_headers, $overwrite);
-        
+        $headers = $this->headers($xtra_headers, $overwrite, $skip_content);
+
+        // Place Received: headers at the beginning of the message
+        // Spam detectors often flag messages with it after the Subject: as spam
+        if (isset($headers['Received'])) {
+            $received = $headers['Received'];
+            unset($headers['Received']);
+            $headers = array('Received' => $received) + $headers;
+        }
+
         $ret = '';
+        $eol = $this->_build_params['eol'];
+
         foreach ($headers as $key => $val) {
-            $ret .= "$key: $val" . MAIL_MIME_CRLF;
+            if (is_array($val)) {
+                foreach ($val as $value) {
+                    $ret .= "$key: $value" . $eol;
+                }
+            } else {
+                $ret .= "$key: $val" . $eol;
+            }
         }
+
         return $ret;
     }
 
+    /**
+     * Sets message Content-Type header.
+     * Use it to build messages with various content-types e.g. miltipart/raport
+     * not supported by _contentHeaders() function.
+     *
+     * @param string $type   Type name
+     * @param array  $params Hash array of header parameters
+     *
+     * @return void
+     * @access public
+     * @since 1.7.0
+     */
+    function setContentType($type, $params = array())
+    {
+        $header = $type;
+
+        $eol = !empty($this->_build_params['eol'])
+            ? $this->_build_params['eol'] : "\r\n";
+
+        // add parameters
+        $token_regexp = '#([^\x21\x23-\x27\x2A\x2B\x2D'
+            . '\x2E\x30-\x39\x41-\x5A\x5E-\x7E])#';
+        if (is_array($params)) {
+            foreach ($params as $name => $value) {
+                if ($name == 'boundary') {
+                    $this->_build_params['boundary'] = $value;
+                }
+                if (!preg_match($token_regexp, $value)) {
+                    $header .= ";$eol $name=$value";
+                } else {
+                    $value = addcslashes($value, '\\"');
+                    $header .= ";$eol $name=\"$value\"";
+                }
+            }
+        }
+
+        // add required boundary parameter if not defined
+        if (preg_match('/^multipart\//i', $type)) {
+            if (empty($this->_build_params['boundary'])) {
+                $this->_build_params['boundary'] = '=_' . md5(rand() . microtime());
+            }
+
+            $header .= ";$eol boundary=\"".$this->_build_params['boundary']."\"";
+        }
+
+        $this->_build_params['ctype'] = $header;
+    }
+
     /**
      * Sets the Subject header
      *
@@ -843,6 +1203,24 @@ class Mail_mime
         $this->_headers['From'] = $email;
     }
 
+    /**
+     * Add an email to the To header
+     * (multiple calls to this method are allowed)
+     *
+     * @param string $email The email direction to add
+     *
+     * @return void
+     * @access public
+     */
+    function addTo($email)
+    {
+        if (isset($this->_headers['To'])) {
+            $this->_headers['To'] .= ", $email";
+        } else {
+            $this->_headers['To'] = $email;
+        }
+    }
+
     /**
      * Add an email to the Cc (carbon copy) header
      * (multiple calls to this method are allowed)
@@ -880,7 +1258,7 @@ class Mail_mime
     }
 
     /**
-     * Since the PHP send function requires you to specifiy 
+     * Since the PHP send function requires you to specify
      * recipients (To: header) separately from the other
      * headers, the To: header is not properly encoded.
      * To fix this, you can use this public method to 
@@ -889,7 +1267,7 @@ class Mail_mime
      *
      * @param string $recipients A comma-delimited list of recipients
      *
-     * @return string Encoded data
+     * @return string            Encoded data
      * @access public
      */
     function encodeRecipients($recipients)
@@ -900,196 +1278,199 @@ class Mail_mime
     }
 
     /**
-     * Encodes a header as per RFC2047
+     * Encodes headers as per RFC2047
      *
      * @param array $input  The header data to encode
      * @param array $params Extra build parameters
      *
-     * @return array Encoded data
+     * @return array        Encoded data
      * @access private
      */
     function _encodeHeaders($input, $params = array())
     {
-        
         $build_params = $this->_build_params;
         while (list($key, $value) = each($params)) {
             $build_params[$key] = $value;
         }
-        //$hdr_name: Name of the heaer
-        //$hdr_value: Full line of header value.
-        //$hdr_value_out: The recombined $hdr_val-atoms, or the encoded string.
-                
-        $useIconv = true;        
-        if (isset($build_params['ignore-iconv'])) {
-            $useIconv = !$build_params['ignore-iconv'];
-        }            
+
         foreach ($input as $hdr_name => $hdr_value) {
-            if (preg_match('#([\x80-\xFF]){1}#', $hdr_value)) {
-                if (function_exists('iconv_mime_encode') && $useIconv) {
-                    $imePrefs = array();
-                    if ($build_params['head_encoding'] == 'base64') {
-                        $imePrefs['scheme'] = 'B';
-                    } else {
-                        $imePrefs['scheme'] = 'Q';
-                    }
-                    $imePrefs['input-charset']  = $build_params['head_charset'];
-                    $imePrefs['output-charset'] = $build_params['head_charset'];
-                    $imePrefs['line-length'] = 74;
-                    $imePrefs['line-break-chars'] = "\r\n"; //Specified in RFC2047
-                    
-                    $hdr_value = iconv_mime_encode($hdr_name, $hdr_value, $imePrefs);
-                    $hdr_value = preg_replace("#^{$hdr_name}\:\ #", "", $hdr_value);
-                } elseif ($build_params['head_encoding'] == 'base64') {
-                    //Base64 encoding has been selected.
-                    //Base64 encode the entire string
-                    $hdr_value = base64_encode($hdr_value);
-                    
-                    //Generate the header using the specified params and dynamicly 
-                    //determine the maximum length of such strings.
-                    //75 is the value specified in the RFC. The first -2 is there so 
-                    //the later regexp doesn't break any of the translated chars.
-                    //The -2 on the first line-regexp is to compensate for the ": "
-                    //between the header-name and the header value
-                    $prefix = '=?' . $build_params['head_charset'] . '?B?';
-                    $suffix = '?=';
-                    $maxLength = 75 - strlen($prefix . $suffix) - 2;
-                    $maxLength1stLine = $maxLength - strlen($hdr_name) - 2;
-
-                    //We can cut base4 every 4 characters, so the real max
-                    //we can get must be rounded down.
-                    $maxLength = $maxLength - ($maxLength % 4);
-                    $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
-                    
-                    $cutpoint = $maxLength1stLine;
-                    $hdr_value_out = $hdr_value;
-                    $output = "";
-                    while ($hdr_value_out) {
-                        //Split translated string at every $maxLength
-                        $part = substr($hdr_value_out, 0, $cutpoint);
-                        $hdr_value_out = substr($hdr_value_out, $cutpoint);
-                        $cutpoint = $maxLength;
-                        //RFC 2047 specifies that any split header should 
-                        //be seperated by a CRLF SPACE. 
-                        if ($output) {
-                            $output .=  "\r\n ";
-                        }
-                        $output .= $prefix . $part . $suffix;
-                    }
-                    $hdr_value = $output;
-                } else {
-                    //quoted-printable encoding has been selected
-
-                    //Fix for Bug #10298, Ota Mares <om@viazenetti.de>
-                    //Check if there is a double quote at beginning or end of
-                    //the string to prevent that an open or closing quote gets 
-                    //ignored because it is encapsuled by an encoding pre/suffix.
-                    //Remove the double quote and set the specific prefix or 
-                    //suffix variable so that we can concat the encoded string and
-                    //the double quotes back together to get the intended string.
-                    $quotePrefix = $quoteSuffix = '';
-                    if ($hdr_value{0} == '"') {
-                        $hdr_value = substr($hdr_value, 1);
-                        $quotePrefix = '"';
-                    }
-                    if ($hdr_value{strlen($hdr_value)-1} == '"') {
-                        $hdr_value = substr($hdr_value, 0, -1);
-                        $quoteSuffix = '"';
-                    }
-                    
-                    //Generate the header using the specified params and dynamicly 
-                    //determine the maximum length of such strings.
-                    //75 is the value specified in the RFC. The -2 is there so 
-                    //the later regexp doesn't break any of the translated chars.
-                    //The -2 on the first line-regexp is to compensate for the ": "
-                    //between the header-name and the header value
-                    $prefix = '=?' . $build_params['head_charset'] . '?Q?';
-                    $suffix = '?=';
-                    $maxLength = 75 - strlen($prefix . $suffix) - 2 - 1;
-                    $maxLength1stLine = $maxLength - strlen($hdr_name) - 2;
-                    $maxLength = $maxLength - 1;
-                    
-                    //Replace all special characters used by the encoder.
-                    $search  = array('=',   '_',   '?',   ' ');
-                    $replace = array('=3D', '=5F', '=3F', '_');
-                    $hdr_value = str_replace($search, $replace, $hdr_value);
-                    
-                    //Replace all extended characters (\x80-xFF) with their
-                    //ASCII values.
-                    $hdr_value = preg_replace('#([\x80-\xFF])#e',
-                        '"=" . strtoupper(dechex(ord("\1")))',
-                        $hdr_value);
-
-                    //This regexp will break QP-encoded text at every $maxLength
-                    //but will not break any encoded letters.
-                    $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
-                    $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
-                    //Fix for Bug #10298, Ota Mares <om@viazenetti.de>
-                    //Concat the double quotes and encoded string together
-                    $hdr_value = $quotePrefix . $hdr_value . $quoteSuffix;
-                    
-
-                    $hdr_value_out = $hdr_value;
-                    $realMax = $maxLength1stLine + strlen($prefix . $suffix);
-                    if (strlen($hdr_value_out) >= $realMax) {
-                        //Begin with the regexp for the first line.
-                        $reg = $reg1st;
-                        $output = "";
-                        while ($hdr_value_out) {
-                            //Split translated string at every $maxLength
-                            //But make sure not to break any translated chars.
-                            $found = preg_match($reg, $hdr_value_out, $matches);
-                            
-                            //After this first line, we need to use a different
-                            //regexp for the first line.
-                            $reg = $reg2nd;
-                            
-                            //Save the found part and encapsulate it in the
-                            //prefix & suffix. Then remove the part from the
-                            //$hdr_value_out variable.
-                            if ($found) {
-                                $part = $matches[0];
-                                $len = strlen($matches[0]);
-                                $hdr_value_out = substr($hdr_value_out, $len);
-                            } else {
-                                $part = $hdr_value_out;
-                                $hdr_value_out = "";
-                            }
-                            
-                            //RFC 2047 specifies that any split header should 
-                            //be seperated by a CRLF SPACE
-                            if ($output) {
-                                $output .=  "\r\n ";
-                            }
-                            $output .= $prefix . $part . $suffix;
-                        }
-                        $hdr_value_out = $output;
-                    } else {
-                        $hdr_value_out = $prefix . $hdr_value_out . $suffix;
-                    }
-                    $hdr_value = $hdr_value_out;
+            if (is_array($hdr_value)) {
+                foreach ($hdr_value as $idx => $value) {
+                    $input[$hdr_name][$idx] = $this->encodeHeader(
+                        $hdr_name, $value,
+                        $build_params['head_charset'], $build_params['head_encoding']
+                    );
                 }
+            } else {
+                $input[$hdr_name] = $this->encodeHeader(
+                    $hdr_name, $hdr_value,
+                    $build_params['head_charset'], $build_params['head_encoding']
+                );
             }
-            $input[$hdr_name] = $hdr_value;
         }
+
         return $input;
     }
 
     /**
-     * Set the object's end-of-line and define the constant if applicable.
+     * Encodes a header as per RFC2047
      *
-     * @param string $eol End Of Line sequence
+     * @param string $name     The header name
+     * @param string $value    The header data to encode
+     * @param string $charset  Character set name
+     * @param string $encoding Encoding name (base64 or quoted-printable)
      *
-     * @return void
+     * @return string          Encoded header data (without a name)
+     * @access public
+     * @since 1.5.3
+     */
+    function encodeHeader($name, $value, $charset, $encoding)
+    {
+        $mime_part = new Mail_mimePart;
+        return $mime_part->encodeHeader(
+            $name, $value, $charset, $encoding, $this->_build_params['eol']
+        );
+    }
+
+    /**
+     * Get file's basename (locale independent) 
+     *
+     * @param string $filename Filename
+     *
+     * @return string          Basename
      * @access private
      */
-    function _setEOL($eol)
+    function _basename($filename)
     {
-        $this->_eol = $eol;
-        if (!defined('MAIL_MIME_CRLF')) {
-            define('MAIL_MIME_CRLF', $this->_eol, true);
+        // basename() is not unicode safe and locale dependent
+        if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
+            return preg_replace('/^.*[\\\\\\/]/', '', $filename);
+        } else {
+            return preg_replace('/^.*[\/]/', '', $filename);
         }
     }
 
-    
+    /**
+     * Get Content-Type and Content-Transfer-Encoding headers of the message
+     *
+     * @return array Headers array
+     * @access private
+     */
+    function _contentHeaders()
+    {
+        $attachments = count($this->_parts)                 ? true : false;
+        $html_images = count($this->_html_images)           ? true : false;
+        $html        = strlen($this->_htmlbody)             ? true : false;
+        $text        = (!$html && strlen($this->_txtbody))  ? true : false;
+        $headers     = array();
+
+        // See get()
+        switch (true) {
+        case $text && !$attachments:
+            $headers['Content-Type'] = 'text/plain';
+            break;
+
+        case !$text && !$html && $attachments:
+        case $text && $attachments:
+        case $html && $attachments && !$html_images:
+        case $html && $attachments && $html_images:
+            $headers['Content-Type'] = 'multipart/mixed';
+            break;
+
+        case $html && !$attachments && !$html_images && isset($this->_txtbody):
+        case $html && !$attachments && $html_images && isset($this->_txtbody):
+            $headers['Content-Type'] = 'multipart/alternative';
+            break;
+
+        case $html && !$attachments && !$html_images && !isset($this->_txtbody):
+            $headers['Content-Type'] = 'text/html';
+            break;
+
+        case $html && !$attachments && $html_images && !isset($this->_txtbody):
+            $headers['Content-Type'] = 'multipart/related';
+            break;
+
+        default:
+            return $headers;
+        }
+
+        $this->_checkParams();
+
+        $eol = !empty($this->_build_params['eol'])
+            ? $this->_build_params['eol'] : "\r\n";
+
+        if ($headers['Content-Type'] == 'text/plain') {
+            // single-part message: add charset and encoding
+            $charset = 'charset=' . $this->_build_params['text_charset'];
+            // place charset parameter in the same line, if possible
+            // 26 = strlen("Content-Type: text/plain; ")
+            $headers['Content-Type']
+                .= (strlen($charset) + 26 <= 76) ? "; $charset" : ";$eol $charset";
+            $headers['Content-Transfer-Encoding']
+                = $this->_build_params['text_encoding'];
+        } else if ($headers['Content-Type'] == 'text/html') {
+            // single-part message: add charset and encoding
+            $charset = 'charset=' . $this->_build_params['html_charset'];
+            // place charset parameter in the same line, if possible
+            $headers['Content-Type']
+                .= (strlen($charset) + 25 <= 76) ? "; $charset" : ";$eol $charset";
+            $headers['Content-Transfer-Encoding']
+                = $this->_build_params['html_encoding'];
+        } else {
+            // multipart message: and boundary
+            if (!empty($this->_build_params['boundary'])) {
+                $boundary = $this->_build_params['boundary'];
+            } else if (!empty($this->_headers['Content-Type'])
+                && preg_match('/boundary="([^"]+)"/', $this->_headers['Content-Type'], $m)
+            ) {
+                $boundary = $m[1];
+            } else {
+                $boundary = '=_' . md5(rand() . microtime());
+            }
+
+            $this->_build_params['boundary'] = $boundary;
+            $headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
+        }
+
+        return $headers;
+    }
+
+    /**
+     * Validate and set build parameters
+     *
+     * @return void
+     * @access private
+     */
+    function _checkParams()
+    {
+        $encodings = array('7bit', '8bit', 'base64', 'quoted-printable');
+
+        $this->_build_params['text_encoding']
+            = strtolower($this->_build_params['text_encoding']);
+        $this->_build_params['html_encoding']
+            = strtolower($this->_build_params['html_encoding']);
+
+        if (!in_array($this->_build_params['text_encoding'], $encodings)) {
+            $this->_build_params['text_encoding'] = '7bit';
+        }
+        if (!in_array($this->_build_params['html_encoding'], $encodings)) {
+            $this->_build_params['html_encoding'] = '7bit';
+        }
+
+        // text body
+        if ($this->_build_params['text_encoding'] == '7bit'
+            && !preg_match('/ascii/i', $this->_build_params['text_charset'])
+            && preg_match('/[^\x00-\x7F]/', $this->_txtbody)
+        ) {
+            $this->_build_params['text_encoding'] = 'quoted-printable';
+        }
+        // html body
+        if ($this->_build_params['html_encoding'] == '7bit'
+            && !preg_match('/ascii/i', $this->_build_params['html_charset'])
+            && preg_match('/[^\x00-\x7F]/', $this->_htmlbody)
+        ) {
+            $this->_build_params['html_encoding'] = 'quoted-printable';
+        }
+    }
 
 } // End of class
diff --git a/include/pear/Mail/mimePart.php b/include/pear/Mail/mimePart.php
index 7ad54e5ef58d1c6ee919b310af05dbfa38bf7a8b..a839402f7a6648c1ffe6ef61284770190c8933f1 100644
--- a/include/pear/Mail/mimePart.php
+++ b/include/pear/Mail/mimePart.php
@@ -40,15 +40,16 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
- * @category   Mail
- * @package    Mail_Mime
- * @author     Richard Heyes  <richard@phpguru.org>
- * @author     Cipriano Groenendal <cipri@php.net>
- * @author     Sean Coates <sean@php.net>
- * @copyright  2003-2006 PEAR <pear-group@php.net>
- * @license    http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version    CVS: $Id: mimePart.php,v 1.25 2007/05/14 21:43:08 cipri Exp $
- * @link       http://pear.php.net/package/Mail_mime
+ * @category  Mail
+ * @package   Mail_Mime
+ * @author    Richard Heyes  <richard@phpguru.org>
+ * @author    Cipriano Groenendal <cipri@php.net>
+ * @author    Sean Coates <sean@php.net>
+ * @author    Aleksander Machniak <alec@php.net>
+ * @copyright 2003-2006 PEAR <pear-group@php.net>
+ * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
+ * @version   CVS: $Id$
+ * @link      http://pear.php.net/package/Mail_mime
  */
 
 
@@ -61,19 +62,20 @@
  * of mime mail.
  * This class however allows full control over the email.
  *
- * @category   Mail
- * @package    Mail_Mime
- * @author     Richard Heyes  <richard@phpguru.org>
- * @author     Cipriano Groenendal <cipri@php.net>
- * @author     Sean Coates <sean@php.net>
- * @copyright  2003-2006 PEAR <pear-group@php.net>
- * @license    http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version    Release: @package_version@
- * @link       http://pear.php.net/package/Mail_mime
+ * @category  Mail
+ * @package   Mail_Mime
+ * @author    Richard Heyes  <richard@phpguru.org>
+ * @author    Cipriano Groenendal <cipri@php.net>
+ * @author    Sean Coates <sean@php.net>
+ * @author    Aleksander Machniak <alec@php.net>
+ * @copyright 2003-2006 PEAR <pear-group@php.net>
+ * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/Mail_mime
  */
-class Mail_mimePart {
-
-   /**
+class Mail_mimePart
+{
+    /**
     * The encoding type of this part
     *
     * @var string
@@ -81,7 +83,7 @@ class Mail_mimePart {
     */
     var $_encoding;
 
-   /**
+    /**
     * An array of subparts
     *
     * @var array
@@ -89,7 +91,7 @@ class Mail_mimePart {
     */
     var $_subparts;
 
-   /**
+    /**
     * The output of this part after being built
     *
     * @var string
@@ -97,7 +99,7 @@ class Mail_mimePart {
     */
     var $_encoded;
 
-   /**
+    /**
     * Headers for this part
     *
     * @var array
@@ -105,7 +107,7 @@ class Mail_mimePart {
     */
     var $_headers;
 
-   /**
+    /**
     * The body of this part (not encoded)
     *
     * @var string
@@ -114,106 +116,169 @@ class Mail_mimePart {
     var $_body;
 
     /**
-     * Constructor.
-     *
-     * Sets up the object.
-     *
-     * @param $body   - The body of the mime part if any.
-     * @param $params - An associative array of parameters:
-     *                  content_type - The content type for this part eg multipart/mixed
-     *                  encoding     - The encoding to use, 7bit, 8bit, base64, or quoted-printable
-     *                  cid          - Content ID to apply
-     *                  disposition  - Content disposition, inline or attachment
-     *                  dfilename    - Optional filename parameter for content disposition
-     *                  description  - Content description
-     *                  charset      - Character set to use
-     * @access public
-     */
+    * The location of file with body of this part (not encoded)
+    *
+    * @var string
+    * @access private
+    */
+    var $_body_file;
+
+    /**
+    * The end-of-line sequence
+    *
+    * @var string
+    * @access private
+    */
+    var $_eol = "\r\n";
+
+
+    /**
+    * Constructor.
+    *
+    * Sets up the object.
+    *
+    * @param string $body   The body of the mime part if any.
+    * @param array  $params An associative array of optional parameters:
+    *     content_type      - The content type for this part eg multipart/mixed
+    *     encoding          - The encoding to use, 7bit, 8bit,
+    *                         base64, or quoted-printable
+    *     charset           - Content character set
+    *     cid               - Content ID to apply
+    *     disposition       - Content disposition, inline or attachment
+    *     filename          - Filename parameter for content disposition
+    *     description       - Content description
+    *     name_encoding     - Encoding of the attachment name (Content-Type)
+    *                         By default filenames are encoded using RFC2231
+    *                         Here you can set RFC2047 encoding (quoted-printable
+    *                         or base64) instead
+    *     filename_encoding - Encoding of the attachment filename (Content-Disposition)
+    *                         See 'name_encoding'
+    *     headers_charset   - Charset of the headers e.g. filename, description.
+    *                         If not set, 'charset' will be used
+    *     eol               - End of line sequence. Default: "\r\n"
+    *     headers           - Hash array with additional part headers. Array keys can be
+    *                         in form of <header_name>:<parameter_name>
+    *     body_file         - Location of file with part's body (instead of $body)
+    *
+    * @access public
+    */
     function Mail_mimePart($body = '', $params = array())
     {
-        if (!defined('MAIL_MIMEPART_CRLF')) {
-            define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", TRUE);
+        if (!empty($params['eol'])) {
+            $this->_eol = $params['eol'];
+        } else if (defined('MAIL_MIMEPART_CRLF')) { // backward-copat.
+            $this->_eol = MAIL_MIMEPART_CRLF;
+        }
+
+        // Additional part headers
+        if (!empty($params['headers']) && is_array($params['headers'])) {
+            $headers = $params['headers'];
         }
 
-        $contentType = array();
-        $contentDisp = array();
         foreach ($params as $key => $value) {
             switch ($key) {
-                case 'content_type':
-                    $contentType['type'] = $value;
-                    //$headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
-                    break;
-
-                case 'encoding':
-                    $this->_encoding = $value;
-                    $headers['Content-Transfer-Encoding'] = $value;
-                    break;
-
-                case 'cid':
-                    $headers['Content-ID'] = '<' . $value . '>';
-                    break;
-
-                case 'disposition':
-                    $contentDisp['disp'] = $value;
-                    break;
-
-                case 'dfilename':
-                    $contentDisp['filename'] = $value;
-                    $contentType['name'] = $value;
-                    break;
-
-                case 'description':
-                    $headers['Content-Description'] = $value;
-                    break;
-
-                case 'charset':
-                    $contentType['charset'] = $value;
-                    $contentDisp['charset'] = $value;
-                    break;
-
-                case 'language':
-                    $contentType['language'] = $value;
-                    $contentDisp['language'] = $value;
-                    break;
-
-                case 'location':
-                    $headers['Content-Location'] = $value;
-                    break;
+            case 'encoding':
+                $this->_encoding = $value;
+                $headers['Content-Transfer-Encoding'] = $value;
+                break;
 
+            case 'cid':
+                $headers['Content-ID'] = '<' . $value . '>';
+                break;
+
+            case 'location':
+                $headers['Content-Location'] = $value;
+                break;
+
+            case 'body_file':
+                $this->_body_file = $value;
+                break;
+
+            // for backward compatibility
+            case 'dfilename':
+                $params['filename'] = $value;
+                break;
             }
         }
-        if (isset($contentType['type'])) {
-            $headers['Content-Type'] = $contentType['type'];
-            if (isset($contentType['name'])) {
-                $headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF;
-                $headers['Content-Type'] .= $this->_buildHeaderParam('name', $contentType['name'], 
-                                                isset($contentType['charset']) ? $contentType['charset'] : 'US-ASCII', 
-                                                isset($contentType['language']) ? $contentType['language'] : NULL);
-            } elseif (isset($contentType['charset'])) {
-                $headers['Content-Type'] .= "; charset=\"{$contentType['charset']}\"";
+
+        // Default content-type
+        if (empty($params['content_type'])) {
+            $params['content_type'] = 'text/plain';
+        }
+
+        // Content-Type
+        $headers['Content-Type'] = $params['content_type'];
+        if (!empty($params['charset'])) {
+            $charset = "charset={$params['charset']}";
+            // place charset parameter in the same line, if possible
+            if ((strlen($headers['Content-Type']) + strlen($charset) + 16) <= 76) {
+                $headers['Content-Type'] .= '; ';
+            } else {
+                $headers['Content-Type'] .= ';' . $this->_eol . ' ';
             }
+            $headers['Content-Type'] .= $charset;
+
+            // Default headers charset
+            if (!isset($params['headers_charset'])) {
+                $params['headers_charset'] = $params['charset'];
+            }
+        }
+
+        // header values encoding parameters
+        $h_charset  = !empty($params['headers_charset']) ? $params['headers_charset'] : 'US-ASCII';
+        $h_language = !empty($params['language']) ? $params['language'] : null;
+        $h_encoding = !empty($params['name_encoding']) ? $params['name_encoding'] : null;
+
+
+        if (!empty($params['filename'])) {
+            $headers['Content-Type'] .= ';' . $this->_eol;
+            $headers['Content-Type'] .= $this->_buildHeaderParam(
+                'name', $params['filename'], $h_charset, $h_language, $h_encoding
+            );
         }
 
+        // Content-Disposition
+        if (!empty($params['disposition'])) {
+            $headers['Content-Disposition'] = $params['disposition'];
+            if (!empty($params['filename'])) {
+                $headers['Content-Disposition'] .= ';' . $this->_eol;
+                $headers['Content-Disposition'] .= $this->_buildHeaderParam(
+                    'filename', $params['filename'], $h_charset, $h_language,
+                    !empty($params['filename_encoding']) ? $params['filename_encoding'] : null
+                );
+            }
 
-        if (isset($contentDisp['disp'])) {
-            $headers['Content-Disposition'] = $contentDisp['disp'];
-            if (isset($contentDisp['filename'])) {
-                $headers['Content-Disposition'] .= ';' . MAIL_MIMEPART_CRLF;
-                $headers['Content-Disposition'] .= $this->_buildHeaderParam('filename', $contentDisp['filename'], 
-                                                isset($contentDisp['charset']) ? $contentDisp['charset'] : 'US-ASCII', 
-                                                isset($contentDisp['language']) ? $contentDisp['language'] : NULL);
+            // add attachment size
+            $size = $this->_body_file ? filesize($this->_body_file) : strlen($body);
+            if ($size) {
+                $headers['Content-Disposition'] .= ';' . $this->_eol . ' size=' . $size;
             }
         }
-        
-        
-        
-        
-        // Default content-type
-        if (!isset($headers['Content-Type'])) {
-            $headers['Content-Type'] = 'text/plain';
+
+        if (!empty($params['description'])) {
+            $headers['Content-Description'] = $this->encodeHeader(
+                'Content-Description', $params['description'], $h_charset, $h_encoding,
+                $this->_eol
+            );
+        }
+
+        // Search and add existing headers' parameters
+        foreach ($headers as $key => $value) {
+            $items = explode(':', $key);
+            if (count($items) == 2) {
+                $header = $items[0];
+                $param  = $items[1];
+                if (isset($headers[$header])) {
+                    $headers[$header] .= ';' . $this->_eol;
+                }
+                $headers[$header] .= $this->_buildHeaderParam(
+                    $param, $value, $h_charset, $h_language, $h_encoding
+                );
+                unset($headers[$key]);
+            }
         }
 
-        //Default encoding
+        // Default encoding
         if (!isset($this->_encoding)) {
             $this->_encoding = '7bit';
         }
@@ -225,41 +290,60 @@ class Mail_mimePart {
     }
 
     /**
-     * encode()
-     *
      * Encodes and returns the email. Also stores
      * it in the encoded member variable
      *
+     * @param string $boundary Pre-defined boundary string
+     *
      * @return An associative array containing two elements,
      *         body and headers. The headers element is itself
-     *         an indexed array.
+     *         an indexed array. On error returns PEAR error object.
      * @access public
      */
-    function encode()
+    function encode($boundary=null)
     {
         $encoded =& $this->_encoded;
 
         if (count($this->_subparts)) {
-            srand((double)microtime()*1000000);
-            $boundary = '=_' . md5(rand() . microtime());
-            $this->_headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"';
+            $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
+            $eol = $this->_eol;
+
+            $this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
+
+            $encoded['body'] = ''; 
 
-            // Add body parts to $subparts
             for ($i = 0; $i < count($this->_subparts); $i++) {
-                $headers = array();
+                $encoded['body'] .= '--' . $boundary . $eol;
                 $tmp = $this->_subparts[$i]->encode();
+                if (PEAR::isError($tmp)) {
+                    return $tmp;
+                }
                 foreach ($tmp['headers'] as $key => $value) {
-                    $headers[] = $key . ': ' . $value;
+                    $encoded['body'] .= $key . ': ' . $value . $eol;
                 }
-                $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'] . MAIL_MIMEPART_CRLF;
+                $encoded['body'] .= $eol . $tmp['body'] . $eol;
             }
 
-            $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF . 
-                               rtrim(implode('--' . $boundary . MAIL_MIMEPART_CRLF , $subparts), MAIL_MIMEPART_CRLF) . MAIL_MIMEPART_CRLF . 
-                               '--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
+            $encoded['body'] .= '--' . $boundary . '--' . $eol;
 
-        } else {
+        } else if ($this->_body) {
             $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding);
+        } else if ($this->_body_file) {
+            // Temporarily reset magic_quotes_runtime for file reads and writes
+            if ($magic_quote_setting = get_magic_quotes_runtime()) {
+                @ini_set('magic_quotes_runtime', 0);
+            }
+            $body = $this->_getEncodedDataFromFile($this->_body_file, $this->_encoding);
+            if ($magic_quote_setting) {
+                @ini_set('magic_quotes_runtime', $magic_quote_setting);
+            }
+
+            if (PEAR::isError($body)) {
+                return $body;
+            }
+            $encoded['body'] = $body;
+        } else {
+            $encoded['body'] = '';
         }
 
         // Add headers to $encoded
@@ -269,154 +353,356 @@ class Mail_mimePart {
     }
 
     /**
-     * &addSubPart()
+     * Encodes and saves the email into file. File must exist.
+     * Data will be appended to the file.
+     *
+     * @param string  $filename  Output file location
+     * @param string  $boundary  Pre-defined boundary string
+     * @param boolean $skip_head True if you don't want to save headers
+     *
+     * @return array An associative array containing message headers
+     *               or PEAR error object
+     * @access public
+     * @since 1.6.0
+     */
+    function encodeToFile($filename, $boundary=null, $skip_head=false)
+    {
+        if (file_exists($filename) && !is_writable($filename)) {
+            $err = PEAR::raiseError('File is not writeable: ' . $filename);
+            return $err;
+        }
+
+        if (!($fh = fopen($filename, 'ab'))) {
+            $err = PEAR::raiseError('Unable to open file: ' . $filename);
+            return $err;
+        }
+
+        // Temporarily reset magic_quotes_runtime for file reads and writes
+        if ($magic_quote_setting = get_magic_quotes_runtime()) {
+            @ini_set('magic_quotes_runtime', 0);
+        }
+
+        $res = $this->_encodePartToFile($fh, $boundary, $skip_head);
+
+        fclose($fh);
+
+        if ($magic_quote_setting) {
+            @ini_set('magic_quotes_runtime', $magic_quote_setting);
+        }
+
+        return PEAR::isError($res) ? $res : $this->_headers;
+    }
+
+    /**
+     * Encodes given email part into file
+     *
+     * @param string  $fh        Output file handle
+     * @param string  $boundary  Pre-defined boundary string
+     * @param boolean $skip_head True if you don't want to save headers
      *
+     * @return array True on sucess or PEAR error object
+     * @access private
+     */
+    function _encodePartToFile($fh, $boundary=null, $skip_head=false)
+    {
+        $eol = $this->_eol;
+
+        if (count($this->_subparts)) {
+            $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
+            $this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
+        }
+
+        if (!$skip_head) {
+            foreach ($this->_headers as $key => $value) {
+                fwrite($fh, $key . ': ' . $value . $eol);
+            }
+            $f_eol = $eol;
+        } else {
+            $f_eol = '';
+        }
+
+        if (count($this->_subparts)) {
+            for ($i = 0; $i < count($this->_subparts); $i++) {
+                fwrite($fh, $f_eol . '--' . $boundary . $eol);
+                $res = $this->_subparts[$i]->_encodePartToFile($fh);
+                if (PEAR::isError($res)) {
+                    return $res;
+                }
+                $f_eol = $eol;
+            }
+
+            fwrite($fh, $eol . '--' . $boundary . '--' . $eol);
+
+        } else if ($this->_body) {
+            fwrite($fh, $f_eol . $this->_getEncodedData($this->_body, $this->_encoding));
+        } else if ($this->_body_file) {
+            fwrite($fh, $f_eol);
+            $res = $this->_getEncodedDataFromFile(
+                $this->_body_file, $this->_encoding, $fh
+            );
+            if (PEAR::isError($res)) {
+                return $res;
+            }
+        }
+
+        return true;
+    }
+
+    /**
      * Adds a subpart to current mime part and returns
      * a reference to it
      *
-     * @param $body   The body of the subpart, if any.
-     * @param $params The parameters for the subpart, same
-     *                as the $params argument for constructor.
-     * @return A reference to the part you just added. It is
-     *         crucial if using multipart/* in your subparts that
-     *         you use =& in your script when calling this function,
-     *         otherwise you will not be able to add further subparts.
+     * @param string $body   The body of the subpart, if any.
+     * @param array  $params The parameters for the subpart, same
+     *                       as the $params argument for constructor.
+     *
+     * @return Mail_mimePart A reference to the part you just added. It is
+     *                       crucial if using multipart/* in your subparts that
+     *                       you use =& in your script when calling this function,
+     *                       otherwise you will not be able to add further subparts.
      * @access public
      */
-    function &addSubPart($body, $params)
+    function &addSubpart($body, $params)
     {
         $this->_subparts[] = new Mail_mimePart($body, $params);
         return $this->_subparts[count($this->_subparts) - 1];
     }
 
     /**
-     * _getEncodedData()
-     *
      * Returns encoded data based upon encoding passed to it
      *
-     * @param $data     The data to encode.
-     * @param $encoding The encoding type to use, 7bit, base64,
-     *                  or quoted-printable.
+     * @param string $data     The data to encode.
+     * @param string $encoding The encoding type to use, 7bit, base64,
+     *                         or quoted-printable.
+     *
+     * @return string
      * @access private
      */
     function _getEncodedData($data, $encoding)
     {
         switch ($encoding) {
-            case '8bit':
-            case '7bit':
-                return $data;
-                break;
+        case 'quoted-printable':
+            return $this->_quotedPrintableEncode($data);
+            break;
 
-            case 'quoted-printable':
-                return $this->_quotedPrintableEncode($data);
-                break;
-
-            case 'base64':
-                return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF));
-                break;
+        case 'base64':
+            return rtrim(chunk_split(base64_encode($data), 76, $this->_eol));
+            break;
 
-            default:
-                return $data;
+        case '8bit':
+        case '7bit':
+        default:
+            return $data;
         }
     }
 
     /**
-     * quotedPrintableEncode()
+     * Returns encoded data based upon encoding passed to it
      *
+     * @param string   $filename Data file location
+     * @param string   $encoding The encoding type to use, 7bit, base64,
+     *                           or quoted-printable.
+     * @param resource $fh       Output file handle. If set, data will be
+     *                           stored into it instead of returning it
+     *
+     * @return string Encoded data or PEAR error object
+     * @access private
+     */
+    function _getEncodedDataFromFile($filename, $encoding, $fh=null)
+    {
+        if (!is_readable($filename)) {
+            $err = PEAR::raiseError('Unable to read file: ' . $filename);
+            return $err;
+        }
+
+        if (!($fd = fopen($filename, 'rb'))) {
+            $err = PEAR::raiseError('Could not open file: ' . $filename);
+            return $err;
+        }
+
+        $data = '';
+
+        switch ($encoding) {
+        case 'quoted-printable':
+            while (!feof($fd)) {
+                $buffer = $this->_quotedPrintableEncode(fgets($fd));
+                if ($fh) {
+                    fwrite($fh, $buffer);
+                } else {
+                    $data .= $buffer;
+                }
+            }
+            break;
+
+        case 'base64':
+            while (!feof($fd)) {
+                // Should read in a multiple of 57 bytes so that
+                // the output is 76 bytes per line. Don't use big chunks
+                // because base64 encoding is memory expensive
+                $buffer = fread($fd, 57 * 9198); // ca. 0.5 MB
+                $buffer = base64_encode($buffer);
+                $buffer = chunk_split($buffer, 76, $this->_eol);
+                if (feof($fd)) {
+                    $buffer = rtrim($buffer);
+                }
+
+                if ($fh) {
+                    fwrite($fh, $buffer);
+                } else {
+                    $data .= $buffer;
+                }
+            }
+            break;
+
+        case '8bit':
+        case '7bit':
+        default:
+            while (!feof($fd)) {
+                $buffer = fread($fd, 1048576); // 1 MB
+                if ($fh) {
+                    fwrite($fh, $buffer);
+                } else {
+                    $data .= $buffer;
+                }
+            }
+        }
+
+        fclose($fd);
+
+        if (!$fh) {
+            return $data;
+        }
+    }
+
+    /**
      * Encodes data to quoted-printable standard.
      *
-     * @param $input    The data to encode
-     * @param $line_max Optional max line length. Should
-     *                  not be more than 76 chars
+     * @param string $input    The data to encode
+     * @param int    $line_max Optional max line length. Should
+     *                         not be more than 76 chars
+     *
+     * @return string Encoded data
      *
      * @access private
      */
     function _quotedPrintableEncode($input , $line_max = 76)
     {
+        $eol = $this->_eol;
+        /*
+        // imap_8bit() is extremely fast, but doesn't handle properly some characters
+        if (function_exists('imap_8bit') && $line_max == 76) {
+            $input = preg_replace('/\r?\n/', "\r\n", $input);
+            $input = imap_8bit($input);
+            if ($eol != "\r\n") {
+                $input = str_replace("\r\n", $eol, $input);
+            }
+            return $input;
+        }
+        */
         $lines  = preg_split("/\r?\n/", $input);
-        $eol    = MAIL_MIMEPART_CRLF;
         $escape = '=';
         $output = '';
 
-        while (list(, $line) = each($lines)) {
-
-            $line    = preg_split('||', $line, -1, PREG_SPLIT_NO_EMPTY);
-            $linlen     = count($line);
+        while (list($idx, $line) = each($lines)) {
             $newline = '';
+            $i = 0;
 
-            for ($i = 0; $i < $linlen; $i++) {
+            while (isset($line[$i])) {
                 $char = $line[$i];
                 $dec  = ord($char);
+                $i++;
 
-                if (($dec == 32) AND ($i == ($linlen - 1))) {    // convert space at eol only
+                if (($dec == 32) && (!isset($line[$i]))) {
+                    // convert space at eol only
                     $char = '=20';
-
-                } elseif (($dec == 9) AND ($i == ($linlen - 1))) {  // convert tab at eol only
-                    $char = '=09';
-                } elseif ($dec == 9) {
-                    ; // Do nothing if a tab.
-                } elseif (($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
-                    $char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
-                } elseif (($dec == 46) AND ($newline == '')) {
-                    //Bug #9722: convert full-stop at bol
-                    //Some Windows servers need this, won't break anything (cipri)
+                } elseif ($dec == 9 && isset($line[$i])) {
+                    ; // Do nothing if a TAB is not on eol
+                } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {
+                    $char = $escape . sprintf('%02X', $dec);
+                } elseif (($dec == 46) && (($newline == '')
+                    || ((strlen($newline) + strlen("=2E")) >= $line_max))
+                ) {
+                    // Bug #9722: convert full-stop at bol,
+                    // some Windows servers need this, won't break anything (cipri)
+                    // Bug #11731: full-stop at bol also needs to be encoded
+                    // if this line would push us over the line_max limit.
                     $char = '=2E';
                 }
 
-                if ((strlen($newline) + strlen($char)) >= $line_max) {        // MAIL_MIMEPART_CRLF is not counted
-                    $output  .= $newline . $escape . $eol;                    // soft line break; " =\r\n" is okay
+                // Note, when changing this line, also change the ($dec == 46)
+                // check line, as it mimics this line due to Bug #11731
+                // EOL is not counted
+                if ((strlen($newline) + strlen($char)) >= $line_max) {
+                    // soft line break; " =\r\n" is okay
+                    $output  .= $newline . $escape . $eol;
                     $newline  = '';
                 }
                 $newline .= $char;
             } // end of for
             $output .= $newline . $eol;
+            unset($lines[$idx]);
         }
-        $output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf
+        // Don't want last crlf
+        $output = substr($output, 0, -1 * strlen($eol));
         return $output;
     }
 
     /**
-     * _buildHeaderParam()
-     *
      * Encodes the paramater of a header.
      *
-     * @param $name         The name of the header-parameter
-     * @param $value        The value of the paramter
-     * @param $charset      The characterset of $value
-     * @param $language     The language used in $value
-     * @param $maxLength    The maximum length of a line. Defauls to 75
+     * @param string $name      The name of the header-parameter
+     * @param string $value     The value of the paramter
+     * @param string $charset   The characterset of $value
+     * @param string $language  The language used in $value
+     * @param string $encoding  Parameter encoding. If not set, parameter value
+     *                          is encoded according to RFC2231
+     * @param int    $maxLength The maximum length of a line. Defauls to 75
+     *
+     * @return string
      *
      * @access private
      */
-    function _buildHeaderParam($name, $value, $charset=NULL, $language=NULL, $maxLength=75)
-    {
-        //If we find chars to encode, or if charset or language
-        //is not any of the defaults, we need to encode the value.
-        $shouldEncode = 0;
-        $secondAsterisk = '';
-        if (preg_match('#([\x80-\xFF]){1}#', $value)) {
-            $shouldEncode = 1;
-        } elseif ($charset && (strtolower($charset) != 'us-ascii')) {
-            $shouldEncode = 1;
-        } elseif ($language && ($language != 'en' && $language != 'en-us')) {
-            $shouldEncode = 1;
-        }
-        if ($shouldEncode) {
-            $search  = array('%',   ' ',   "\t");
-            $replace = array('%25', '%20', '%09');
-            $encValue = str_replace($search, $replace, $value);
-            $encValue = preg_replace('#([\x80-\xFF])#e', '"%" . strtoupper(dechex(ord("\1")))', $encValue);
-            $value = "$charset'$language'$encValue";
-            $secondAsterisk = '*';
-        }
-        $header = " {$name}{$secondAsterisk}=\"{$value}\"; ";
+    function _buildHeaderParam($name, $value, $charset=null, $language=null,
+        $encoding=null, $maxLength=75
+    ) {
+        // RFC 2045:
+        // value needs encoding if contains non-ASCII chars or is longer than 78 chars
+        if (!preg_match('#[^\x20-\x7E]#', $value)) {
+            $token_regexp = '#([^\x21\x23-\x27\x2A\x2B\x2D'
+                . '\x2E\x30-\x39\x41-\x5A\x5E-\x7E])#';
+            if (!preg_match($token_regexp, $value)) {
+                // token
+                if (strlen($name) + strlen($value) + 3 <= $maxLength) {
+                    return " {$name}={$value}";
+                }
+            } else {
+                // quoted-string
+                $quoted = addcslashes($value, '\\"');
+                if (strlen($name) + strlen($quoted) + 5 <= $maxLength) {
+                    return " {$name}=\"{$quoted}\"";
+                }
+            }
+        }
+
+        // RFC2047: use quoted-printable/base64 encoding
+        if ($encoding == 'quoted-printable' || $encoding == 'base64') {
+            return $this->_buildRFC2047Param($name, $value, $charset, $encoding);
+        }
+
+        // RFC2231:
+        $encValue = preg_replace_callback(
+            '/([^\x21\x23\x24\x26\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E])/',
+            array($this, '_encodeReplaceCallback'), $value
+        );
+        $value = "$charset'$language'$encValue";
+
+        $header = " {$name}*={$value}";
         if (strlen($header) <= $maxLength) {
             return $header;
         }
 
-        $preLength = strlen(" {$name}*0{$secondAsterisk}=\"");
-        $sufLength = strlen("\";");
-        $maxLength = MAX(16, $maxLength - $preLength - $sufLength - 2);
+        $preLength = strlen(" {$name}*0*=");
+        $maxLength = max(16, $maxLength - $preLength - 3);
         $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
 
         $headers = array();
@@ -425,15 +711,518 @@ class Mail_mimePart {
             $matches = array();
             $found = preg_match($maxLengthReg, $value, $matches);
             if ($found) {
-                $headers[] = " {$name}*{$headCount}{$secondAsterisk}=\"{$matches[0]}\"";
+                $headers[] = " {$name}*{$headCount}*={$matches[0]}";
                 $value = substr($value, strlen($matches[0]));
             } else {
-                $headers[] = " {$name}*{$headCount}{$secondAsterisk}=\"{$value}\"";
-                $value = "";
+                $headers[] = " {$name}*{$headCount}*={$value}";
+                $value = '';
             }
             $headCount++;
         }
-        $headers = implode(MAIL_MIMEPART_CRLF, $headers) . ';';
+
+        $headers = implode(';' . $this->_eol, $headers);
         return $headers;
     }
+
+    /**
+     * Encodes header parameter as per RFC2047 if needed
+     *
+     * @param string $name      The parameter name
+     * @param string $value     The parameter value
+     * @param string $charset   The parameter charset
+     * @param string $encoding  Encoding type (quoted-printable or base64)
+     * @param int    $maxLength Encoded parameter max length. Default: 76
+     *
+     * @return string Parameter line
+     * @access private
+     */
+    function _buildRFC2047Param($name, $value, $charset,
+        $encoding='quoted-printable', $maxLength=76
+    ) {
+        // WARNING: RFC 2047 says: "An 'encoded-word' MUST NOT be used in
+        // parameter of a MIME Content-Type or Content-Disposition field",
+        // but... it's supported by many clients/servers
+        $quoted = '';
+
+        if ($encoding == 'base64') {
+            $value = base64_encode($value);
+            $prefix = '=?' . $charset . '?B?';
+            $suffix = '?=';
+
+            // 2 x SPACE, 2 x '"', '=', ';'
+            $add_len = strlen($prefix . $suffix) + strlen($name) + 6;
+            $len = $add_len + strlen($value);
+
+            while ($len > $maxLength) { 
+                // We can cut base64-encoded string every 4 characters
+                $real_len = floor(($maxLength - $add_len) / 4) * 4;
+                $_quote = substr($value, 0, $real_len);
+                $value = substr($value, $real_len);
+
+                $quoted .= $prefix . $_quote . $suffix . $this->_eol . ' ';
+                $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
+                $len = strlen($value) + $add_len;
+            }
+            $quoted .= $prefix . $value . $suffix;
+
+        } else {
+            // quoted-printable
+            $value = $this->encodeQP($value);
+            $prefix = '=?' . $charset . '?Q?';
+            $suffix = '?=';
+
+            // 2 x SPACE, 2 x '"', '=', ';'
+            $add_len = strlen($prefix . $suffix) + strlen($name) + 6;
+            $len = $add_len + strlen($value);
+
+            while ($len > $maxLength) {
+                $length = $maxLength - $add_len;
+                // don't break any encoded letters
+                if (preg_match("/^(.{0,$length}[^\=][^\=])/", $value, $matches)) {
+                    $_quote = $matches[1];
+                }
+
+                $quoted .= $prefix . $_quote . $suffix . $this->_eol . ' ';
+                $value = substr($value, strlen($_quote));
+                $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
+                $len = strlen($value) + $add_len;
+            }
+
+            $quoted .= $prefix . $value . $suffix;
+        }
+
+        return " {$name}=\"{$quoted}\"";
+    }
+
+    /**
+     * Encodes a header as per RFC2047
+     *
+     * @param string $name     The header name
+     * @param string $value    The header data to encode
+     * @param string $charset  Character set name
+     * @param string $encoding Encoding name (base64 or quoted-printable)
+     * @param string $eol      End-of-line sequence. Default: "\r\n"
+     *
+     * @return string          Encoded header data (without a name)
+     * @access public
+     * @since 1.6.1
+     */
+    function encodeHeader($name, $value, $charset='ISO-8859-1',
+        $encoding='quoted-printable', $eol="\r\n"
+    ) {
+        // Structured headers
+        $comma_headers = array(
+            'from', 'to', 'cc', 'bcc', 'sender', 'reply-to',
+            'resent-from', 'resent-to', 'resent-cc', 'resent-bcc',
+            'resent-sender', 'resent-reply-to',
+            'return-receipt-to', 'disposition-notification-to',
+        );
+        $other_headers = array(
+            'references', 'in-reply-to', 'message-id', 'resent-message-id',
+        );
+
+        $name = strtolower($name);
+
+        if (in_array($name, $comma_headers)) {
+            $separator = ',';
+        } else if (in_array($name, $other_headers)) {
+            $separator = ' ';
+        }
+
+        if (!$charset) {
+            $charset = 'ISO-8859-1';
+        }
+
+        // Structured header (make sure addr-spec inside is not encoded)
+        if (!empty($separator)) {
+            // Simple e-mail address regexp
+            $email_regexp = '([^\s<]+|("[^\r\n"]+"))@\S+';
+
+            $parts = Mail_mimePart::_explodeQuotedString($separator, $value);
+            $value = '';
+
+            foreach ($parts as $part) {
+                $part = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $part);
+                $part = trim($part);
+
+                if (!$part) {
+                    continue;
+                }
+                if ($value) {
+                    $value .= $separator==',' ? $separator.' ' : ' ';
+                } else {
+                    $value = $name . ': ';
+                }
+
+                // let's find phrase (name) and/or addr-spec
+                if (preg_match('/^<' . $email_regexp . '>$/', $part)) {
+                    $value .= $part;
+                } else if (preg_match('/^' . $email_regexp . '$/', $part)) {
+                    // address without brackets and without name
+                    $value .= $part;
+                } else if (preg_match('/<*' . $email_regexp . '>*$/', $part, $matches)) {
+                    // address with name (handle name)
+                    $address = $matches[0];
+                    $word = str_replace($address, '', $part);
+                    $word = trim($word);
+                    // check if phrase requires quoting
+                    if ($word) {
+                        // non-ASCII: require encoding
+                        if (preg_match('#([\x80-\xFF]){1}#', $word)) {
+                            if ($word[0] == '"' && $word[strlen($word)-1] == '"') {
+                                // de-quote quoted-string, encoding changes
+                                // string to atom
+                                $search = array("\\\"", "\\\\");
+                                $replace = array("\"", "\\");
+                                $word = str_replace($search, $replace, $word);
+                                $word = substr($word, 1, -1);
+                            }
+                            // find length of last line
+                            if (($pos = strrpos($value, $eol)) !== false) {
+                                $last_len = strlen($value) - $pos;
+                            } else {
+                                $last_len = strlen($value);
+                            }
+                            $word = Mail_mimePart::encodeHeaderValue(
+                                $word, $charset, $encoding, $last_len, $eol
+                            );
+                        } else if (($word[0] != '"' || $word[strlen($word)-1] != '"')
+                            && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $word)
+                        ) {
+                            // ASCII: quote string if needed
+                            $word = '"'.addcslashes($word, '\\"').'"';
+                        }
+                    }
+                    $value .= $word.' '.$address;
+                } else {
+                    // addr-spec not found, don't encode (?)
+                    $value .= $part;
+                }
+
+                // RFC2822 recommends 78 characters limit, use 76 from RFC2047
+                $value = wordwrap($value, 76, $eol . ' ');
+            }
+
+            // remove header name prefix (there could be EOL too)
+            $value = preg_replace(
+                '/^'.$name.':('.preg_quote($eol, '/').')* /', '', $value
+            );
+
+        } else {
+            // Unstructured header
+            // non-ASCII: require encoding
+            if (preg_match('#([\x80-\xFF]){1}#', $value)) {
+                if ($value[0] == '"' && $value[strlen($value)-1] == '"') {
+                    // de-quote quoted-string, encoding changes
+                    // string to atom
+                    $search = array("\\\"", "\\\\");
+                    $replace = array("\"", "\\");
+                    $value = str_replace($search, $replace, $value);
+                    $value = substr($value, 1, -1);
+                }
+                $value = Mail_mimePart::encodeHeaderValue(
+                    $value, $charset, $encoding, strlen($name) + 2, $eol
+                );
+            } else if (strlen($name.': '.$value) > 78) {
+                // ASCII: check if header line isn't too long and use folding
+                $value = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $value);
+                $tmp = wordwrap($name.': '.$value, 78, $eol . ' ');
+                $value = preg_replace('/^'.$name.':\s*/', '', $tmp);
+                // hard limit 998 (RFC2822)
+                $value = wordwrap($value, 998, $eol . ' ', true);
+            }
+        }
+
+        return $value;
+    }
+
+    /**
+     * Explode quoted string
+     *
+     * @param string $delimiter Delimiter expression string for preg_match()
+     * @param string $string    Input string
+     *
+     * @return array            String tokens array
+     * @access private
+     */
+    function _explodeQuotedString($delimiter, $string)
+    {
+        $result = array();
+        $strlen = strlen($string);
+
+        for ($q=$p=$i=0; $i < $strlen; $i++) {
+            if ($string[$i] == "\""
+                && (empty($string[$i-1]) || $string[$i-1] != "\\")
+            ) {
+                $q = $q ? false : true;
+            } else if (!$q && preg_match("/$delimiter/", $string[$i])) {
+                $result[] = substr($string, $p, $i - $p);
+                $p = $i + 1;
+            }
+        }
+
+        $result[] = substr($string, $p);
+        return $result;
+    }
+
+    /**
+     * Encodes a header value as per RFC2047
+     *
+     * @param string $value      The header data to encode
+     * @param string $charset    Character set name
+     * @param string $encoding   Encoding name (base64 or quoted-printable)
+     * @param int    $prefix_len Prefix length. Default: 0
+     * @param string $eol        End-of-line sequence. Default: "\r\n"
+     *
+     * @return string            Encoded header data
+     * @access public
+     * @since 1.6.1
+     */
+    function encodeHeaderValue($value, $charset, $encoding, $prefix_len=0, $eol="\r\n")
+    {
+        // #17311: Use multibyte aware method (requires mbstring extension)
+        if ($result = Mail_mimePart::encodeMB($value, $charset, $encoding, $prefix_len, $eol)) {
+            return $result;
+        }
+
+        // Generate the header using the specified params and dynamicly
+        // determine the maximum length of such strings.
+        // 75 is the value specified in the RFC.
+        $encoding = $encoding == 'base64' ? 'B' : 'Q';
+        $prefix = '=?' . $charset . '?' . $encoding .'?';
+        $suffix = '?=';
+        $maxLength = 75 - strlen($prefix . $suffix);
+        $maxLength1stLine = $maxLength - $prefix_len;
+
+        if ($encoding == 'B') {
+            // Base64 encode the entire string
+            $value = base64_encode($value);
+
+            // We can cut base64 every 4 characters, so the real max
+            // we can get must be rounded down.
+            $maxLength = $maxLength - ($maxLength % 4);
+            $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
+
+            $cutpoint = $maxLength1stLine;
+            $output = '';
+
+            while ($value) {
+                // Split translated string at every $maxLength
+                $part = substr($value, 0, $cutpoint);
+                $value = substr($value, $cutpoint);
+                $cutpoint = $maxLength;
+                // RFC 2047 specifies that any split header should
+                // be seperated by a CRLF SPACE.
+                if ($output) {
+                    $output .= $eol . ' ';
+                }
+                $output .= $prefix . $part . $suffix;
+            }
+            $value = $output;
+        } else {
+            // quoted-printable encoding has been selected
+            $value = Mail_mimePart::encodeQP($value);
+
+            // This regexp will break QP-encoded text at every $maxLength
+            // but will not break any encoded letters.
+            $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
+            $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
+
+            if (strlen($value) > $maxLength1stLine) {
+                // Begin with the regexp for the first line.
+                $reg = $reg1st;
+                $output = '';
+                while ($value) {
+                    // Split translated string at every $maxLength
+                    // But make sure not to break any translated chars.
+                    $found = preg_match($reg, $value, $matches);
+
+                    // After this first line, we need to use a different
+                    // regexp for the first line.
+                    $reg = $reg2nd;
+
+                    // Save the found part and encapsulate it in the
+                    // prefix & suffix. Then remove the part from the
+                    // $value_out variable.
+                    if ($found) {
+                        $part = $matches[0];
+                        $len = strlen($matches[0]);
+                        $value = substr($value, $len);
+                    } else {
+                        $part = $value;
+                        $value = '';
+                    }
+
+                    // RFC 2047 specifies that any split header should
+                    // be seperated by a CRLF SPACE
+                    if ($output) {
+                        $output .= $eol . ' ';
+                    }
+                    $output .= $prefix . $part . $suffix;
+                }
+                $value = $output;
+            } else {
+                $value = $prefix . $value . $suffix;
+            }
+        }
+
+        return $value;
+    }
+
+    /**
+     * Encodes the given string using quoted-printable
+     *
+     * @param string $str String to encode
+     *
+     * @return string     Encoded string
+     * @access public
+     * @since 1.6.0
+     */
+    function encodeQP($str)
+    {
+        // Bug #17226 RFC 2047 restricts some characters
+        // if the word is inside a phrase, permitted chars are only:
+        // ASCII letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
+
+        // "=",  "_",  "?" must be encoded
+        $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
+        $str = preg_replace_callback(
+            $regexp, array('Mail_mimePart', '_qpReplaceCallback'), $str
+        );
+
+        return str_replace(' ', '_', $str);
+    }
+
+    /**
+     * Encodes the given string using base64 or quoted-printable.
+     * This method makes sure that encoded-word represents an integral
+     * number of characters as per RFC2047.
+     *
+     * @param string $str        String to encode
+     * @param string $charset    Character set name
+     * @param string $encoding   Encoding name (base64 or quoted-printable)
+     * @param int    $prefix_len Prefix length. Default: 0
+     * @param string $eol        End-of-line sequence. Default: "\r\n"
+     *
+     * @return string     Encoded string
+     * @access public
+     * @since 1.8.0
+     */
+    function encodeMB($str, $charset, $encoding, $prefix_len=0, $eol="\r\n")
+    {
+        if (!function_exists('mb_substr') || !function_exists('mb_strlen')) {
+            return;
+        }
+
+        $encoding = $encoding == 'base64' ? 'B' : 'Q';
+        // 75 is the value specified in the RFC
+        $prefix = '=?' . $charset . '?'.$encoding.'?';
+        $suffix = '?=';
+        $maxLength = 75 - strlen($prefix . $suffix);
+
+        // A multi-octet character may not be split across adjacent encoded-words
+        // So, we'll loop over each character
+        // mb_stlen() with wrong charset will generate a warning here and return null
+        $length      = mb_strlen($str, $charset);
+        $result      = '';
+        $line_length = $prefix_len;
+
+        if ($encoding == 'B') {
+            // base64
+            $start = 0;
+            $prev  = '';
+
+            for ($i=1; $i<=$length; $i++) {
+                // See #17311
+                $chunk = mb_substr($str, $start, $i-$start, $charset);
+                $chunk = base64_encode($chunk);
+                $chunk_len = strlen($chunk);
+
+                if ($line_length + $chunk_len == $maxLength || $i == $length) {
+                    if ($result) {
+                        $result .= "\n";
+                    }
+                    $result .= $chunk;
+                    $line_length = 0;
+                    $start = $i;
+                } else if ($line_length + $chunk_len > $maxLength) {
+                    if ($result) {
+                        $result .= "\n";
+                    }
+                    if ($prev) {
+                        $result .= $prev;
+                    }
+                    $line_length = 0;
+                    $start = $i - 1;
+                } else {
+                    $prev = $chunk;
+                }
+            }
+        } else {
+            // quoted-printable
+            // see encodeQP()
+            $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
+
+            for ($i=0; $i<=$length; $i++) {
+                $char = mb_substr($str, $i, 1, $charset);
+                // RFC recommends underline (instead of =20) in place of the space
+                // that's one of the reasons why we're not using iconv_mime_encode()
+                if ($char == ' ') {
+                    $char = '_';
+                    $char_len = 1;
+                } else {
+                    $char = preg_replace_callback(
+                        $regexp, array('Mail_mimePart', '_qpReplaceCallback'), $char
+                    );
+                    $char_len = strlen($char);
+                }
+
+                if ($line_length + $char_len > $maxLength) {
+                    if ($result) {
+                        $result .= "\n";
+                    }
+                    $line_length = 0;
+                }
+
+                $result      .= $char;
+                $line_length += $char_len;
+            }
+        }
+
+        if ($result) {
+            $result = $prefix
+                .str_replace("\n", $suffix.$eol.' '.$prefix, $result).$suffix;
+        }
+
+        return $result;
+    }
+
+    /**
+     * Callback function to replace extended characters (\x80-xFF) with their
+     * ASCII values (RFC2047: quoted-printable)
+     *
+     * @param array $matches Preg_replace's matches array
+     *
+     * @return string        Encoded character string
+     * @access private
+     */
+    function _qpReplaceCallback($matches)
+    {
+        return sprintf('=%02X', ord($matches[1]));
+    }
+
+    /**
+     * Callback function to replace extended characters (\x80-xFF) with their
+     * ASCII values (RFC2231)
+     *
+     * @param array $matches Preg_replace's matches array
+     *
+     * @return string        Encoded character string
+     * @access private
+     */
+    function _encodeReplaceCallback($matches)
+    {
+        return sprintf('%%%02X', ord($matches[1]));
+    }
+
 } // End of class
diff --git a/include/pear/Mail/mock.php b/include/pear/Mail/mock.php
index 1dfdadb8bb39e47a0b76446505e0de2e3234210c..61570ba408cdcec0b6cd5814f080d4aa78581a45 100644
--- a/include/pear/Mail/mock.php
+++ b/include/pear/Mail/mock.php
@@ -1,119 +1,143 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org>                            |
-// +----------------------------------------------------------------------+
-//
-// $Id: mock.php,v 1.1 2007/12/08 17:57:54 chagenbu Exp $
-//
-
-/**
- * Mock implementation of the PEAR Mail:: interface for testing.
- * @access public
- * @package Mail
- * @version $Revision: 1.1 $
- */
-class Mail_mock extends Mail {
-
-    /**
-     * Array of messages that have been sent with the mock.
-     *
-     * @var array
-     * @access public
-     */
-    var $sentMessages = array();
-
-    /**
-     * Callback before sending mail.
-     *
-     * @var callback
-     */
-    var $_preSendCallback;
-
-    /**
-     * Callback after sending mai.
-     *
-     * @var callback
-     */
-    var $_postSendCallback;
-
-    /**
-     * Constructor.
-     *
-     * Instantiates a new Mail_mock:: object based on the parameters
-     * passed in. It looks for the following parameters, both optional:
-     *     preSendCallback   Called before an email would be sent.
-     *     postSendCallback  Called after an email would have been sent.
-     *
-     * @param array Hash containing any parameters.
-     * @access public
-     */
-    function Mail_mock($params)
-    {
-        if (isset($params['preSendCallback']) &&
-            is_callable($params['preSendCallback'])) {
-            $this->_preSendCallback = $params['preSendCallback'];
-        }
-
-        if (isset($params['postSendCallback']) &&
-            is_callable($params['postSendCallback'])) {
-            $this->_postSendCallback = $params['postSendCallback'];
-        }
-    }
-
-    /**
-     * Implements Mail_mock::send() function. Silently discards all
-     * mail.
-     *
-     * @param mixed $recipients Either a comma-seperated list of recipients
-     *              (RFC822 compliant), or an array of recipients,
-     *              each RFC822 valid. This may contain recipients not
-     *              specified in the headers, for Bcc:, resending
-     *              messages, etc.
-     *
-     * @param array $headers The array of headers to send with the mail, in an
-     *              associative array, where the array key is the
-     *              header name (ie, 'Subject'), and the array value
-     *              is the header value (ie, 'test'). The header
-     *              produced from those values would be 'Subject:
-     *              test'.
-     *
-     * @param string $body The full text of the message body, including any
-     *               Mime parts, etc.
-     *
-     * @return mixed Returns true on success, or a PEAR_Error
-     *               containing a descriptive error message on
-     *               failure.
-     * @access public
-     */
-    function send($recipients, $headers, $body)
-    {
-        if ($this->_preSendCallback) {
-            call_user_func_array($this->_preSendCallback,
-                                 array(&$this, $recipients, $headers, $body));
-        }
-
-        $entry = array('recipients' => $recipients, 'headers' => $headers, 'body' => $body);
-        $this->sentMessages[] = $entry;
-
-        if ($this->_postSendCallback) {
-            call_user_func_array($this->_postSendCallback,
-                                 array(&$this, $recipients, $headers, $body));
-        }
-
-        return true;
-    }
-
-}
+<?php
+/**
+ * Mock implementation
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2010 Chuck Hagenbuch
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category    Mail
+ * @package     Mail
+ * @author      Chuck Hagenbuch <chuck@horde.org> 
+ * @copyright   2010 Chuck Hagenbuch
+ * @license     http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version     CVS: $Id: mock.php 294747 2010-02-08 08:18:33Z clockwerx $
+ * @link        http://pear.php.net/package/Mail/
+ */
+
+/**
+ * Mock implementation of the PEAR Mail:: interface for testing.
+ * @access public
+ * @package Mail
+ * @version $Revision: 294747 $
+ */
+class Mail_mock extends Mail {
+
+    /**
+     * Array of messages that have been sent with the mock.
+     *
+     * @var array
+     * @access public
+     */
+    var $sentMessages = array();
+
+    /**
+     * Callback before sending mail.
+     *
+     * @var callback
+     */
+    var $_preSendCallback;
+
+    /**
+     * Callback after sending mai.
+     *
+     * @var callback
+     */
+    var $_postSendCallback;
+
+    /**
+     * Constructor.
+     *
+     * Instantiates a new Mail_mock:: object based on the parameters
+     * passed in. It looks for the following parameters, both optional:
+     *     preSendCallback   Called before an email would be sent.
+     *     postSendCallback  Called after an email would have been sent.
+     *
+     * @param array Hash containing any parameters.
+     * @access public
+     */
+    function Mail_mock($params)
+    {
+        if (isset($params['preSendCallback']) &&
+            is_callable($params['preSendCallback'])) {
+            $this->_preSendCallback = $params['preSendCallback'];
+        }
+
+        if (isset($params['postSendCallback']) &&
+            is_callable($params['postSendCallback'])) {
+            $this->_postSendCallback = $params['postSendCallback'];
+        }
+    }
+
+    /**
+     * Implements Mail_mock::send() function. Silently discards all
+     * mail.
+     *
+     * @param mixed $recipients Either a comma-seperated list of recipients
+     *              (RFC822 compliant), or an array of recipients,
+     *              each RFC822 valid. This may contain recipients not
+     *              specified in the headers, for Bcc:, resending
+     *              messages, etc.
+     *
+     * @param array $headers The array of headers to send with the mail, in an
+     *              associative array, where the array key is the
+     *              header name (ie, 'Subject'), and the array value
+     *              is the header value (ie, 'test'). The header
+     *              produced from those values would be 'Subject:
+     *              test'.
+     *
+     * @param string $body The full text of the message body, including any
+     *               Mime parts, etc.
+     *
+     * @return mixed Returns true on success, or a PEAR_Error
+     *               containing a descriptive error message on
+     *               failure.
+     * @access public
+     */
+    function send($recipients, $headers, $body)
+    {
+        if ($this->_preSendCallback) {
+            call_user_func_array($this->_preSendCallback,
+                                 array(&$this, $recipients, $headers, $body));
+        }
+
+        $entry = array('recipients' => $recipients, 'headers' => $headers, 'body' => $body);
+        $this->sentMessages[] = $entry;
+
+        if ($this->_postSendCallback) {
+            call_user_func_array($this->_postSendCallback,
+                                 array(&$this, $recipients, $headers, $body));
+        }
+
+        return true;
+    }
+
+}
diff --git a/include/pear/Mail/null.php b/include/pear/Mail/null.php
index 982bfa45b6d652132a5219fb273d4327e505e856..f8d58272eea5df5abe4d8e9a25b0f24dee2ba776 100644
--- a/include/pear/Mail/null.php
+++ b/include/pear/Mail/null.php
@@ -1,29 +1,53 @@
 <?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Author: Phil Kernick <philk@rotfl.com.au>                            |
-// +----------------------------------------------------------------------+
-//
-// $Id: null.php,v 1.2 2004/04/06 05:19:03 jon Exp $
-//
+/**
+ * Null implementation of the PEAR Mail interface
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2010 Phil Kernick
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category    Mail
+ * @package     Mail
+ * @author      Phil Kernick <philk@rotfl.com.au>
+ * @copyright   2010 Phil Kernick
+ * @license     http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version     CVS: $Id: null.php 294747 2010-02-08 08:18:33Z clockwerx $
+ * @link        http://pear.php.net/package/Mail/
+ */
 
 /**
  * Null implementation of the PEAR Mail:: interface.
  * @access public
  * @package Mail
- * @version $Revision: 1.2 $
+ * @version $Revision: 294747 $
  */
 class Mail_null extends Mail {
 
diff --git a/include/pear/Mail/sendmail.php b/include/pear/Mail/sendmail.php
index 183890a80990851b7e11c6bac6a939a2e603bbf3..b056575e99274f886b1473b5ee35f002d2699329 100644
--- a/include/pear/Mail/sendmail.php
+++ b/include/pear/Mail/sendmail.php
@@ -1,171 +1,171 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org>                            |
-// +----------------------------------------------------------------------+
-
-/**
- * Sendmail implementation of the PEAR Mail:: interface.
- * @access public
- * @package Mail
- * @version $Revision: 1.20 $
- */
-class Mail_sendmail extends Mail {
-
-    /**
-     * The location of the sendmail or sendmail wrapper binary on the
-     * filesystem.
-     * @var string
-     */
-    var $sendmail_path = '/usr/sbin/sendmail';
-
-    /**
-     * Any extra command-line parameters to pass to the sendmail or
-     * sendmail wrapper binary.
-     * @var string
-     */
-    var $sendmail_args = '-i';
-
-    /**
-     * Constructor.
-     *
-     * Instantiates a new Mail_sendmail:: object based on the parameters
-     * passed in. It looks for the following parameters:
-     *     sendmail_path    The location of the sendmail binary on the
-     *                      filesystem. Defaults to '/usr/sbin/sendmail'.
-     *
-     *     sendmail_args    Any extra parameters to pass to the sendmail
-     *                      or sendmail wrapper binary.
-     *
-     * If a parameter is present in the $params array, it replaces the
-     * default.
-     *
-     * @param array $params Hash containing any parameters different from the
-     *              defaults.
-     * @access public
-     */
-    function Mail_sendmail($params)
-    {
-        if (isset($params['sendmail_path'])) {
-            $this->sendmail_path = $params['sendmail_path'];
-        }
-        if (isset($params['sendmail_args'])) {
-            $this->sendmail_args = $params['sendmail_args'];
-        }
-
-        /*
-         * Because we need to pass message headers to the sendmail program on
-         * the commandline, we can't guarantee the use of the standard "\r\n"
-         * separator.  Instead, we use the system's native line separator.
-         */
-        if (defined('PHP_EOL')) {
-            $this->sep = PHP_EOL;
-        } else {
-            $this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
-        }
-    }
-
-    /**
-     * Implements Mail::send() function using the sendmail
-     * command-line binary.
-     *
-     * @param mixed $recipients Either a comma-seperated list of recipients
-     *              (RFC822 compliant), or an array of recipients,
-     *              each RFC822 valid. This may contain recipients not
-     *              specified in the headers, for Bcc:, resending
-     *              messages, etc.
-     *
-     * @param array $headers The array of headers to send with the mail, in an
-     *              associative array, where the array key is the
-     *              header name (ie, 'Subject'), and the array value
-     *              is the header value (ie, 'test'). The header
-     *              produced from those values would be 'Subject:
-     *              test'.
-     *
-     * @param string $body The full text of the message body, including any
-     *               Mime parts, etc.
-     *
-     * @return mixed Returns true on success, or a PEAR_Error
-     *               containing a descriptive error message on
-     *               failure.
-     * @access public
-     */
-    function send($recipients, $headers, $body)
-    {
-        if (!is_array($headers)) {
-            return PEAR::raiseError('$headers must be an array');
-        }
-
-        $result = $this->_sanitizeHeaders($headers);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        $recipients = $this->parseRecipients($recipients);
-        if (is_a($recipients, 'PEAR_Error')) {
-            return $recipients;
-        }
-        $recipients = escapeShellCmd(implode(' ', $recipients));
-
-        $headerElements = $this->prepareHeaders($headers);
-        if (is_a($headerElements, 'PEAR_Error')) {
-            return $headerElements;
-        }
-        list($from, $text_headers) = $headerElements;
-
-        /* Since few MTAs are going to allow this header to be forged
-         * unless it's in the MAIL FROM: exchange, we'll use
-         * Return-Path instead of From: if it's set. */
-        if (!empty($headers['Return-Path'])) {
-            $from = $headers['Return-Path'];
-        }
-
-        if (!isset($from)) {
-            return PEAR::raiseError('No from address given.');
-        } elseif (strpos($from, ' ') !== false ||
-                  strpos($from, ';') !== false ||
-                  strpos($from, '&') !== false ||
-                  strpos($from, '`') !== false) {
-            return PEAR::raiseError('From address specified with dangerous characters.');
-        }
-
-        $from = escapeshellarg($from); // Security bug #16200
-        
-        $mail = @popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
-        if (!$mail) {
-            return PEAR::raiseError('Failed to open sendmail [' . $this->sendmail_path . '] for execution.');
-        }
-
-        // Write the headers following by two newlines: one to end the headers
-        // section and a second to separate the headers block from the body.
-        fputs($mail, $text_headers . $this->sep . $this->sep);
-
-        fputs($mail, $body);
-        $result = pclose($mail);
-        if (version_compare(phpversion(), '4.2.3') == -1) {
-            // With older php versions, we need to shift the pclose
-            // result to get the exit code.
-            $result = $result >> 8 & 0xFF;
-        }
-
-        if ($result != 0) {
-            return PEAR::raiseError('sendmail returned error code ' . $result,
-                                    $result);
-        }
-
-        return true;
-    }
-
-}
+<?php
+//
+// +----------------------------------------------------------------------+
+// | PHP Version 4                                                        |
+// +----------------------------------------------------------------------+
+// | Copyright (c) 1997-2003 The PHP Group                                |
+// +----------------------------------------------------------------------+
+// | This source file is subject to version 2.02 of the PHP license,      |
+// | that is bundled with this package in the file LICENSE, and is        |
+// | available at through the world-wide-web at                           |
+// | http://www.php.net/license/2_02.txt.                                 |
+// | If you did not receive a copy of the PHP license and are unable to   |
+// | obtain it through the world-wide-web, please send a note to          |
+// | license@php.net so we can mail you a copy immediately.               |
+// +----------------------------------------------------------------------+
+// | Author: Chuck Hagenbuch <chuck@horde.org>                            |
+// +----------------------------------------------------------------------+
+
+/**
+ * Sendmail implementation of the PEAR Mail:: interface.
+ * @access public
+ * @package Mail
+ * @version $Revision: 294744 $
+ */
+class Mail_sendmail extends Mail {
+
+    /**
+     * The location of the sendmail or sendmail wrapper binary on the
+     * filesystem.
+     * @var string
+     */
+    var $sendmail_path = '/usr/sbin/sendmail';
+
+    /**
+     * Any extra command-line parameters to pass to the sendmail or
+     * sendmail wrapper binary.
+     * @var string
+     */
+    var $sendmail_args = '-i';
+
+    /**
+     * Constructor.
+     *
+     * Instantiates a new Mail_sendmail:: object based on the parameters
+     * passed in. It looks for the following parameters:
+     *     sendmail_path    The location of the sendmail binary on the
+     *                      filesystem. Defaults to '/usr/sbin/sendmail'.
+     *
+     *     sendmail_args    Any extra parameters to pass to the sendmail
+     *                      or sendmail wrapper binary.
+     *
+     * If a parameter is present in the $params array, it replaces the
+     * default.
+     *
+     * @param array $params Hash containing any parameters different from the
+     *              defaults.
+     * @access public
+     */
+    function Mail_sendmail($params)
+    {
+        if (isset($params['sendmail_path'])) {
+            $this->sendmail_path = $params['sendmail_path'];
+        }
+        if (isset($params['sendmail_args'])) {
+            $this->sendmail_args = $params['sendmail_args'];
+        }
+
+        /*
+         * Because we need to pass message headers to the sendmail program on
+         * the commandline, we can't guarantee the use of the standard "\r\n"
+         * separator.  Instead, we use the system's native line separator.
+         */
+        if (defined('PHP_EOL')) {
+            $this->sep = PHP_EOL;
+        } else {
+            $this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
+        }
+    }
+
+    /**
+     * Implements Mail::send() function using the sendmail
+     * command-line binary.
+     *
+     * @param mixed $recipients Either a comma-seperated list of recipients
+     *              (RFC822 compliant), or an array of recipients,
+     *              each RFC822 valid. This may contain recipients not
+     *              specified in the headers, for Bcc:, resending
+     *              messages, etc.
+     *
+     * @param array $headers The array of headers to send with the mail, in an
+     *              associative array, where the array key is the
+     *              header name (ie, 'Subject'), and the array value
+     *              is the header value (ie, 'test'). The header
+     *              produced from those values would be 'Subject:
+     *              test'.
+     *
+     * @param string $body The full text of the message body, including any
+     *               Mime parts, etc.
+     *
+     * @return mixed Returns true on success, or a PEAR_Error
+     *               containing a descriptive error message on
+     *               failure.
+     * @access public
+     */
+    function send($recipients, $headers, $body)
+    {
+        if (!is_array($headers)) {
+            return PEAR::raiseError('$headers must be an array');
+        }
+
+        $result = $this->_sanitizeHeaders($headers);
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+
+        $recipients = $this->parseRecipients($recipients);
+        if (is_a($recipients, 'PEAR_Error')) {
+            return $recipients;
+        }
+        $recipients = implode(' ', array_map('escapeshellarg', $recipients));
+
+        $headerElements = $this->prepareHeaders($headers);
+        if (is_a($headerElements, 'PEAR_Error')) {
+            return $headerElements;
+        }
+        list($from, $text_headers) = $headerElements;
+
+        /* Since few MTAs are going to allow this header to be forged
+         * unless it's in the MAIL FROM: exchange, we'll use
+         * Return-Path instead of From: if it's set. */
+        if (!empty($headers['Return-Path'])) {
+            $from = $headers['Return-Path'];
+        }
+
+        if (!isset($from)) {
+            return PEAR::raiseError('No from address given.');
+        } elseif (strpos($from, ' ') !== false ||
+                  strpos($from, ';') !== false ||
+                  strpos($from, '&') !== false ||
+                  strpos($from, '`') !== false) {
+            return PEAR::raiseError('From address specified with dangerous characters.');
+        }
+
+        $from = escapeshellarg($from); // Security bug #16200
+
+        $mail = @popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
+        if (!$mail) {
+            return PEAR::raiseError('Failed to open sendmail [' . $this->sendmail_path . '] for execution.');
+        }
+
+        // Write the headers following by two newlines: one to end the headers
+        // section and a second to separate the headers block from the body.
+        fputs($mail, $text_headers . $this->sep . $this->sep);
+
+        fputs($mail, $body);
+        $result = pclose($mail);
+        if (version_compare(phpversion(), '4.2.3') == -1) {
+            // With older php versions, we need to shift the pclose
+            // result to get the exit code.
+            $result = $result >> 8 & 0xFF;
+        }
+
+        if ($result != 0) {
+            return PEAR::raiseError('sendmail returned error code ' . $result,
+                                    $result);
+        }
+
+        return true;
+    }
+
+}
diff --git a/include/pear/Mail/smtp.php b/include/pear/Mail/smtp.php
index 850695d39fce73df99b98a373358b4214167a086..75171891ea61351ed3ac3530228b549ad4a14a31 100644
--- a/include/pear/Mail/smtp.php
+++ b/include/pear/Mail/smtp.php
@@ -1,421 +1,453 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license,      |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Authors: Chuck Hagenbuch <chuck@horde.org>                           |
-// |          Jon Parise <jon@php.net>                                    |
-// +----------------------------------------------------------------------+
-
-/** Error: Failed to create a Net_SMTP object */
-define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);
-
-/** Error: Failed to connect to SMTP server */
-define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);
-
-/** Error: SMTP authentication failure */
-define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);
-
-/** Error: No From: address has been provided */
-define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);
-
-/** Error: Failed to set sender */
-define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);
-
-/** Error: Failed to add recipient */
-define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);
-
-/** Error: Failed to send data */
-define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);
-
-/**
- * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
- * @access public
- * @package Mail
- * @version $Revision: 1.33 $
- */
-class Mail_smtp extends Mail {
-
-    /**
-     * SMTP connection object.
-     *
-     * @var object
-     * @access private
-     */
-    var $_smtp = null;
-
-    /**
-     * The list of service extension parameters to pass to the Net_SMTP
-     * mailFrom() command.
-     * @var array
-     */
-    var $_extparams = array();
-
-    /**
-     * The SMTP host to connect to.
-     * @var string
-     */
-    var $host = 'localhost';
-
-    /**
-     * The port the SMTP server is on.
-     * @var integer
-     */
-    var $port = 25;
-
-    /**
-     * Should SMTP authentication be used?
-     *
-     * This value may be set to true, false or the name of a specific
-     * authentication method.
-     *
-     * If the value is set to true, the Net_SMTP package will attempt to use
-     * the best authentication method advertised by the remote SMTP server.
-     *
-     * @var mixed
-     */
-    var $auth = false;
-
-    /**
-     * The username to use if the SMTP server requires authentication.
-     * @var string
-     */
-    var $username = '';
-
-    /**
-     * The password to use if the SMTP server requires authentication.
-     * @var string
-     */
-    var $password = '';
-
-    /**
-     * Hostname or domain that will be sent to the remote SMTP server in the
-     * HELO / EHLO message.
-     *
-     * @var string
-     */
-    var $localhost = 'localhost';
-
-    /**
-     * SMTP connection timeout value.  NULL indicates no timeout.
-     *
-     * @var integer
-     */
-    var $timeout = null;
-
-    /**
-     * Turn on Net_SMTP debugging?
-     *
-     * @var boolean $debug
-     */
-    var $debug = false;
-
-    /**
-     * Indicates whether or not the SMTP connection should persist over
-     * multiple calls to the send() method.
-     *
-     * @var boolean
-     */
-    var $persist = false;
-
-    /**
-     * Use SMTP command pipelining (specified in RFC 2920) if the SMTP server
-     * supports it. This speeds up delivery over high-latency connections. By
-     * default, use the default value supplied by Net_SMTP.
-     * @var bool
-     */
-    var $pipelining;
-
-    /**
-     * Constructor.
-     *
-     * Instantiates a new Mail_smtp:: object based on the parameters
-     * passed in. It looks for the following parameters:
-     *     host        The server to connect to. Defaults to localhost.
-     *     port        The port to connect to. Defaults to 25.
-     *     auth        SMTP authentication.  Defaults to none.
-     *     username    The username to use for SMTP auth. No default.
-     *     password    The password to use for SMTP auth. No default.
-     *     localhost   The local hostname / domain. Defaults to localhost.
-     *     timeout     The SMTP connection timeout. Defaults to none.
-     *     verp        Whether to use VERP or not. Defaults to false.
-     *                 DEPRECATED as of 1.2.0 (use setMailParams()).
-     *     debug       Activate SMTP debug mode? Defaults to false.
-     *     persist     Should the SMTP connection persist?
-     *     pipelining  Use SMTP command pipelining
-     *
-     * If a parameter is present in the $params array, it replaces the
-     * default.
-     *
-     * @param array Hash containing any parameters different from the
-     *              defaults.
-     * @access public
-     */
-    function Mail_smtp($params)
-    {
-        if (isset($params['host'])) $this->host = $params['host'];
-        if (isset($params['port'])) $this->port = $params['port'];
-        if (isset($params['auth'])) $this->auth = $params['auth'];
-        if (isset($params['username'])) $this->username = $params['username'];
-        if (isset($params['password'])) $this->password = $params['password'];
-        if (isset($params['localhost'])) $this->localhost = $params['localhost'];
-        if (isset($params['timeout'])) $this->timeout = $params['timeout'];
-        if (isset($params['debug'])) $this->debug = (bool)$params['debug'];
-        if (isset($params['persist'])) $this->persist = (bool)$params['persist'];
-        if (isset($params['pipelining'])) $this->pipelining = (bool)$params['pipelining'];
-
-        // Deprecated options
-        if (isset($params['verp'])) {
-            $this->addServiceExtensionParameter('XVERP', is_bool($params['verp']) ? null : $params['verp']);
-        }
-
-        register_shutdown_function(array(&$this, '_Mail_smtp'));
-    }
-
-    /**
-     * Destructor implementation to ensure that we disconnect from any
-     * potentially-alive persistent SMTP connections.
-     */
-    function _Mail_smtp()
-    {
-        $this->disconnect();
-    }
-
-    /**
-     * Implements Mail::send() function using SMTP.
-     *
-     * @param mixed $recipients Either a comma-seperated list of recipients
-     *              (RFC822 compliant), or an array of recipients,
-     *              each RFC822 valid. This may contain recipients not
-     *              specified in the headers, for Bcc:, resending
-     *              messages, etc.
-     *
-     * @param array $headers The array of headers to send with the mail, in an
-     *              associative array, where the array key is the
-     *              header name (e.g., 'Subject'), and the array value
-     *              is the header value (e.g., 'test'). The header
-     *              produced from those values would be 'Subject:
-     *              test'.
-     *
-     * @param string $body The full text of the message body, including any
-     *               MIME parts, etc.
-     *
-     * @return mixed Returns true on success, or a PEAR_Error
-     *               containing a descriptive error message on
-     *               failure.
-     * @access public
-     */
-    function send($recipients, $headers, $body)
-    {
-        /* If we don't already have an SMTP object, create one. */
-        $result = &$this->getSMTPObject();
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        if (!is_array($headers)) {
-            return PEAR::raiseError('$headers must be an array');
-        }
-
-        $this->_sanitizeHeaders($headers);
-
-        $headerElements = $this->prepareHeaders($headers);
-        if (is_a($headerElements, 'PEAR_Error')) {
-            $this->_smtp->rset();
-            return $headerElements;
-        }
-        list($from, $textHeaders) = $headerElements;
-
-        /* Since few MTAs are going to allow this header to be forged
-         * unless it's in the MAIL FROM: exchange, we'll use
-         * Return-Path instead of From: if it's set. */
-        if (!empty($headers['Return-Path'])) {
-            $from = $headers['Return-Path'];
-        }
-
-        if (!isset($from)) {
-            $this->_smtp->rset();
-            return PEAR::raiseError('No From: address has been provided',
-                                    PEAR_MAIL_SMTP_ERROR_FROM);
-        }
-
-        $params = null;
-        if (!empty($this->_extparams)) {
-            foreach ($this->_extparams as $key => $val) {
-                $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
-            }
-        }
-        if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
-            $error = $this->_error("Failed to set sender: $from", $res);
-            $this->_smtp->rset();
-            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
-        }
-
-        $recipients = $this->parseRecipients($recipients);
-        if (is_a($recipients, 'PEAR_Error')) {
-            $this->_smtp->rset();
-            return $recipients;
-        }
-
-        foreach ($recipients as $recipient) {
-            $res = $this->_smtp->rcptTo($recipient);
-            if (is_a($res, 'PEAR_Error')) {
-                $error = $this->_error("Failed to add recipient: $recipient", $res);
-                $this->_smtp->rset();
-                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
-            }
-        }
-
-        /* Send the message's headers and the body as SMTP data. */
-        $res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body);
-        if (is_a($res, 'PEAR_Error')) {
-            $error = $this->_error('Failed to send data', $res);
-            $this->_smtp->rset();
-            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
-        }
-
-        /* If persistent connections are disabled, destroy our SMTP object. */
-        if ($this->persist === false) {
-            $this->disconnect();
-        }
-
-        return true;
-    }
-
-    /**
-     * Connection wrapper
-     *
-     *
-     */
-    function &connect() {
-        return $this->getSMTPObject();
-    }
-
-
-    /**
-     * Connect to the SMTP server by instantiating a Net_SMTP object.
-     *
-     * @return mixed Returns a reference to the Net_SMTP object on success, or
-     *               a PEAR_Error containing a descriptive error message on
-     *               failure.
-     *
-     * @since  1.2.0
-     * @access public
-     */
-    function &getSMTPObject()
-    {
-        if (is_object($this->_smtp) !== false) {
-            return $this->_smtp;
-        }
-
-        include_once 'Net/SMTP.php';
-        $this->_smtp = &new Net_SMTP($this->host,
-                                     $this->port,
-                                     $this->localhost);
-
-        /* If we still don't have an SMTP object at this point, fail. */
-        if (is_object($this->_smtp) === false) {
-            return PEAR::raiseError('Failed to create a Net_SMTP object',
-                                    PEAR_MAIL_SMTP_ERROR_CREATE);
-        }
-
-        /* Configure the SMTP connection. */
-        if ($this->debug) {
-            $this->_smtp->setDebug(true);
-        }
-
-        /* Attempt to connect to the configured SMTP server. */
-        if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
-
-            $error = $this->_error('Failed to connect to ' .
-                                   $this->host . ':' . $this->port,
-                                   $res);
-            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
-        }
-
-        /* Attempt to authenticate if authentication has been enabled. */
-        if ($this->auth) {
-            $method = is_string($this->auth) ? $this->auth : '';
-
-            if (PEAR::isError($res = $this->_smtp->auth($this->username,
-                                                        $this->password,
-                                                        $method))) {
-                $error = $this->_error("$method authentication failure",
-                                       $res);
-                $this->_smtp->rset();
-                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
-            }
-        }
-
-        return $this->_smtp;
-    }
-
-    /**
-     * Add parameter associated with a SMTP service extension.
-     *
-     * @param string Extension keyword.
-     * @param string Any value the keyword needs.
-     *
-     * @since 1.2.0
-     * @access public
-     */
-    function addServiceExtensionParameter($keyword, $value = null)
-    {
-        $this->_extparams[$keyword] = $value;
-    }
-
-
-
-
-    /**
-     * Disconnect and destroy the current SMTP connection.
-     *
-     * @return boolean True if the SMTP connection no longer exists.
-     *
-     * @since  1.1.9
-     * @access public
-     */
-    function disconnect()
-    {
-        /* If we have an SMTP object, disconnect and destroy it. */
-        if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
-            $this->_smtp = null;
-        }
-
-        /* We are disconnected if we no longer have an SMTP object. */
-        return ($this->_smtp === null);
-    }
-
-    /**
-     * Build a standardized string describing the current SMTP error.
-     *
-     * @param string $text  Custom string describing the error context.
-     * @param object $error Reference to the current PEAR_Error object.
-     *
-     * @return string       A string describing the current SMTP error.
-     *
-     * @since  1.1.7
-     * @access private
-     */
-    function _error($text, &$error)
-    {
-        /* Split the SMTP response into a code and a response string. */
-        list($code, $response) = $this->_smtp->getResponse();
-
-        /* Build our standardized error string. */
-        return $text
-            . ' [SMTP: ' . $error->getMessage()
-            . " (code: $code, response: $response)]";
-    }
-
-}
+<?php
+/**
+ * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2010, Chuck Hagenbuch
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category    HTTP
+ * @package     HTTP_Request
+ * @author      Jon Parise <jon@php.net> 
+ * @author      Chuck Hagenbuch <chuck@horde.org>
+ * @copyright   2010 Chuck Hagenbuch
+ * @license     http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version     CVS: $Id: smtp.php 294747 2010-02-08 08:18:33Z clockwerx $
+ * @link        http://pear.php.net/package/Mail/
+ */
+
+/** Error: Failed to create a Net_SMTP object */
+define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);
+
+/** Error: Failed to connect to SMTP server */
+define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);
+
+/** Error: SMTP authentication failure */
+define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);
+
+/** Error: No From: address has been provided */
+define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);
+
+/** Error: Failed to set sender */
+define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);
+
+/** Error: Failed to add recipient */
+define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);
+
+/** Error: Failed to send data */
+define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);
+
+/**
+ * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
+ * @access public
+ * @package Mail
+ * @version $Revision: 294747 $
+ */
+class Mail_smtp extends Mail {
+
+    /**
+     * SMTP connection object.
+     *
+     * @var object
+     * @access private
+     */
+    var $_smtp = null;
+
+    /**
+     * The list of service extension parameters to pass to the Net_SMTP
+     * mailFrom() command.
+     * @var array
+     */
+    var $_extparams = array();
+
+    /**
+     * The SMTP host to connect to.
+     * @var string
+     */
+    var $host = 'localhost';
+
+    /**
+     * The port the SMTP server is on.
+     * @var integer
+     */
+    var $port = 25;
+
+    /**
+     * Should SMTP authentication be used?
+     *
+     * This value may be set to true, false or the name of a specific
+     * authentication method.
+     *
+     * If the value is set to true, the Net_SMTP package will attempt to use
+     * the best authentication method advertised by the remote SMTP server.
+     *
+     * @var mixed
+     */
+    var $auth = false;
+
+    /**
+     * The username to use if the SMTP server requires authentication.
+     * @var string
+     */
+    var $username = '';
+
+    /**
+     * The password to use if the SMTP server requires authentication.
+     * @var string
+     */
+    var $password = '';
+
+    /**
+     * Hostname or domain that will be sent to the remote SMTP server in the
+     * HELO / EHLO message.
+     *
+     * @var string
+     */
+    var $localhost = 'localhost';
+
+    /**
+     * SMTP connection timeout value.  NULL indicates no timeout.
+     *
+     * @var integer
+     */
+    var $timeout = null;
+
+    /**
+     * Turn on Net_SMTP debugging?
+     *
+     * @var boolean $debug
+     */
+    var $debug = false;
+
+    /**
+     * Indicates whether or not the SMTP connection should persist over
+     * multiple calls to the send() method.
+     *
+     * @var boolean
+     */
+    var $persist = false;
+
+    /**
+     * Use SMTP command pipelining (specified in RFC 2920) if the SMTP server
+     * supports it. This speeds up delivery over high-latency connections. By
+     * default, use the default value supplied by Net_SMTP.
+     * @var bool
+     */
+    var $pipelining;
+
+    /**
+     * Constructor.
+     *
+     * Instantiates a new Mail_smtp:: object based on the parameters
+     * passed in. It looks for the following parameters:
+     *     host        The server to connect to. Defaults to localhost.
+     *     port        The port to connect to. Defaults to 25.
+     *     auth        SMTP authentication.  Defaults to none.
+     *     username    The username to use for SMTP auth. No default.
+     *     password    The password to use for SMTP auth. No default.
+     *     localhost   The local hostname / domain. Defaults to localhost.
+     *     timeout     The SMTP connection timeout. Defaults to none.
+     *     verp        Whether to use VERP or not. Defaults to false.
+     *                 DEPRECATED as of 1.2.0 (use setMailParams()).
+     *     debug       Activate SMTP debug mode? Defaults to false.
+     *     persist     Should the SMTP connection persist?
+     *     pipelining  Use SMTP command pipelining
+     *
+     * If a parameter is present in the $params array, it replaces the
+     * default.
+     *
+     * @param array Hash containing any parameters different from the
+     *              defaults.
+     * @access public
+     */
+    function Mail_smtp($params)
+    {
+        if (isset($params['host'])) $this->host = $params['host'];
+        if (isset($params['port'])) $this->port = $params['port'];
+        if (isset($params['auth'])) $this->auth = $params['auth'];
+        if (isset($params['username'])) $this->username = $params['username'];
+        if (isset($params['password'])) $this->password = $params['password'];
+        if (isset($params['localhost'])) $this->localhost = $params['localhost'];
+        if (isset($params['timeout'])) $this->timeout = $params['timeout'];
+        if (isset($params['debug'])) $this->debug = (bool)$params['debug'];
+        if (isset($params['persist'])) $this->persist = (bool)$params['persist'];
+        if (isset($params['pipelining'])) $this->pipelining = (bool)$params['pipelining'];
+
+        // Deprecated options
+        if (isset($params['verp'])) {
+            $this->addServiceExtensionParameter('XVERP', is_bool($params['verp']) ? null : $params['verp']);
+        }
+
+        register_shutdown_function(array(&$this, '_Mail_smtp'));
+    }
+
+    /**
+     * Destructor implementation to ensure that we disconnect from any
+     * potentially-alive persistent SMTP connections.
+     */
+    function _Mail_smtp()
+    {
+        $this->disconnect();
+    }
+
+    /**
+     * Implements Mail::send() function using SMTP.
+     *
+     * @param mixed $recipients Either a comma-seperated list of recipients
+     *              (RFC822 compliant), or an array of recipients,
+     *              each RFC822 valid. This may contain recipients not
+     *              specified in the headers, for Bcc:, resending
+     *              messages, etc.
+     *
+     * @param array $headers The array of headers to send with the mail, in an
+     *              associative array, where the array key is the
+     *              header name (e.g., 'Subject'), and the array value
+     *              is the header value (e.g., 'test'). The header
+     *              produced from those values would be 'Subject:
+     *              test'.
+     *
+     * @param string $body The full text of the message body, including any
+     *               MIME parts, etc.
+     *
+     * @return mixed Returns true on success, or a PEAR_Error
+     *               containing a descriptive error message on
+     *               failure.
+     * @access public
+     */
+    function send($recipients, $headers, $body)
+    {
+        /* If we don't already have an SMTP object, create one. */
+        $result = &$this->getSMTPObject();
+        if (PEAR::isError($result)) {
+            return $result;
+        }
+
+        if (!is_array($headers)) {
+            return PEAR::raiseError('$headers must be an array');
+        }
+
+        $this->_sanitizeHeaders($headers);
+
+        $headerElements = $this->prepareHeaders($headers);
+        if (is_a($headerElements, 'PEAR_Error')) {
+            $this->_smtp->rset();
+            return $headerElements;
+        }
+        list($from, $textHeaders) = $headerElements;
+
+        /* Since few MTAs are going to allow this header to be forged
+         * unless it's in the MAIL FROM: exchange, we'll use
+         * Return-Path instead of From: if it's set. */
+        if (!empty($headers['Return-Path'])) {
+            $from = $headers['Return-Path'];
+        }
+
+        if (!isset($from)) {
+            $this->_smtp->rset();
+            return PEAR::raiseError('No From: address has been provided',
+                                    PEAR_MAIL_SMTP_ERROR_FROM);
+        }
+
+        $params = null;
+        if (!empty($this->_extparams)) {
+            foreach ($this->_extparams as $key => $val) {
+                $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
+            }
+        }
+        if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
+            $error = $this->_error("Failed to set sender: $from", $res);
+            $this->_smtp->rset();
+            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
+        }
+
+        $recipients = $this->parseRecipients($recipients);
+        if (is_a($recipients, 'PEAR_Error')) {
+            $this->_smtp->rset();
+            return $recipients;
+        }
+
+        foreach ($recipients as $recipient) {
+            $res = $this->_smtp->rcptTo($recipient);
+            if (is_a($res, 'PEAR_Error')) {
+                $error = $this->_error("Failed to add recipient: $recipient", $res);
+                $this->_smtp->rset();
+                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
+            }
+        }
+
+        /* Send the message's headers and the body as SMTP data. */
+        $res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body);
+		list(,$args) = $this->_smtp->getResponse();
+
+		if (preg_match("/Ok: queued as (.*)/", $args, $queued)) {
+			$this->queued_as = $queued[1];
+		}
+
+		/* we need the greeting; from it we can extract the authorative name of the mail server we've really connected to.
+		 * ideal if we're connecting to a round-robin of relay servers and need to track which exact one took the email */
+		$this->greeting = $this->_smtp->getGreeting();
+
+        if (is_a($res, 'PEAR_Error')) {
+            $error = $this->_error('Failed to send data', $res);
+            $this->_smtp->rset();
+            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
+        }
+
+        /* If persistent connections are disabled, destroy our SMTP object. */
+        if ($this->persist === false) {
+            $this->disconnect();
+        }
+
+        return true;
+    }
+
+    /**
+     * Connect to the SMTP server by instantiating a Net_SMTP object.
+     *
+     * @return mixed Returns a reference to the Net_SMTP object on success, or
+     *               a PEAR_Error containing a descriptive error message on
+     *               failure.
+     *
+     * @since  1.2.0
+     * @access public
+     */
+    function &getSMTPObject()
+    {
+        if (is_object($this->_smtp) !== false) {
+            return $this->_smtp;
+        }
+
+        include_once 'Net/SMTP.php';
+        $this->_smtp = &new Net_SMTP($this->host,
+                                     $this->port,
+                                     $this->localhost);
+
+        /* If we still don't have an SMTP object at this point, fail. */
+        if (is_object($this->_smtp) === false) {
+            return PEAR::raiseError('Failed to create a Net_SMTP object',
+                                    PEAR_MAIL_SMTP_ERROR_CREATE);
+        }
+
+        /* Configure the SMTP connection. */
+        if ($this->debug) {
+            $this->_smtp->setDebug(true);
+        }
+
+        /* Attempt to connect to the configured SMTP server. */
+        if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
+            $error = $this->_error('Failed to connect to ' .
+                                   $this->host . ':' . $this->port,
+                                   $res);
+            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
+        }
+
+        /* Attempt to authenticate if authentication has been enabled. */
+        if ($this->auth) {
+            $method = is_string($this->auth) ? $this->auth : '';
+
+            if (PEAR::isError($res = $this->_smtp->auth($this->username,
+                                                        $this->password,
+                                                        $method))) {
+                $error = $this->_error("$method authentication failure",
+                                       $res);
+                $this->_smtp->rset();
+                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
+            }
+        }
+
+        return $this->_smtp;
+    }
+
+    /**
+     * Connection wrapper
+     *
+     *
+     */
+    function &connect() {
+        return $this->getSMTPObject();
+    }
+
+    /**
+     * Add parameter associated with a SMTP service extension.
+     *
+     * @param string Extension keyword.
+     * @param string Any value the keyword needs.
+     *
+     * @since 1.2.0
+     * @access public
+     */
+    function addServiceExtensionParameter($keyword, $value = null)
+    {
+        $this->_extparams[$keyword] = $value;
+    }
+
+    /**
+     * Disconnect and destroy the current SMTP connection.
+     *
+     * @return boolean True if the SMTP connection no longer exists.
+     *
+     * @since  1.1.9
+     * @access public
+     */
+    function disconnect()
+    {
+        /* If we have an SMTP object, disconnect and destroy it. */
+        if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
+            $this->_smtp = null;
+        }
+
+        /* We are disconnected if we no longer have an SMTP object. */
+        return ($this->_smtp === null);
+    }
+
+    /**
+     * Build a standardized string describing the current SMTP error.
+     *
+     * @param string $text  Custom string describing the error context.
+     * @param object $error Reference to the current PEAR_Error object.
+     *
+     * @return string       A string describing the current SMTP error.
+     *
+     * @since  1.1.7
+     * @access private
+     */
+    function _error($text, &$error)
+    {
+        /* Split the SMTP response into a code and a response string. */
+        list($code, $response) = $this->_smtp->getResponse();
+
+        /* Build our standardized error string. */
+        return $text
+            . ' [SMTP: ' . $error->getMessage()
+            . " (code: $code, response: $response)]";
+    }
+
+}
diff --git a/include/pear/Mail/smtpmx.php b/include/pear/Mail/smtpmx.php
new file mode 100755
index 0000000000000000000000000000000000000000..f0b69408681bdea1c2d8831616428323b67f8598
--- /dev/null
+++ b/include/pear/Mail/smtpmx.php
@@ -0,0 +1,502 @@
+<?PHP
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * SMTP MX
+ *
+ * SMTP MX implementation of the PEAR Mail interface. Requires the Net_SMTP class.
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2010, gERD Schaufelberger
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * o Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * o The names of the authors may not be used to endorse or promote
+ *   products derived from this software without specific prior written
+ *   permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category   Mail
+ * @package    Mail_smtpmx
+ * @author     gERD Schaufelberger <gerd@php-tools.net>
+ * @copyright  2010 gERD Schaufelberger
+ * @license    http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version    CVS: $Id: smtpmx.php 294747 2010-02-08 08:18:33Z clockwerx $
+ * @link       http://pear.php.net/package/Mail/
+ */
+
+require_once 'Net/SMTP.php';
+
+/**
+ * SMTP MX implementation of the PEAR Mail interface. Requires the Net_SMTP class.
+ *
+ *
+ * @access public
+ * @author  gERD Schaufelberger <gerd@php-tools.net>
+ * @package Mail
+ * @version $Revision: 294747 $
+ */
+class Mail_smtpmx extends Mail {
+
+    /**
+     * SMTP connection object.
+     *
+     * @var object
+     * @access private
+     */
+    var $_smtp = null;
+
+    /**
+     * The port the SMTP server is on.
+     * @var integer
+     * @see getservicebyname()
+     */
+    var $port = 25;
+
+    /**
+     * Hostname or domain that will be sent to the remote SMTP server in the
+     * HELO / EHLO message.
+     *
+     * @var string
+     * @see posix_uname()
+     */
+    var $mailname = 'localhost';
+
+    /**
+     * SMTP connection timeout value.  NULL indicates no timeout.
+     *
+     * @var integer
+     */
+    var $timeout = 10;
+
+    /**
+     * use either PEAR:Net_DNS or getmxrr
+     *
+     * @var boolean
+     */
+    var $withNetDns = true;
+
+    /**
+     * PEAR:Net_DNS_Resolver
+     *
+     * @var object
+     */
+    var $resolver;
+
+    /**
+     * Whether to use VERP or not. If not a boolean, the string value
+     * will be used as the VERP separators.
+     *
+     * @var mixed boolean or string
+     */
+    var $verp = false;
+
+    /**
+     * Whether to use VRFY or not.
+     *
+     * @var boolean $vrfy
+     */
+    var $vrfy = false;
+
+    /**
+     * Switch to test mode - don't send emails for real
+     *
+     * @var boolean $debug
+     */
+    var $test = false;
+
+    /**
+     * Turn on Net_SMTP debugging?
+     *
+     * @var boolean $peardebug
+     */
+    var $debug = false;
+
+    /**
+     * internal error codes
+     *
+     * translate internal error identifier to PEAR-Error codes and human
+     * readable messages.
+     *
+     * @var boolean $debug
+     * @todo as I need unique error-codes to identify what exactly went wrond
+     *       I did not use intergers as it should be. Instead I added a "namespace"
+     *       for each code. This avoids conflicts with error codes from different
+     *       classes. How can I use unique error codes and stay conform with PEAR?
+     */
+    var $errorCode = array(
+        'not_connected' => array(
+            'code'  => 1,
+            'msg'   => 'Could not connect to any mail server ({HOST}) at port {PORT} to send mail to {RCPT}.'
+        ),
+        'failed_vrfy_rcpt' => array(
+            'code'  => 2,
+            'msg'   => 'Recipient "{RCPT}" could not be veryfied.'
+        ),
+        'failed_set_from' => array(
+            'code'  => 3,
+            'msg'   => 'Failed to set sender: {FROM}.'
+        ),
+        'failed_set_rcpt' => array(
+            'code'  => 4,
+            'msg'   => 'Failed to set recipient: {RCPT}.'
+        ),
+        'failed_send_data' => array(
+            'code'  => 5,
+            'msg'   => 'Failed to send mail to: {RCPT}.'
+        ),
+        'no_from' => array(
+            'code'  => 5,
+            'msg'   => 'No from address has be provided.'
+        ),
+        'send_data' => array(
+            'code'  => 7,
+            'msg'   => 'Failed to create Net_SMTP object.'
+        ),
+        'no_mx' => array(
+            'code'  => 8,
+            'msg'   => 'No MX-record for {RCPT} found.'
+        ),
+        'no_resolver' => array(
+            'code'  => 9,
+            'msg'   => 'Could not start resolver! Install PEAR:Net_DNS or switch off "netdns"'
+        ),
+        'failed_rset' => array(
+            'code'  => 10,
+            'msg'   => 'RSET command failed, SMTP-connection corrupt.'
+        ),
+    );
+
+    /**
+     * Constructor.
+     *
+     * Instantiates a new Mail_smtp:: object based on the parameters
+     * passed in. It looks for the following parameters:
+     *     mailname    The name of the local mail system (a valid hostname which matches the reverse lookup)
+     *     port        smtp-port - the default comes from getservicebyname() and should work fine
+     *     timeout     The SMTP connection timeout. Defaults to 30 seconds.
+     *     vrfy        Whether to use VRFY or not. Defaults to false.
+     *     verp        Whether to use VERP or not. Defaults to false.
+     *     test        Activate test mode? Defaults to false.
+     *     debug       Activate SMTP and Net_DNS debug mode? Defaults to false.
+     *     netdns      whether to use PEAR:Net_DNS or the PHP build in function getmxrr, default is true
+     *
+     * If a parameter is present in the $params array, it replaces the
+     * default.
+     *
+     * @access public
+     * @param array Hash containing any parameters different from the
+     *              defaults.
+     * @see _Mail_smtpmx()
+     */
+    function __construct($params)
+    {
+        if (isset($params['mailname'])) {
+            $this->mailname = $params['mailname'];
+        } else {
+            // try to find a valid mailname
+            if (function_exists('posix_uname')) {
+                $uname = posix_uname();
+                $this->mailname = $uname['nodename'];
+            }
+        }
+
+        // port number
+        if (isset($params['port'])) {
+            $this->_port = $params['port'];
+        } else {
+            $this->_port = getservbyname('smtp', 'tcp');
+        }
+
+        if (isset($params['timeout'])) $this->timeout = $params['timeout'];
+        if (isset($params['verp'])) $this->verp = $params['verp'];
+        if (isset($params['test'])) $this->test = $params['test'];
+        if (isset($params['peardebug'])) $this->test = $params['peardebug'];
+        if (isset($params['netdns'])) $this->withNetDns = $params['netdns'];
+    }
+
+    /**
+     * Constructor wrapper for PHP4
+     *
+     * @access public
+     * @param array Hash containing any parameters different from the defaults
+     * @see __construct()
+     */
+    function Mail_smtpmx($params)
+    {
+        $this->__construct($params);
+        register_shutdown_function(array(&$this, '__destruct'));
+    }
+
+    /**
+     * Destructor implementation to ensure that we disconnect from any
+     * potentially-alive persistent SMTP connections.
+     */
+    function __destruct()
+    {
+        if (is_object($this->_smtp)) {
+            $this->_smtp->disconnect();
+            $this->_smtp = null;
+        }
+    }
+
+    /**
+     * Implements Mail::send() function using SMTP direct delivery
+     *
+     * @access public
+     * @param mixed $recipients in RFC822 style or array
+     * @param array $headers The array of headers to send with the mail.
+     * @param string $body The full text of the message body,
+     * @return mixed Returns true on success, or a PEAR_Error
+     */
+    function send($recipients, $headers, $body)
+    {
+        if (!is_array($headers)) {
+            return PEAR::raiseError('$headers must be an array');
+        }
+
+        $result = $this->_sanitizeHeaders($headers);
+        if (is_a($result, 'PEAR_Error')) {
+            return $result;
+        }
+
+        // Prepare headers
+        $headerElements = $this->prepareHeaders($headers);
+        if (is_a($headerElements, 'PEAR_Error')) {
+            return $headerElements;
+        }
+        list($from, $textHeaders) = $headerElements;
+
+        // use 'Return-Path' if possible
+        if (!empty($headers['Return-Path'])) {
+            $from = $headers['Return-Path'];
+        }
+        if (!isset($from)) {
+            return $this->_raiseError('no_from');
+        }
+
+        // Prepare recipients
+        $recipients = $this->parseRecipients($recipients);
+        if (is_a($recipients, 'PEAR_Error')) {
+            return $recipients;
+        }
+
+        foreach ($recipients as $rcpt) {
+            list($user, $host) = explode('@', $rcpt);
+
+            $mx = $this->_getMx($host);
+            if (is_a($mx, 'PEAR_Error')) {
+                return $mx;
+            }
+
+            if (empty($mx)) {
+                $info = array('rcpt' => $rcpt);
+                return $this->_raiseError('no_mx', $info);
+            }
+
+            $connected = false;
+            foreach ($mx as $mserver => $mpriority) {
+                $this->_smtp = new Net_SMTP($mserver, $this->port, $this->mailname);
+
+                // configure the SMTP connection.
+                if ($this->debug) {
+                    $this->_smtp->setDebug(true);
+                }
+
+                // attempt to connect to the configured SMTP server.
+                $res = $this->_smtp->connect($this->timeout);
+                if (is_a($res, 'PEAR_Error')) {
+                    $this->_smtp = null;
+                    continue;
+                }
+
+                // connection established
+                if ($res) {
+                    $connected = true;
+                    break;
+                }
+            }
+
+            if (!$connected) {
+                $info = array(
+                    'host' => implode(', ', array_keys($mx)),
+                    'port' => $this->port,
+                    'rcpt' => $rcpt,
+                );
+                return $this->_raiseError('not_connected', $info);
+            }
+
+            // Verify recipient
+            if ($this->vrfy) {
+                $res = $this->_smtp->vrfy($rcpt);
+                if (is_a($res, 'PEAR_Error')) {
+                    $info = array('rcpt' => $rcpt);
+                    return $this->_raiseError('failed_vrfy_rcpt', $info);
+                }
+            }
+
+            // mail from:
+            $args['verp'] = $this->verp;
+            $res = $this->_smtp->mailFrom($from, $args);
+            if (is_a($res, 'PEAR_Error')) {
+                $info = array('from' => $from);
+                return $this->_raiseError('failed_set_from', $info);
+            }
+
+            // rcpt to:
+            $res = $this->_smtp->rcptTo($rcpt);
+            if (is_a($res, 'PEAR_Error')) {
+                $info = array('rcpt' => $rcpt);
+                return $this->_raiseError('failed_set_rcpt', $info);
+            }
+
+            // Don't send anything in test mode
+            if ($this->test) {
+                $result = $this->_smtp->rset();
+                $res = $this->_smtp->rset();
+                if (is_a($res, 'PEAR_Error')) {
+                    return $this->_raiseError('failed_rset');
+                }
+
+                $this->_smtp->disconnect();
+                $this->_smtp = null;
+                return true;
+            }
+
+            // Send data
+            $res = $this->_smtp->data("$textHeaders\r\n$body");
+            if (is_a($res, 'PEAR_Error')) {
+                $info = array('rcpt' => $rcpt);
+                return $this->_raiseError('failed_send_data', $info);
+            }
+
+            $this->_smtp->disconnect();
+            $this->_smtp = null;
+        }
+
+        return true;
+    }
+
+    /**
+     * Recieve mx rexords for a spciefied host
+     *
+     * The MX records
+     *
+     * @access private
+     * @param string $host mail host
+     * @return mixed sorted
+     */
+    function _getMx($host)
+    {
+        $mx = array();
+
+        if ($this->withNetDns) {
+            $res = $this->_loadNetDns();
+            if (is_a($res, 'PEAR_Error')) {
+                return $res;
+            }
+
+            $response = $this->resolver->query($host, 'MX');
+            if (!$response) {
+                return false;
+            }
+
+            foreach ($response->answer as $rr) {
+                if ($rr->type == 'MX') {
+                    $mx[$rr->exchange] = $rr->preference;
+                }
+            }
+        } else {
+            $mxHost = array();
+            $mxWeight = array();
+
+            if (!getmxrr($host, $mxHost, $mxWeight)) {
+                return false;
+            }
+            for ($i = 0; $i < count($mxHost); ++$i) {
+                $mx[$mxHost[$i]] = $mxWeight[$i];
+            }
+        }
+
+        asort($mx);
+        return $mx;
+    }
+
+    /**
+     * initialize PEAR:Net_DNS_Resolver
+     *
+     * @access private
+     * @return boolean true on success
+     */
+    function _loadNetDns()
+    {
+        if (is_object($this->resolver)) {
+            return true;
+        }
+
+        if (!include_once 'Net/DNS.php') {
+            return $this->_raiseError('no_resolver');
+        }
+
+        $this->resolver = new Net_DNS_Resolver();
+        if ($this->debug) {
+            $this->resolver->test = 1;
+        }
+
+        return true;
+    }
+
+    /**
+     * raise standardized error
+     *
+     * include additional information in error message
+     *
+     * @access private
+     * @param string $id maps error ids to codes and message
+     * @param array $info optional information in associative array
+     * @see _errorCode
+     */
+    function _raiseError($id, $info = array())
+    {
+        $code = $this->errorCode[$id]['code'];
+        $msg = $this->errorCode[$id]['msg'];
+
+        // include info to messages
+        if (!empty($info)) {
+            $search = array();
+            $replace = array();
+
+            foreach ($info as $key => $value) {
+                array_push($search, '{' . strtoupper($key) . '}');
+                array_push($replace, $value);
+            }
+
+            $msg = str_replace($search, $replace, $msg);
+        }
+
+        return PEAR::raiseError($msg, $code);
+    }
+
+}
diff --git a/include/pear/Net/SMTP.php b/include/pear/Net/SMTP.php
index bf0a5a1aa0440a2e6ce1dc0ceb392832e0ab14b8..8d0682f361d85593954d67895e64c2dcb23bea93 100644
--- a/include/pear/Net/SMTP.php
+++ b/include/pear/Net/SMTP.php
@@ -18,7 +18,7 @@
 // |          Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar>      |
 // +----------------------------------------------------------------------+
 //
-// $Id: SMTP.php,v 1.64 2008/12/20 23:03:49 jon Exp $
+// $Id: SMTP.php 314875 2011-08-13 17:03:30Z jon $
 
 require_once 'PEAR.php';
 require_once 'Net/Socket.php';
@@ -62,7 +62,7 @@ class Net_SMTP
      * @var array
      * @access public
      */
-    var $auth_methods = array('DIGEST-MD5', 'CRAM-MD5', 'LOGIN', 'PLAIN');
+    var $auth_methods = array();
 
     /**
      * Use SMTP command pipelining (specified in RFC 2920) if the SMTP
@@ -91,6 +91,13 @@ class Net_SMTP
      */
     var $_debug = false;
 
+    /**
+     * Debug output handler.
+     * @var callback
+     * @access private
+     */
+    var $_debug_handler = null;
+
     /**
      * The socket resource being used to connect to the SMTP server.
      * @var resource
@@ -98,6 +105,21 @@ class Net_SMTP
      */
     var $_socket = null;
 
+    /**
+     * Array of socket options that will be passed to Net_Socket::connect().
+     * @see stream_context_create()
+     * @var array
+     * @access private
+     */
+    var $_socket_options = null;
+
+    /**
+     * The socket I/O timeout value in seconds.
+     * @var int
+     * @access private
+     */
+    var $_timeout = 0;
+
     /**
      * The most recent server response code.
      * @var int
@@ -112,6 +134,13 @@ class Net_SMTP
      */
     var $_arguments = array();
 
+    /**
+     * Stores the SMTP server's greeting string.
+     * @var string
+     * @access private
+     */
+    var $_greeting = null;
+
     /**
      * Stores detected features of the SMTP server.
      * @var array
@@ -134,11 +163,14 @@ class Net_SMTP
      * @param integer $port       The port to connect to.
      * @param string  $localhost  The value to give when sending EHLO or HELO.
      * @param boolean $pipeling   Use SMTP command pipelining
+     * @param integer $timeout    Socket I/O timeout in seconds.
+     * @param array   $socket_options Socket stream_context_create() options.
      *
      * @access  public
      * @since   1.0
      */
-    function Net_SMTP($host = null, $port = null, $localhost = null, $pipelining = false)
+    function Net_SMTP($host = null, $port = null, $localhost = null,
+        $pipelining = false, $timeout = 0, $socket_options = null)
     {
         if (isset($host)) {
             $this->host = $host;
@@ -152,16 +184,32 @@ class Net_SMTP
         $this->pipelining = $pipelining;
 
         $this->_socket = new Net_Socket();
+        $this->_socket_options = $socket_options;
+        $this->_timeout = $timeout;
 
-        /* Include the Auth_SASL package.  If the package is not
-         * available, we disable the authentication methods that
-         * depend upon it. */
-        if ((@include_once 'Auth/SASL.php') === false) {
-            $pos = array_search('DIGEST-MD5', $this->auth_methods);
-            unset($this->auth_methods[$pos]);
-            $pos = array_search('CRAM-MD5', $this->auth_methods);
-            unset($this->auth_methods[$pos]);
+        /* Include the Auth_SASL package.  If the package is available, we 
+         * enable the authentication methods that depend upon it. */
+        if (@include_once 'Auth/SASL.php') {
+            $this->setAuthMethod('CRAM-MD5', array($this, '_authCram_MD5'));
+            $this->setAuthMethod('DIGEST-MD5', array($this, '_authDigest_MD5'));
         }
+
+        /* These standard authentication methods are always available. */
+        $this->setAuthMethod('LOGIN', array($this, '_authLogin'), false);
+        $this->setAuthMethod('PLAIN', array($this, '_authPlain'), false);
+    }
+
+    /**
+     * Set the socket I/O timeout value in seconds plus microseconds.
+     *
+     * @param   integer $seconds        Timeout value in seconds.
+     * @param   integer $microseconds   Additional value in microseconds.
+     *
+     * @access  public
+     * @since   1.5.0
+     */
+    function setTimeout($seconds, $microseconds = 0) {
+        return $this->_socket->setTimeout($seconds, $microseconds);
     }
 
     /**
@@ -172,9 +220,30 @@ class Net_SMTP
      * @access  public
      * @since   1.1.0
      */
-    function setDebug($debug)
+    function setDebug($debug, $handler = null)
     {
         $this->_debug = $debug;
+        $this->_debug_handler = $handler;
+    }
+
+    /**
+     * Write the given debug text to the current debug output handler.
+     *
+     * @param   string  $message    Debug mesage text.
+     *
+     * @access  private
+     * @since   1.3.3
+     */
+    function _debug($message)
+    {
+        if ($this->_debug) {
+            if ($this->_debug_handler) {
+                call_user_func_array($this->_debug_handler,
+                                     array(&$this, $message));
+            } else {
+                echo "DEBUG: $message\n";
+            }
+        }
     }
 
     /**
@@ -182,23 +251,24 @@ class Net_SMTP
      *
      * @param   string  $data       The string of data to send.
      *
-     * @return  mixed   True on success or a PEAR_Error object on failure.
+     * @return  mixed   The number of bytes that were actually written,
+     *                  or a PEAR_Error object on failure.
      *
      * @access  private
      * @since   1.1.0
      */
     function _send($data)
     {
-        if ($this->_debug) {
-            echo "DEBUG: Send: $data\n";
-        }
+        $this->_debug("Send: $data");
 
-        if (PEAR::isError($error = $this->_socket->write($data))) {
-            return PEAR::raiseError('Failed to write to socket: ' .
-                                    $error->getMessage());
+        $result = $this->_socket->write($data);
+        if (!$result || PEAR::isError($result)) {
+            $msg = ($result) ? $result->getMessage() : "unknown error";
+            return PEAR::raiseError("Failed to write to socket: $msg",
+                                    null, PEAR_ERROR_RETURN);
         }
 
-        return true;
+        return $result;
     }
 
     /**
@@ -225,7 +295,8 @@ class Net_SMTP
         }
 
         if (strcspn($command, "\r\n") !== strlen($command)) {
-            return PEAR::raiseError('Commands cannot contain newlines');
+            return PEAR::raiseError('Commands cannot contain newlines',
+                                    null, PEAR_ERROR_RETURN);
         }
 
         return $this->_send($command . "\r\n");
@@ -255,7 +326,6 @@ class Net_SMTP
         $this->_code = -1;
         $this->_arguments = array();
 
-
         if ($later) {
             $this->_pipelined_commands++;
             return true;
@@ -263,14 +333,13 @@ class Net_SMTP
 
         for ($i = 0; $i <= $this->_pipelined_commands; $i++) {
             while ($line = $this->_socket->readLine()) {
-                if ($this->_debug) {
-                    echo "DEBUG: Recv: $line\n";
-                }
+                $this->_debug("Recv: $line");
 
-                /* If we receive an empty line, the connection has been closed. */
+                /* If we receive an empty line, the connection was closed. */
                 if (empty($line)) {
                     $this->disconnect();
-                    return PEAR::raiseError('Connection was unexpectedly closed');
+                    return PEAR::raiseError('Connection was closed',
+                                            null, PEAR_ERROR_RETURN);
                 }
 
                 /* Read the code and store the rest in the arguments array. */
@@ -302,7 +371,32 @@ class Net_SMTP
         }
 
         return PEAR::raiseError('Invalid response code received from server',
-                                $this->_code);
+                                $this->_code, PEAR_ERROR_RETURN);
+    }
+
+    /**
+     * Issue an SMTP command and verify its response.
+     *
+     * @param   string  $command    The SMTP command string or data.
+     * @param   mixed   $valid      The set of valid response codes.  These
+     *                              may be specified as an array of integer
+     *                              values or as a single integer value.
+     *
+     * @return  mixed   True on success or a PEAR_Error object on failure.
+     *
+     * @access  public
+     * @since   1.6.0
+     */
+    function command($command, $valid)
+    {
+        if (PEAR::isError($error = $this->_put($command))) {
+            return $error;
+        }
+        if (PEAR::isError($error = $this->_parseResponse($valid))) {
+            return $error;
+        }
+
+        return true;
     }
 
     /**
@@ -320,11 +414,25 @@ class Net_SMTP
         return array($this->_code, join("\n", $this->_arguments));
     }
 
+    /**
+     * Return the SMTP server's greeting string.
+     *
+     * @return  string  A string containing the greeting string, or null if a 
+     *                  greeting has not been received.
+     *
+     * @access  public
+     * @since   1.3.3
+     */
+    function getGreeting()
+    {
+        return $this->_greeting;
+    }
+
     /**
      * Attempt to connect to the SMTP server.
      *
      * @param   int     $timeout    The timeout value (in seconds) for the
-     *                              socket connection.
+     *                              socket connection attempt.
      * @param   bool    $persistent Should a persistent socket connection
      *                              be used?
      *
@@ -335,23 +443,38 @@ class Net_SMTP
      */
     function connect($timeout = null, $persistent = false)
     {
+        $this->_greeting = null;
         $result = $this->_socket->connect($this->host, $this->port,
-                                          $persistent, $timeout);
-
+                                          $persistent, $timeout,
+                                          $this->_socket_options);
         if (PEAR::isError($result)) {
             return PEAR::raiseError('Failed to connect socket: ' .
                                     $result->getMessage());
         }
 
+        /*
+         * Now that we're connected, reset the socket's timeout value for 
+         * future I/O operations.  This allows us to have different socket 
+         * timeout values for the initial connection (our $timeout parameter) 
+         * and all other socket operations.
+         */
+        if ($this->_timeout > 0) {
+            if (PEAR::isError($error = $this->setTimeout($this->_timeout))) {
+                return $error;
+            }
+        }
 
         if (PEAR::isError($error = $this->_parseResponse(220))) {
             return $error;
         }
+
+        /* Extract and store a copy of the server's greeting string. */
+        list(, $this->_greeting) = $this->getResponse();
+
         if (PEAR::isError($error = $this->_negotiate())) {
             return $error;
         }
 
-
         return true;
     }
 
@@ -406,7 +529,8 @@ class Net_SMTP
                 return $error;
             }
             if (PEAR::isError($this->_parseResponse(250))) {
-                return PEAR::raiseError('HELO was not accepted: ', $this->_code);
+                return PEAR::raiseError('HELO was not accepted: ', $this->_code,
+                                        PEAR_ERROR_RETURN);
             }
 
             return true;
@@ -440,13 +564,14 @@ class Net_SMTP
     {
         $available_methods = explode(' ', $this->_esmtp['AUTH']);
 
-        foreach ($this->auth_methods as $method) {
+        foreach ($this->auth_methods as $method => $callback) {
             if (in_array($method, $available_methods)) {
                 return $method;
             }
         }
 
-        return PEAR::raiseError('No supported authentication methods');
+        return PEAR::raiseError('No supported authentication methods',
+                                null, PEAR_ERROR_RETURN);
     }
 
     /**
@@ -456,15 +581,26 @@ class Net_SMTP
      * @param string The password to authenticate with.
      * @param string The requested authentication method.  If none is
      *               specified, the best supported method will be used.
+     * @param bool   Flag indicating whether or not TLS should be attempted.
+     * @param string An optional authorization identifier.  If specified, this
+     *               identifier will be used as the authorization proxy.
      *
      * @return mixed Returns a PEAR_Error with an error message on any
      *               kind of failure, or true on success.
      * @access public
      * @since  1.0
      */
-    function auth($uid, $pwd , $method = '')
+    function auth($uid, $pwd , $method = '', $tls = true, $authz = '')
     {
-        if (version_compare(PHP_VERSION, '5.1.0', '>=') && (isset($this->_esmtp['STARTTLS']) || ($this->_esmtp['STARTTLS'] == true))) {
+        /* We can only attempt a TLS connection if one has been requested,
+         * we're running PHP 5.1.0 or later, have access to the OpenSSL 
+         * extension, are connected to an SMTP server which supports the 
+         * STARTTLS extension, and aren't already connected over a secure 
+         * (SSL) socket connection. */
+        if ($tls && version_compare(PHP_VERSION, '5.1.0', '>=') &&
+            extension_loaded('openssl') && isset($this->_esmtp['STARTTLS']) &&
+            strncasecmp($this->host, 'ssl://', 6) !== 0) {
+            /* Start the TLS connection attempt. */
             if (PEAR::isError($result = $this->_put('STARTTLS'))) {
                 return $result;
             }
@@ -495,33 +631,27 @@ class Net_SMTP
             }
         } else {
             $method = strtoupper($method);
-            if (!in_array($method, $this->auth_methods)) {
+            if (!array_key_exists($method, $this->auth_methods)) {
                 return PEAR::raiseError("$method is not a supported authentication method");
             }
         }
 
-        switch ($method) {
-        case 'DIGEST-MD5':
-            $result = $this->_authDigest_MD5($uid, $pwd);
-            break;
-
-        case 'CRAM-MD5':
-            $result = $this->_authCRAM_MD5($uid, $pwd);
-            break;
-
-        case 'LOGIN':
-            $result = $this->_authLogin($uid, $pwd);
-            break;
-
-        case 'PLAIN':
-            $result = $this->_authPlain($uid, $pwd);
-            break;
+        if (!isset($this->auth_methods[$method])) {
+            return PEAR::raiseError("$method is not a supported authentication method");
+        }
 
-        default:
-            $result = PEAR::raiseError("$method is not a supported authentication method");
-            break;
+        if (!is_callable($this->auth_methods[$method], false)) {
+            return PEAR::raiseError("$method authentication method cannot be called");
         }
 
+        if (is_array($this->auth_methods[$method])) {
+            list($object, $method) = $this->auth_methods[$method];
+            $result = $object->{$method}($uid, $pwd, $authz, $this);
+        } else {
+            $func =  $this->auth_methods[$method];
+            $result = $func($uid, $pwd, $authz, $this);
+         }
+
         /* If an error was encountered, return the PEAR_Error object. */
         if (PEAR::isError($result)) {
             return $result;
@@ -530,18 +660,59 @@ class Net_SMTP
         return true;
     }
 
+    /**
+     * Add a new authentication method.
+     *
+     * @param string    The authentication method name (e.g. 'PLAIN')
+     * @param mixed     The authentication callback (given as the name of a 
+     *                  function or as an (object, method name) array).
+     * @param bool      Should the new method be prepended to the list of 
+     *                  available methods?  This is the default behavior, 
+     *                  giving the new method the highest priority.
+     *
+     * @return  mixed   True on success or a PEAR_Error object on failure.
+     *
+     * @access public
+     * @since  1.6.0
+     */
+    function setAuthMethod($name, $callback, $prepend = true)
+    {
+        if (!is_string($name)) {
+            return PEAR::raiseError('Method name is not a string');
+        }
+
+        if (!is_string($callback) && !is_array($callback)) {
+            return PEAR::raiseError('Method callback must be string or array');
+        }
+
+        if (is_array($callback)) {
+            if (!is_object($callback[0]) || !is_string($callback[1]))
+                return PEAR::raiseError('Bad mMethod callback array');
+        }
+
+        if ($prepend) {
+            $this->auth_methods = array_merge(array($name => $callback),
+                                              $this->auth_methods);
+        } else {
+            $this->auth_methods[$name] = $callback;
+        }
+
+        return true;
+    }
+
     /**
      * Authenticates the user using the DIGEST-MD5 method.
      *
      * @param string The userid to authenticate as.
      * @param string The password to authenticate with.
+     * @param string The optional authorization proxy identifier.
      *
      * @return mixed Returns a PEAR_Error with an error message on any
      *               kind of failure, or true on success.
      * @access private
      * @since  1.1.0
      */
-    function _authDigest_MD5($uid, $pwd)
+    function _authDigest_MD5($uid, $pwd, $authz = '')
     {
         if (PEAR::isError($error = $this->_put('AUTH', 'DIGEST-MD5'))) {
             return $error;
@@ -558,7 +729,8 @@ class Net_SMTP
         $challenge = base64_decode($this->_arguments[0]);
         $digest = &Auth_SASL::factory('digestmd5');
         $auth_str = base64_encode($digest->getResponse($uid, $pwd, $challenge,
-                                                       $this->host, "smtp"));
+                                                       $this->host, "smtp",
+                                                       $authz));
 
         if (PEAR::isError($error = $this->_put($auth_str))) {
             return $error;
@@ -585,13 +757,14 @@ class Net_SMTP
      *
      * @param string The userid to authenticate as.
      * @param string The password to authenticate with.
+     * @param string The optional authorization proxy identifier.
      *
      * @return mixed Returns a PEAR_Error with an error message on any
      *               kind of failure, or true on success.
      * @access private
      * @since  1.1.0
      */
-    function _authCRAM_MD5($uid, $pwd)
+    function _authCRAM_MD5($uid, $pwd, $authz = '')
     {
         if (PEAR::isError($error = $this->_put('AUTH', 'CRAM-MD5'))) {
             return $error;
@@ -624,13 +797,14 @@ class Net_SMTP
      *
      * @param string The userid to authenticate as.
      * @param string The password to authenticate with.
+     * @param string The optional authorization proxy identifier.
      *
      * @return mixed Returns a PEAR_Error with an error message on any
      *               kind of failure, or true on success.
      * @access private
      * @since  1.1.0
      */
-    function _authLogin($uid, $pwd)
+    function _authLogin($uid, $pwd, $authz = '')
     {
         if (PEAR::isError($error = $this->_put('AUTH', 'LOGIN'))) {
             return $error;
@@ -669,13 +843,14 @@ class Net_SMTP
      *
      * @param string The userid to authenticate as.
      * @param string The password to authenticate with.
+     * @param string The optional authorization proxy identifier.
      *
      * @return mixed Returns a PEAR_Error with an error message on any
      *               kind of failure, or true on success.
      * @access private
      * @since  1.1.0
      */
-    function _authPlain($uid, $pwd)
+    function _authPlain($uid, $pwd, $authz = '')
     {
         if (PEAR::isError($error = $this->_put('AUTH', 'PLAIN'))) {
             return $error;
@@ -689,7 +864,7 @@ class Net_SMTP
             return $error;
         }
 
-        $auth_str = base64_encode(chr(0) . $uid . chr(0) . $pwd);
+        $auth_str = base64_encode($authz . chr(0) . $uid . chr(0) . $pwd);
 
         if (PEAR::isError($error = $this->_put($auth_str))) {
             return $error;
@@ -770,7 +945,7 @@ class Net_SMTP
             } elseif (trim($params['verp'])) {
                 $args .= ' XVERP=' . $params['verp'];
             }
-        } elseif (is_string($params)) {
+        } elseif (is_string($params) && !empty($params)) {
             $args .= ' ' . $params;
         }
 
@@ -842,30 +1017,49 @@ class Net_SMTP
     /**
      * Send the DATA command.
      *
-     * @param string $data  The message body to send.
+     * @param mixed $data     The message data, either as a string or an open
+     *                        file resource.
+     * @param string $headers The message headers.  If $headers is provided,
+     *                        $data is assumed to contain only body data.
      *
      * @return mixed Returns a PEAR_Error with an error message on any
      *               kind of failure, or true on success.
      * @access public
      * @since  1.0
      */
-    function data($data)
+    function data($data, $headers = null)
     {
-        /* RFC 1870, section 3, subsection 3 states "a value of zero
-         * indicates that no fixed maximum message size is in force".
-         * Furthermore, it says that if "the parameter is omitted no
-         * information is conveyed about the server's fixed maximum
-         * message size". */
-        if (isset($this->_esmtp['SIZE']) && ($this->_esmtp['SIZE'] > 0)) {
-            if (strlen($data) >= $this->_esmtp['SIZE']) {
-                $this->disconnect();
-                return PEAR::raiseError('Message size excedes the server limit');
+        /* Verify that $data is a supported type. */
+        if (!is_string($data) && !is_resource($data)) {
+            return PEAR::raiseError('Expected a string or file resource');
+        }
+
+        /* Start by considering the size of the optional headers string.  We
+         * also account for the addition 4 character "\r\n\r\n" separator
+         * sequence. */
+        $size = (is_null($headers)) ? 0 : strlen($headers) + 4;
+
+        if (is_resource($data)) {
+            $stat = fstat($data);
+            if ($stat === false) {
+                return PEAR::raiseError('Failed to get file size');
             }
+            $size += $stat['size'];
+        } else {
+            $size += strlen($data);
         }
 
-        /* Quote the data based on the SMTP standards. */
-        $this->quotedata($data);
+        /* RFC 1870, section 3, subsection 3 states "a value of zero indicates
+         * that no fixed maximum message size is in force".  Furthermore, it
+         * says that if "the parameter is omitted no information is conveyed
+         * about the server's fixed maximum message size". */
+        $limit = (isset($this->_esmtp['SIZE'])) ? $this->_esmtp['SIZE'] : 0;
+        if ($limit > 0 && $size >= $limit) {
+            $this->disconnect();
+            return PEAR::raiseError('Message size exceeds server limit');
+        }
 
+        /* Initiate the DATA command. */
         if (PEAR::isError($error = $this->_put('DATA'))) {
             return $error;
         }
@@ -873,9 +1067,77 @@ class Net_SMTP
             return $error;
         }
 
-        if (PEAR::isError($result = $this->_send($data . "\r\n.\r\n"))) {
+        /* If we have a separate headers string, send it first. */
+        if (!is_null($headers)) {
+            $this->quotedata($headers);
+            if (PEAR::isError($result = $this->_send($headers . "\r\n\r\n"))) {
+                return $result;
+            }
+        }
+
+        /* Now we can send the message body data. */
+        if (is_resource($data)) {
+            /* Stream the contents of the file resource out over our socket 
+             * connection, line by line.  Each line must be run through the 
+             * quoting routine. */
+            while (strlen($line = fread($data, 8192)) > 0) {
+                /* If the last character is an newline, we need to grab the
+                 * next character to check to see if it is a period. */
+                while (!feof($data)) {
+                    $char = fread($data, 1);
+                    $line .= $char;
+                    if ($char != "\n") {
+                        break;
+                    }
+                }
+                $this->quotedata($line);
+                if (PEAR::isError($result = $this->_send($line))) {
+                    return $result;
+                }
+            }
+        } else {
+            /*
+             * Break up the data by sending one chunk (up to 512k) at a time.  
+             * This approach reduces our peak memory usage.
+             */
+            for ($offset = 0; $offset < $size;) {
+                $end = $offset + 512000;
+
+                /*
+                 * Ensure we don't read beyond our data size or span multiple 
+                 * lines.  quotedata() can't properly handle character data 
+                 * that's split across two line break boundaries.
+                 */
+                if ($end >= $size) {
+                    $end = $size;
+                } else {
+                    for (; $end < $size; $end++) {
+                        if ($data[$end] != "\n") {
+                            break;
+                        }
+                    }
+                }
+
+                /* Extract our chunk and run it through the quoting routine. */
+                $chunk = substr($data, $offset, $end - $offset);
+                $this->quotedata($chunk);
+
+                /* If we run into a problem along the way, abort. */
+                if (PEAR::isError($result = $this->_send($chunk))) {
+                    return $result;
+                }
+
+                /* Advance the offset to the end of this chunk. */
+                $offset = $end;
+            }
+        }
+
+        /* Finally, send the DATA terminator sequence. */
+        if (PEAR::isError($result = $this->_send("\r\n.\r\n"))) {
             return $result;
         }
+
+        /* Verify that the data was successfully received by the server. */
         if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
             return $error;
         }
diff --git a/include/pear/Net/Socket.php b/include/pear/Net/Socket.php
index cc495bf9fc621c41c5c30bdef83c06bf1c74670e..8a5ca5f5a0baeb809530d2a51900796a235e6d6a 100644
--- a/include/pear/Net/Socket.php
+++ b/include/pear/Net/Socket.php
@@ -1,39 +1,51 @@
 <?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license,       |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net>                                   |
-// |          Chuck Hagenbuch <chuck@horde.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Socket.php,v 1.38 2008/02/15 18:24:17 chagenbu Exp $
+/**
+ * Net_Socket
+ *
+ * PHP Version 4
+ *
+ * Copyright (c) 1997-2003 The PHP Group
+ *
+ * This source file is subject to version 2.0 of the PHP license,
+ * that is bundled with this package in the file LICENSE, and is
+ * available at through the world-wide-web at
+ * http://www.php.net/license/2_02.txt.
+ * If you did not receive a copy of the PHP license and are unable to
+ * obtain it through the world-wide-web, please send a note to
+ * license@php.net so we can mail you a copy immediately.
+ *
+ * Authors: Stig Bakken <ssb@php.net>
+ *          Chuck Hagenbuch <chuck@horde.org>
+ *
+ * @category  Net
+ * @package   Net_Socket
+ * @author    Stig Bakken <ssb@php.net>
+ * @author    Chuck Hagenbuch <chuck@horde.org>
+ * @copyright 1997-2003 The PHP Group
+ * @license   http://www.php.net/license/2_02.txt PHP 2.02
+ * @version   CVS: $Id: Socket.php 304428 2010-10-15 13:51:46Z clockwerx $
+ * @link      http://pear.php.net/packages/Net_Socket
+ */
 
 require_once 'PEAR.php';
 
-define('NET_SOCKET_READ',  1);
+define('NET_SOCKET_READ', 1);
 define('NET_SOCKET_WRITE', 2);
 define('NET_SOCKET_ERROR', 4);
 
 /**
  * Generalized Socket class.
  *
- * @version 1.1
- * @author Stig Bakken <ssb@php.net>
- * @author Chuck Hagenbuch <chuck@horde.org>
+ * @category  Net
+ * @package   Net_Socket
+ * @author    Stig Bakken <ssb@php.net>
+ * @author    Chuck Hagenbuch <chuck@horde.org>
+ * @copyright 1997-2003 The PHP Group
+ * @license   http://www.php.net/license/2_02.txt PHP 2.02
+ * @link      http://pear.php.net/packages/Net_Socket
  */
-class Net_Socket extends PEAR {
-
+class Net_Socket extends PEAR
+{
     /**
      * Socket file pointer.
      * @var resource $fp
@@ -78,23 +90,30 @@ class Net_Socket extends PEAR {
      */
     var $lineLength = 2048;
 
+    /**
+     * The string to use as a newline terminator. Usually "\r\n" or "\n".
+     * @var string $newline
+     */
+    var $newline = "\r\n";
+
     /**
      * Connect to the specified port. If called when the socket is
      * already connected, it disconnects and connects again.
      *
-     * @param string  $addr        IP address or host name.
-     * @param integer $port        TCP port number.
-     * @param boolean $persistent  (optional) Whether the connection is
-     *                             persistent (kept open between requests
-     *                             by the web server).
-     * @param integer $timeout     (optional) How long to wait for data.
-     * @param array   $options     See options for stream_context_create.
+     * @param string  $addr       IP address or host name.
+     * @param integer $port       TCP port number.
+     * @param boolean $persistent (optional) Whether the connection is
+     *                            persistent (kept open between requests
+     *                            by the web server).
+     * @param integer $timeout    (optional) How long to wait for data.
+     * @param array   $options    See options for stream_context_create.
      *
      * @access public
      *
      * @return boolean | PEAR_Error  True on success or a PEAR_Error on failure.
      */
-    function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
+    function connect($addr, $port = 0, $persistent = null,
+                     $timeout = null, $options = null)
     {
         if (is_resource($this->fp)) {
             @fclose($this->fp);
@@ -121,9 +140,11 @@ class Net_Socket extends PEAR {
         }
 
         $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
-        $errno = 0;
-        $errstr = '';
+        $errno    = 0;
+        $errstr   = '';
+
         $old_track_errors = @ini_set('track_errors', 1);
+
         if ($options && function_exists('stream_context_create')) {
             if ($this->timeout) {
                 $timeout = $this->timeout;
@@ -134,29 +155,36 @@ class Net_Socket extends PEAR {
 
             // Since PHP 5 fsockopen doesn't allow context specification
             if (function_exists('stream_socket_client')) {
-                $flags = $this->persistent ? STREAM_CLIENT_PERSISTENT : STREAM_CLIENT_CONNECT;
+                $flags = STREAM_CLIENT_CONNECT;
+
+                if ($this->persistent) {
+                    $flags = STREAM_CLIENT_PERSISTENT;
+                }
+
                 $addr = $this->addr . ':' . $this->port;
-                $fp = stream_socket_client($addr, $errno, $errstr, $timeout, $flags, $context);
+                $fp   = stream_socket_client($addr, $errno, $errstr,
+                                             $timeout, $flags, $context);
             } else {
-                $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
+                $fp = @$openfunc($this->addr, $this->port, $errno,
+                                 $errstr, $timeout, $context);
             }
         } else {
             if ($this->timeout) {
-                $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
+                $fp = @$openfunc($this->addr, $this->port, $errno,
+                                 $errstr, $this->timeout);
             } else {
                 $fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
             }
         }
 
         if (!$fp) {
-            if ($errno == 0 && isset($php_errormsg)) {
+            if ($errno == 0 && !strlen($errstr) && isset($php_errormsg)) {
                 $errstr = $php_errormsg;
             }
             @ini_set('track_errors', $old_track_errors);
             return $this->raiseError($errstr, $errno);
         }
 
-
         @ini_set('track_errors', $old_track_errors);
         $this->fp = $fp;
 
@@ -180,6 +208,18 @@ class Net_Socket extends PEAR {
         return true;
     }
 
+    /**
+     * Set the newline character/sequence to use.
+     *
+     * @param string $newline  Newline character(s)
+     * @return boolean True
+     */
+    function setNewline($newline)
+    {
+        $this->newline = $newline;
+        return true;
+    }
+
     /**
      * Find out if the socket is in blocking mode.
      *
@@ -197,7 +237,8 @@ class Net_Socket extends PEAR {
      * if there is no data available, whereas it will block until there
      * is data for blocking sockets.
      *
-     * @param boolean $mode  True for blocking sockets, false for nonblocking.
+     * @param boolean $mode True for blocking sockets, false for nonblocking.
+     *
      * @access public
      * @return mixed true on success or a PEAR_Error instance otherwise
      */
@@ -206,9 +247,9 @@ class Net_Socket extends PEAR {
         if (!is_resource($this->fp)) {
             return $this->raiseError('not connected');
         }
-        $this->blocking = $mode;
-        socket_set_blocking($this->fp, $this->blocking);
 
+        $this->blocking = $mode;
+        stream_set_blocking($this->fp, (int)$this->blocking);
         return true;
     }
 
@@ -216,8 +257,9 @@ class Net_Socket extends PEAR {
      * Sets the timeout value on socket descriptor,
      * expressed in the sum of seconds and microseconds
      *
-     * @param integer $seconds  Seconds.
-     * @param integer $microseconds  Microseconds.
+     * @param integer $seconds      Seconds.
+     * @param integer $microseconds Microseconds.
+     *
      * @access public
      * @return mixed true on success or a PEAR_Error instance otherwise
      */
@@ -234,7 +276,8 @@ class Net_Socket extends PEAR {
      * Sets the file buffering size on the stream.
      * See php's stream_set_write_buffer for more information.
      *
-     * @param integer $size     Write buffer size.
+     * @param integer $size Write buffer size.
+     *
      * @access public
      * @return mixed on success or an PEAR_Error object otherwise
      */
@@ -263,7 +306,8 @@ class Net_Socket extends PEAR {
      * </p>
      *
      * @access public
-     * @return mixed Array containing information about existing socket resource or a PEAR_Error instance otherwise
+     * @return mixed Array containing information about existing socket
+     *               resource or a PEAR_Error instance otherwise
      */
     function getStatus()
     {
@@ -277,17 +321,23 @@ class Net_Socket extends PEAR {
     /**
      * Get a specified line of data
      *
+     * @param int $size ??
+     *
      * @access public
      * @return $size bytes of data from the socket, or a PEAR_Error if
      *         not connected.
      */
-    function gets($size)
+    function gets($size = null)
     {
         if (!is_resource($this->fp)) {
             return $this->raiseError('not connected');
         }
 
-        return @fgets($this->fp, $size);
+        if (is_null($size)) {
+            return @fgets($this->fp);
+        } else {
+            return @fgets($this->fp, $size);
+        }
     }
 
     /**
@@ -296,7 +346,8 @@ class Net_Socket extends PEAR {
      * chunk; if you know the size of the data you're getting
      * beforehand, this is definitely the way to go.
      *
-     * @param integer $size  The number of bytes to read from the socket.
+     * @param integer $size The number of bytes to read from the socket.
+     *
      * @access public
      * @return $size bytes of data from the socket, or a PEAR_Error if
      *         not connected.
@@ -313,12 +364,13 @@ class Net_Socket extends PEAR {
     /**
      * Write a specified amount of data.
      *
-     * @param string  $data       Data to write.
-     * @param integer $blocksize  Amount of data to write at once.
-     *                            NULL means all at once.
+     * @param string  $data      Data to write.
+     * @param integer $blocksize Amount of data to write at once.
+     *                           NULL means all at once.
      *
      * @access public
-     * @return mixed If the socket is not connected, returns an instance of PEAR_Error
+     * @return mixed If the socket is not connected, returns an instance of
+     *               PEAR_Error
      *               If the write succeeds, returns the number of bytes written
      *               If the write fails, returns false.
      */
@@ -335,12 +387,12 @@ class Net_Socket extends PEAR {
                 $blocksize = 1024;
             }
 
-            $pos = 0;
+            $pos  = 0;
             $size = strlen($data);
             while ($pos < $size) {
                 $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
-                if ($written === false) {
-                    return false;
+                if (!$written) {
+                    return $written;
                 }
                 $pos += $written;
             }
@@ -350,7 +402,9 @@ class Net_Socket extends PEAR {
     }
 
     /**
-     * Write a line of data to the socket, followed by a trailing "\r\n".
+     * Write a line of data to the socket, followed by a trailing newline.
+     *
+     * @param string $data Data to write
      *
      * @access public
      * @return mixed fputs result, or an error
@@ -361,7 +415,7 @@ class Net_Socket extends PEAR {
             return $this->raiseError('not connected');
         }
 
-        return fwrite($this->fp, $data . "\r\n");
+        return fwrite($this->fp, $data . $this->newline);
     }
 
     /**
@@ -442,7 +496,7 @@ class Net_Socket extends PEAR {
         }
 
         $string = '';
-        while (($char = @fread($this->fp, 1)) != "\x00")  {
+        while (($char = @fread($this->fp, 1)) != "\x00") {
             $string .= $char;
         }
         return $string;
@@ -482,11 +536,13 @@ class Net_Socket extends PEAR {
         }
 
         $line = '';
+
         $timeout = time() + $this->timeout;
+
         while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
             $line .= @fgets($this->fp, $this->lineLength);
             if (substr($line, -1) == "\n") {
-                return rtrim($line, "\r\n");
+                return rtrim($line, $this->newline);
             }
         }
         return $line;
@@ -522,9 +578,9 @@ class Net_Socket extends PEAR {
      * Runs the equivalent of the select() system call on the socket
      * with a timeout specified by tv_sec and tv_usec.
      *
-     * @param integer $state    Which of read/write/error to check for.
-     * @param integer $tv_sec   Number of seconds for timeout.
-     * @param integer $tv_usec  Number of microseconds for timeout.
+     * @param integer $state   Which of read/write/error to check for.
+     * @param integer $tv_sec  Number of seconds for timeout.
+     * @param integer $tv_usec Number of microseconds for timeout.
      *
      * @access public
      * @return False if select fails, integer describing which of read/write/error
@@ -536,8 +592,8 @@ class Net_Socket extends PEAR {
             return $this->raiseError('not connected');
         }
 
-        $read = null;
-        $write = null;
+        $read   = null;
+        $write  = null;
         $except = null;
         if ($state & NET_SOCKET_READ) {
             $read[] = $this->fp;
@@ -548,7 +604,8 @@ class Net_Socket extends PEAR {
         if ($state & NET_SOCKET_ERROR) {
             $except[] = $this->fp;
         }
-        if (false === ($sr = stream_select($read, $write, $except, $tv_sec, $tv_usec))) {
+        if (false === ($sr = stream_select($read, $write, $except,
+                                          $tv_sec, $tv_usec))) {
             return false;
         }
 
@@ -568,15 +625,17 @@ class Net_Socket extends PEAR {
     /**
      * Turns encryption on/off on a connected socket.
      *
-     * @param bool    $enabled  Set this parameter to true to enable encryption
-     *                          and false to disable encryption.
-     * @param integer $type     Type of encryption. See
-     *                          http://se.php.net/manual/en/function.stream-socket-enable-crypto.php for values.
+     * @param bool    $enabled Set this parameter to true to enable encryption
+     *                         and false to disable encryption.
+     * @param integer $type    Type of encryption. See stream_socket_enable_crypto()
+     *                         for values.
      *
+     * @see    http://se.php.net/manual/en/function.stream-socket-enable-crypto.php
      * @access public
-     * @return false on error, true on success and 0 if there isn't enough data and the
-     *         user should try again (non-blocking sockets only). A PEAR_Error object
-     *         is returned if the socket is not connected
+     * @return false on error, true on success and 0 if there isn't enough data
+     *         and the user should try again (non-blocking sockets only).
+     *         A PEAR_Error object is returned if the socket is not
+     *         connected
      */
     function enableCrypto($enabled, $type)
     {
@@ -586,7 +645,8 @@ class Net_Socket extends PEAR {
             }
             return @stream_socket_enable_crypto($this->fp, $enabled, $type);
         } else {
-            return $this->raiseError('Net_Socket::enableCrypto() requires php version >= 5.1.0');
+            $msg = 'Net_Socket::enableCrypto() requires php version >= 5.1.0';
+            return $this->raiseError($msg);
         }
     }
 
diff --git a/include/pear/PEAR.php b/include/pear/PEAR.php
index 4de89ee3ace62cf172d259cee0733c8b6e6b11d5..2aa85259d62dc69c0cad3f38320bc82fdcf28af9 100644
--- a/include/pear/PEAR.php
+++ b/include/pear/PEAR.php
@@ -12,9 +12,9 @@
  * @author     Stig Bakken <ssb@php.net>
  * @author     Tomas V.V.Cox <cox@idecnet.com>
  * @author     Greg Beaver <cellog@php.net>
- * @copyright  1997-2009 The Authors
+ * @copyright  1997-2010 The Authors
  * @license    http://opensource.org/licenses/bsd-license.php New BSD License
- * @version    CVS: $Id: PEAR.php,v 1.112 2009/04/15 04:05:13 dufuz Exp $
+ * @version    CVS: $Id: PEAR.php 313023 2011-07-06 19:17:11Z dufuz $
  * @link       http://pear.php.net/package/PEAR
  * @since      File available since Release 0.1
  */
@@ -78,7 +78,7 @@ $GLOBALS['_PEAR_error_handler_stack']    = array();
  * @author     Greg Beaver <cellog@php.net>
  * @copyright  1997-2006 The PHP Group
  * @license    http://opensource.org/licenses/bsd-license.php New BSD License
- * @version    Release: 1.8.1
+ * @version    Release: 1.9.4
  * @link       http://pear.php.net/package/PEAR
  * @see        PEAR_Error
  * @since      Class available since PHP 4.0.2
@@ -86,8 +86,6 @@ $GLOBALS['_PEAR_error_handler_stack']    = array();
  */
 class PEAR
 {
-    // {{{ properties
-
     /**
      * Whether to enable internal debug messages.
      *
@@ -138,10 +136,6 @@ class PEAR
      */
     var $_expected_errors = array();
 
-    // }}}
-
-    // {{{ constructor
-
     /**
      * Constructor.  Registers this object in
      * $_PEAR_destructor_object_list for destructor emulation if a
@@ -158,9 +152,11 @@ class PEAR
         if ($this->_debug) {
             print "PEAR constructor called, class=$classname\n";
         }
+
         if ($error_class !== null) {
             $this->_error_class = $error_class;
         }
+
         while ($classname && strcasecmp($classname, "pear")) {
             $destructor = "_$classname";
             if (method_exists($this, $destructor)) {
@@ -177,9 +173,6 @@ class PEAR
         }
     }
 
-    // }}}
-    // {{{ destructor
-
     /**
      * Destructor (the emulated type of...).  Does nothing right now,
      * but is included for forward compatibility, so subclass
@@ -197,9 +190,6 @@ class PEAR
         }
     }
 
-    // }}}
-    // {{{ getStaticProperty()
-
     /**
     * If you have a class that's mostly/entirely static, and you need static
     * properties, you can use this method to simulate them. Eg. in your method(s)
@@ -226,9 +216,6 @@ class PEAR
         return $properties[$class][$var];
     }
 
-    // }}}
-    // {{{ registerShutdownFunc()
-
     /**
     * Use this function to register a shutdown method for static
     * classes.
@@ -249,9 +236,6 @@ class PEAR
         $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
     }
 
-    // }}}
-    // {{{ isError()
-
     /**
      * Tell whether a value is a PEAR error.
      *
@@ -278,9 +262,6 @@ class PEAR
         return $data->getCode() == $code;
     }
 
-    // }}}
-    // {{{ setErrorHandling()
-
     /**
      * Sets how errors generated by this object should be handled.
      * Can be invoked both in objects and statically.  If called
@@ -319,7 +300,6 @@ class PEAR
      *
      * @since PHP 4.0.5
      */
-
     function setErrorHandling($mode = null, $options = null)
     {
         if (isset($this) && is_a($this, 'PEAR')) {
@@ -357,9 +337,6 @@ class PEAR
         }
     }
 
-    // }}}
-    // {{{ expectError()
-
     /**
      * This method is used to tell which errors you expect to get.
      * Expected errors are always returned with error mode
@@ -382,12 +359,9 @@ class PEAR
         } else {
             array_push($this->_expected_errors, array($code));
         }
-        return sizeof($this->_expected_errors);
+        return count($this->_expected_errors);
     }
 
-    // }}}
-    // {{{ popExpect()
-
     /**
      * This method pops one element off the expected error codes
      * stack.
@@ -399,9 +373,6 @@ class PEAR
         return array_pop($this->_expected_errors);
     }
 
-    // }}}
-    // {{{ _checkDelExpect()
-
     /**
      * This method checks unsets an error code if available
      *
@@ -413,8 +384,7 @@ class PEAR
     function _checkDelExpect($error_code)
     {
         $deleted = false;
-
-        foreach ($this->_expected_errors AS $key => $error_array) {
+        foreach ($this->_expected_errors as $key => $error_array) {
             if (in_array($error_code, $error_array)) {
                 unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
                 $deleted = true;
@@ -425,12 +395,10 @@ class PEAR
                 unset($this->_expected_errors[$key]);
             }
         }
+
         return $deleted;
     }
 
-    // }}}
-    // {{{ delExpect()
-
     /**
      * This method deletes all occurences of the specified element from
      * the expected error codes stack.
@@ -444,33 +412,26 @@ class PEAR
     {
         $deleted = false;
         if ((is_array($error_code) && (0 != count($error_code)))) {
-            // $error_code is a non-empty array here;
-            // we walk through it trying to unset all
-            // values
-            foreach($error_code as $key => $error) {
-                if ($this->_checkDelExpect($error)) {
-                    $deleted =  true;
-                } else {
-                    $deleted = false;
-                }
+            // $error_code is a non-empty array here; we walk through it trying
+            // to unset all values
+            foreach ($error_code as $key => $error) {
+                $deleted =  $this->_checkDelExpect($error) ? true : false;
             }
+
             return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
         } elseif (!empty($error_code)) {
             // $error_code comes alone, trying to unset it
             if ($this->_checkDelExpect($error_code)) {
                 return true;
-            } else {
-                return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
             }
+
+            return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
         }
 
         // $error_code is empty
         return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
     }
 
-    // }}}
-    // {{{ raiseError()
-
     /**
      * This method is a wrapper that returns an instance of the
      * configured error class with this object's default error
@@ -525,10 +486,16 @@ class PEAR
             $message     = $message->getMessage();
         }
 
-        if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) {
+        if (
+            isset($this) &&
+            isset($this->_expected_errors) &&
+            count($this->_expected_errors) > 0 &&
+            count($exp = end($this->_expected_errors))
+        ) {
             if ($exp[0] == "*" ||
                 (is_int(reset($exp)) && in_array($code, $exp)) ||
-                (is_string(reset($exp)) && in_array($message, $exp))) {
+                (is_string(reset($exp)) && in_array($message, $exp))
+            ) {
                 $mode = PEAR_ERROR_RETURN;
             }
         }
@@ -569,19 +536,23 @@ class PEAR
         return $a;
     }
 
-    // }}}
-    // {{{ throwError()
-
     /**
      * Simpler form of raiseError with fewer options.  In most cases
      * message, code and userinfo are enough.
      *
-     * @param string $message
+     * @param mixed $message a text error message or a PEAR error object
      *
+     * @param int $code      a numeric error code (it is up to your class
+     *                  to define these if you want to use codes)
+     *
+     * @param string $userinfo If you need to pass along for example debug
+     *                  information, this parameter is meant for that.
+     *
+     * @access public
+     * @return object   a PEAR error object
+     * @see PEAR::raiseError
      */
-    function &throwError($message = null,
-                         $code = null,
-                         $userinfo = null)
+    function &throwError($message = null, $code = null, $userinfo = null)
     {
         if (isset($this) && is_a($this, 'PEAR')) {
             $a = &$this->raiseError($message, $code, null, null, $userinfo);
@@ -592,10 +563,9 @@ class PEAR
         return $a;
     }
 
-    // }}}
     function staticPushErrorHandling($mode, $options = null)
     {
-        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
+        $stack       = &$GLOBALS['_PEAR_error_handler_stack'];
         $def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
         $def_options = &$GLOBALS['_PEAR_default_error_options'];
         $stack[] = array($def_mode, $def_options);
@@ -664,8 +634,6 @@ class PEAR
         return true;
     }
 
-    // {{{ pushErrorHandling()
-
     /**
      * Push a new error handler on top of the error handler options stack. With this
      * you can easily override the actual error handler for some code and restore
@@ -699,9 +667,6 @@ class PEAR
         return true;
     }
 
-    // }}}
-    // {{{ popErrorHandling()
-
     /**
     * Pop the last error handler used
     *
@@ -723,9 +688,6 @@ class PEAR
         return true;
     }
 
-    // }}}
-    // {{{ loadExtension()
-
     /**
     * OS independant PHP extension load. Remember to take care
     * on the correct extension name for case sensitive OSes.
@@ -735,39 +697,39 @@ class PEAR
     */
     function loadExtension($ext)
     {
-        if (!extension_loaded($ext)) {
-            // if either returns true dl() will produce a FATAL error, stop that
-            if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
-                return false;
-            }
+        if (extension_loaded($ext)) {
+            return true;
+        }
 
-            if (OS_WINDOWS) {
-                $suffix = '.dll';
-            } elseif (PHP_OS == 'HP-UX') {
-                $suffix = '.sl';
-            } elseif (PHP_OS == 'AIX') {
-                $suffix = '.a';
-            } elseif (PHP_OS == 'OSX') {
-                $suffix = '.bundle';
-            } else {
-                $suffix = '.so';
-            }
+        // if either returns true dl() will produce a FATAL error, stop that
+        if (
+            function_exists('dl') === false ||
+            ini_get('enable_dl') != 1 ||
+            ini_get('safe_mode') == 1
+        ) {
+            return false;
+        }
 
-            return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
+        if (OS_WINDOWS) {
+            $suffix = '.dll';
+        } elseif (PHP_OS == 'HP-UX') {
+            $suffix = '.sl';
+        } elseif (PHP_OS == 'AIX') {
+            $suffix = '.a';
+        } elseif (PHP_OS == 'OSX') {
+            $suffix = '.bundle';
+        } else {
+            $suffix = '.so';
         }
 
-        return true;
+        return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
     }
-
-    // }}}
 }
 
 if (PEAR_ZE2) {
     include_once 'PEAR5.php';
 }
 
-// {{{ _PEAR_call_destructors()
-
 function _PEAR_call_destructors()
 {
     global $_PEAR_destructor_object_list;
@@ -803,14 +765,17 @@ function _PEAR_call_destructors()
     }
 
     // Now call the shutdown functions
-    if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) {
+    if (
+        isset($GLOBALS['_PEAR_shutdown_funcs']) &&
+        is_array($GLOBALS['_PEAR_shutdown_funcs']) &&
+        !empty($GLOBALS['_PEAR_shutdown_funcs'])
+    ) {
         foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
             call_user_func_array($value[0], $value[1]);
         }
     }
 }
 
-// }}}
 /**
  * Standard PEAR error class for PHP 4
  *
@@ -823,15 +788,13 @@ function _PEAR_call_destructors()
  * @author     Gregory Beaver <cellog@php.net>
  * @copyright  1997-2006 The PHP Group
  * @license    http://opensource.org/licenses/bsd-license.php New BSD License
- * @version    Release: 1.8.1
+ * @version    Release: 1.9.4
  * @link       http://pear.php.net/manual/en/core.pear.pear-error.php
  * @see        PEAR::raiseError(), PEAR::throwError()
  * @since      Class available since PHP 4.0.2
  */
 class PEAR_Error
 {
-    // {{{ properties
-
     var $error_message_prefix = '';
     var $mode                 = PEAR_ERROR_RETURN;
     var $level                = E_USER_NOTICE;
@@ -840,9 +803,6 @@ class PEAR_Error
     var $userinfo             = '';
     var $backtrace            = null;
 
-    // }}}
-    // {{{ constructor
-
     /**
      * PEAR_Error constructor
      *
@@ -886,6 +846,7 @@ class PEAR_Error
                 unset($this->backtrace[0]['object']);
             }
         }
+
         if ($mode & PEAR_ERROR_CALLBACK) {
             $this->level = E_USER_NOTICE;
             $this->callback = $options;
@@ -893,20 +854,25 @@ class PEAR_Error
             if ($options === null) {
                 $options = E_USER_NOTICE;
             }
+
             $this->level = $options;
             $this->callback = null;
         }
+
         if ($this->mode & PEAR_ERROR_PRINT) {
             if (is_null($options) || is_int($options)) {
                 $format = "%s";
             } else {
                 $format = $options;
             }
+
             printf($format, $this->getMessage());
         }
+
         if ($this->mode & PEAR_ERROR_TRIGGER) {
             trigger_error($this->getMessage(), $this->level);
         }
+
         if ($this->mode & PEAR_ERROR_DIE) {
             $msg = $this->getMessage();
             if (is_null($options) || is_int($options)) {
@@ -919,47 +885,39 @@ class PEAR_Error
             }
             die(sprintf($format, $msg));
         }
-        if ($this->mode & PEAR_ERROR_CALLBACK) {
-            if (is_callable($this->callback)) {
-                call_user_func($this->callback, $this);
-            }
+
+        if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) {
+            call_user_func($this->callback, $this);
         }
+
         if ($this->mode & PEAR_ERROR_EXCEPTION) {
             trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
             eval('$e = new Exception($this->message, $this->code);throw($e);');
         }
     }
 
-    // }}}
-    // {{{ getMode()
-
     /**
      * Get the error mode from an error object.
      *
      * @return int error mode
      * @access public
      */
-    function getMode() {
+    function getMode()
+    {
         return $this->mode;
     }
 
-    // }}}
-    // {{{ getCallback()
-
     /**
      * Get the callback function/method from an error object.
      *
      * @return mixed callback function or object/method array
      * @access public
      */
-    function getCallback() {
+    function getCallback()
+    {
         return $this->callback;
     }
 
-    // }}}
-    // {{{ getMessage()
-
-
     /**
      * Get the error message from an error object.
      *
@@ -971,10 +929,6 @@ class PEAR_Error
         return ($this->error_message_prefix . $this->message);
     }
 
-
-    // }}}
-    // {{{ getCode()
-
     /**
      * Get error code from an error object
      *
@@ -986,9 +940,6 @@ class PEAR_Error
         return $this->code;
      }
 
-    // }}}
-    // {{{ getType()
-
     /**
      * Get the name of this error/exception.
      *
@@ -1000,9 +951,6 @@ class PEAR_Error
         return get_class($this);
     }
 
-    // }}}
-    // {{{ getUserInfo()
-
     /**
      * Get additional user-supplied information.
      *
@@ -1014,9 +962,6 @@ class PEAR_Error
         return $this->userinfo;
     }
 
-    // }}}
-    // {{{ getDebugInfo()
-
     /**
      * Get additional debug information supplied by the application.
      *
@@ -1028,9 +973,6 @@ class PEAR_Error
         return $this->getUserInfo();
     }
 
-    // }}}
-    // {{{ getBacktrace()
-
     /**
      * Get the call backtrace from where the error was generated.
      * Supported with PHP 4.3.0 or newer.
@@ -1050,9 +992,6 @@ class PEAR_Error
         return $this->backtrace[$frame];
     }
 
-    // }}}
-    // {{{ addUserInfo()
-
     function addUserInfo($info)
     {
         if (empty($this->userinfo)) {
@@ -1062,14 +1001,10 @@ class PEAR_Error
         }
     }
 
-    // }}}
-    // {{{ toString()
     function __toString()
     {
         return $this->getMessage();
     }
-    // }}}
-    // {{{ toString()
 
     /**
      * Make a string representation of this object.
@@ -1077,7 +1012,8 @@ class PEAR_Error
      * @return string a string with an object summary
      * @access public
      */
-    function toString() {
+    function toString()
+    {
         $modes = array();
         $levels = array(E_USER_NOTICE  => 'notice',
                         E_USER_WARNING => 'warning',
@@ -1116,8 +1052,6 @@ class PEAR_Error
                        $this->error_message_prefix,
                        $this->userinfo);
     }
-
-    // }}}
 }
 
 /*
diff --git a/include/pear/PEAR/FixPHP5PEARWarnings.php b/include/pear/PEAR/FixPHP5PEARWarnings.php
index da77106f8ecd3e245f8de483df9a45d7d4755abe..be5dc3ce707c3e06189b89395819ae49edbab19c 100644
--- a/include/pear/PEAR/FixPHP5PEARWarnings.php
+++ b/include/pear/PEAR/FixPHP5PEARWarnings.php
@@ -4,4 +4,4 @@ if ($skipmsg) {
 } else {
     $a = &new $ec($message, $code, $mode, $options, $userinfo);
 }
-?>
+?>
\ No newline at end of file
diff --git a/include/pear/PEAR5.php b/include/pear/PEAR5.php
index 5cee090351ff0aac31f0ac628aeec8f69cef01f4..428606780b7bf322bbf8bf2379da80d1340cb86b 100644
--- a/include/pear/PEAR5.php
+++ b/include/pear/PEAR5.php
@@ -30,4 +30,4 @@ class PEAR5
 
         return $properties[$class][$var];
     }
-}
+}
\ No newline at end of file