3 * This file contains the Net_Sieve class.
7 * +-----------------------------------------------------------------------+
8 * | All rights reserved. |
10 * | Redistribution and use in source and binary forms, with or without |
11 * | modification, are permitted provided that the following conditions |
14 * | o Redistributions of source code must retain the above copyright |
15 * | notice, this list of conditions and the following disclaimer. |
16 * | o Redistributions in binary form must reproduce the above copyright |
17 * | notice, this list of conditions and the following disclaimer in the |
18 * | documentation and/or other materials provided with the distribution.|
20 * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
21 * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
22 * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
23 * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
24 * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
25 * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
26 * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
27 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
28 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
29 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
30 * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
31 * +-----------------------------------------------------------------------+
33 * @category Networking
35 * @author Richard Heyes <richard@phpguru.org>
36 * @author Damian Fernandez Sosa <damlists@cnba.uba.ar>
37 * @author Anish Mistry <amistry@am-productions.biz>
38 * @author Jan Schneider <jan@horde.org>
39 * @copyright 2002-2003 Richard Heyes
40 * @copyright 2006-2008 Anish Mistry
41 * @license http://www.opensource.org/licenses/bsd-license.php BSD
42 * @version SVN: $Id: Sieve.php 300898 2010-07-01 09:49:02Z yunosh $
43 * @link http://pear.php.net/package/Net_Sieve
46 require_once 'PEAR.php';
47 require_once 'Net/Socket.php';
52 * o supportsAuthMech()
57 * @const NET_SIEVE_STATE_DISCONNECTED
59 define('NET_SIEVE_STATE_DISCONNECTED', 1, true);
63 * @const NET_SIEVE_STATE_AUTHORISATION
65 define('NET_SIEVE_STATE_AUTHORISATION', 2, true);
69 * @const NET_SIEVE_STATE_TRANSACTION
71 define('NET_SIEVE_STATE_TRANSACTION', 3, true);
75 * A class for talking to the timsieved server which comes with Cyrus IMAP.
77 * @category Networking
79 * @author Richard Heyes <richard@phpguru.org>
80 * @author Damian Fernandez Sosa <damlists@cnba.uba.ar>
81 * @author Anish Mistry <amistry@am-productions.biz>
82 * @author Jan Schneider <jan@horde.org>
83 * @copyright 2002-2003 Richard Heyes
84 * @copyright 2006-2008 Anish Mistry
85 * @license http://www.opensource.org/licenses/bsd-license.php BSD
86 * @version Release: 1.3.0
87 * @link http://pear.php.net/package/Net_Sieve
88 * @link http://www.ietf.org/rfc/rfc3028.txt RFC 3028 (Sieve: A Mail
90 * @link http://tools.ietf.org/html/draft-ietf-sieve-managesieve A
91 * Protocol for Remotely Managing Sieve Scripts
96 * The authentication methods this class supports.
98 * Can be overwritten if having problems with certain methods.
102 var $supportedAuthMethods = array('DIGEST-MD5', 'CRAM-MD5', 'EXTERNAL',
106 * SASL authentication methods that require Auth_SASL.
110 var $supportedSASLAuthMethods = array('DIGEST-MD5', 'CRAM-MD5');
120 * Parameters and connection information.
127 * Current state of the connection.
129 * One of the NET_SIEVE_STATE_* constants.
143 * Whether to enable debugging.
150 * Debug output handler.
152 * This has to be a valid callback.
156 var $_debug_handler = null;
159 * Whether to pick up an already established connection.
163 var $_bypassAuth = false;
166 * Whether to use TLS if available.
173 * Additional options for stream_context_create().
177 var $_options = null;
180 * Maximum number of referral loops
184 var $_maxReferralCount = 15;
189 * Sets up the object, connects to the server and logs in. Stores any
190 * generated error in $this->_error, which can be retrieved using the
193 * @param string $user Login username.
194 * @param string $pass Login password.
195 * @param string $host Hostname of server.
196 * @param string $port Port of server.
197 * @param string $logintype Type of login to perform (see
198 * $supportedAuthMethods).
199 * @param string $euser Effective user. If authenticating as an
200 * administrator, login as this user.
201 * @param boolean $debug Whether to enable debugging (@see setDebug()).
202 * @param string $bypassAuth Skip the authentication phase. Useful if the
203 * socket is already open.
204 * @param boolean $useTLS Use TLS if available.
205 * @param array $options Additional options for
206 * stream_context_create().
207 * @param mixed $handler A callback handler for the debug output.
209 function Net_Sieve($user = null, $pass = null, $host = 'localhost',
210 $port = 2000, $logintype = '', $euser = '',
211 $debug = false, $bypassAuth = false, $useTLS = true,
212 $options = null, $handler = null)
214 $this->_state = NET_SIEVE_STATE_DISCONNECTED;
215 $this->_data['user'] = $user;
216 $this->_data['pass'] = $pass;
217 $this->_data['host'] = $host;
218 $this->_data['port'] = $port;
219 $this->_data['logintype'] = $logintype;
220 $this->_data['euser'] = $euser;
221 $this->_sock = new Net_Socket();
222 $this->_bypassAuth = $bypassAuth;
223 $this->_useTLS = $useTLS;
224 $this->_options = $options;
225 $this->setDebug($debug, $handler);
227 /* Try to include the Auth_SASL package. If the package is not
228 * available, we disable the authentication methods that depend upon
230 if ((@include_once 'Auth/SASL.php') === false) {
231 $this->_debug('Auth_SASL not present');
232 foreach ($this->supportedSASLAuthMethods as $SASLMethod) {
233 $pos = array_search($SASLMethod, $this->supportedAuthMethods);
234 $this->_debug('Disabling method ' . $SASLMethod);
235 unset($this->supportedAuthMethods[$pos]);
239 if (strlen($user) && strlen($pass)) {
240 $this->_error = $this->_handleConnectAndLogin();
245 * Returns any error that may have been generated in the constructor.
247 * @return boolean|PEAR_Error False if no error, PEAR_Error otherwise.
251 return PEAR::isError($this->_error) ? $this->_error : false;
255 * Sets the debug state and handler function.
257 * @param boolean $debug Whether to enable debugging.
258 * @param string $handler A custom debug handler. Must be a valid callback.
262 function setDebug($debug = true, $handler = null)
264 $this->_debug = $debug;
265 $this->_debug_handler = $handler;
269 * Connects to the server and logs in.
271 * @return boolean True on success, PEAR_Error on failure.
273 function _handleConnectAndLogin()
275 if (PEAR::isError($res = $this->connect($this->_data['host'], $this->_data['port'], $this->_options, $this->_useTLS))) {
278 if ($this->_bypassAuth === false) {
279 if (PEAR::isError($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'], $this->_data['euser'], $this->_bypassAuth))) {
287 * Handles connecting to the server and checks the response validity.
289 * @param string $host Hostname of server.
290 * @param string $port Port of server.
291 * @param array $options List of options to pass to
292 * stream_context_create().
293 * @param boolean $useTLS Use TLS if available.
295 * @return boolean True on success, PEAR_Error otherwise.
297 function connect($host, $port, $options = null, $useTLS = true)
299 if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
300 return PEAR::raiseError('Not currently in DISCONNECTED state', 1);
303 if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
307 if ($this->_bypassAuth) {
308 $this->_state = NET_SIEVE_STATE_TRANSACTION;
310 $this->_state = NET_SIEVE_STATE_AUTHORISATION;
311 if (PEAR::isError($res = $this->_doCmd())) {
316 // Explicitly ask for the capabilities in case the connection is
317 // picked up from an existing connection.
318 if (PEAR::isError($res = $this->_cmdCapability())) {
319 return PEAR::raiseError(
320 'Failed to connect, server said: ' . $res->getMessage(), 2
324 // Check if we can enable TLS via STARTTLS.
325 if ($useTLS && !empty($this->_capability['starttls'])
326 && function_exists('stream_socket_enable_crypto')
328 if (PEAR::isError($res = $this->_startTLS())) {
337 * Disconnect from the Sieve server.
339 * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
342 * @return boolean True on success, PEAR_Error otherwise.
344 function disconnect($sendLogoutCMD = true)
346 return $this->_cmdLogout($sendLogoutCMD);
352 * @param string $user Login username.
353 * @param string $pass Login password.
354 * @param string $logintype Type of login method to use.
355 * @param string $euser Effective UID (perform on behalf of $euser).
356 * @param boolean $bypassAuth Do not perform authentication.
358 * @return boolean True on success, PEAR_Error otherwise.
360 function login($user, $pass, $logintype = null, $euser = '', $bypassAuth = false)
362 if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
363 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
367 if (PEAR::isError($res = $this->_cmdAuthenticate($user, $pass, $logintype, $euser))) {
371 $this->_state = NET_SIEVE_STATE_TRANSACTION;
377 * Returns an indexed array of scripts currently on the server.
379 * @return array Indexed array of scriptnames.
381 function listScripts()
383 if (is_array($scripts = $this->_cmdListScripts())) {
384 $this->_active = $scripts[1];
392 * Returns the active script.
394 * @return string The active scriptname.
398 if (!empty($this->_active)) {
399 return $this->_active;
401 if (is_array($scripts = $this->_cmdListScripts())) {
402 $this->_active = $scripts[1];
408 * Sets the active script.
410 * @param string $scriptname The name of the script to be set as active.
412 * @return boolean True on success, PEAR_Error on failure.
414 function setActive($scriptname)
416 return $this->_cmdSetActive($scriptname);
420 * Retrieves a script.
422 * @param string $scriptname The name of the script to be retrieved.
424 * @return string The script on success, PEAR_Error on failure.
426 function getScript($scriptname)
428 return $this->_cmdGetScript($scriptname);
432 * Adds a script to the server.
434 * @param string $scriptname Name of the script.
435 * @param string $script The script content.
436 * @param boolean $makeactive Whether to make this the active script.
438 * @return boolean True on success, PEAR_Error on failure.
440 function installScript($scriptname, $script, $makeactive = false)
442 if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
446 return $this->_cmdSetActive($scriptname);
452 * Removes a script from the server.
454 * @param string $scriptname Name of the script.
456 * @return boolean True on success, PEAR_Error on failure.
458 function removeScript($scriptname)
460 return $this->_cmdDeleteScript($scriptname);
464 * Checks if the server has space to store the script by the server.
466 * @param string $scriptname The name of the script to mark as active.
467 * @param integer $size The size of the script.
469 * @return boolean|PEAR_Error True if there is space, PEAR_Error otherwise.
471 * @todo Rename to hasSpace()
473 function haveSpace($scriptname, $size)
475 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
476 return PEAR::raiseError('Not currently in TRANSACTION state', 1);
478 if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %d', $scriptname, $size)))) {
485 * Returns the list of extensions the server supports.
487 * @return array List of extensions or PEAR_Error on failure.
489 function getExtensions()
491 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
492 return PEAR::raiseError('Not currently connected', 7);
494 return $this->_capability['extensions'];
498 * Returns whether the server supports an extension.
500 * @param string $extension The extension to check.
502 * @return boolean Whether the extension is supported or PEAR_Error on
505 function hasExtension($extension)
507 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
508 return PEAR::raiseError('Not currently connected', 7);
511 $extension = trim($this->_toUpper($extension));
512 if (is_array($this->_capability['extensions'])) {
513 foreach ($this->_capability['extensions'] as $ext) {
514 if ($ext == $extension) {
524 * Returns the list of authentication methods the server supports.
526 * @return array List of authentication methods or PEAR_Error on failure.
528 function getAuthMechs()
530 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
531 return PEAR::raiseError('Not currently connected', 7);
533 return $this->_capability['sasl'];
537 * Returns whether the server supports an authentication method.
539 * @param string $method The method to check.
541 * @return boolean Whether the method is supported or PEAR_Error on
544 function hasAuthMech($method)
546 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
547 return PEAR::raiseError('Not currently connected', 7);
550 $method = trim($this->_toUpper($method));
551 if (is_array($this->_capability['sasl'])) {
552 foreach ($this->_capability['sasl'] as $sasl) {
553 if ($sasl == $method) {
563 * Handles the authentication using any known method.
565 * @param string $uid The userid to authenticate as.
566 * @param string $pwd The password to authenticate with.
567 * @param string $userMethod The method to use. If empty, the class chooses
568 * the best (strongest) available method.
569 * @param string $euser The effective uid to authenticate as.
573 function _cmdAuthenticate($uid, $pwd, $userMethod = null, $euser = '')
575 if (PEAR::isError($method = $this->_getBestAuthMethod($userMethod))) {
580 return $this->_authDigestMD5($uid, $pwd, $euser);
582 $result = $this->_authCRAMMD5($uid, $pwd, $euser);
585 $result = $this->_authLOGIN($uid, $pwd, $euser);
588 $result = $this->_authPLAIN($uid, $pwd, $euser);
591 $result = $this->_authEXTERNAL($uid, $pwd, $euser);
594 $result = PEAR::raiseError(
595 $method . ' is not a supported authentication method'
600 if (PEAR::isError($res = $this->_doCmd())) {
608 * Authenticates the user using the PLAIN method.
610 * @param string $user The userid to authenticate as.
611 * @param string $pass The password to authenticate with.
612 * @param string $euser The effective uid to authenticate as.
616 function _authPLAIN($user, $pass, $euser)
618 return $this->_sendCmd(
620 'AUTHENTICATE "PLAIN" "%s"',
621 base64_encode($euser . chr(0) . $user . chr(0) . $pass)
627 * Authenticates the user using the LOGIN method.
629 * @param string $user The userid to authenticate as.
630 * @param string $pass The password to authenticate with.
631 * @param string $euser The effective uid to authenticate as.
635 function _authLOGIN($user, $pass, $euser)
637 if (PEAR::isError($result = $this->_sendCmd('AUTHENTICATE "LOGIN"'))) {
640 if (PEAR::isError($result = $this->_doCmd('"' . base64_encode($user) . '"', true))) {
643 return $this->_doCmd('"' . base64_encode($pass) . '"', true);
647 * Authenticates the user using the CRAM-MD5 method.
649 * @param string $user The userid to authenticate as.
650 * @param string $pass The password to authenticate with.
651 * @param string $euser The effective uid to authenticate as.
655 function _authCRAMMD5($user, $pass, $euser)
657 if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "CRAM-MD5"', true))) {
661 $challenge = base64_decode(trim($challenge));
662 $cram = Auth_SASL::factory('crammd5');
663 if (PEAR::isError($response = $cram->getResponse($user, $pass, $challenge))) {
667 return $this->_sendStringResponse(base64_encode($response));
671 * Authenticates the user using the DIGEST-MD5 method.
673 * @param string $user The userid to authenticate as.
674 * @param string $pass The password to authenticate with.
675 * @param string $euser The effective uid to authenticate as.
679 function _authDigestMD5($user, $pass, $euser)
681 if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"', true))) {
685 $challenge = base64_decode(trim($challenge));
686 $digest = Auth_SASL::factory('digestmd5');
687 // @todo Really 'localhost'?
688 if (PEAR::isError($response = $digest->getResponse($user, $pass, $challenge, 'localhost', 'sieve', $euser))) {
692 if (PEAR::isError($result = $this->_sendStringResponse(base64_encode($response)))) {
695 if (PEAR::isError($result = $this->_doCmd('', true))) {
698 if ($this->_toUpper(substr($result, 0, 2)) == 'OK') {
702 /* We don't use the protocol's third step because SIEVE doesn't allow
703 * subsequent authentication, so we just silently ignore it. */
704 if (PEAR::isError($result = $this->_sendStringResponse(''))) {
708 return $this->_doCmd();
712 * Authenticates the user using the EXTERNAL method.
714 * @param string $user The userid to authenticate as.
715 * @param string $pass The password to authenticate with.
716 * @param string $euser The effective uid to authenticate as.
722 function _authEXTERNAL($user, $pass, $euser)
725 'AUTHENTICATE "EXTERNAL" "%s"',
726 base64_encode(strlen($euser) ? $euser : $user)
728 return $this->_sendCmd($cmd);
732 * Removes a script from the server.
734 * @param string $scriptname Name of the script to delete.
736 * @return boolean True on success, PEAR_Error otherwise.
738 function _cmdDeleteScript($scriptname)
740 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
741 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
743 if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname)))) {
750 * Retrieves the contents of the named script.
752 * @param string $scriptname Name of the script to retrieve.
754 * @return string The script if successful, PEAR_Error otherwise.
756 function _cmdGetScript($scriptname)
758 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
759 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
762 if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname)))) {
766 return preg_replace('/{[0-9]+}\r\n/', '', $res);
770 * Sets the active script, i.e. the one that gets run on new mail by the
773 * @param string $scriptname The name of the script to mark as active.
775 * @return boolean True on success, PEAR_Error otherwise.
777 function _cmdSetActive($scriptname)
779 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
780 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
782 if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname)))) {
785 $this->_activeScript = $scriptname;
790 * Returns the list of scripts on the server.
792 * @return array An array with the list of scripts in the first element
793 * and the active script in the second element on success,
794 * PEAR_Error otherwise.
796 function _cmdListScripts()
798 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
799 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
802 if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
807 $activescript = null;
808 $res = explode("\r\n", $res);
809 foreach ($res as $value) {
810 if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
811 $scripts[] = $matches[1];
812 if (!empty($matches[2])) {
813 $activescript = $matches[1];
818 return array($scripts, $activescript);
822 * Adds a script to the server.
824 * @param string $scriptname Name of the new script.
825 * @param string $scriptdata The new script.
827 * @return boolean True on success, PEAR_Error otherwise.
829 function _cmdPutScript($scriptname, $scriptdata)
831 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
832 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
835 $stringLength = $this->_getLineLength($scriptdata);
837 if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata)))) {
845 * Logs out of the server and terminates the connection.
847 * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
850 * @return boolean True on success, PEAR_Error otherwise.
852 function _cmdLogout($sendLogoutCMD = true)
854 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
855 return PEAR::raiseError('Not currently connected', 1);
858 if ($sendLogoutCMD) {
859 if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
864 $this->_sock->disconnect();
865 $this->_state = NET_SIEVE_STATE_DISCONNECTED;
871 * Sends the CAPABILITY command
873 * @return boolean True on success, PEAR_Error otherwise.
875 function _cmdCapability()
877 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
878 return PEAR::raiseError('Not currently connected', 1);
880 if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
883 $this->_parseCapability($res);
888 * Parses the response from the CAPABILITY command and stores the result
891 * @param string $data The response from the capability command.
895 function _parseCapability($data)
897 // Clear the cached capabilities.
898 $this->_capability = array('sasl' => array(),
899 'extensions' => array());
901 $data = preg_split('/\r?\n/', $this->_toUpper($data), -1, PREG_SPLIT_NO_EMPTY);
903 for ($i = 0; $i < count($data); $i++) {
904 if (!preg_match('/^"([A-Z]+)"( "(.*)")?$/', $data[$i], $matches)) {
907 switch ($matches[1]) {
908 case 'IMPLEMENTATION':
909 $this->_capability['implementation'] = $matches[3];
913 $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
917 $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
921 $this->_capability['starttls'] = true;
928 * Sends a command to the server
930 * @param string $cmd The command to send.
934 function _sendCmd($cmd)
936 $status = $this->_sock->getStatus();
937 if (PEAR::isError($status) || $status['eof']) {
938 return PEAR::raiseError('Failed to write to socket: connection lost');
940 if (PEAR::isError($error = $this->_sock->write($cmd . "\r\n"))) {
941 return PEAR::raiseError(
942 'Failed to write to socket: ' . $error->getMessage()
945 $this->_debug("C: $cmd");
949 * Sends a string response to the server.
951 * @param string $str The string to send.
955 function _sendStringResponse($str)
957 return $this->_sendCmd('{' . $this->_getLineLength($str) . "+}\r\n" . $str);
961 * Receives a single line from the server.
963 * @return string The server response line.
967 if (PEAR::isError($lastline = $this->_sock->gets(8192))) {
968 return PEAR::raiseError(
969 'Failed to read from socket: ' . $lastline->getMessage()
973 $lastline = rtrim($lastline);
974 $this->_debug("S: $lastline");
976 if ($lastline === '') {
977 return PEAR::raiseError('Failed to read from socket');
984 * Send a command and retrieves a response from the server.
986 * @param string $cmd The command to send.
987 * @param boolean $auth Whether this is an authentication command.
989 * @return string|PEAR_Error Reponse string if an OK response, PEAR_Error
992 function _doCmd($cmd = '', $auth = false)
995 while ($referralCount < $this->_maxReferralCount) {
997 if (PEAR::isError($error = $this->_sendCmd($cmd))) {
1004 if (PEAR::isError($line = $this->_recvLn())) {
1007 $uc_line = $this->_toUpper($line);
1009 if ('OK' == substr($uc_line, 0, 2)) {
1011 return rtrim($response);
1014 if ('NO' == substr($uc_line, 0, 2)) {
1015 // Check for string literal error message.
1016 if (preg_match('/^no {([0-9]+)\+?}/i', $line, $matches)) {
1017 $line .= str_replace(
1018 "\r\n", ' ', $this->_sock->read($matches[1] + 2)
1020 $this->_debug("S: $line");
1022 return PEAR::raiseError(trim($response . substr($line, 2)), 3);
1025 if ('BYE' == substr($uc_line, 0, 3)) {
1026 if (PEAR::isError($error = $this->disconnect(false))) {
1027 return PEAR::raiseError(
1028 'Cannot handle BYE, the error was: '
1029 . $error->getMessage(),
1033 // Check for referral, then follow it. Otherwise, carp an
1035 if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
1036 // Replace the old host with the referral host
1037 // preserving any protocol prefix.
1038 $this->_data['host'] = preg_replace(
1039 '/\w+(?!(\w|\:\/\/)).*/', $matches[2],
1040 $this->_data['host']
1042 if (PEAR::isError($error = $this->_handleConnectAndLogin())) {
1043 return PEAR::raiseError(
1044 'Cannot follow referral to '
1045 . $this->_data['host'] . ', the error was: '
1046 . $error->getMessage(),
1052 return PEAR::raiseError(trim($response . $line), 6);
1055 if (preg_match('/^{([0-9]+)\+?}/i', $line, $matches)) {
1056 // Matches String Responses.
1057 $str_size = $matches[1] + 2;
1060 while ($line_length < $str_size) {
1061 $line .= $this->_sock->read($str_size - $line_length);
1062 $line_length = $this->_getLineLength($line);
1064 $this->_debug("S: $line");
1067 // Receive the pending OK only if we aren't
1068 // authenticating since string responses during
1069 // authentication don't need an OK.
1076 // String responses during authentication don't need an
1079 return rtrim($response);
1082 $response .= $line . "\r\n";
1087 return PEAR::raiseError('Max referral count (' . $referralCount . ') reached. Cyrus murder loop error?', 7);
1091 * Returns the name of the best authentication method that the server
1094 * @param string $userMethod Only consider this method as available.
1096 * @return string The name of the best supported authentication method or
1097 * a PEAR_Error object on failure.
1099 function _getBestAuthMethod($userMethod = null)
1101 if (!isset($this->_capability['sasl'])) {
1102 return PEAR::raiseError('This server doesn\'t support any authentication methods. SASL problem?');
1104 if (!$this->_capability['sasl']) {
1105 return PEAR::raiseError('This server doesn\'t support any authentication methods.');
1109 if (in_array($userMethod, $this->_capability['sasl'])) {
1112 return PEAR::raiseError(
1113 sprintf('No supported authentication method found. The server supports these methods: %s, but we want to use: %s',
1114 implode(', ', $this->_capability['sasl']),
1118 foreach ($this->supportedAuthMethods as $method) {
1119 if (in_array($method, $this->_capability['sasl'])) {
1124 return PEAR::raiseError(
1125 sprintf('No supported authentication method found. The server supports these methods: %s, but we only support: %s',
1126 implode(', ', $this->_capability['sasl']),
1127 implode(', ', $this->supportedAuthMethods)));
1131 * Starts a TLS connection.
1133 * @return boolean True on success, PEAR_Error on failure.
1135 function _startTLS()
1137 if (PEAR::isError($res = $this->_doCmd('STARTTLS'))) {
1141 if (!stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
1142 return PEAR::raiseError('Failed to establish TLS connection', 2);
1145 $this->_debug('STARTTLS negotiation successful');
1147 // The server should be sending a CAPABILITY response after
1148 // negotiating TLS. Read it, and ignore if it doesn't.
1151 // RFC says we need to query the server capabilities again now that we
1152 // are under encryption.
1153 if (PEAR::isError($res = $this->_cmdCapability())) {
1154 return PEAR::raiseError(
1155 'Failed to connect, server said: ' . $res->getMessage(), 2
1163 * Returns the length of a string.
1165 * @param string $string A string.
1167 * @return integer The length of the string.
1169 function _getLineLength($string)
1171 if (extension_loaded('mbstring')) {
1172 return mb_strlen($string, 'latin1');
1174 return strlen($string);
1179 * Locale independant strtoupper() implementation.
1181 * @param string $string The string to convert to lowercase.
1183 * @return string The lowercased string, based on ASCII encoding.
1185 function _toUpper($string)
1187 $language = setlocale(LC_CTYPE, 0);
1188 setlocale(LC_CTYPE, 'C');
1189 $string = strtoupper($string);
1190 setlocale(LC_CTYPE, $language);
1195 * Write debug text to the current debug output handler.
1197 * @param string $message Debug message text.
1201 function _debug($message)
1203 if ($this->_debug) {
1204 if ($this->_debug_handler) {
1205 call_user_func_array($this->_debug_handler, array(&$this, $message));