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);
479 $command = sprintf('HAVESPACE %s %d', $this->_escape($scriptname), $size);
480 if (PEAR::isError($res = $this->_doCmd($command))) {
487 * Returns the list of extensions the server supports.
489 * @return array List of extensions or PEAR_Error on failure.
491 function getExtensions()
493 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
494 return PEAR::raiseError('Not currently connected', 7);
496 return $this->_capability['extensions'];
500 * Returns whether the server supports an extension.
502 * @param string $extension The extension to check.
504 * @return boolean Whether the extension is supported or PEAR_Error on
507 function hasExtension($extension)
509 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
510 return PEAR::raiseError('Not currently connected', 7);
513 $extension = trim($this->_toUpper($extension));
514 if (is_array($this->_capability['extensions'])) {
515 foreach ($this->_capability['extensions'] as $ext) {
516 if ($ext == $extension) {
526 * Returns the list of authentication methods the server supports.
528 * @return array List of authentication methods or PEAR_Error on failure.
530 function getAuthMechs()
532 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
533 return PEAR::raiseError('Not currently connected', 7);
535 return $this->_capability['sasl'];
539 * Returns whether the server supports an authentication method.
541 * @param string $method The method to check.
543 * @return boolean Whether the method is supported or PEAR_Error on
546 function hasAuthMech($method)
548 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
549 return PEAR::raiseError('Not currently connected', 7);
552 $method = trim($this->_toUpper($method));
553 if (is_array($this->_capability['sasl'])) {
554 foreach ($this->_capability['sasl'] as $sasl) {
555 if ($sasl == $method) {
565 * Handles the authentication using any known method.
567 * @param string $uid The userid to authenticate as.
568 * @param string $pwd The password to authenticate with.
569 * @param string $userMethod The method to use. If empty, the class chooses
570 * the best (strongest) available method.
571 * @param string $euser The effective uid to authenticate as.
575 function _cmdAuthenticate($uid, $pwd, $userMethod = null, $euser = '')
577 if (PEAR::isError($method = $this->_getBestAuthMethod($userMethod))) {
582 return $this->_authDigestMD5($uid, $pwd, $euser);
584 $result = $this->_authCRAMMD5($uid, $pwd, $euser);
587 $result = $this->_authLOGIN($uid, $pwd, $euser);
590 $result = $this->_authPLAIN($uid, $pwd, $euser);
593 $result = $this->_authEXTERNAL($uid, $pwd, $euser);
596 $result = PEAR::raiseError(
597 $method . ' is not a supported authentication method'
602 if (PEAR::isError($res = $this->_doCmd())) {
610 * Authenticates the user using the PLAIN method.
612 * @param string $user The userid to authenticate as.
613 * @param string $pass The password to authenticate with.
614 * @param string $euser The effective uid to authenticate as.
618 function _authPLAIN($user, $pass, $euser)
620 return $this->_sendCmd(
622 'AUTHENTICATE "PLAIN" "%s"',
623 base64_encode($euser . chr(0) . $user . chr(0) . $pass)
629 * Authenticates the user using the LOGIN method.
631 * @param string $user The userid to authenticate as.
632 * @param string $pass The password to authenticate with.
633 * @param string $euser The effective uid to authenticate as.
637 function _authLOGIN($user, $pass, $euser)
639 if (PEAR::isError($result = $this->_sendCmd('AUTHENTICATE "LOGIN"'))) {
642 if (PEAR::isError($result = $this->_doCmd('"' . base64_encode($user) . '"', true))) {
645 return $this->_doCmd('"' . base64_encode($pass) . '"', true);
649 * Authenticates the user using the CRAM-MD5 method.
651 * @param string $user The userid to authenticate as.
652 * @param string $pass The password to authenticate with.
653 * @param string $euser The effective uid to authenticate as.
657 function _authCRAMMD5($user, $pass, $euser)
659 if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "CRAM-MD5"', true))) {
663 $challenge = base64_decode(trim($challenge));
664 $cram = Auth_SASL::factory('crammd5');
665 if (PEAR::isError($response = $cram->getResponse($user, $pass, $challenge))) {
669 return $this->_sendStringResponse(base64_encode($response));
673 * Authenticates the user using the DIGEST-MD5 method.
675 * @param string $user The userid to authenticate as.
676 * @param string $pass The password to authenticate with.
677 * @param string $euser The effective uid to authenticate as.
681 function _authDigestMD5($user, $pass, $euser)
683 if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"', true))) {
687 $challenge = base64_decode(trim($challenge));
688 $digest = Auth_SASL::factory('digestmd5');
689 // @todo Really 'localhost'?
690 if (PEAR::isError($response = $digest->getResponse($user, $pass, $challenge, 'localhost', 'sieve', $euser))) {
694 if (PEAR::isError($result = $this->_sendStringResponse(base64_encode($response)))) {
697 if (PEAR::isError($result = $this->_doCmd('', true))) {
700 if ($this->_toUpper(substr($result, 0, 2)) == 'OK') {
704 /* We don't use the protocol's third step because SIEVE doesn't allow
705 * subsequent authentication, so we just silently ignore it. */
706 if (PEAR::isError($result = $this->_sendStringResponse(''))) {
710 return $this->_doCmd();
714 * Authenticates the user using the EXTERNAL method.
716 * @param string $user The userid to authenticate as.
717 * @param string $pass The password to authenticate with.
718 * @param string $euser The effective uid to authenticate as.
724 function _authEXTERNAL($user, $pass, $euser)
727 'AUTHENTICATE "EXTERNAL" "%s"',
728 base64_encode(strlen($euser) ? $euser : $user)
730 return $this->_sendCmd($cmd);
734 * Removes a script from the server.
736 * @param string $scriptname Name of the script to delete.
738 * @return boolean True on success, PEAR_Error otherwise.
740 function _cmdDeleteScript($scriptname)
742 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
743 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
746 $command = sprintf('DELETESCRIPT %s', $this->_escape($scriptname));
747 if (PEAR::isError($res = $this->_doCmd($command))) {
754 * Retrieves the contents of the named script.
756 * @param string $scriptname Name of the script to retrieve.
758 * @return string The script if successful, PEAR_Error otherwise.
760 function _cmdGetScript($scriptname)
762 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
763 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
766 $command = sprintf('GETSCRIPT %s', $this->_escape($scriptname));
767 if (PEAR::isError($res = $this->_doCmd($command))) {
771 return preg_replace('/^{[0-9]+}\r\n/', '', $res);
775 * Sets the active script, i.e. the one that gets run on new mail by the
778 * @param string $scriptname The name of the script to mark as active.
780 * @return boolean True on success, PEAR_Error otherwise.
782 function _cmdSetActive($scriptname)
784 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
785 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
788 $command = sprintf('SETACTIVE %s', $this->_escape($scriptname));
789 if (PEAR::isError($res = $this->_doCmd($command))) {
793 $this->_activeScript = $scriptname;
798 * Returns the list of scripts on the server.
800 * @return array An array with the list of scripts in the first element
801 * and the active script in the second element on success,
802 * PEAR_Error otherwise.
804 function _cmdListScripts()
806 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
807 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
810 if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
815 $activescript = null;
816 $res = explode("\r\n", $res);
817 foreach ($res as $value) {
818 if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
819 $script_name = stripslashes($matches[1]);
820 $scripts[] = $script_name;
821 if (!empty($matches[2])) {
822 $activescript = $script_name;
827 return array($scripts, $activescript);
831 * Adds a script to the server.
833 * @param string $scriptname Name of the new script.
834 * @param string $scriptdata The new script.
836 * @return boolean True on success, PEAR_Error otherwise.
838 function _cmdPutScript($scriptname, $scriptdata)
840 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
841 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
844 $stringLength = $this->_getLineLength($scriptdata);
845 $command = sprintf("PUTSCRIPT %s {%d+}\r\n%s",
846 $this->_escape($scriptname), $stringLength, $scriptdata);
848 if (PEAR::isError($res = $this->_doCmd($command))) {
856 * Logs out of the server and terminates the connection.
858 * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
861 * @return boolean True on success, PEAR_Error otherwise.
863 function _cmdLogout($sendLogoutCMD = true)
865 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
866 return PEAR::raiseError('Not currently connected', 1);
869 if ($sendLogoutCMD) {
870 if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
875 $this->_sock->disconnect();
876 $this->_state = NET_SIEVE_STATE_DISCONNECTED;
882 * Sends the CAPABILITY command
884 * @return boolean True on success, PEAR_Error otherwise.
886 function _cmdCapability()
888 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
889 return PEAR::raiseError('Not currently connected', 1);
891 if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
894 $this->_parseCapability($res);
899 * Parses the response from the CAPABILITY command and stores the result
902 * @param string $data The response from the capability command.
906 function _parseCapability($data)
908 // Clear the cached capabilities.
909 $this->_capability = array('sasl' => array(),
910 'extensions' => array());
912 $data = preg_split('/\r?\n/', $this->_toUpper($data), -1, PREG_SPLIT_NO_EMPTY);
914 for ($i = 0; $i < count($data); $i++) {
915 if (!preg_match('/^"([A-Z]+)"( "(.*)")?$/', $data[$i], $matches)) {
918 switch ($matches[1]) {
919 case 'IMPLEMENTATION':
920 $this->_capability['implementation'] = $matches[3];
924 $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
928 $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
932 $this->_capability['starttls'] = true;
939 * Sends a command to the server
941 * @param string $cmd The command to send.
945 function _sendCmd($cmd)
947 $status = $this->_sock->getStatus();
948 if (PEAR::isError($status) || $status['eof']) {
949 return PEAR::raiseError('Failed to write to socket: connection lost');
951 if (PEAR::isError($error = $this->_sock->write($cmd . "\r\n"))) {
952 return PEAR::raiseError(
953 'Failed to write to socket: ' . $error->getMessage()
956 $this->_debug("C: $cmd");
960 * Sends a string response to the server.
962 * @param string $str The string to send.
966 function _sendStringResponse($str)
968 return $this->_sendCmd('{' . $this->_getLineLength($str) . "+}\r\n" . $str);
972 * Receives a single line from the server.
974 * @return string The server response line.
978 if (PEAR::isError($lastline = $this->_sock->gets(8192))) {
979 return PEAR::raiseError(
980 'Failed to read from socket: ' . $lastline->getMessage()
984 $lastline = rtrim($lastline);
985 $this->_debug("S: $lastline");
987 if ($lastline === '') {
988 return PEAR::raiseError('Failed to read from socket');
995 * Receives x bytes from the server.
997 * @param int $length Number of bytes to read
999 * @return string The server response.
1001 function _recvBytes($length)
1004 $response_length = 0;
1006 while ($response_length < $length) {
1007 $response .= $this->_sock->read($length - $response_length);
1008 $response_length = $this->_getLineLength($response);
1011 $this->_debug("S: " . rtrim($response));
1017 * Send a command and retrieves a response from the server.
1019 * @param string $cmd The command to send.
1020 * @param boolean $auth Whether this is an authentication command.
1022 * @return string|PEAR_Error Reponse string if an OK response, PEAR_Error
1025 function _doCmd($cmd = '', $auth = false)
1028 while ($referralCount < $this->_maxReferralCount) {
1030 if (PEAR::isError($error = $this->_sendCmd($cmd))) {
1037 if (PEAR::isError($line = $this->_recvLn())) {
1040 $uc_line = $this->_toUpper($line);
1042 if ('OK' == substr($uc_line, 0, 2)) {
1044 return rtrim($response);
1047 if ('NO' == substr($uc_line, 0, 2)) {
1048 // Check for string literal error message.
1049 if (preg_match('/{([0-9]+)}$/i', $line, $matches)) {
1050 $line = substr($line, 0, -(strlen($matches[1])+2))
1052 "\r\n", ' ', $this->_recvBytes($matches[1] + 2)
1055 return PEAR::raiseError(trim($response . substr($line, 2)), 3);
1058 if ('BYE' == substr($uc_line, 0, 3)) {
1059 if (PEAR::isError($error = $this->disconnect(false))) {
1060 return PEAR::raiseError(
1061 'Cannot handle BYE, the error was: '
1062 . $error->getMessage(),
1066 // Check for referral, then follow it. Otherwise, carp an
1068 if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
1069 // Replace the old host with the referral host
1070 // preserving any protocol prefix.
1071 $this->_data['host'] = preg_replace(
1072 '/\w+(?!(\w|\:\/\/)).*/', $matches[2],
1073 $this->_data['host']
1075 if (PEAR::isError($error = $this->_handleConnectAndLogin())) {
1076 return PEAR::raiseError(
1077 'Cannot follow referral to '
1078 . $this->_data['host'] . ', the error was: '
1079 . $error->getMessage(),
1085 return PEAR::raiseError(trim($response . $line), 6);
1088 if (preg_match('/^{([0-9]+)}/i', $line, $matches)) {
1089 // Matches literal string responses.
1090 $line = $this->_recvBytes($matches[1] + 2);
1093 // Receive the pending OK only if we aren't
1094 // authenticating since string responses during
1095 // authentication don't need an OK.
1102 // String responses during authentication don't need an
1105 return rtrim($response);
1108 $response .= $line . "\r\n";
1113 return PEAR::raiseError('Max referral count (' . $referralCount . ') reached. Cyrus murder loop error?', 7);
1117 * Returns the name of the best authentication method that the server
1120 * @param string $userMethod Only consider this method as available.
1122 * @return string The name of the best supported authentication method or
1123 * a PEAR_Error object on failure.
1125 function _getBestAuthMethod($userMethod = null)
1127 if (!isset($this->_capability['sasl'])) {
1128 return PEAR::raiseError('This server doesn\'t support any authentication methods. SASL problem?');
1130 if (!$this->_capability['sasl']) {
1131 return PEAR::raiseError('This server doesn\'t support any authentication methods.');
1135 if (in_array($userMethod, $this->_capability['sasl'])) {
1138 return PEAR::raiseError(
1139 sprintf('No supported authentication method found. The server supports these methods: %s, but we want to use: %s',
1140 implode(', ', $this->_capability['sasl']),
1144 foreach ($this->supportedAuthMethods as $method) {
1145 if (in_array($method, $this->_capability['sasl'])) {
1150 return PEAR::raiseError(
1151 sprintf('No supported authentication method found. The server supports these methods: %s, but we only support: %s',
1152 implode(', ', $this->_capability['sasl']),
1153 implode(', ', $this->supportedAuthMethods)));
1157 * Starts a TLS connection.
1159 * @return boolean True on success, PEAR_Error on failure.
1161 function _startTLS()
1163 if (PEAR::isError($res = $this->_doCmd('STARTTLS'))) {
1167 if (!stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
1168 return PEAR::raiseError('Failed to establish TLS connection', 2);
1171 $this->_debug('STARTTLS negotiation successful');
1173 // The server should be sending a CAPABILITY response after
1174 // negotiating TLS. Read it, and ignore if it doesn't.
1175 // Doesn't work with older timsieved versions
1176 $regexp = '/^CYRUS TIMSIEVED V([0-9.]+)/';
1177 if (!preg_match($regexp, $this->_capability['implementation'], $matches)
1178 || version_compare($matches[1], '2.3.10', '>=')
1183 // RFC says we need to query the server capabilities again now that we
1184 // are under encryption.
1185 if (PEAR::isError($res = $this->_cmdCapability())) {
1186 return PEAR::raiseError(
1187 'Failed to connect, server said: ' . $res->getMessage(), 2
1195 * Returns the length of a string.
1197 * @param string $string A string.
1199 * @return integer The length of the string.
1201 function _getLineLength($string)
1203 if (extension_loaded('mbstring')) {
1204 return mb_strlen($string, 'latin1');
1206 return strlen($string);
1211 * Locale independant strtoupper() implementation.
1213 * @param string $string The string to convert to lowercase.
1215 * @return string The lowercased string, based on ASCII encoding.
1217 function _toUpper($string)
1219 $language = setlocale(LC_CTYPE, 0);
1220 setlocale(LC_CTYPE, 'C');
1221 $string = strtoupper($string);
1222 setlocale(LC_CTYPE, $language);
1227 * Convert string into RFC's quoted-string or literal-c2s form
1229 * @param string $string The string to convert.
1231 * @return string Result string
1233 function _escape($string)
1235 // Some implementations doesn't allow UTF-8 characters in quoted-string
1236 // It's safe to use literal-c2s
1237 if (preg_match('/[^\x01-\x09\x0B-\x0C\x0E-\x7F]/', $string)) {
1238 return sprintf("{%d+}\r\n%s", $this->_getLineLength($string), $string);
1241 return '"' . addcslashes($string, '\\"') . '"';
1245 * Write debug text to the current debug output handler.
1247 * @param string $message Debug message text.
1251 function _debug($message)
1253 if ($this->_debug) {
1254 if ($this->_debug_handler) {
1255 call_user_func_array($this->_debug_handler, array(&$this, $message));