2 // +-----------------------------------------------------------------------+
3 // | Copyright (c) 2002-2003, Richard Heyes |
4 // | Copyright (c) 2006,2008 Anish Mistry |
5 // | All rights reserved. |
7 // | Redistribution and use in source and binary forms, with or without |
8 // | modification, are permitted provided that the following conditions |
11 // | o Redistributions of source code must retain the above copyright |
12 // | notice, this list of conditions and the following disclaimer. |
13 // | o Redistributions in binary form must reproduce the above copyright |
14 // | notice, this list of conditions and the following disclaimer in the |
15 // | documentation and/or other materials provided with the distribution.|
16 // | o The names of the authors may not be used to endorse or promote |
17 // | products derived from this software without specific prior written |
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. |
32 // +-----------------------------------------------------------------------+
33 // | Author: Richard Heyes <richard@phpguru.org> |
34 // | Co-Author: Damian Fernandez Sosa <damlists@cnba.uba.ar> |
35 // | Co-Author: Anish Mistry <amistry@am-productions.biz> |
36 // +-----------------------------------------------------------------------+
38 require_once('Net/Socket.php');
43 * o supportsAuthMech()
48 * @const NET_SIEVE_STATE_DISCONNECTED
50 define('NET_SIEVE_STATE_DISCONNECTED', 1, true);
54 * @const NET_SIEVE_STATE_AUTHORISATION
56 define('NET_SIEVE_STATE_AUTHORISATION', 2, true);
60 * @const NET_SIEVE_STATE_TRANSACTION
62 define('NET_SIEVE_STATE_TRANSACTION', 3, true);
65 * A class for talking to the timsieved server which
66 * comes with Cyrus IMAP.
68 * SIEVE: RFC3028 http://www.ietf.org/rfc/rfc3028.txt
69 * MANAGE-SIEVE: http://www.ietf.org/internet-drafts/draft-martin-managesieve-07.txt
71 * @author Richard Heyes <richard@php.net>
72 * @author Damian Fernandez Sosa <damlists@cnba.uba.ar>
73 * @author Anish Mistry <amistry@am-productions.biz>
88 * Info about the connect
94 * Current state of the connection
100 * Constructor error is any
106 * To allow class debuging
112 * Allows picking up of an already established connection
115 var $_bypassAuth = false;
118 * Whether to use TLS if available
124 * Additional options for stream_context_create()
127 var $_options = null;
130 * The auth methods this class support
133 var $supportedAuthMethods=array('DIGEST-MD5', 'CRAM-MD5', 'EXTERNAL', 'PLAIN' , 'LOGIN');
134 //if you have problems using DIGEST-MD5 authentication please comment the line above and uncomment the following line
135 //var $supportedAuthMethods=array( 'CRAM-MD5', 'PLAIN' , 'LOGIN');
137 //var $supportedAuthMethods=array( 'PLAIN' , 'LOGIN');
140 * The auth methods this class support
143 var $supportedSASLAuthMethods=array('DIGEST-MD5', 'CRAM-MD5');
146 * Handles posible referral loops
149 var $_maxReferralCount = 15;
153 * Sets up the object, connects to the server and logs in. stores
154 * any generated error in $this->_error, which can be retrieved
155 * using the getError() method.
157 * @param string $user Login username
158 * @param string $pass Login password
159 * @param string $host Hostname of server
160 * @param string $port Port of server
161 * @param string $logintype Type of login to perform
162 * @param string $euser Effective User (if $user=admin, login as $euser)
163 * @param string $bypassAuth Skip the authentication phase. Useful if the socket
165 * @param boolean $useTLS Use TLS if available
166 * @param array $options options for stream_context_create()
168 function Net_Sieve($user = null , $pass = null , $host = 'localhost', $port = 2000, $logintype = '', $euser = '', $debug = false, $bypassAuth = false, $useTLS = true, $options = null)
170 $this->_state = NET_SIEVE_STATE_DISCONNECTED;
171 $this->_data['user'] = $user;
172 $this->_data['pass'] = $pass;
173 $this->_data['host'] = $host;
174 $this->_data['port'] = $port;
175 $this->_data['logintype'] = $logintype;
176 $this->_data['euser'] = $euser;
177 $this->_sock = &new Net_Socket();
178 $this->_debug = $debug;
179 $this->_bypassAuth = $bypassAuth;
180 $this->_useTLS = $useTLS;
181 $this->_options = $options;
183 * Include the Auth_SASL package. If the package is not available,
184 * we disable the authentication methods that depend upon it.
186 if ((@include_once 'Auth/SASL.php') === false) {
188 echo "AUTH_SASL NOT PRESENT!\n";
190 foreach($this->supportedSASLAuthMethods as $SASLMethod){
191 $pos = array_search( $SASLMethod, $this->supportedAuthMethods );
193 echo "DISABLING METHOD $SASLMethod\n";
195 unset($this->supportedAuthMethods[$pos]);
198 if( ($user != null) && ($pass != null) ){
199 $this->_error = $this->_handleConnectAndLogin();
204 * Handles the errors the class can find
208 * @param mixed $msg Text error message or PEAR error object
209 * @param integer $code Numeric error code
212 function _raiseError($msg, $code)
214 include_once 'PEAR.php';
215 return PEAR::raiseError($msg, $code);
219 * Handles connect and login.
223 * @return mixed Indexed array of scriptnames or PEAR_Error on failure
225 function _handleConnectAndLogin()
227 if (PEAR::isError($res = $this->connect($this->_data['host'] , $this->_data['port'], $this->_options, $this->_useTLS ))) {
230 if($this->_bypassAuth === false) {
231 if (PEAR::isError($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'] , $this->_data['euser'] , $this->_bypassAuth) ) ) {
239 * Returns an indexed array of scripts currently
242 * @return mixed Indexed array of scriptnames or PEAR_Error on failure
244 function listScripts()
246 if (is_array($scripts = $this->_cmdListScripts())) {
247 $this->_active = $scripts[1];
255 * Returns the active script
257 * @return mixed The active scriptname or PEAR_Error on failure
261 if (!empty($this->_active)) {
262 return $this->_active;
264 } elseif (is_array($scripts = $this->_cmdListScripts())) {
265 $this->_active = $scripts[1];
271 * Sets the active script
273 * @param string $scriptname The name of the script to be set as active
274 * @return mixed true on success, PEAR_Error on failure
276 function setActive($scriptname)
278 return $this->_cmdSetActive($scriptname);
284 * @param string $scriptname The name of the script to be retrieved
285 * @return mixed The script on success, PEAR_Error on failure
287 function getScript($scriptname)
289 return $this->_cmdGetScript($scriptname);
293 * Adds a script to the server
295 * @param string $scriptname Name of the script
296 * @param string $script The script
297 * @param boolean $makeactive Whether to make this the active script
298 * @return mixed true on success, PEAR_Error on failure
300 function installScript($scriptname, $script, $makeactive = false)
302 if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
305 } elseif ($makeactive) {
306 return $this->_cmdSetActive($scriptname);
314 * Removes a script from the server
316 * @param string $scriptname Name of the script
317 * @return mixed True on success, PEAR_Error on failure
319 function removeScript($scriptname)
321 return $this->_cmdDeleteScript($scriptname);
325 * Returns any error that may have been generated in the
328 * @return mixed False if no error, PEAR_Error otherwise
332 return PEAR::isError($this->_error) ? $this->_error : false;
336 * Handles connecting to the server and checking the
340 * @param string $host Hostname of server
341 * @param string $port Port of server
342 * @param array $options List of options to pass to connect
343 * @param boolean $useTLS Use TLS if available
344 * @return mixed True on success, PEAR_Error otherwise
346 function connect($host, $port, $options = null, $useTLS = true)
348 if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
349 $msg='Not currently in DISCONNECTED state';
351 return $this->_raiseError($msg,$code);
354 if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
358 if($this->_bypassAuth === false) {
359 $this->_state = NET_SIEVE_STATE_AUTHORISATION;
360 if (PEAR::isError($res = $this->_doCmd())) {
364 $this->_state = NET_SIEVE_STATE_TRANSACTION;
367 // Explicitly ask for the capabilities in case the connection
368 // is picked up from an existing connection.
369 if(PEAR::isError($res = $this->_cmdCapability() )) {
370 $msg='Failed to connect, server said: ' . $res->getMessage();
372 return $this->_raiseError($msg,$code);
375 if($useTLS === true) {
376 // check if we can enable TLS via STARTTLS
377 if(isset($this->_capability['starttls']) && function_exists('stream_socket_enable_crypto') === true) {
378 if (PEAR::isError($res = $this->_startTLS())) {
390 * @param string $user Login username
391 * @param string $pass Login password
392 * @param string $logintype Type of login method to use
393 * @param string $euser Effective UID (perform on behalf of $euser)
394 * @param boolean $bypassAuth Do not perform authentication
395 * @return mixed True on success, PEAR_Error otherwise
397 function login($user, $pass, $logintype = null , $euser = '', $bypassAuth = false)
399 if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
400 $msg='Not currently in AUTHORISATION state';
402 return $this->_raiseError($msg,$code);
405 if( $bypassAuth === false ){
406 if(PEAR::isError($res=$this->_cmdAuthenticate($user , $pass , $logintype, $euser ) ) ){
410 $this->_state = NET_SIEVE_STATE_TRANSACTION;
415 * Handles the authentication using any known method
417 * @param string $uid The userid to authenticate as.
418 * @param string $pwd The password to authenticate with.
419 * @param string $userMethod The method to use ( if $userMethod == '' then the class chooses the best method (the stronger is the best ) )
420 * @param string $euser The effective uid to authenticate as.
422 * @return mixed string or PEAR_Error
427 function _cmdAuthenticate($uid , $pwd , $userMethod = null , $euser = '' )
429 if ( PEAR::isError( $method = $this->_getBestAuthMethod($userMethod) ) ) {
434 $result = $this->_authDigest_MD5( $uid , $pwd , $euser );
438 $result = $this->_authCRAM_MD5( $uid , $pwd, $euser);
441 $result = $this->_authLOGIN( $uid , $pwd , $euser );
444 $result = $this->_authPLAIN( $uid , $pwd , $euser );
447 $result = $this->_authEXTERNAL( $uid , $pwd , $euser );
450 $result = new PEAR_Error( "$method is not a supported authentication method" );
454 if (PEAR::isError($res = $this->_doCmd() )) {
461 * Authenticates the user using the PLAIN method.
463 * @param string $user The userid to authenticate as.
464 * @param string $pass The password to authenticate with.
465 * @param string $euser The effective uid to authenticate as.
467 * @return array Returns an array containing the response
472 function _authPLAIN($user, $pass , $euser )
475 $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode($euser . chr(0) . $user . chr(0) . $pass ) ) ;
477 $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode( chr(0) . $user . chr(0) . $pass ) );
479 return $this->_sendCmd( $cmd ) ;
483 * Authenticates the user using the PLAIN method.
485 * @param string $user The userid to authenticate as.
486 * @param string $pass The password to authenticate with.
487 * @param string $euser The effective uid to authenticate as.
489 * @return array Returns an array containing the response
494 function _authLOGIN($user, $pass , $euser )
496 $this->_sendCmd('AUTHENTICATE "LOGIN"');
497 $this->_doCmd(sprintf('"%s"', base64_encode($user)));
498 $this->_doCmd(sprintf('"%s"', base64_encode($pass)));
502 * Authenticates the user using the CRAM-MD5 method.
504 * @param string $uid The userid to authenticate as.
505 * @param string $pwd The password to authenticate with.
506 * @param string $euser The effective uid to authenticate as.
508 * @return array Returns an array containing the response
513 function _authCRAM_MD5($uid, $pwd, $euser)
515 if ( PEAR::isError( $challenge = $this->_doCmd( 'AUTHENTICATE "CRAM-MD5"' ) ) ) {
516 $this->_error=$challenge;
519 $challenge=trim($challenge);
520 $challenge = base64_decode( trim($challenge) );
521 $cram = &Auth_SASL::factory('crammd5');
522 if ( PEAR::isError($resp=$cram->getResponse( $uid , $pwd , $challenge ) ) ) {
526 $auth_str = base64_encode( $resp );
527 if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str ) ) ) {
528 $this->_error=$error;
535 * Authenticates the user using the DIGEST-MD5 method.
537 * @param string $uid The userid to authenticate as.
538 * @param string $pwd The password to authenticate with.
539 * @param string $euser The effective uid to authenticate as.
541 * @return array Returns an array containing the response
546 function _authDigest_MD5($uid, $pwd, $euser)
548 if ( PEAR::isError( $challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"') ) ) {
549 $this->_error= $challenge;
552 $challenge = base64_decode( $challenge );
553 $digest = &Auth_SASL::factory('digestmd5');
555 if(PEAR::isError($param=$digest->getResponse($uid, $pwd, $challenge, "localhost", "sieve" , $euser) )) {
558 $auth_str = base64_encode($param);
560 if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str ) ) ) {
561 $this->_error=$error;
565 if ( PEAR::isError( $challenge = $this->_doCmd() ) ) {
566 $this->_error=$challenge ;
570 if( strtoupper(substr($challenge,0,2))== 'OK' ){
575 * We don't use the protocol's third step because SIEVE doesn't allow
576 * subsequent authentication, so we just silently ignore it.
578 if ( PEAR::isError($error = $this->_sendStringResponse( '' ) ) ) {
579 $this->_error=$error;
583 if (PEAR::isError($res = $this->_doCmd() )) {
589 * Authenticates the user using the EXTERNAL method.
591 * @param string $user The userid to authenticate as.
592 * @param string $pass The password to authenticate with.
593 * @param string $euser The effective uid to authenticate as.
595 * @return array Returns an array containing the response
600 function _authEXTERNAL($user, $pass, $euser)
603 $cmd=sprintf('AUTHENTICATE "EXTERNAL" "%s"', base64_encode($euser) ) ;
605 $cmd=sprintf('AUTHENTICATE "EXTERNAL" "%s"', base64_encode($user) );
607 return $this->_sendCmd( $cmd ) ;
611 * Removes a script from the server
614 * @param string $scriptname Name of the script to delete
615 * @return mixed True on success, PEAR_Error otherwise
617 function _cmdDeleteScript($scriptname)
619 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
620 $msg='Not currently in AUTHORISATION state';
622 return $this->_raiseError($msg,$code);
624 if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname) ) )) {
631 * Retrieves the contents of the named script
634 * @param string $scriptname Name of the script to retrieve
635 * @return mixed The script if successful, PEAR_Error otherwise
637 function _cmdGetScript($scriptname)
639 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
640 $msg='Not currently in AUTHORISATION state';
642 return $this->_raiseError($msg,$code);
645 if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname) ) ) ) {
649 return preg_replace('/{[0-9]+}\r\n/', '', $res);
653 * Sets the ACTIVE script, ie the one that gets run on new mail
657 * @param string $scriptname The name of the script to mark as active
658 * @return mixed True on success, PEAR_Error otherwise
660 function _cmdSetActive($scriptname)
662 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
663 $msg='Not currently in AUTHORISATION state';
665 return $this->_raiseError($msg,$code);
668 if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname) ) ) ) {
672 $this->_activeScript = $scriptname;
677 * Sends the LISTSCRIPTS command
680 * @return mixed Two item array of scripts, and active script on success,
681 * PEAR_Error otherwise.
683 function _cmdListScripts()
685 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
686 $msg='Not currently in AUTHORISATION state';
688 return $this->_raiseError($msg,$code);
692 $activescript = null;
694 if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
698 $res = explode("\r\n", $res);
700 foreach ($res as $value) {
701 if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
702 $scripts[] = $matches[1];
703 if (!empty($matches[2])) {
704 $activescript = $matches[1];
709 return array($scripts, $activescript);
713 * Sends the PUTSCRIPT command to add a script to
717 * @param string $scriptname Name of the new script
718 * @param string $scriptdata The new script
719 * @return mixed True on success, PEAR_Error otherwise
721 function _cmdPutScript($scriptname, $scriptdata)
723 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
724 $msg='Not currently in TRANSACTION state';
726 return $this->_raiseError($msg,$code);
729 $stringLength = $this->_getLineLength($scriptdata);
731 if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata) ))) {
739 * Sends the LOGOUT command and terminates the connection
742 * @param boolean $sendLogoutCMD True to send LOGOUT command before disconnecting
743 * @return mixed True on success, PEAR_Error otherwise
745 function _cmdLogout($sendLogoutCMD=true)
747 if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
748 $msg='Not currently connected';
750 return $this->_raiseError($msg,$code);
751 //return PEAR::raiseError('Not currently connected');
755 if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
760 $this->_sock->disconnect();
761 $this->_state = NET_SIEVE_STATE_DISCONNECTED;
766 * Sends the CAPABILITY command
769 * @return mixed True on success, PEAR_Error otherwise
771 function _cmdCapability()
773 if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
774 $msg='Not currently connected';
776 return $this->_raiseError($msg,$code);
779 if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
782 $this->_parseCapability($res);
787 * Checks if the server has space to store the script
790 * @param string $scriptname The name of the script to mark as active
791 * @param integer $size The size of the script
792 * @return mixed True on success, PEAR_Error otherwise
794 function haveSpace($scriptname,$size)
796 if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
797 $msg='Not currently in TRANSACTION state';
799 return $this->_raiseError($msg,$code);
802 if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %d', $scriptname, $size) ) ) ) {
810 * Parses the response from the capability command. Stores
811 * the result in $this->_capability
814 * @param string $data The response from the capability command
816 function _parseCapability($data)
818 // clear the cached capabilities
819 $this->_capability = array();
821 $data = preg_split('/\r?\n/', $data, -1, PREG_SPLIT_NO_EMPTY);
823 for ($i = 0; $i < count($data); $i++) {
824 if (preg_match('/^"([a-z]+)"( "(.*)")?$/i', $data[$i], $matches)) {
825 switch (strtolower($matches[1])) {
826 case 'implementation':
827 $this->_capability['implementation'] = $matches[3];
831 $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
835 $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
839 $this->_capability['starttls'] = true;
847 * Sends a command to the server
850 * @param string $cmd The command to send
852 function _sendCmd($cmd)
854 $status = $this->_sock->getStatus();
855 if (PEAR::isError($status) || $status['eof']) {
856 return new PEAR_Error( 'Failed to write to socket: (connection lost!) ' );
858 if ( PEAR::isError( $error = $this->_sock->write( $cmd . "\r\n" ) ) ) {
859 return new PEAR_Error( 'Failed to write to socket: ' . $error->getMessage() );
863 // C: means this data was sent by the client (this class)
870 * Sends a string response to the server
873 * @param string $cmd The command to send
875 function _sendStringResponse($str)
877 $response='{' . $this->_getLineLength($str) . "+}\r\n" . $str ;
878 return $this->_sendCmd($response);
884 if (PEAR::isError( $lastline = $this->_sock->gets( 8192 ) ) ) {
885 return new PEAR_Error( 'Failed to write to socket: ' . $lastline->getMessage() );
887 $lastline=rtrim($lastline);
889 // S: means this data was sent by the IMAP Server
890 echo "S:$lastline\n" ;
893 if( $lastline === '' ) {
894 return new PEAR_Error( 'Failed to receive from the socket' );
901 * Send a command and retrieves a response from the server.
905 * @param string $cmd The command to send
906 * @return mixed Reponse string if an OK response, PEAR_Error if a NO response
908 function _doCmd($cmd = '' )
911 while($referralCount < $this->_maxReferralCount ){
914 if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
921 if(PEAR::isError( $line=$this->_recvLn() )){
924 if ('ok' === strtolower(substr($line, 0, 2))) {
926 return rtrim($response);
928 } elseif ('no' === strtolower(substr($line, 0, 2))) {
929 // Check for string literal error message
930 if (preg_match('/^no {([0-9]+)\+?}/i', $line, $matches)) {
931 $line .= str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
936 $msg=trim($response . substr($line, 2));
938 return $this->_raiseError($msg,$code);
939 } elseif ('bye' === strtolower(substr($line, 0, 3))) {
941 if(PEAR::isError($error = $this->disconnect(false) ) ){
942 $msg="Can't handle bye, The error was= " . $error->getMessage() ;
944 return $this->_raiseError($msg,$code);
946 //if (preg_match('/^bye \(referral "([^"]+)/i', $line, $matches)) {
947 if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
948 // Check for referral, then follow it. Otherwise, carp an error.
949 // Replace the old host with the referral host preserving any protocol prefix
950 $this->_data['host'] = preg_replace('/\w+(?!(\w|\:\/\/)).*/',$matches[2],$this->_data['host']);
951 if (PEAR::isError($error = $this->_handleConnectAndLogin() ) ){
952 $msg="Can't follow referral to " . $this->_data['host'] . ", The error was= " . $error->getMessage() ;
954 return $this->_raiseError($msg,$code);
958 if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
963 $msg=trim($response . $line);
965 return $this->_raiseError($msg,$code);
966 } elseif (preg_match('/^{([0-9]+)\+?}/i', $line, $matches)) {
967 // Matches String Responses.
968 //$line = str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
969 $str_size = $matches[1] + 2;
972 while ($line_length < $str_size) {
973 $line .= $this->_sock->read($str_size - $line_length);
974 $line_length = $this->_getLineLength($line);
979 if($this->_state != NET_SIEVE_STATE_AUTHORISATION) {
980 // receive the pending OK only if we aren't authenticating
981 // since string responses during authentication don't need an
987 $response .= $line . "\r\n";
991 $msg="Max referral count reached ($referralCount times) Cyrus murder loop error?";
993 return $this->_raiseError($msg,$code);
997 * Sets the debug state
999 * @param boolean $debug
1002 function setDebug($debug = true)
1004 $this->_debug = $debug;
1008 * Disconnect from the Sieve server
1010 * @param string $scriptname The name of the script to be set as active
1011 * @return mixed true on success, PEAR_Error on failure
1013 function disconnect($sendLogoutCMD=true)
1015 return $this->_cmdLogout($sendLogoutCMD);
1019 * Returns the name of the best authentication method that the server
1022 * @param string if !=null,authenticate with this method ($userMethod).
1024 * @return mixed Returns a string containing the name of the best
1025 * supported authentication method or a PEAR_Error object
1026 * if a failure condition is encountered.
1030 function _getBestAuthMethod($userMethod = null)
1032 if( isset($this->_capability['sasl']) ){
1033 $serverMethods=$this->_capability['sasl'];
1035 // if the server don't send an sasl capability fallback to login auth
1037 return new PEAR_Error("This server don't support any Auth methods SASL problem?");
1040 if($userMethod != null ){
1042 $methods[] = $userMethod;
1045 $methods = $this->supportedAuthMethods;
1047 if( ($methods != null) && ($serverMethods != null)){
1048 foreach ( $methods as $method ) {
1049 if ( in_array( $method , $serverMethods ) ) {
1053 $serverMethods=implode(',' , $serverMethods );
1054 $myMethods=implode(',' ,$this->supportedAuthMethods);
1055 return new PEAR_Error("$method NOT supported authentication method!. This server " .
1056 "supports these methods= $serverMethods, but I support $myMethods");
1058 return new PEAR_Error("This server don't support any Auth methods");
1063 * Return the list of extensions the server supports
1065 * @return mixed array on success, PEAR_Error on failure
1067 function getExtensions()
1069 if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1070 $msg='Not currently connected';
1072 return $this->_raiseError($msg,$code);
1075 return $this->_capability['extensions'];
1079 * Return true if tyhe server has that extension
1081 * @param string the extension to compare
1082 * @return mixed array on success, PEAR_Error on failure
1084 function hasExtension($extension)
1086 if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1087 $msg='Not currently connected';
1089 return $this->_raiseError($msg,$code);
1092 if(is_array($this->_capability['extensions'] ) ){
1093 foreach( $this->_capability['extensions'] as $ext){
1094 if( trim( strtolower( $ext ) ) === trim( strtolower( $extension ) ) )
1102 * Return the list of auth methods the server supports
1104 * @return mixed array on success, PEAR_Error on failure
1106 function getAuthMechs()
1108 if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1109 $msg='Not currently connected';
1111 return $this->_raiseError($msg,$code);
1113 if(!isset($this->_capability['sasl']) ){
1114 $this->_capability['sasl']=array();
1116 return $this->_capability['sasl'];
1120 * Return true if the server has that extension
1122 * @param string the extension to compare
1123 * @return mixed array on success, PEAR_Error on failure
1125 function hasAuthMech($method)
1127 if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1128 $msg='Not currently connected';
1130 return $this->_raiseError($msg,$code);
1131 //return PEAR::raiseError('Not currently connected');
1134 if(is_array($this->_capability['sasl'] ) ){
1135 foreach( $this->_capability['sasl'] as $ext){
1136 if( trim( strtolower( $ext ) ) === trim( strtolower( $method ) ) )
1144 * Return true if the TLS negotiation was successful
1147 * @return mixed true on success, PEAR_Error on failure
1149 function _startTLS()
1151 if (PEAR::isError($res = $this->_doCmd("STARTTLS"))) {
1155 if(stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) == false) {
1156 $msg='Failed to establish TLS connection';
1158 return $this->_raiseError($msg,$code);
1161 if($this->_debug === true) {
1162 echo "STARTTLS Negotiation Successful\n";
1165 // The server should be sending a CAPABILITY response after
1166 // negotiating TLS. Read it, and ignore if it doesn't.
1169 // RFC says we need to query the server capabilities again now that
1170 // we are under encryption
1171 if(PEAR::isError($res = $this->_cmdCapability() )) {
1172 $msg='Failed to connect, server said: ' . $res->getMessage();
1174 return $this->_raiseError($msg,$code);
1180 function _getLineLength($string) {
1181 if (extension_loaded('mbstring') || @dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX)) {
1182 return mb_strlen($string,'latin1');
1184 return strlen($string);