]> git.donarmstrong.com Git - roundcube.git/blob - plugins/managesieve/lib/Net/Sieve.php
Imported Upstream version 0.3
[roundcube.git] / plugins / managesieve / lib / Net / Sieve.php
1 <?php
2 // +-----------------------------------------------------------------------+
3 // | Copyright (c) 2002-2003, Richard Heyes                                |
4 // | Copyright (c) 2006,2008 Anish Mistry                                  |
5 // | All rights reserved.                                                  |
6 // |                                                                       |
7 // | Redistribution and use in source and binary forms, with or without    |
8 // | modification, are permitted provided that the following conditions    |
9 // | are met:                                                              |
10 // |                                                                       |
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  |
18 // |   permission.                                                         |
19 // |                                                                       |
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 // |                                                                       |
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 // +-----------------------------------------------------------------------+
37
38 require_once('Net/Socket.php');
39
40 /**
41 * TODO
42 *
43 * o supportsAuthMech()
44 */
45
46 /**
47 * Disconnected state
48 * @const NET_SIEVE_STATE_DISCONNECTED
49 */
50 define('NET_SIEVE_STATE_DISCONNECTED',  1, true);
51
52 /**
53 * Authorisation state
54 * @const NET_SIEVE_STATE_AUTHORISATION
55 */
56 define('NET_SIEVE_STATE_AUTHORISATION', 2, true);
57
58 /**
59 * Transaction state
60 * @const NET_SIEVE_STATE_TRANSACTION
61 */
62 define('NET_SIEVE_STATE_TRANSACTION',   3, true);
63
64 /**
65 * A class for talking to the timsieved server which
66 * comes with Cyrus IMAP.
67 *
68 * SIEVE: RFC3028 http://www.ietf.org/rfc/rfc3028.txt
69 * MANAGE-SIEVE: http://www.ietf.org/internet-drafts/draft-martin-managesieve-07.txt
70 *
71 * @author  Richard Heyes <richard@php.net>
72 * @author  Damian Fernandez Sosa <damlists@cnba.uba.ar>
73 * @author  Anish Mistry <amistry@am-productions.biz>
74 * @access  public
75 * @version 1.2.0
76 * @package Net_Sieve
77 */
78
79 class Net_Sieve
80 {
81     /**
82     * The socket object
83     * @var object
84     */
85     var $_sock;
86
87     /**
88     * Info about the connect
89     * @var array
90     */
91     var $_data;
92
93     /**
94     * Current state of the connection
95     * @var integer
96     */
97     var $_state;
98
99     /**
100     * Constructor error is any
101     * @var object
102     */
103     var $_error;
104
105     /**
106     * To allow class debuging
107     * @var boolean
108     */
109     var $_debug = false;
110
111     /**
112     * Allows picking up of an already established connection
113     * @var boolean
114     */
115     var $_bypassAuth = false;
116
117     /**
118     * Whether to use TLS if available
119     * @var boolean
120     */
121     var $_useTLS = true;
122
123     /**
124     * Additional options for stream_context_create()
125     * @var array
126     */
127     var $_options = null;
128
129     /**
130     * The auth methods this class support
131     * @var array
132     */
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');
136
137     //var $supportedAuthMethods=array( 'PLAIN' , 'LOGIN');
138
139     /**
140     * The auth methods this class support
141     * @var array
142     */
143     var $supportedSASLAuthMethods=array('DIGEST-MD5', 'CRAM-MD5');
144
145     /**
146     * Handles posible referral loops
147     * @var array
148     */
149     var $_maxReferralCount = 15;
150
151     /**
152     * Constructor
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.
156     *
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
164                                   is already open.
165     * @param  boolean $useTLS Use TLS if available
166     * @param  array  $options   options for stream_context_create()
167     */
168     function Net_Sieve($user = null , $pass  = null , $host = 'localhost', $port = 2000, $logintype = '', $euser = '', $debug = false, $bypassAuth = false, $useTLS = true, $options = null)
169     {
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;
182         /*
183         * Include the Auth_SASL package.  If the package is not available,
184         * we disable the authentication methods that depend upon it.
185         */
186         if ((@include_once 'Auth/SASL.php') === false) {
187             if($this->_debug){
188                 echo "AUTH_SASL NOT PRESENT!\n";
189             }
190             foreach($this->supportedSASLAuthMethods as $SASLMethod){
191                 $pos = array_search( $SASLMethod, $this->supportedAuthMethods );
192                 if($this->_debug){
193                     echo "DISABLING METHOD $SASLMethod\n";
194                 }
195                 unset($this->supportedAuthMethods[$pos]);
196             }
197         }
198         if( ($user != null) && ($pass != null) ){
199             $this->_error = $this->_handleConnectAndLogin();
200         }
201     }
202
203     /**
204     * Handles the errors the class can find
205     * on the server
206     *
207     * @access private
208     * @param mixed $msg  Text error message or PEAR error object
209     * @param integer $code  Numeric error code
210     * @return PEAR_Error
211     */
212     function _raiseError($msg, $code)
213     {
214         include_once 'PEAR.php';
215         return PEAR::raiseError($msg, $code);
216     }
217
218     /**
219     * Handles connect and login.
220     * on the server
221     *
222     * @access private
223     * @return mixed Indexed array of scriptnames or PEAR_Error on failure
224     */
225     function _handleConnectAndLogin()
226     {
227         if (PEAR::isError($res = $this->connect($this->_data['host'] , $this->_data['port'], $this->_options, $this->_useTLS ))) {
228             return $res;
229         }
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) ) ) {
232                 return $res;
233             }
234         }
235         return true;
236     }
237
238     /**
239     * Returns an indexed array of scripts currently
240     * on the server
241     *
242     * @return mixed Indexed array of scriptnames or PEAR_Error on failure
243     */
244     function listScripts()
245     {
246         if (is_array($scripts = $this->_cmdListScripts())) {
247             $this->_active = $scripts[1];
248             return $scripts[0];
249         } else {
250             return $scripts;
251         }
252     }
253
254     /**
255     * Returns the active script
256     *
257     * @return mixed The active scriptname or PEAR_Error on failure
258     */
259     function getActive()
260     {
261         if (!empty($this->_active)) {
262             return $this->_active;
263
264         } elseif (is_array($scripts = $this->_cmdListScripts())) {
265             $this->_active = $scripts[1];
266             return $scripts[1];
267         }
268     }
269
270     /**
271     * Sets the active script
272     *
273     * @param  string $scriptname The name of the script to be set as active
274     * @return mixed              true on success, PEAR_Error on failure
275     */
276     function setActive($scriptname)
277     {
278         return $this->_cmdSetActive($scriptname);
279     }
280
281     /**
282     * Retrieves a script
283     *
284     * @param  string $scriptname The name of the script to be retrieved
285     * @return mixed              The script on success, PEAR_Error on failure
286     */
287     function getScript($scriptname)
288     {
289         return $this->_cmdGetScript($scriptname);
290     }
291
292     /**
293     * Adds a script to the server
294     *
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
299     */
300     function installScript($scriptname, $script, $makeactive = false)
301     {
302         if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
303             return $res;
304
305         } elseif ($makeactive) {
306             return $this->_cmdSetActive($scriptname);
307
308         } else {
309             return true;
310         }
311     }
312
313     /**
314     * Removes a script from the server
315     *
316     * @param  string $scriptname Name of the script
317     * @return mixed              True on success, PEAR_Error on failure
318     */
319     function removeScript($scriptname)
320     {
321         return $this->_cmdDeleteScript($scriptname);
322     }
323
324     /**
325     * Returns any error that may have been generated in the
326     * constructor
327     *
328     * @return mixed False if no error, PEAR_Error otherwise
329     */
330     function getError()
331     {
332         return PEAR::isError($this->_error) ? $this->_error : false;
333     }
334
335     /**
336     * Handles connecting to the server and checking the
337     * response is valid.
338     *
339     * @access private
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
345     */
346     function connect($host, $port, $options = null, $useTLS = true)
347     {
348         if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
349             $msg='Not currently in DISCONNECTED state';
350             $code=1;
351             return $this->_raiseError($msg,$code);
352         }
353
354         if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
355             return $res;
356         }
357
358         if($this->_bypassAuth === false) {
359             $this->_state = NET_SIEVE_STATE_AUTHORISATION;
360             if (PEAR::isError($res = $this->_doCmd())) {
361                 return $res;
362             }
363         } else {
364             $this->_state = NET_SIEVE_STATE_TRANSACTION;
365         }
366
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();
371             $code=2;
372             return $this->_raiseError($msg,$code);
373         }
374
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())) {
379                     return $res;
380                 }
381             }
382         }
383
384         return true;
385     }
386
387     /**
388     * Logs into server.
389     *
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
396     */
397     function login($user, $pass, $logintype = null , $euser = '', $bypassAuth = false)
398     {
399         if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
400             $msg='Not currently in AUTHORISATION state';
401             $code=1;
402             return $this->_raiseError($msg,$code);
403         }
404
405         if( $bypassAuth === false ){
406             if(PEAR::isError($res=$this->_cmdAuthenticate($user , $pass , $logintype, $euser ) ) ){
407                 return $res;
408             }
409         }
410         $this->_state = NET_SIEVE_STATE_TRANSACTION;
411         return true;
412     }
413
414     /**
415      * Handles the authentication using any known method
416      *
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.
421      *
422      * @return mixed  string or PEAR_Error
423      *
424      * @access private
425      * @since  1.0
426      */
427     function _cmdAuthenticate($uid , $pwd , $userMethod = null , $euser = '' )
428     {
429         if ( PEAR::isError( $method = $this->_getBestAuthMethod($userMethod) ) ) {
430             return $method;
431         }
432         switch ($method) {
433             case 'DIGEST-MD5':
434                 $result = $this->_authDigest_MD5( $uid , $pwd , $euser );
435                 return $result;
436                 break;
437             case 'CRAM-MD5':
438                 $result = $this->_authCRAM_MD5( $uid , $pwd, $euser);
439                 break;
440             case 'LOGIN':
441                 $result = $this->_authLOGIN( $uid , $pwd , $euser );
442                 break;
443             case 'PLAIN':
444                 $result = $this->_authPLAIN( $uid , $pwd , $euser );
445                 break;
446             case 'EXTERNAL':
447                 $result = $this->_authEXTERNAL( $uid , $pwd , $euser );
448                 break;
449             default :
450                 $result = new PEAR_Error( "$method is not a supported authentication method" );
451                 break;
452         }
453
454         if (PEAR::isError($res = $this->_doCmd() )) {
455             return $res;
456         }
457         return $result;
458     }
459
460     /**
461      * Authenticates the user using the PLAIN method.
462      *
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.
466      *
467      * @return array Returns an array containing the response
468      *
469      * @access private
470      * @since  1.0
471      */
472     function _authPLAIN($user, $pass , $euser )
473     {
474         if ($euser != '') {
475             $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode($euser . chr(0) . $user . chr(0) . $pass ) ) ;
476         } else {
477             $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode( chr(0) . $user . chr(0) . $pass ) );
478         }
479         return  $this->_sendCmd( $cmd ) ;
480     }
481
482     /**
483      * Authenticates the user using the PLAIN method.
484      *
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.
488      *
489      * @return array Returns an array containing the response
490      *
491      * @access private
492      * @since  1.0
493      */
494     function _authLOGIN($user, $pass , $euser )
495     {
496         $this->_sendCmd('AUTHENTICATE "LOGIN"');
497         $this->_doCmd(sprintf('"%s"', base64_encode($user)));
498         $this->_doCmd(sprintf('"%s"', base64_encode($pass)));
499     }
500
501     /**
502      * Authenticates the user using the CRAM-MD5 method.
503      *
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.
507      *
508      * @return array Returns an array containing the response
509      *
510      * @access private
511      * @since  1.0
512      */
513     function _authCRAM_MD5($uid, $pwd, $euser)
514     {
515         if ( PEAR::isError( $challenge = $this->_doCmd( 'AUTHENTICATE "CRAM-MD5"' ) ) ) {
516             $this->_error=$challenge;
517             return $challenge;
518         }
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 ) ) ) {
523             $this->_error=$resp;
524             return $resp;
525         }
526         $auth_str = base64_encode( $resp );
527         if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str  ) ) ) {
528             $this->_error=$error;
529             return $error;
530         }
531
532     }
533
534     /**
535      * Authenticates the user using the DIGEST-MD5 method.
536      *
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.
540      *
541      * @return array Returns an array containing the response
542      *
543      * @access private
544      * @since  1.0
545      */
546     function _authDigest_MD5($uid, $pwd, $euser)
547     {
548         if ( PEAR::isError( $challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"') ) ) {
549             $this->_error= $challenge;
550             return $challenge;
551         }
552         $challenge = base64_decode( $challenge );
553         $digest = &Auth_SASL::factory('digestmd5');
554
555         if(PEAR::isError($param=$digest->getResponse($uid, $pwd, $challenge, "localhost", "sieve" , $euser) )) {
556             return $param;
557         }
558         $auth_str = base64_encode($param);
559
560         if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str  ) ) ) {
561             $this->_error=$error;
562             return $error;
563         }
564
565         if ( PEAR::isError( $challenge = $this->_doCmd() ) ) {
566             $this->_error=$challenge ;
567             return $challenge ;
568         }
569
570         if( strtoupper(substr($challenge,0,2))== 'OK' ){
571                 return true;
572         }
573
574         /**
575         * We don't use the protocol's third step because SIEVE doesn't allow
576         * subsequent authentication, so we just silently ignore it.
577         */
578         if ( PEAR::isError($error = $this->_sendStringResponse( '' ) ) ) {
579             $this->_error=$error;
580             return $error;
581         }
582
583         if (PEAR::isError($res = $this->_doCmd() )) {
584             return $res;
585         }
586     }
587
588      /**
589      * Authenticates the user using the EXTERNAL method.
590      *
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.
594      *
595      * @return array Returns an array containing the response
596      *
597      * @access private
598      * @since  1.1.7
599      */
600     function _authEXTERNAL($user, $pass, $euser)
601     {
602         if ($euser != '') {
603             $cmd=sprintf('AUTHENTICATE "EXTERNAL" "%s"', base64_encode($euser) ) ;
604         } else {
605             $cmd=sprintf('AUTHENTICATE "EXTERNAL" "%s"', base64_encode($user) );
606         }
607         return $this->_sendCmd( $cmd ) ;
608     }
609
610     /**
611     * Removes a script from the server
612     *
613     * @access private
614     * @param  string $scriptname Name of the script to delete
615     * @return mixed              True on success, PEAR_Error otherwise
616     */
617     function _cmdDeleteScript($scriptname)
618     {
619         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
620             $msg='Not currently in AUTHORISATION state';
621             $code=1;
622             return $this->_raiseError($msg,$code);
623         }
624         if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname) ) )) {
625             return $res;
626         }
627         return true;
628     }
629
630     /**
631     * Retrieves the contents of the named script
632     *
633     * @access private
634     * @param  string $scriptname Name of the script to retrieve
635     * @return mixed              The script if successful, PEAR_Error otherwise
636     */
637     function _cmdGetScript($scriptname)
638     {
639         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
640             $msg='Not currently in AUTHORISATION state';
641             $code=1;
642             return $this->_raiseError($msg,$code);
643         }
644
645         if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname) ) ) ) {
646             return $res;
647         }
648
649         return preg_replace('/{[0-9]+}\r\n/', '', $res);
650     }
651
652     /**
653     * Sets the ACTIVE script, ie the one that gets run on new mail
654     * by the server
655     *
656     * @access private
657     * @param  string $scriptname The name of the script to mark as active
658     * @return mixed              True on success, PEAR_Error otherwise
659     */
660     function _cmdSetActive($scriptname)
661     {
662         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
663             $msg='Not currently in AUTHORISATION state';
664             $code=1;
665             return $this->_raiseError($msg,$code);
666         }
667
668         if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname) ) ) ) {
669             return $res;
670         }
671
672         $this->_activeScript = $scriptname;
673         return true;
674     }
675
676     /**
677     * Sends the LISTSCRIPTS command
678     *
679     * @access private
680     * @return mixed Two item array of scripts, and active script on success,
681     *               PEAR_Error otherwise.
682     */
683     function _cmdListScripts()
684     {
685         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
686             $msg='Not currently in AUTHORISATION state';
687             $code=1;
688             return $this->_raiseError($msg,$code);
689         }
690
691         $scripts = array();
692         $activescript = null;
693
694         if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
695             return $res;
696         }
697
698         $res = explode("\r\n", $res);
699
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];
705                 }
706             }
707         }
708
709         return array($scripts, $activescript);
710     }
711
712     /**
713     * Sends the PUTSCRIPT command to add a script to
714     * the server.
715     *
716     * @access private
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
720     */
721     function _cmdPutScript($scriptname, $scriptdata)
722     {
723         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
724             $msg='Not currently in TRANSACTION state';
725             $code=1;
726             return $this->_raiseError($msg,$code);
727         }
728
729         $stringLength = $this->_getLineLength($scriptdata);
730
731         if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata) ))) {
732             return $res;
733         }
734
735         return true;
736     }
737
738     /**
739     * Sends the LOGOUT command and terminates the connection
740     *
741     * @access private
742     * @param boolean $sendLogoutCMD True to send LOGOUT command before disconnecting
743     * @return mixed True on success, PEAR_Error otherwise
744     */
745     function _cmdLogout($sendLogoutCMD=true)
746     {
747         if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
748             $msg='Not currently connected';
749             $code=1;
750             return $this->_raiseError($msg,$code);
751             //return PEAR::raiseError('Not currently connected');
752         }
753
754         if($sendLogoutCMD){
755             if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
756                 return $res;
757             }
758         }
759
760         $this->_sock->disconnect();
761         $this->_state = NET_SIEVE_STATE_DISCONNECTED;
762         return true;
763     }
764
765     /**
766     * Sends the CAPABILITY command
767     *
768     * @access private
769     * @return mixed True on success, PEAR_Error otherwise
770     */
771     function _cmdCapability()
772     {
773         if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
774             $msg='Not currently connected';
775             $code=1;
776             return $this->_raiseError($msg,$code);
777         }
778
779         if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
780             return $res;
781         }
782         $this->_parseCapability($res);
783         return true;
784     }
785
786     /**
787     * Checks if the server has space to store the script
788     * by the server
789     *
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
793     */
794     function haveSpace($scriptname,$size)
795     {
796         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
797             $msg='Not currently in TRANSACTION state';
798             $code=1;
799             return $this->_raiseError($msg,$code);
800         }
801
802         if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %d', $scriptname, $size) ) ) ) {
803             return $res;
804         }
805
806         return true;
807     }
808
809     /**
810     * Parses the response from the capability command. Stores
811     * the result in $this->_capability
812     *
813     * @access private
814     * @param string $data The response from the capability command
815     */
816     function _parseCapability($data)
817     {
818         // clear the cached capabilities
819         $this->_capability = array();
820
821         $data = preg_split('/\r?\n/', $data, -1, PREG_SPLIT_NO_EMPTY);
822
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];
828                         break;
829
830                     case 'sasl':
831                         $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
832                         break;
833
834                     case 'sieve':
835                         $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
836                         break;
837
838                     case 'starttls':
839                         $this->_capability['starttls'] = true;
840                         break;
841                 }
842             }
843         }
844     }
845
846     /**
847     * Sends a command to the server
848     *
849     * @access private
850     * @param string $cmd The command to send
851     */
852     function _sendCmd($cmd)
853     {
854         $status = $this->_sock->getStatus();
855         if (PEAR::isError($status) || $status['eof']) {
856             return new PEAR_Error( 'Failed to write to socket: (connection lost!) ' );
857         }
858         if ( PEAR::isError( $error = $this->_sock->write( $cmd . "\r\n" ) ) ) {
859             return new PEAR_Error( 'Failed to write to socket: ' . $error->getMessage() );
860         }
861
862         if( $this->_debug ){
863             // C: means this data was sent by  the client (this class)
864             echo "C:$cmd\n";
865         }
866         return true;
867     }
868
869     /**
870     * Sends a string response to the server
871     *
872     * @access private
873     * @param string $cmd The command to send
874     */
875     function _sendStringResponse($str)
876     {
877         $response='{' .  $this->_getLineLength($str) . "+}\r\n" . $str  ;
878         return $this->_sendCmd($response);
879     }
880
881     function _recvLn()
882     {
883         $lastline='';
884         if (PEAR::isError( $lastline = $this->_sock->gets( 8192 ) ) ) {
885             return new PEAR_Error( 'Failed to write to socket: ' . $lastline->getMessage() );
886         }
887         $lastline=rtrim($lastline);
888         if($this->_debug){
889             // S: means this data was sent by  the IMAP Server
890             echo "S:$lastline\n" ;
891         }
892
893         if( $lastline === '' ) {
894             return new PEAR_Error( 'Failed to receive from the socket' );
895         }
896
897         return $lastline;
898     }
899
900     /**
901     * Send a command and retrieves a response from the server.
902     *
903     *
904     * @access private
905     * @param string $cmd The command to send
906     * @return mixed Reponse string if an OK response, PEAR_Error if a NO response
907     */
908     function _doCmd($cmd = '' )
909     {
910         $referralCount=0;
911         while($referralCount < $this->_maxReferralCount ){
912
913             if($cmd != '' ){
914                 if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
915                     return $error;
916                 }
917             }
918             $response = '';
919
920             while (true) {
921                     if(PEAR::isError( $line=$this->_recvLn() )){
922                         return $line;
923                     }
924                     if ('ok' === strtolower(substr($line, 0, 2))) {
925                         $response .= $line;
926                         return rtrim($response);
927
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 ));
932                             if($this->_debug){
933                                 echo "S:$line\n";
934                             }
935                         }
936                         $msg=trim($response . substr($line, 2));
937                         $code=3;
938                         return $this->_raiseError($msg,$code);
939                     } elseif ('bye' === strtolower(substr($line, 0, 3))) {
940
941                         if(PEAR::isError($error = $this->disconnect(false) ) ){
942                             $msg="Can't handle bye, The error was= " . $error->getMessage() ;
943                             $code=4;
944                             return $this->_raiseError($msg,$code);
945                         }
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() ;
953                                 $code=5;
954                                 return $this->_raiseError($msg,$code);
955                             }
956                             break;
957                             // Retry the command
958                             if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
959                                 return $error;
960                             }
961                             continue;
962                         }
963                         $msg=trim($response . $line);
964                         $code=6;
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;
970                         $line = '';
971                         $line_length = 0;
972                         while ($line_length < $str_size) {
973                             $line .= $this->_sock->read($str_size - $line_length);
974                             $line_length = $this->_getLineLength($line);
975                         }
976                         if($this->_debug){
977                             echo "S:$line\n";
978                         }
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
982                             // OK.
983                             $this->_recvLn();
984                         }
985                         return $line;
986                     }
987                     $response .= $line . "\r\n";
988                     $referralCount++;
989                 }
990         }
991         $msg="Max referral count reached ($referralCount times) Cyrus murder loop error?";
992         $code=7;
993         return $this->_raiseError($msg,$code);
994     }
995
996     /**
997     * Sets the debug state
998     *
999     * @param boolean $debug
1000     * @return void
1001     */
1002     function setDebug($debug = true)
1003     {
1004         $this->_debug = $debug;
1005     }
1006
1007     /**
1008     * Disconnect from the Sieve server
1009     *
1010     * @param  string $scriptname The name of the script to be set as active
1011     * @return mixed              true on success, PEAR_Error on failure
1012     */
1013     function disconnect($sendLogoutCMD=true)
1014     {
1015         return $this->_cmdLogout($sendLogoutCMD);
1016     }
1017
1018     /**
1019      * Returns the name of the best authentication method that the server
1020      * has advertised.
1021      *
1022      * @param string if !=null,authenticate with this method ($userMethod).
1023      *
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.
1027      * @access private
1028      * @since  1.0
1029      */
1030     function _getBestAuthMethod($userMethod = null)
1031     {
1032        if( isset($this->_capability['sasl']) ){
1033            $serverMethods=$this->_capability['sasl'];
1034        }else{
1035            // if the server don't send an sasl capability fallback to login auth
1036            //return 'LOGIN';
1037            return new PEAR_Error("This server don't support any Auth methods SASL problem?");
1038        }
1039
1040         if($userMethod != null ){
1041             $methods = array();
1042             $methods[] = $userMethod;
1043         }else{
1044
1045             $methods = $this->supportedAuthMethods;
1046         }
1047         if( ($methods != null) && ($serverMethods != null)){
1048             foreach ( $methods as $method ) {
1049                 if ( in_array( $method , $serverMethods ) ) {
1050                     return $method;
1051                 }
1052             }
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");
1057         }else{
1058             return new PEAR_Error("This server don't support any Auth methods");
1059         }
1060     }
1061
1062     /**
1063     * Return the list of extensions the server supports
1064     *
1065     * @return mixed              array  on success, PEAR_Error on failure
1066     */
1067     function getExtensions()
1068     {
1069         if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1070             $msg='Not currently connected';
1071             $code=7;
1072             return $this->_raiseError($msg,$code);
1073         }
1074
1075         return $this->_capability['extensions'];
1076     }
1077
1078     /**
1079     * Return true if tyhe server has that extension
1080     *
1081     * @param string  the extension to compare
1082     * @return mixed              array  on success, PEAR_Error on failure
1083     */
1084     function hasExtension($extension)
1085     {
1086         if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1087             $msg='Not currently connected';
1088             $code=7;
1089             return $this->_raiseError($msg,$code);
1090         }
1091
1092         if(is_array($this->_capability['extensions'] ) ){
1093             foreach( $this->_capability['extensions'] as $ext){
1094                 if( trim( strtolower( $ext ) ) === trim( strtolower( $extension ) ) )
1095                     return true;
1096             }
1097         }
1098         return false;
1099     }
1100
1101     /**
1102     * Return the list of auth methods the server supports
1103     *
1104     * @return mixed              array  on success, PEAR_Error on failure
1105     */
1106     function getAuthMechs()
1107     {
1108         if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1109             $msg='Not currently connected';
1110             $code=7;
1111             return $this->_raiseError($msg,$code);
1112         }
1113         if(!isset($this->_capability['sasl']) ){
1114             $this->_capability['sasl']=array();
1115         }
1116         return $this->_capability['sasl'];
1117     }
1118
1119     /**
1120     * Return true if the server has that extension
1121     *
1122     * @param string  the extension to compare
1123     * @return mixed              array  on success, PEAR_Error on failure
1124     */
1125     function hasAuthMech($method)
1126     {
1127         if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1128             $msg='Not currently connected';
1129             $code=7;
1130             return $this->_raiseError($msg,$code);
1131             //return PEAR::raiseError('Not currently connected');
1132         }
1133
1134         if(is_array($this->_capability['sasl'] ) ){
1135             foreach( $this->_capability['sasl'] as $ext){
1136                 if( trim( strtolower( $ext ) ) === trim( strtolower( $method ) ) )
1137                     return true;
1138             }
1139         }
1140         return false;
1141     }
1142
1143     /**
1144     * Return true if the TLS negotiation was successful
1145     *
1146     * @access private
1147     * @return mixed              true on success, PEAR_Error on failure
1148     */
1149     function _startTLS()
1150     {
1151         if (PEAR::isError($res = $this->_doCmd("STARTTLS"))) {
1152             return $res;
1153         }
1154
1155         if(stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) == false) {
1156             $msg='Failed to establish TLS connection';
1157             $code=2;
1158             return $this->_raiseError($msg,$code);
1159         }
1160
1161         if($this->_debug === true) {
1162             echo "STARTTLS Negotiation Successful\n";
1163         }
1164
1165         // The server should be sending a CAPABILITY response after
1166         // negotiating TLS. Read it, and ignore if it doesn't.
1167         $this->_doCmd();
1168
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();
1173             $code=2;
1174             return $this->_raiseError($msg,$code);
1175         }
1176
1177         return true;
1178     }
1179
1180     function _getLineLength($string) {
1181         if (extension_loaded('mbstring') || @dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX)) {
1182           return mb_strlen($string,'latin1');
1183         } else {
1184           return strlen($string);
1185         }
1186     }
1187 }
1188 ?>