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 $this->_data['host'] = $host;
300 $this->_data['port'] = $port;
301 $this->_useTLS = $useTLS;
302 if (!empty($options) && is_array($options)) {
303 $this->_options = array_merge($this->_options, $options);
306 if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
307 return PEAR::raiseError('Not currently in DISCONNECTED state', 1);
310 if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
314 if ($this->_bypassAuth) {
315 $this->_state = NET_SIEVE_STATE_TRANSACTION;
317 $this->_state = NET_SIEVE_STATE_AUTHORISATION;
318 if (PEAR::isError($res = $this->_doCmd())) {
323 // Explicitly ask for the capabilities in case the connection is
324 // picked up from an existing connection.
325 if (PEAR::isError($res = $this->_cmdCapability())) {
326 return PEAR::raiseError(
327 'Failed to connect, server said: ' . $res->getMessage(), 2
331 // Check if we can enable TLS via STARTTLS.
332 if ($useTLS && !empty($this->_capability['starttls'])
333 && function_exists('stream_socket_enable_crypto')
335 if (PEAR::isError($res = $this->_startTLS())) {
344 * Disconnect from the Sieve server.
346 * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
349 * @return boolean True on success, PEAR_Error otherwise.
351 function disconnect($sendLogoutCMD = true)
353 return $this->_cmdLogout($sendLogoutCMD);
359 * @param string $user Login username.
360 * @param string $pass Login password.
361 * @param string $logintype Type of login method to use.
362 * @param string $euser Effective UID (perform on behalf of $euser).
363 * @param boolean $bypassAuth Do not perform authentication.
365 * @return boolean True on success, PEAR_Error otherwise.
367 function login($user, $pass, $logintype = null, $euser = '', $bypassAuth = false)
369 $this->_data['user'] = $user;
370 $this->_data['pass'] = $pass;
371 $this->_data['logintype'] = $logintype;
372 $this->_data['euser'] = $euser;
373 $this->_bypassAuth = $bypassAuth;
375 if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
376 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
380 if (PEAR::isError($res = $this->_cmdAuthenticate($user, $pass, $logintype, $euser))) {
384 $this->_state = NET_SIEVE_STATE_TRANSACTION;
390 * Returns an indexed array of scripts currently on the server.
392 * @return array Indexed array of scriptnames.
394 function listScripts()
396 if (is_array($scripts = $this->_cmdListScripts())) {
397 $this->_active = $scripts[1];
405 * Returns the active script.
407 * @return string The active scriptname.
411 if (!empty($this->_active)) {
412 return $this->_active;
414 if (is_array($scripts = $this->_cmdListScripts())) {
415 $this->_active = $scripts[1];
421 * Sets the active script.
423 * @param string $scriptname The name of the script to be set as active.
425 * @return boolean True on success, PEAR_Error on failure.
427 function setActive($scriptname)
429 return $this->_cmdSetActive($scriptname);
433 * Retrieves a script.
435 * @param string $scriptname The name of the script to be retrieved.
437 * @return string The script on success, PEAR_Error on failure.
439 function getScript($scriptname)
441 return $this->_cmdGetScript($scriptname);
445 * Adds a script to the server.
447 * @param string $scriptname Name of the script.
448 * @param string $script The script content.
449 * @param boolean $makeactive Whether to make this the active script.
451 * @return boolean True on success, PEAR_Error on failure.
453 function installScript($scriptname, $script, $makeactive = false)
455 if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
459 return $this->_cmdSetActive($scriptname);
465 * Removes a script from the server.
467 * @param string $scriptname Name of the script.
469 * @return boolean True on success, PEAR_Error on failure.
471 function removeScript($scriptname)
473 return $this->_cmdDeleteScript($scriptname);
477 * Checks if the server has space to store the script by the server.
479 * @param string $scriptname The name of the script to mark as active.
480 * @param integer $size The size of the script.
482 * @return boolean|PEAR_Error True if there is space, PEAR_Error otherwise.
484 * @todo Rename to hasSpace()
486 function haveSpace($scriptname, $size)
488 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
489 return PEAR::raiseError('Not currently in TRANSACTION state', 1);
492 $command = sprintf('HAVESPACE %s %d', $this->_escape($scriptname), $size);
493 if (PEAR::isError($res = $this->_doCmd($command))) {
500 * Returns the list of extensions the server supports.
502 * @return array List of extensions or PEAR_Error on failure.
504 function getExtensions()
506 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
507 return PEAR::raiseError('Not currently connected', 7);
509 return $this->_capability['extensions'];
513 * Returns whether the server supports an extension.
515 * @param string $extension The extension to check.
517 * @return boolean Whether the extension is supported or PEAR_Error on
520 function hasExtension($extension)
522 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
523 return PEAR::raiseError('Not currently connected', 7);
526 $extension = trim($this->_toUpper($extension));
527 if (is_array($this->_capability['extensions'])) {
528 foreach ($this->_capability['extensions'] as $ext) {
529 if ($ext == $extension) {
539 * Returns the list of authentication methods the server supports.
541 * @return array List of authentication methods or PEAR_Error on failure.
543 function getAuthMechs()
545 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
546 return PEAR::raiseError('Not currently connected', 7);
548 return $this->_capability['sasl'];
552 * Returns whether the server supports an authentication method.
554 * @param string $method The method to check.
556 * @return boolean Whether the method is supported or PEAR_Error on
559 function hasAuthMech($method)
561 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
562 return PEAR::raiseError('Not currently connected', 7);
565 $method = trim($this->_toUpper($method));
566 if (is_array($this->_capability['sasl'])) {
567 foreach ($this->_capability['sasl'] as $sasl) {
568 if ($sasl == $method) {
578 * Handles the authentication using any known method.
580 * @param string $uid The userid to authenticate as.
581 * @param string $pwd The password to authenticate with.
582 * @param string $userMethod The method to use. If empty, the class chooses
583 * the best (strongest) available method.
584 * @param string $euser The effective uid to authenticate as.
588 function _cmdAuthenticate($uid, $pwd, $userMethod = null, $euser = '')
590 if (PEAR::isError($method = $this->_getBestAuthMethod($userMethod))) {
595 return $this->_authDigestMD5($uid, $pwd, $euser);
597 $result = $this->_authCRAMMD5($uid, $pwd, $euser);
600 $result = $this->_authLOGIN($uid, $pwd, $euser);
603 $result = $this->_authPLAIN($uid, $pwd, $euser);
606 $result = $this->_authEXTERNAL($uid, $pwd, $euser);
609 $result = PEAR::raiseError(
610 $method . ' is not a supported authentication method'
615 if (PEAR::isError($res = $this->_doCmd())) {
623 * Authenticates the user using the PLAIN method.
625 * @param string $user The userid to authenticate as.
626 * @param string $pass The password to authenticate with.
627 * @param string $euser The effective uid to authenticate as.
631 function _authPLAIN($user, $pass, $euser)
633 return $this->_sendCmd(
635 'AUTHENTICATE "PLAIN" "%s"',
636 base64_encode($euser . chr(0) . $user . chr(0) . $pass)
642 * Authenticates the user using the LOGIN method.
644 * @param string $user The userid to authenticate as.
645 * @param string $pass The password to authenticate with.
646 * @param string $euser The effective uid to authenticate as.
650 function _authLOGIN($user, $pass, $euser)
652 if (PEAR::isError($result = $this->_sendCmd('AUTHENTICATE "LOGIN"'))) {
655 if (PEAR::isError($result = $this->_doCmd('"' . base64_encode($user) . '"', true))) {
658 return $this->_doCmd('"' . base64_encode($pass) . '"', true);
662 * Authenticates the user using the CRAM-MD5 method.
664 * @param string $user The userid to authenticate as.
665 * @param string $pass The password to authenticate with.
666 * @param string $euser The effective uid to authenticate as.
670 function _authCRAMMD5($user, $pass, $euser)
672 if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "CRAM-MD5"', true))) {
676 $challenge = base64_decode(trim($challenge));
677 $cram = Auth_SASL::factory('crammd5');
678 if (PEAR::isError($response = $cram->getResponse($user, $pass, $challenge))) {
682 return $this->_sendStringResponse(base64_encode($response));
686 * Authenticates the user using the DIGEST-MD5 method.
688 * @param string $user The userid to authenticate as.
689 * @param string $pass The password to authenticate with.
690 * @param string $euser The effective uid to authenticate as.
694 function _authDigestMD5($user, $pass, $euser)
696 if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"', true))) {
700 $challenge = base64_decode(trim($challenge));
701 $digest = Auth_SASL::factory('digestmd5');
702 // @todo Really 'localhost'?
703 if (PEAR::isError($response = $digest->getResponse($user, $pass, $challenge, 'localhost', 'sieve', $euser))) {
707 if (PEAR::isError($result = $this->_sendStringResponse(base64_encode($response)))) {
710 if (PEAR::isError($result = $this->_doCmd('', true))) {
713 if ($this->_toUpper(substr($result, 0, 2)) == 'OK') {
717 /* We don't use the protocol's third step because SIEVE doesn't allow
718 * subsequent authentication, so we just silently ignore it. */
719 if (PEAR::isError($result = $this->_sendStringResponse(''))) {
723 return $this->_doCmd();
727 * Authenticates the user using the EXTERNAL method.
729 * @param string $user The userid to authenticate as.
730 * @param string $pass The password to authenticate with.
731 * @param string $euser The effective uid to authenticate as.
737 function _authEXTERNAL($user, $pass, $euser)
740 'AUTHENTICATE "EXTERNAL" "%s"',
741 base64_encode(strlen($euser) ? $euser : $user)
743 return $this->_sendCmd($cmd);
747 * Removes a script from the server.
749 * @param string $scriptname Name of the script to delete.
751 * @return boolean True on success, PEAR_Error otherwise.
753 function _cmdDeleteScript($scriptname)
755 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
756 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
759 $command = sprintf('DELETESCRIPT %s', $this->_escape($scriptname));
760 if (PEAR::isError($res = $this->_doCmd($command))) {
767 * Retrieves the contents of the named script.
769 * @param string $scriptname Name of the script to retrieve.
771 * @return string The script if successful, PEAR_Error otherwise.
773 function _cmdGetScript($scriptname)
775 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
776 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
779 $command = sprintf('GETSCRIPT %s', $this->_escape($scriptname));
780 if (PEAR::isError($res = $this->_doCmd($command))) {
784 return preg_replace('/^{[0-9]+}\r\n/', '', $res);
788 * Sets the active script, i.e. the one that gets run on new mail by the
791 * @param string $scriptname The name of the script to mark as active.
793 * @return boolean True on success, PEAR_Error otherwise.
795 function _cmdSetActive($scriptname)
797 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
798 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
801 $command = sprintf('SETACTIVE %s', $this->_escape($scriptname));
802 if (PEAR::isError($res = $this->_doCmd($command))) {
806 $this->_activeScript = $scriptname;
811 * Returns the list of scripts on the server.
813 * @return array An array with the list of scripts in the first element
814 * and the active script in the second element on success,
815 * PEAR_Error otherwise.
817 function _cmdListScripts()
819 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
820 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
823 if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
828 $activescript = null;
829 $res = explode("\r\n", $res);
830 foreach ($res as $value) {
831 if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
832 $script_name = stripslashes($matches[1]);
833 $scripts[] = $script_name;
834 if (!empty($matches[2])) {
835 $activescript = $script_name;
840 return array($scripts, $activescript);
844 * Adds a script to the server.
846 * @param string $scriptname Name of the new script.
847 * @param string $scriptdata The new script.
849 * @return boolean True on success, PEAR_Error otherwise.
851 function _cmdPutScript($scriptname, $scriptdata)
853 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
854 return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
857 $stringLength = $this->_getLineLength($scriptdata);
858 $command = sprintf("PUTSCRIPT %s {%d+}\r\n%s",
859 $this->_escape($scriptname), $stringLength, $scriptdata);
861 if (PEAR::isError($res = $this->_doCmd($command))) {
869 * Logs out of the server and terminates the connection.
871 * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
874 * @return boolean True on success, PEAR_Error otherwise.
876 function _cmdLogout($sendLogoutCMD = true)
878 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
879 return PEAR::raiseError('Not currently connected', 1);
882 if ($sendLogoutCMD) {
883 if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
888 $this->_sock->disconnect();
889 $this->_state = NET_SIEVE_STATE_DISCONNECTED;
895 * Sends the CAPABILITY command
897 * @return boolean True on success, PEAR_Error otherwise.
899 function _cmdCapability()
901 if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
902 return PEAR::raiseError('Not currently connected', 1);
904 if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
907 $this->_parseCapability($res);
912 * Parses the response from the CAPABILITY command and stores the result
915 * @param string $data The response from the capability command.
919 function _parseCapability($data)
921 // Clear the cached capabilities.
922 $this->_capability = array('sasl' => array(),
923 'extensions' => array());
925 $data = preg_split('/\r?\n/', $this->_toUpper($data), -1, PREG_SPLIT_NO_EMPTY);
927 for ($i = 0; $i < count($data); $i++) {
928 if (!preg_match('/^"([A-Z]+)"( "(.*)")?$/', $data[$i], $matches)) {
931 switch ($matches[1]) {
932 case 'IMPLEMENTATION':
933 $this->_capability['implementation'] = $matches[3];
937 $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
941 $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
945 $this->_capability['starttls'] = true;
952 * Sends a command to the server
954 * @param string $cmd The command to send.
958 function _sendCmd($cmd)
960 $status = $this->_sock->getStatus();
961 if (PEAR::isError($status) || $status['eof']) {
962 return PEAR::raiseError('Failed to write to socket: connection lost');
964 if (PEAR::isError($error = $this->_sock->write($cmd . "\r\n"))) {
965 return PEAR::raiseError(
966 'Failed to write to socket: ' . $error->getMessage()
969 $this->_debug("C: $cmd");
973 * Sends a string response to the server.
975 * @param string $str The string to send.
979 function _sendStringResponse($str)
981 return $this->_sendCmd('{' . $this->_getLineLength($str) . "+}\r\n" . $str);
985 * Receives a single line from the server.
987 * @return string The server response line.
991 if (PEAR::isError($lastline = $this->_sock->gets(8192))) {
992 return PEAR::raiseError(
993 'Failed to read from socket: ' . $lastline->getMessage()
997 $lastline = rtrim($lastline);
998 $this->_debug("S: $lastline");
1000 if ($lastline === '') {
1001 return PEAR::raiseError('Failed to read from socket');
1008 * Receives x bytes from the server.
1010 * @param int $length Number of bytes to read
1012 * @return string The server response.
1014 function _recvBytes($length)
1017 $response_length = 0;
1019 while ($response_length < $length) {
1020 $response .= $this->_sock->read($length - $response_length);
1021 $response_length = $this->_getLineLength($response);
1024 $this->_debug("S: " . rtrim($response));
1030 * Send a command and retrieves a response from the server.
1032 * @param string $cmd The command to send.
1033 * @param boolean $auth Whether this is an authentication command.
1035 * @return string|PEAR_Error Reponse string if an OK response, PEAR_Error
1038 function _doCmd($cmd = '', $auth = false)
1041 while ($referralCount < $this->_maxReferralCount) {
1043 if (PEAR::isError($error = $this->_sendCmd($cmd))) {
1050 if (PEAR::isError($line = $this->_recvLn())) {
1053 $uc_line = $this->_toUpper($line);
1055 if ('OK' == substr($uc_line, 0, 2)) {
1057 return rtrim($response);
1060 if ('NO' == substr($uc_line, 0, 2)) {
1061 // Check for string literal error message.
1062 if (preg_match('/{([0-9]+)}$/i', $line, $matches)) {
1063 $line = substr($line, 0, -(strlen($matches[1])+2))
1065 "\r\n", ' ', $this->_recvBytes($matches[1] + 2)
1068 return PEAR::raiseError(trim($response . substr($line, 2)), 3);
1071 if ('BYE' == substr($uc_line, 0, 3)) {
1072 if (PEAR::isError($error = $this->disconnect(false))) {
1073 return PEAR::raiseError(
1074 'Cannot handle BYE, the error was: '
1075 . $error->getMessage(),
1079 // Check for referral, then follow it. Otherwise, carp an
1081 if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
1082 // Replace the old host with the referral host
1083 // preserving any protocol prefix.
1084 $this->_data['host'] = preg_replace(
1085 '/\w+(?!(\w|\:\/\/)).*/', $matches[2],
1086 $this->_data['host']
1088 if (PEAR::isError($error = $this->_handleConnectAndLogin())) {
1089 return PEAR::raiseError(
1090 'Cannot follow referral to '
1091 . $this->_data['host'] . ', the error was: '
1092 . $error->getMessage(),
1098 return PEAR::raiseError(trim($response . $line), 6);
1101 if (preg_match('/^{([0-9]+)}/i', $line, $matches)) {
1102 // Matches literal string responses.
1103 $line = $this->_recvBytes($matches[1] + 2);
1106 // Receive the pending OK only if we aren't
1107 // authenticating since string responses during
1108 // authentication don't need an OK.
1115 // String responses during authentication don't need an
1118 return rtrim($response);
1121 $response .= $line . "\r\n";
1126 return PEAR::raiseError('Max referral count (' . $referralCount . ') reached. Cyrus murder loop error?', 7);
1130 * Returns the name of the best authentication method that the server
1133 * @param string $userMethod Only consider this method as available.
1135 * @return string The name of the best supported authentication method or
1136 * a PEAR_Error object on failure.
1138 function _getBestAuthMethod($userMethod = null)
1140 if (!isset($this->_capability['sasl'])) {
1141 return PEAR::raiseError('This server doesn\'t support any authentication methods. SASL problem?');
1143 if (!$this->_capability['sasl']) {
1144 return PEAR::raiseError('This server doesn\'t support any authentication methods.');
1148 if (in_array($userMethod, $this->_capability['sasl'])) {
1151 return PEAR::raiseError(
1152 sprintf('No supported authentication method found. The server supports these methods: %s, but we want to use: %s',
1153 implode(', ', $this->_capability['sasl']),
1157 foreach ($this->supportedAuthMethods as $method) {
1158 if (in_array($method, $this->_capability['sasl'])) {
1163 return PEAR::raiseError(
1164 sprintf('No supported authentication method found. The server supports these methods: %s, but we only support: %s',
1165 implode(', ', $this->_capability['sasl']),
1166 implode(', ', $this->supportedAuthMethods)));
1170 * Starts a TLS connection.
1172 * @return boolean True on success, PEAR_Error on failure.
1174 function _startTLS()
1176 if (PEAR::isError($res = $this->_doCmd('STARTTLS'))) {
1180 if (!stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
1181 return PEAR::raiseError('Failed to establish TLS connection', 2);
1184 $this->_debug('STARTTLS negotiation successful');
1186 // The server should be sending a CAPABILITY response after
1187 // negotiating TLS. Read it, and ignore if it doesn't.
1188 // Doesn't work with older timsieved versions
1189 $regexp = '/^CYRUS TIMSIEVED V([0-9.]+)/';
1190 if (!preg_match($regexp, $this->_capability['implementation'], $matches)
1191 || version_compare($matches[1], '2.3.10', '>=')
1196 // RFC says we need to query the server capabilities again now that we
1197 // are under encryption.
1198 if (PEAR::isError($res = $this->_cmdCapability())) {
1199 return PEAR::raiseError(
1200 'Failed to connect, server said: ' . $res->getMessage(), 2
1208 * Returns the length of a string.
1210 * @param string $string A string.
1212 * @return integer The length of the string.
1214 function _getLineLength($string)
1216 if (extension_loaded('mbstring')) {
1217 return mb_strlen($string, 'latin1');
1219 return strlen($string);
1224 * Locale independant strtoupper() implementation.
1226 * @param string $string The string to convert to lowercase.
1228 * @return string The lowercased string, based on ASCII encoding.
1230 function _toUpper($string)
1232 $language = setlocale(LC_CTYPE, 0);
1233 setlocale(LC_CTYPE, 'C');
1234 $string = strtoupper($string);
1235 setlocale(LC_CTYPE, $language);
1240 * Convert string into RFC's quoted-string or literal-c2s form
1242 * @param string $string The string to convert.
1244 * @return string Result string
1246 function _escape($string)
1248 // Some implementations doesn't allow UTF-8 characters in quoted-string
1249 // It's safe to use literal-c2s
1250 if (preg_match('/[^\x01-\x09\x0B-\x0C\x0E-\x7F]/', $string)) {
1251 return sprintf("{%d+}\r\n%s", $this->_getLineLength($string), $string);
1254 return '"' . addcslashes($string, '\\"') . '"';
1258 * Write debug text to the current debug output handler.
1260 * @param string $message Debug message text.
1264 function _debug($message)
1266 if ($this->_debug) {
1267 if ($this->_debug_handler) {
1268 call_user_func_array($this->_debug_handler, array(&$this, $message));