From ac67db19802abd7d2a18c1bb804c3bfd887e9bdf Mon Sep 17 00:00:00 2001
From: alecpl <alec@alec.pl>
Date: Mon, 02 Nov 2009 02:41:21 -0500
Subject: [PATCH] - Managesieve 2.0: multi-script support

---
 plugins/managesieve/localization/et_EE.inc                   |    2 
 plugins/managesieve/localization/fr_FR.inc                   |    2 
 plugins/managesieve/localization/sl_SI.inc                   |    2 
 plugins/managesieve/localization/uk_UA.inc                   |    2 
 plugins/managesieve/localization/zh_CN.inc                   |    2 
 plugins/managesieve/localization/en_US.inc                   |   23 
 plugins/managesieve/skins/default/managesieve_toolbar.png    |    0 
 plugins/managesieve/managesieve.php                          |  233 ++++
 plugins/managesieve/skins/default/managesieve.css            |  108 ++
 plugins/managesieve/localization/es_ES.inc                   |    2 
 plugins/managesieve/localization/fi_FI.inc                   |    2 
 plugins/managesieve/localization/bg_BG.inc                   |    2 
 plugins/managesieve/config.inc.php.dist                      |    3 
 plugins/managesieve/skins/default/templates/filteredit.html  |    2 
 plugins/managesieve/localization/de_CH.inc                   |    2 
 plugins/managesieve/localization/en_GB.inc                   |    2 
 plugins/managesieve/localization/nl_NL.inc                   |    2 
 plugins/managesieve/skins/default/templates/setedit.html     |   24 
 plugins/managesieve/localization/it_IT.inc                   |    2 
 plugins/managesieve/localization/pt_BR.inc                   |    2 
 CHANGELOG                                                    |    1 
 plugins/managesieve/skins/default/templates/managesieve.html |   18 
 plugins/managesieve/localization/pl_PL.inc                   |   21 
 plugins/managesieve/localization/cs_CZ.inc                   |    2 
 plugins/managesieve/localization/hu_HU.inc                   |    2 
 plugins/managesieve/localization/ru_RU.inc                   |    6 
 plugins/managesieve/Changelog                                |    7 
 plugins/managesieve/lib/Net/Sieve.php                        | 1610 +++++++++++++++++++------------------
 /dev/null                                                    |    0 
 plugins/managesieve/lib/rcube_sieve.php                      |  307 +++++--
 plugins/managesieve/localization/de_DE.inc                   |    2 
 plugins/managesieve/localization/sv_SE.inc                   |    2 
 plugins/managesieve/managesieve.js                           |   90 ++
 33 files changed, 1,527 insertions(+), 960 deletions(-)

diff --git a/CHANGELOG b/CHANGELOG
index 4ec48fc..d64b18a 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,6 +1,7 @@
 CHANGELOG RoundCube Webmail
 ===========================
 
+- Managesieve 2.0: multi-script support
 - Fix imap_auth_type regression (#1486263)
 
 RELEASE 0.3.1
diff --git a/plugins/managesieve/Changelog b/plugins/managesieve/Changelog
index d5abbb2..2b46e9f 100644
--- a/plugins/managesieve/Changelog
+++ b/plugins/managesieve/Changelog
@@ -1,3 +1,10 @@
+* version 2.0 [2009-11-02]
+-----------------------------------------------------------
+- Added 'managesieve_debug' option
+- Added multi-script support
+- Small css improvements + sprite image buttons
+- PEAR::NetSieve 1.2.0b1
+
 * version 1.7 [2009-09-20]
 -----------------------------------------------------------
 - Support multiple managesieve hosts using %h variable
diff --git a/plugins/managesieve/config.inc.php.dist b/plugins/managesieve/config.inc.php.dist
index c9ea44e..e50c091 100644
--- a/plugins/managesieve/config.inc.php.dist
+++ b/plugins/managesieve/config.inc.php.dist
@@ -31,4 +31,7 @@
 // Note: not all extensions are implemented
 $rcmail_config['managesieve_disabled_extensions'] = array();
 
+// Enables debugging of conversation with sieve server. Logs it into <log_dir>/sieve
+$rcmail_config['managesieve_debug'] = false;
+
 ?>
diff --git a/plugins/managesieve/lib/Net/Sieve.php b/plugins/managesieve/lib/Net/Sieve.php
index 072905d..be52540 100644
--- a/plugins/managesieve/lib/Net/Sieve.php
+++ b/plugins/managesieve/lib/Net/Sieve.php
@@ -1,234 +1,280 @@
 <?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2003, Richard Heyes                                |
-// | Copyright (c) 2006,2008 Anish Mistry                                  |
-// | All rights reserved.                                                  |
-// |                                                                       |
-// | Redistribution and use in source and binary forms, with or without    |
-// | modification, are permitted provided that the following conditions    |
-// | are met:                                                              |
-// |                                                                       |
-// | o Redistributions of source code must retain the above copyright      |
-// |   notice, this list of conditions and the following disclaimer.       |
-// | o Redistributions in binary form must reproduce the above copyright   |
-// |   notice, this list of conditions and the following disclaimer in the |
-// |   documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote      |
-// |   products derived from this software without specific prior written  |
-// |   permission.                                                         |
-// |                                                                       |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
-// |                                                                       |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard@phpguru.org>                           |
-// | Co-Author: Damian Fernandez Sosa <damlists@cnba.uba.ar>               |
-// | Co-Author: Anish Mistry <amistry@am-productions.biz>                  |
-// +-----------------------------------------------------------------------+
+/**
+ * This file contains the Net_Sieve class.
+ *
+ * PHP version 4
+ *
+ * +-----------------------------------------------------------------------+
+ * | All rights reserved.                                                  |
+ * |                                                                       |
+ * | Redistribution and use in source and binary forms, with or without    |
+ * | modification, are permitted provided that the following conditions    |
+ * | are met:                                                              |
+ * |                                                                       |
+ * | o Redistributions of source code must retain the above copyright      |
+ * |   notice, this list of conditions and the following disclaimer.       |
+ * | o Redistributions in binary form must reproduce the above copyright   |
+ * |   notice, this list of conditions and the following disclaimer in the |
+ * |   documentation and/or other materials provided with the distribution.|
+ * |                                                                       |
+ * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
+ * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
+ * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
+ * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
+ * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
+ * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
+ * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
+ * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
+ * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
+ * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
+ * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
+ * +-----------------------------------------------------------------------+
+ *
+ * @category  Networking
+ * @package   Net_Sieve
+ * @author    Richard Heyes <richard@phpguru.org>
+ * @author    Damian Fernandez Sosa <damlists@cnba.uba.ar>
+ * @author    Anish Mistry <amistry@am-productions.biz>
+ * @author    Jan Schneider <jan@horde.org>
+ * @copyright 2002-2003 Richard Heyes
+ * @copyright 2006-2008 Anish Mistry
+ * @license   http://www.opensource.org/licenses/bsd-license.php BSD
+ * @version   SVN: $Id: Sieve.php 289313 2009-10-07 22:26:33Z yunosh $
+ * @link      http://pear.php.net/package/Net_Sieve
+ */
 
-require_once('Net/Socket.php');
+require_once 'PEAR.php';
+require_once 'Net/Socket.php';
 
 /**
-* TODO
-*
-* o supportsAuthMech()
-*/
+ * TODO
+ *
+ * o supportsAuthMech()
+ */
 
 /**
-* Disconnected state
-* @const NET_SIEVE_STATE_DISCONNECTED
-*/
-define('NET_SIEVE_STATE_DISCONNECTED',  1, true);
+ * Disconnected state
+ * @const NET_SIEVE_STATE_DISCONNECTED
+ */
+define('NET_SIEVE_STATE_DISCONNECTED', 1, true);
 
 /**
-* Authorisation state
-* @const NET_SIEVE_STATE_AUTHORISATION
-*/
+ * Authorisation state
+ * @const NET_SIEVE_STATE_AUTHORISATION
+ */
 define('NET_SIEVE_STATE_AUTHORISATION', 2, true);
 
 /**
-* Transaction state
-* @const NET_SIEVE_STATE_TRANSACTION
-*/
-define('NET_SIEVE_STATE_TRANSACTION',   3, true);
+ * Transaction state
+ * @const NET_SIEVE_STATE_TRANSACTION
+ */
+define('NET_SIEVE_STATE_TRANSACTION', 3, true);
+
 
 /**
-* A class for talking to the timsieved server which
-* comes with Cyrus IMAP.
-*
-* SIEVE: RFC3028 http://www.ietf.org/rfc/rfc3028.txt
-* MANAGE-SIEVE: http://www.ietf.org/internet-drafts/draft-martin-managesieve-07.txt
-*
-* @author  Richard Heyes <richard@php.net>
-* @author  Damian Fernandez Sosa <damlists@cnba.uba.ar>
-* @author  Anish Mistry <amistry@am-productions.biz>
-* @access  public
-* @version 1.2.0
-* @package Net_Sieve
-*/
-
+ * A class for talking to the timsieved server which comes with Cyrus IMAP.
+ *
+ * @category  Networking
+ * @package   Net_Sieve
+ * @author    Richard Heyes <richard@phpguru.org>
+ * @author    Damian Fernandez Sosa <damlists@cnba.uba.ar>
+ * @author    Anish Mistry <amistry@am-productions.biz>
+ * @author    Jan Schneider <jan@horde.org>
+ * @copyright 2002-2003 Richard Heyes
+ * @copyright 2006-2008 Anish Mistry
+ * @license   http://www.opensource.org/licenses/bsd-license.php BSD
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/Net_Sieve
+ * @link      http://www.ietf.org/rfc/rfc3028.txt RFC 3028 (Sieve: A Mail
+ *            Filtering Language)
+ * @link      http://tools.ietf.org/html/draft-ietf-sieve-managesieve A
+ *            Protocol for Remotely Managing Sieve Scripts
+ */
 class Net_Sieve
 {
     /**
-    * The socket object
-    * @var object
-    */
+     * The authentication methods this class supports.
+     *
+     * Can be overwritten if having problems with certain methods.
+     *
+     * @var array
+     */
+    var $supportedAuthMethods = array('DIGEST-MD5', 'CRAM-MD5', 'EXTERNAL',
+                                      'PLAIN' , 'LOGIN');
+
+    /**
+     * SASL authentication methods that require Auth_SASL.
+     *
+     * @var array
+     */
+    var $_supportedSASLAuthMethods = array('DIGEST-MD5', 'CRAM-MD5');
+
+    /**
+     * The socket handle.
+     *
+     * @var resource
+     */
     var $_sock;
 
     /**
-    * Info about the connect
-    * @var array
-    */
+     * Parameters and connection information.
+     *
+     * @var array
+     */
     var $_data;
 
     /**
-    * Current state of the connection
-    * @var integer
-    */
+     * Current state of the connection.
+     *
+     * One of the NET_SIEVE_STATE_* constants.
+     *
+     * @var integer
+     */
     var $_state;
 
     /**
-    * Constructor error is any
-    * @var object
-    */
+     * Constructor error.
+     *
+     * @var PEAR_Error
+     */
     var $_error;
 
     /**
-    * To allow class debuging
-    * @var boolean
-    */
+     * Whether to enable debugging.
+     *
+     * @var boolean
+     */
     var $_debug = false;
 
     /**
-    * Allows picking up of an already established connection
-    * @var boolean
-    */
+     * Debug output handler.
+     *
+     * This has to be a valid callback.
+     *
+     * @var string|array
+     */
+    var $_debug_handler = null;
+
+    /**
+     * Whether to pick up an already established connection.
+     *
+     * @var boolean
+     */
     var $_bypassAuth = false;
 
     /**
-    * Whether to use TLS if available
-    * @var boolean
-    */
+     * Whether to use TLS if available.
+     *
+     * @var boolean
+     */
     var $_useTLS = true;
 
     /**
-    * Additional options for stream_context_create()
-    * @var array
-    */
+     * Additional options for stream_context_create().
+     *
+     * @var array
+     */
     var $_options = null;
 
     /**
-    * The auth methods this class support
-    * @var array
-    */
-    var $supportedAuthMethods=array('DIGEST-MD5', 'CRAM-MD5', 'EXTERNAL', 'PLAIN' , 'LOGIN');
-    //if you have problems using DIGEST-MD5 authentication  please comment the line above and uncomment the following line
-    //var $supportedAuthMethods=array( 'CRAM-MD5', 'PLAIN' , 'LOGIN');
-
-    //var $supportedAuthMethods=array( 'PLAIN' , 'LOGIN');
-
-    /**
-    * The auth methods this class support
-    * @var array
-    */
-    var $supportedSASLAuthMethods=array('DIGEST-MD5', 'CRAM-MD5');
-
-    /**
-    * Handles posible referral loops
-    * @var array
-    */
+     * Maximum number of referral loops
+     *
+     * @var array
+     */
     var $_maxReferralCount = 15;
 
     /**
-    * Constructor
-    * Sets up the object, connects to the server and logs in. stores
-    * any generated error in $this->_error, which can be retrieved
-    * using the getError() method.
-    *
-    * @param  string $user      Login username
-    * @param  string $pass      Login password
-    * @param  string $host      Hostname of server
-    * @param  string $port      Port of server
-    * @param  string $logintype Type of login to perform
-    * @param  string $euser     Effective User (if $user=admin, login as $euser)
-    * @param  string $bypassAuth Skip the authentication phase.  Useful if the socket
-                                  is already open.
-    * @param  boolean $useTLS Use TLS if available
-    * @param  array  $options   options for stream_context_create()
-    */
-    function Net_Sieve($user = null , $pass  = null , $host = 'localhost', $port = 2000, $logintype = '', $euser = '', $debug = false, $bypassAuth = false, $useTLS = true, $options = null)
-    {
-        $this->_state = NET_SIEVE_STATE_DISCONNECTED;
-        $this->_data['user'] = $user;
-        $this->_data['pass'] = $pass;
-        $this->_data['host'] = $host;
-        $this->_data['port'] = $port;
+     * Constructor.
+     *
+     * Sets up the object, connects to the server and logs in. Stores any
+     * generated error in $this->_error, which can be retrieved using the
+     * getError() method.
+     *
+     * @param string  $user       Login username.
+     * @param string  $pass       Login password.
+     * @param string  $host       Hostname of server.
+     * @param string  $port       Port of server.
+     * @param string  $logintype  Type of login to perform (see
+     *                            $supportedAuthMethods).
+     * @param string  $euser      Effective user. If authenticating as an
+     *                            administrator, login as this user.
+     * @param boolean $debug      Whether to enable debugging (@see setDebug()).
+     * @param string  $bypassAuth Skip the authentication phase. Useful if the
+     *                            socket is already open.
+     * @param boolean $useTLS     Use TLS if available.
+     * @param array   $options    Additional options for
+     *                            stream_context_create().
+     */
+    function Net_Sieve($user = null, $pass  = null, $host = 'localhost',
+        $port = 2000, $logintype = '', $euser = '', $debug = false,
+        $bypassAuth = false, $useTLS = true, $options = null
+    ) {
+        $this->_state             = NET_SIEVE_STATE_DISCONNECTED;
+        $this->_data['user']      = $user;
+        $this->_data['pass']      = $pass;
+        $this->_data['host']      = $host;
+        $this->_data['port']      = $port;
         $this->_data['logintype'] = $logintype;
-        $this->_data['euser'] = $euser;
-        $this->_sock = &new Net_Socket();
-        $this->_debug = $debug;
-        $this->_bypassAuth = $bypassAuth;
-        $this->_useTLS = $useTLS;
-        $this->_options = $options;
-        /*
-        * Include the Auth_SASL package.  If the package is not available,
-        * we disable the authentication methods that depend upon it.
-        */
+        $this->_data['euser']     = $euser;
+        $this->_sock              = new Net_Socket();
+        $this->_debug             = $debug;
+        $this->_bypassAuth        = $bypassAuth;
+        $this->_useTLS            = $useTLS;
+        $this->_options           = $options;
+
+        /* Try to include the Auth_SASL package.  If the package is not
+         * available, we disable the authentication methods that depend upon
+         * it. */
         if ((@include_once 'Auth/SASL.php') === false) {
-            if($this->_debug){
-                echo "AUTH_SASL NOT PRESENT!\n";
-            }
-            foreach($this->supportedSASLAuthMethods as $SASLMethod){
-                $pos = array_search( $SASLMethod, $this->supportedAuthMethods );
-                if($this->_debug){
-                    echo "DISABLING METHOD $SASLMethod\n";
-                }
+            $this->_debug('Auth_SASL not present');
+            foreach ($this->supportedSASLAuthMethods as $SASLMethod) {
+                $pos = array_search($SASLMethod, $this->supportedAuthMethods);
+                $this->_debug('Disabling method ' . $SASLMethod);
                 unset($this->supportedAuthMethods[$pos]);
             }
         }
-        if( ($user != null) && ($pass != null) ){
+
+        if (strlen($user) && strlen($pass)) {
             $this->_error = $this->_handleConnectAndLogin();
         }
     }
 
     /**
-    * Handles the errors the class can find
-    * on the server
-    *
-    * @access private
-    * @param mixed $msg  Text error message or PEAR error object
-    * @param integer $code  Numeric error code
-    * @return PEAR_Error
-    */
-    function _raiseError($msg, $code)
+     * Returns any error that may have been generated in the constructor.
+     *
+     * @return boolean|PEAR_Error  False if no error, PEAR_Error otherwise.
+     */
+    function getError()
     {
-        include_once 'PEAR.php';
-        return PEAR::raiseError($msg, $code);
+        return PEAR::isError($this->_error) ? $this->_error : false;
     }
 
     /**
-    * Handles connect and login.
-    * on the server
-    *
-    * @access private
-    * @return mixed Indexed array of scriptnames or PEAR_Error on failure
-    */
+     * Sets the debug state and handler function.
+     *
+     * @param boolean $debug   Whether to enable debugging.
+     * @param string  $handler A custom debug handler. Must be a valid callback.
+     *
+     * @return void
+     */
+    function setDebug($debug = true, $handler = null)
+    {
+        $this->_debug = $debug;
+        $this->_debug_handler = $handler;
+    }
+
+    /**
+     * Connects to the server and logs in.
+     *
+     * @return boolean  True on success, PEAR_Error on failure.
+     */
     function _handleConnectAndLogin()
     {
-        if (PEAR::isError($res = $this->connect($this->_data['host'] , $this->_data['port'], $this->_options, $this->_useTLS ))) {
+        if (PEAR::isError($res = $this->connect($this->_data['host'], $this->_data['port'], $this->_options, $this->_useTLS))) {
             return $res;
         }
-        if($this->_bypassAuth === false) {
-           if (PEAR::isError($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'] , $this->_data['euser'] , $this->_bypassAuth) ) ) {
+        if ($this->_bypassAuth === false) {
+            if (PEAR::isError($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'], $this->_data['euser'], $this->_bypassAuth))) {
                 return $res;
             }
         }
@@ -236,11 +282,100 @@
     }
 
     /**
-    * Returns an indexed array of scripts currently
-    * on the server
-    *
-    * @return mixed Indexed array of scriptnames or PEAR_Error on failure
-    */
+     * Handles connecting to the server and checks the response validity.
+     *
+     * @param string  $host    Hostname of server.
+     * @param string  $port    Port of server.
+     * @param array   $options List of options to pass to
+     *                         stream_context_create().
+     * @param boolean $useTLS  Use TLS if available.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
+    function connect($host, $port, $options = null, $useTLS = true)
+    {
+        if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
+            return PEAR::raiseError('Not currently in DISCONNECTED state', 1);
+        }
+
+        if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
+            return $res;
+        }
+
+        if ($this->_bypassAuth) {
+            $this->_state = NET_SIEVE_STATE_TRANSACTION;
+        } else {
+            $this->_state = NET_SIEVE_STATE_AUTHORISATION;
+            if (PEAR::isError($res = $this->_doCmd())) {
+                return $res;
+            }
+        }
+
+        // Explicitly ask for the capabilities in case the connection is
+        // picked up from an existing connection.
+        if (PEAR::isError($res = $this->_cmdCapability())) {
+            return PEAR::raiseError(
+                'Failed to connect, server said: ' . $res->getMessage(), 2
+            );
+        }
+
+        // Check if we can enable TLS via STARTTLS.
+        if ($useTLS && !empty($this->_capability['starttls'])
+            && function_exists('stream_socket_enable_crypto')
+        ) {
+            if (PEAR::isError($res = $this->_startTLS())) {
+                return $res;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Disconnect from the Sieve server.
+     *
+     * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
+     *                               disconnecting.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
+    function disconnect($sendLogoutCMD = true)
+    {
+        return $this->_cmdLogout($sendLogoutCMD);
+    }
+
+    /**
+     * Logs into server.
+     *
+     * @param string  $user       Login username.
+     * @param string  $pass       Login password.
+     * @param string  $logintype  Type of login method to use.
+     * @param string  $euser      Effective UID (perform on behalf of $euser).
+     * @param boolean $bypassAuth Do not perform authentication.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
+    function login($user, $pass, $logintype = null, $euser = '', $bypassAuth = false)
+    {
+        if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
+            return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
+        }
+
+        if (!$bypassAuth ) {
+            if (PEAR::isError($res = $this->_cmdAuthenticate($user, $pass, $logintype, $euser))) {
+                return $res;
+            }
+        }
+        $this->_state = NET_SIEVE_STATE_TRANSACTION;
+
+        return true;
+    }
+
+    /**
+     * Returns an indexed array of scripts currently on the server.
+     *
+     * @return array  Indexed array of scriptnames.
+     */
     function listScripts()
     {
         if (is_array($scripts = $this->_cmdListScripts())) {
@@ -252,37 +387,39 @@
     }
 
     /**
-    * Returns the active script
-    *
-    * @return mixed The active scriptname or PEAR_Error on failure
-    */
+     * Returns the active script.
+     *
+     * @return string  The active scriptname.
+     */
     function getActive()
     {
         if (!empty($this->_active)) {
             return $this->_active;
-
-        } elseif (is_array($scripts = $this->_cmdListScripts())) {
+        }
+        if (is_array($scripts = $this->_cmdListScripts())) {
             $this->_active = $scripts[1];
             return $scripts[1];
         }
     }
 
     /**
-    * Sets the active script
-    *
-    * @param  string $scriptname The name of the script to be set as active
-    * @return mixed              true on success, PEAR_Error on failure
-    */
+     * Sets the active script.
+     *
+     * @param string $scriptname The name of the script to be set as active.
+     *
+     * @return boolean  True on success, PEAR_Error on failure.
+     */
     function setActive($scriptname)
     {
         return $this->_cmdSetActive($scriptname);
     }
 
     /**
-    * Retrieves a script
-    *
-    * @param  string $scriptname The name of the script to be retrieved
-    * @return mixed              The script on success, PEAR_Error on failure
+     * Retrieves a script.
+     *
+     * @param string $scriptname The name of the script to be retrieved.
+     *
+     * @return string  The script on success, PEAR_Error on failure.
     */
     function getScript($scriptname)
     {
@@ -290,359 +427,337 @@
     }
 
     /**
-    * Adds a script to the server
-    *
-    * @param  string $scriptname Name of the script
-    * @param  string $script     The script
-    * @param  boolean $makeactive Whether to make this the active script
-    * @return mixed              true on success, PEAR_Error on failure
-    */
+     * Adds a script to the server.
+     *
+     * @param string  $scriptname Name of the script.
+     * @param string  $script     The script content.
+     * @param boolean $makeactive Whether to make this the active script.
+     *
+     * @return boolean  True on success, PEAR_Error on failure.
+     */
     function installScript($scriptname, $script, $makeactive = false)
     {
         if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
             return $res;
-
-        } elseif ($makeactive) {
-            return $this->_cmdSetActive($scriptname);
-
-        } else {
-            return true;
         }
+        if ($makeactive) {
+            return $this->_cmdSetActive($scriptname);
+        }
+        return true;
     }
 
     /**
-    * Removes a script from the server
-    *
-    * @param  string $scriptname Name of the script
-    * @return mixed              True on success, PEAR_Error on failure
-    */
+     * Removes a script from the server.
+     *
+     * @param string $scriptname Name of the script.
+     *
+     * @return boolean  True on success, PEAR_Error on failure.
+     */
     function removeScript($scriptname)
     {
         return $this->_cmdDeleteScript($scriptname);
     }
 
     /**
-    * Returns any error that may have been generated in the
-    * constructor
-    *
-    * @return mixed False if no error, PEAR_Error otherwise
-    */
-    function getError()
+     * Checks if the server has space to store the script by the server.
+     *
+     * @param string  $scriptname The name of the script to mark as active.
+     * @param integer $size       The size of the script.
+     *
+     * @return boolean|PEAR_Error  True if there is space, PEAR_Error otherwise.
+     *
+     * @todo Rename to hasSpace()
+     */
+    function haveSpace($scriptname, $size)
     {
-        return PEAR::isError($this->_error) ? $this->_error : false;
+        if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
+            return PEAR::raiseError('Not currently in TRANSACTION state', 1);
+        }
+        if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %d', $scriptname, $size)))) {
+            return $res;
+        }
+        return true;
     }
 
     /**
-    * Handles connecting to the server and checking the
-    * response is valid.
-    *
-    * @access private
-    * @param  string $host Hostname of server
-    * @param  string $port Port of server
-    * @param  array  $options List of options to pass to connect
-    * @param  boolean $useTLS Use TLS if available
-    * @return mixed        True on success, PEAR_Error otherwise
-    */
-    function connect($host, $port, $options = null, $useTLS = true)
+     * Returns the list of extensions the server supports.
+     *
+     * @return array  List of extensions or PEAR_Error on failure.
+     */
+    function getExtensions()
     {
-        if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
-            $msg='Not currently in DISCONNECTED state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+        if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
+            return PEAR::raiseError('Not currently connected', 7);
+        }
+        return $this->_capability['extensions'];
+    }
+
+    /**
+     * Returns whether the server supports an extension.
+     *
+     * @param string $extension The extension to check.
+     *
+     * @return boolean  Whether the extension is supported or PEAR_Error on
+     *                  failure.
+     */
+    function hasExtension($extension)
+    {
+        if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
+            return PEAR::raiseError('Not currently connected', 7);
         }
 
-        if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
-            return $res;
-        }
-
-        if($this->_bypassAuth === false) {
-            $this->_state = NET_SIEVE_STATE_AUTHORISATION;
-            if (PEAR::isError($res = $this->_doCmd())) {
-                return $res;
-            }
-        } else {
-            $this->_state = NET_SIEVE_STATE_TRANSACTION;
-        }
-
-        // Explicitly ask for the capabilities in case the connection
-        // is picked up from an existing connection.
-        if(PEAR::isError($res = $this->_cmdCapability() )) {
-            $msg='Failed to connect, server said: ' . $res->getMessage();
-            $code=2;
-            return $this->_raiseError($msg,$code);
-        }
-
-        if($useTLS === true) {
-            // check if we can enable TLS via STARTTLS
-            if(isset($this->_capability['starttls']) && function_exists('stream_socket_enable_crypto') === true) {
-                if (PEAR::isError($res = $this->_startTLS())) {
-                    return $res;
+        $extension = trim($this->_toUpper($extension));
+        if (is_array($this->_capability['extensions'])) {
+            foreach ($this->_capability['extensions'] as $ext) {
+                if ($ext == $extension) {
+                    return true;
                 }
             }
         }
 
-        return true;
+        return false;
     }
 
     /**
-    * Logs into server.
-    *
-    * @param  string  $user          Login username
-    * @param  string  $pass          Login password
-    * @param  string  $logintype     Type of login method to use
-    * @param  string  $euser         Effective UID (perform on behalf of $euser)
-    * @param  boolean $bypassAuth    Do not perform authentication
-    * @return mixed                  True on success, PEAR_Error otherwise
-    */
-    function login($user, $pass, $logintype = null , $euser = '', $bypassAuth = false)
+     * Returns the list of authentication methods the server supports.
+     *
+     * @return array  List of authentication methods or PEAR_Error on failure.
+     */
+    function getAuthMechs()
     {
-        if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
-            $msg='Not currently in AUTHORISATION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+        if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
+            return PEAR::raiseError('Not currently connected', 7);
+        }
+        return $this->_capability['sasl'];
+    }
+
+    /**
+     * Returns whether the server supports an authentication method.
+     *
+     * @param string $method The method to check.
+     *
+     * @return boolean  Whether the method is supported or PEAR_Error on
+     *                  failure.
+     */
+    function hasAuthMech($method)
+    {
+        if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
+            return PEAR::raiseError('Not currently connected', 7);
         }
 
-        if( $bypassAuth === false ){
-            if(PEAR::isError($res=$this->_cmdAuthenticate($user , $pass , $logintype, $euser ) ) ){
-                return $res;
+        $method = trim($this->_toUpper($method));
+        if (is_array($this->_capability['sasl'])) {
+            foreach ($this->_capability['sasl'] as $sasl) {
+                if ($sasl == $method) {
+                    return true;
+                }
             }
         }
-        $this->_state = NET_SIEVE_STATE_TRANSACTION;
-        return true;
+
+        return false;
     }
 
     /**
-     * Handles the authentication using any known method
+     * Handles the authentication using any known method.
      *
-     * @param string $uid The userid to authenticate as.
-     * @param string $pwd The password to authenticate with.
-     * @param string $userMethod The method to use ( if $userMethod == '' then the class chooses the best method (the stronger is the best ) )
-     * @param string $euser The effective uid to authenticate as.
+     * @param string $uid        The userid to authenticate as.
+     * @param string $pwd        The password to authenticate with.
+     * @param string $userMethod The method to use. If empty, the class chooses
+     *                           the best (strongest) available method.
+     * @param string $euser      The effective uid to authenticate as.
      *
-     * @return mixed  string or PEAR_Error
-     *
-     * @access private
-     * @since  1.0
+     * @return void
      */
-    function _cmdAuthenticate($uid , $pwd , $userMethod = null , $euser = '' )
+    function _cmdAuthenticate($uid, $pwd, $userMethod = null, $euser = '')
     {
-        if ( PEAR::isError( $method = $this->_getBestAuthMethod($userMethod) ) ) {
+        if (PEAR::isError($method = $this->_getBestAuthMethod($userMethod))) {
             return $method;
         }
         switch ($method) {
-            case 'DIGEST-MD5':
-                $result = $this->_authDigest_MD5( $uid , $pwd , $euser );
-                return $result;
-                break;
-            case 'CRAM-MD5':
-                $result = $this->_authCRAM_MD5( $uid , $pwd, $euser);
-                break;
-            case 'LOGIN':
-                $result = $this->_authLOGIN( $uid , $pwd , $euser );
-                break;
-            case 'PLAIN':
-                $result = $this->_authPLAIN( $uid , $pwd , $euser );
-                break;
-            case 'EXTERNAL':
-                $result = $this->_authEXTERNAL( $uid , $pwd , $euser );
-                break;
-            default :
-                $result = new PEAR_Error( "$method is not a supported authentication method" );
-                break;
+        case 'DIGEST-MD5':
+            return $this->_authDigestMD5($uid, $pwd, $euser);
+        case 'CRAM-MD5':
+            $result = $this->_authCRAMMD5($uid, $pwd, $euser);
+            break;
+        case 'LOGIN':
+            $result = $this->_authLOGIN($uid, $pwd, $euser);
+            break;
+        case 'PLAIN':
+            $result = $this->_authPLAIN($uid, $pwd, $euser);
+            break;
+        case 'EXTERNAL':
+            $result = $this->_authEXTERNAL($uid, $pwd, $euser);
+            break;
+        default :
+            $result = PEAR::raiseError(
+                $method . ' is not a supported authentication method'
+            );
+            break;
         }
 
-        if (PEAR::isError($res = $this->_doCmd() )) {
+        if (PEAR::isError($res = $this->_doCmd())) {
             return $res;
         }
+
         return $result;
     }
 
     /**
      * Authenticates the user using the PLAIN method.
      *
-     * @param string $user The userid to authenticate as.
-     * @param string $pass The password to authenticate with.
+     * @param string $user  The userid to authenticate as.
+     * @param string $pass  The password to authenticate with.
      * @param string $euser The effective uid to authenticate as.
      *
-     * @return array Returns an array containing the response
-     *
-     * @access private
-     * @since  1.0
+     * @return void
      */
-    function _authPLAIN($user, $pass , $euser )
+    function _authPLAIN($user, $pass, $euser)
     {
-        if ($euser != '') {
-            $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode($euser . chr(0) . $user . chr(0) . $pass ) ) ;
-        } else {
-            $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode( chr(0) . $user . chr(0) . $pass ) );
-        }
-        return  $this->_sendCmd( $cmd ) ;
+        return $this->_sendCmd(
+            sprintf(
+                'AUTHENTICATE "PLAIN" "%s"',
+                base64_encode($euser . chr(0) . $user . chr(0) . $pass)
+            )
+        );
     }
 
     /**
-     * Authenticates the user using the PLAIN method.
+     * Authenticates the user using the LOGIN method.
      *
-     * @param string $user The userid to authenticate as.
-     * @param string $pass The password to authenticate with.
+     * @param string $user  The userid to authenticate as.
+     * @param string $pass  The password to authenticate with.
      * @param string $euser The effective uid to authenticate as.
      *
-     * @return array Returns an array containing the response
-     *
-     * @access private
-     * @since  1.0
+     * @return void
      */
-    function _authLOGIN($user, $pass , $euser )
+    function _authLOGIN($user, $pass, $euser)
     {
-        $this->_sendCmd('AUTHENTICATE "LOGIN"');
-        $this->_doCmd(sprintf('"%s"', base64_encode($user)));
-        $this->_doCmd(sprintf('"%s"', base64_encode($pass)));
+        if (PEAR::isError($result = $this->_sendCmd('AUTHENTICATE "LOGIN"'))) {
+            return $result;
+        }
+        if (PEAR::isError($result = $this->_doCmd('"' . base64_encode($user) . '"'))) {
+            return $result;
+        }
+        return $this->_doCmd('"' . base64_encode($pass) . '"');
     }
 
     /**
      * Authenticates the user using the CRAM-MD5 method.
      *
-     * @param string $uid The userid to authenticate as.
-     * @param string $pwd The password to authenticate with.
+     * @param string $user  The userid to authenticate as.
+     * @param string $pass  The password to authenticate with.
      * @param string $euser The effective uid to authenticate as.
      *
-     * @return array Returns an array containing the response
-     *
-     * @access private
-     * @since  1.0
+     * @return void
      */
-    function _authCRAM_MD5($uid, $pwd, $euser)
+    function _authCRAMMD5($user, $pass, $euser)
     {
-        if ( PEAR::isError( $challenge = $this->_doCmd( 'AUTHENTICATE "CRAM-MD5"' ) ) ) {
-            $this->_error=$challenge;
+        if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "CRAM-MD5"', true))) {
             return $challenge;
         }
-        $challenge=trim($challenge);
-        $challenge = base64_decode( trim($challenge) );
-        $cram = &Auth_SASL::factory('crammd5');
-        if ( PEAR::isError($resp=$cram->getResponse( $uid , $pwd , $challenge ) ) ) {
-            $this->_error=$resp;
-            return $resp;
-        }
-        $auth_str = base64_encode( $resp );
-        if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str  ) ) ) {
-            $this->_error=$error;
-            return $error;
+
+        $challenge = base64_decode(trim($challenge));
+        $cram = Auth_SASL::factory('crammd5');
+        if (PEAR::isError($response = $cram->getResponse($user, $pass, $challenge))) {
+            return $response;
         }
 
+        return $this->_sendStringResponse(base64_encode($response));
     }
 
     /**
      * Authenticates the user using the DIGEST-MD5 method.
      *
-     * @param string $uid The userid to authenticate as.
-     * @param string $pwd The password to authenticate with.
+     * @param string $user  The userid to authenticate as.
+     * @param string $pass  The password to authenticate with.
      * @param string $euser The effective uid to authenticate as.
      *
-     * @return array Returns an array containing the response
-     *
-     * @access private
-     * @since  1.0
+     * @return void
      */
-    function _authDigest_MD5($uid, $pwd, $euser)
+    function _authDigestMD5($user, $pass, $euser)
     {
-        if ( PEAR::isError( $challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"') ) ) {
-            $this->_error= $challenge;
+        if (PEAR::isError($challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"', true))) {
             return $challenge;
         }
-        $challenge = base64_decode( $challenge );
-        $digest = &Auth_SASL::factory('digestmd5');
 
-        if(PEAR::isError($param=$digest->getResponse($uid, $pwd, $challenge, "localhost", "sieve" , $euser) )) {
-            return $param;
-        }
-        $auth_str = base64_encode($param);
-
-        if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str  ) ) ) {
-            $this->_error=$error;
-            return $error;
+        $challenge = base64_decode(trim($challenge));
+        $digest = Auth_SASL::factory('digestmd5');
+        // @todo Really 'localhost'?
+        if (PEAR::isError($response = $digest->getResponse($user, $pass, $challenge, 'localhost', 'sieve', $euser))) {
+            return $response;
         }
 
-        if ( PEAR::isError( $challenge = $this->_doCmd() ) ) {
-            $this->_error=$challenge ;
-            return $challenge ;
+        if (PEAR::isError($result = $this->_sendStringResponse(base64_encode($param)))) {
+            return $result;
+        }
+        if (PEAR::isError($result = $this->_doCmd())) {
+            return $result;
+        }
+        if ($this->_toUpper(substr($result, 0, 2)) == 'OK') {
+            return;
         }
 
-        if( strtoupper(substr($challenge,0,2))== 'OK' ){
-                return true;
+        /* We don't use the protocol's third step because SIEVE doesn't allow
+         * subsequent authentication, so we just silently ignore it. */
+        if (PEAR::isError($result = $this->_sendStringResponse(''))) {
+            return $result;
         }
 
-        /**
-        * We don't use the protocol's third step because SIEVE doesn't allow
-        * subsequent authentication, so we just silently ignore it.
-        */
-        if ( PEAR::isError($error = $this->_sendStringResponse( '' ) ) ) {
-            $this->_error=$error;
-            return $error;
-        }
-
-        if (PEAR::isError($res = $this->_doCmd() )) {
-            return $res;
-        }
+        return $this->_doCmd();
     }
 
-     /**
+    /**
      * Authenticates the user using the EXTERNAL method.
      *
-     * @param string $user The userid to authenticate as.
-     * @param string $pass The password to authenticate with.
+     * @param string $user  The userid to authenticate as.
+     * @param string $pass  The password to authenticate with.
      * @param string $euser The effective uid to authenticate as.
      *
-     * @return array Returns an array containing the response
+     * @return void
      *
-     * @access private
      * @since  1.1.7
      */
     function _authEXTERNAL($user, $pass, $euser)
     {
-        if ($euser != '') {
-            $cmd=sprintf('AUTHENTICATE "EXTERNAL" "%s"', base64_encode($euser) ) ;
-        } else {
-            $cmd=sprintf('AUTHENTICATE "EXTERNAL" "%s"', base64_encode($user) );
-        }
-        return $this->_sendCmd( $cmd ) ;
+        $cmd = sprintf(
+            'AUTHENTICATE "EXTERNAL" "%s"',
+            base64_encode(strlen($euser) ? $euser : $user)
+        );
+        return $this->_sendCmd($cmd);
     }
 
     /**
-    * Removes a script from the server
-    *
-    * @access private
-    * @param  string $scriptname Name of the script to delete
-    * @return mixed              True on success, PEAR_Error otherwise
-    */
+     * Removes a script from the server.
+     *
+     * @param string $scriptname Name of the script to delete.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
     function _cmdDeleteScript($scriptname)
     {
         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
-            $msg='Not currently in AUTHORISATION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+            return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
         }
-        if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname) ) )) {
+        if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname)))) {
             return $res;
         }
         return true;
     }
 
     /**
-    * Retrieves the contents of the named script
-    *
-    * @access private
-    * @param  string $scriptname Name of the script to retrieve
-    * @return mixed              The script if successful, PEAR_Error otherwise
-    */
+     * Retrieves the contents of the named script.
+     *
+     * @param string $scriptname Name of the script to retrieve.
+     *
+     * @return string  The script if successful, PEAR_Error otherwise.
+     */
     function _cmdGetScript($scriptname)
     {
         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
-            $msg='Not currently in AUTHORISATION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+            return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
         }
 
-        if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname) ) ) ) {
+        if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname)))) {
             return $res;
         }
 
@@ -650,53 +765,45 @@
     }
 
     /**
-    * Sets the ACTIVE script, ie the one that gets run on new mail
-    * by the server
-    *
-    * @access private
-    * @param  string $scriptname The name of the script to mark as active
-    * @return mixed              True on success, PEAR_Error otherwise
+     * Sets the active script, i.e. the one that gets run on new mail by the
+     * server.
+     *
+     * @param string $scriptname The name of the script to mark as active.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
     */
     function _cmdSetActive($scriptname)
     {
         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
-            $msg='Not currently in AUTHORISATION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+            return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
         }
-
-        if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname) ) ) ) {
+        if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname)))) {
             return $res;
         }
-
         $this->_activeScript = $scriptname;
         return true;
     }
 
     /**
-    * Sends the LISTSCRIPTS command
-    *
-    * @access private
-    * @return mixed Two item array of scripts, and active script on success,
-    *               PEAR_Error otherwise.
-    */
+     * Returns the list of scripts on the server.
+     *
+     * @return array  An array with the list of scripts in the first element
+     *                and the active script in the second element on success,
+     *                PEAR_Error otherwise.
+     */
     function _cmdListScripts()
     {
         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
-            $msg='Not currently in AUTHORISATION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+            return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
         }
-
-        $scripts = array();
-        $activescript = null;
 
         if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
             return $res;
         }
 
+        $scripts = array();
+        $activescript = null;
         $res = explode("\r\n", $res);
-
         foreach ($res as $value) {
             if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
                 $scripts[] = $matches[1];
@@ -710,25 +817,22 @@
     }
 
     /**
-    * Sends the PUTSCRIPT command to add a script to
-    * the server.
-    *
-    * @access private
-    * @param  string $scriptname Name of the new script
-    * @param  string $scriptdata The new script
-    * @return mixed              True on success, PEAR_Error otherwise
-    */
+     * Adds a script to the server.
+     *
+     * @param string $scriptname Name of the new script.
+     * @param string $scriptdata The new script.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
     function _cmdPutScript($scriptname, $scriptdata)
     {
         if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
-            $msg='Not currently in TRANSACTION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+            return PEAR::raiseError('Not currently in AUTHORISATION state', 1);
         }
 
         $stringLength = $this->_getLineLength($scriptdata);
 
-        if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata) ))) {
+        if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata)))) {
             return $res;
         }
 
@@ -736,22 +840,20 @@
     }
 
     /**
-    * Sends the LOGOUT command and terminates the connection
-    *
-    * @access private
-    * @param boolean $sendLogoutCMD True to send LOGOUT command before disconnecting
-    * @return mixed True on success, PEAR_Error otherwise
-    */
-    function _cmdLogout($sendLogoutCMD=true)
+     * Logs out of the server and terminates the connection.
+     *
+     * @param boolean $sendLogoutCMD Whether to send LOGOUT command before
+     *                               disconnecting.
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
+    function _cmdLogout($sendLogoutCMD = true)
     {
-        if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
-            $msg='Not currently connected';
-            $code=1;
-            return $this->_raiseError($msg,$code);
-            //return PEAR::raiseError('Not currently connected');
+        if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
+            return PEAR::raiseError('Not currently connected', 1);
         }
 
-        if($sendLogoutCMD){
+        if ($sendLogoutCMD) {
             if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
                 return $res;
             }
@@ -759,23 +861,20 @@
 
         $this->_sock->disconnect();
         $this->_state = NET_SIEVE_STATE_DISCONNECTED;
+
         return true;
     }
 
     /**
-    * Sends the CAPABILITY command
-    *
-    * @access private
-    * @return mixed True on success, PEAR_Error otherwise
-    */
+     * Sends the CAPABILITY command
+     *
+     * @return boolean  True on success, PEAR_Error otherwise.
+     */
     function _cmdCapability()
     {
-        if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
-            $msg='Not currently connected';
-            $code=1;
-            return $this->_raiseError($msg,$code);
+        if (NET_SIEVE_STATE_DISCONNECTED == $this->_state) {
+            return PEAR::raiseError('Not currently connected', 1);
         }
-
         if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
             return $res;
         }
@@ -784,405 +883,332 @@
     }
 
     /**
-    * Checks if the server has space to store the script
-    * by the server
-    *
-    * @param  string $scriptname The name of the script to mark as active
-    * @param integer $size The size of the script
-    * @return mixed              True on success, PEAR_Error otherwise
-    */
-    function haveSpace($scriptname,$size)
-    {
-        if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
-            $msg='Not currently in TRANSACTION state';
-            $code=1;
-            return $this->_raiseError($msg,$code);
-        }
-
-        if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %d', $scriptname, $size) ) ) ) {
-            return $res;
-        }
-
-        return true;
-    }
-
-    /**
-    * Parses the response from the capability command. Stores
-    * the result in $this->_capability
-    *
-    * @access private
-    * @param string $data The response from the capability command
-    */
+     * Parses the response from the CAPABILITY command and stores the result
+     * in $_capability.
+     *
+     * @param string $data The response from the capability command.
+     *
+     * @return void
+     */
     function _parseCapability($data)
     {
-        // clear the cached capabilities
-        $this->_capability = array();
+        // Clear the cached capabilities.
+        $this->_capability = array('sasl' => array(),
+                                   'extensions' => array());
 
-        $data = preg_split('/\r?\n/', $data, -1, PREG_SPLIT_NO_EMPTY);
+        $data = preg_split('/\r?\n/', $this->_toUpper($data), -1, PREG_SPLIT_NO_EMPTY);
 
         for ($i = 0; $i < count($data); $i++) {
-            if (preg_match('/^"([a-z]+)"( "(.*)")?$/i', $data[$i], $matches)) {
-                switch (strtolower($matches[1])) {
-                    case 'implementation':
-                        $this->_capability['implementation'] = $matches[3];
-                        break;
+            if (!preg_match('/^"([A-Z]+)"( "(.*)")?$/', $data[$i], $matches)) {
+                continue;
+            }
+            switch ($matches[1]) {
+            case 'IMPLEMENTATION':
+                $this->_capability['implementation'] = $matches[3];
+                break;
 
-                    case 'sasl':
-                        $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
-                        break;
+            case 'SASL':
+                $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
+                break;
 
-                    case 'sieve':
-                        $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
-                        break;
+            case 'SIEVE':
+                $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
+                break;
 
-                    case 'starttls':
-                        $this->_capability['starttls'] = true;
-                        break;
-                }
+            case 'STARTTLS':
+                $this->_capability['starttls'] = true;
+                break;
             }
         }
     }
 
     /**
-    * Sends a command to the server
-    *
-    * @access private
-    * @param string $cmd The command to send
-    */
+     * Sends a command to the server
+     *
+     * @param string $cmd The command to send.
+     *
+     * @return void
+     */
     function _sendCmd($cmd)
     {
         $status = $this->_sock->getStatus();
         if (PEAR::isError($status) || $status['eof']) {
-            return new PEAR_Error( 'Failed to write to socket: (connection lost!) ' );
+            return PEAR::raiseError('Failed to write to socket: connection lost');
         }
-        if ( PEAR::isError( $error = $this->_sock->write( $cmd . "\r\n" ) ) ) {
-            return new PEAR_Error( 'Failed to write to socket: ' . $error->getMessage() );
+        if (PEAR::isError($error = $this->_sock->write($cmd . "\r\n"))) {
+            return PEAR::raiseError(
+                'Failed to write to socket: ' . $error->getMessage()
+            );
         }
-
-        if( $this->_debug ){
-            // C: means this data was sent by  the client (this class)
-            echo "C:$cmd\n";
-        }
-        return true;
+        $this->_debug("C: $cmd");
     }
 
     /**
-    * Sends a string response to the server
-    *
-    * @access private
-    * @param string $cmd The command to send
-    */
+     * Sends a string response to the server.
+     *
+     * @param string $str The string to send.
+     *
+     * @return void
+     */
     function _sendStringResponse($str)
     {
-        $response='{' .  $this->_getLineLength($str) . "+}\r\n" . $str  ;
-        return $this->_sendCmd($response);
+        return $this->_sendCmd('{' . $this->_getLineLength($str) . "+}\r\n" . $str);
     }
 
+    /**
+     * Receives a single line from the server.
+     *
+     * @return string  The server response line.
+     */
     function _recvLn()
     {
-        $lastline='';
-        if (PEAR::isError( $lastline = $this->_sock->gets( 8192 ) ) ) {
-            return new PEAR_Error( 'Failed to write to socket: ' . $lastline->getMessage() );
-        }
-        $lastline=rtrim($lastline);
-        if($this->_debug){
-            // S: means this data was sent by  the IMAP Server
-            echo "S:$lastline\n" ;
+        if (PEAR::isError($lastline = $this->_sock->gets(8192))) {
+            return PEAR::raiseError(
+                'Failed to read from socket: ' . $lastline->getMessage()
+            );
         }
 
-        if( $lastline === '' ) {
-            return new PEAR_Error( 'Failed to receive from the socket' );
+        $lastline = rtrim($lastline);
+        $this->_debug("S: $lastline");
+
+        if ($lastline === '') {
+            return PEAR::raiseError('Failed to read from socket');
         }
 
         return $lastline;
     }
 
     /**
-    * Send a command and retrieves a response from the server.
-    *
-    *
-    * @access private
-    * @param string $cmd The command to send
-    * @return mixed Reponse string if an OK response, PEAR_Error if a NO response
-    */
-    function _doCmd($cmd = '' )
+     * Send a command and retrieves a response from the server.
+     *
+     * @param string $cmd   The command to send.
+     * @param boolean $auth Whether this is an authentication command.
+     *
+     * @return string|PEAR_Error  Reponse string if an OK response, PEAR_Error
+     *                            if a NO response.
+     */
+    function _doCmd($cmd = '', $auth = false)
     {
-        $referralCount=0;
-        while($referralCount < $this->_maxReferralCount ){
-
-            if($cmd != '' ){
-                if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
+        $referralCount = 0;
+        while ($referralCount < $this->_maxReferralCount) {
+            if (strlen($cmd)) {
+                if (PEAR::isError($error = $this->_sendCmd($cmd))) {
                     return $error;
                 }
             }
+
             $response = '';
-
             while (true) {
-                    if(PEAR::isError( $line=$this->_recvLn() )){
-                        return $line;
-                    }
-                    if ('ok' === strtolower(substr($line, 0, 2))) {
-                        $response .= $line;
-                        return rtrim($response);
-
-                    } elseif ('no' === strtolower(substr($line, 0, 2))) {
-                        // Check for string literal error message
-                        if (preg_match('/^no {([0-9]+)\+?}/i', $line, $matches)) {
-                            $line .= str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
-                            if($this->_debug){
-                                echo "S:$line\n";
-                            }
-                        }
-                        $msg=trim($response . substr($line, 2));
-                        $code=3;
-                        return $this->_raiseError($msg,$code);
-                    } elseif ('bye' === strtolower(substr($line, 0, 3))) {
-
-                        if(PEAR::isError($error = $this->disconnect(false) ) ){
-                            $msg="Can't handle bye, The error was= " . $error->getMessage() ;
-                            $code=4;
-                            return $this->_raiseError($msg,$code);
-                        }
-                        //if (preg_match('/^bye \(referral "([^"]+)/i', $line, $matches)) {
-                        if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
-                            // Check for referral, then follow it.  Otherwise, carp an error.
-                            // Replace the old host with the referral host preserving any protocol prefix
-                            $this->_data['host'] = preg_replace('/\w+(?!(\w|\:\/\/)).*/',$matches[2],$this->_data['host']);
-                           if (PEAR::isError($error = $this->_handleConnectAndLogin() ) ){
-                                $msg="Can't follow referral to " . $this->_data['host'] . ", The error was= " . $error->getMessage() ;
-                                $code=5;
-                                return $this->_raiseError($msg,$code);
-                            }
-                            break;
-                            // Retry the command
-                            if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
-                                return $error;
-                            }
-                            continue;
-                        }
-                        $msg=trim($response . $line);
-                        $code=6;
-                        return $this->_raiseError($msg,$code);
-                    } elseif (preg_match('/^{([0-9]+)\+?}/i', $line, $matches)) {
-                        // Matches String Responses.
-                        //$line = str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
-                        $str_size = $matches[1] + 2;
-                        $line = '';
-                        $line_length = 0;
-                        while ($line_length < $str_size) {
-                            $line .= $this->_sock->read($str_size - $line_length);
-                            $line_length = $this->_getLineLength($line);
-                        }
-                        if($this->_debug){
-                            echo "S:$line\n";
-                        }
-                        if($this->_state != NET_SIEVE_STATE_AUTHORISATION) {
-                            // receive the pending OK only if we aren't authenticating
-                            // since string responses during authentication don't need an
-                            // OK.
-                            $this->_recvLn();
-                        }
-                        return $line;
-                    }
-                    $response .= $line . "\r\n";
-                    $referralCount++;
+                if (PEAR::isError($line = $this->_recvLn())) {
+                    return $line;
                 }
+                $uc_line = $this->_toUpper($line);
+
+                if ('OK' == substr($uc_line, 0, 2)) {
+                    $response .= $line;
+                    return rtrim($response);
+                }
+
+                if ('NO' == substr($uc_line, 0, 2)) {
+                    // Check for string literal error message.
+                    if (preg_match('/^no {([0-9]+)\+?}/i', $line, $matches)) {
+                        $line .= str_replace(
+                            "\r\n", ' ', $this->_sock->read($matches[1] + 2)
+                        );
+                        $this->_debug("S: $line");
+                    }
+                    return PEAR::raiseError(trim($response . substr($line, 2)), 3);
+                }
+
+                if ('BYE' == substr($uc_line, 0, 3)) {
+                    if (PEAR::isError($error = $this->disconnect(false))) {
+                        return PEAR::raiseError(
+                            'Cannot handle BYE, the error was: '
+                            . $error->getMessage(),
+                            4
+                        );
+                    }
+                    // Check for referral, then follow it.  Otherwise, carp an
+                    // error.
+                    if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
+                        // Replace the old host with the referral host
+                        // preserving any protocol prefix.
+                        $this->_data['host'] = preg_replace(
+                            '/\w+(?!(\w|\:\/\/)).*/', $matches[2],
+                            $this->_data['host']
+                        );
+                        if (PEAR::isError($error = $this->_handleConnectAndLogin())) {
+                            return PEAR::raiseError(
+                                'Cannot follow referral to '
+                                . $this->_data['host'] . ', the error was: '
+                                . $error->getMessage(),
+                                5
+                            );
+                        }
+                        break;
+                    }
+                    return PEAR::raiseError(trim($response . $line), 6);
+                }
+
+                if (preg_match('/^{([0-9]+)\+?}/i', $line, $matches)) {
+                    // Matches String Responses.
+                    $str_size = $matches[1] + 2;
+                    $line = '';
+                    $line_length = 0;
+                    while ($line_length < $str_size) {
+                        $line .= $this->_sock->read($str_size - $line_length);
+                        $line_length = $this->_getLineLength($line);
+                    }
+                    $this->_debug("S: $line");
+
+                    if (!$auth) {
+                        // Receive the pending OK only if we aren't
+                        // authenticating since string responses during
+                        // authentication don't need an OK.
+                        $this->_recvLn();
+                    }
+                    return $line;
+                }
+
+                if ($auth) {
+                    // String responses during authentication don't need an
+                    // OK.
+                    $response .= $line;
+                    return rtrim($response);
+                }
+
+                $response .= $line . "\r\n";
+                $referralCount++;
+            }
         }
-        $msg="Max referral count reached ($referralCount times) Cyrus murder loop error?";
-        $code=7;
-        return $this->_raiseError($msg,$code);
-    }
 
-    /**
-    * Sets the debug state
-    *
-    * @param boolean $debug
-    * @return void
-    */
-    function setDebug($debug = true)
-    {
-        $this->_debug = $debug;
-    }
-
-    /**
-    * Disconnect from the Sieve server
-    *
-    * @param  string $scriptname The name of the script to be set as active
-    * @return mixed              true on success, PEAR_Error on failure
-    */
-    function disconnect($sendLogoutCMD=true)
-    {
-        return $this->_cmdLogout($sendLogoutCMD);
+        return PEAR::raiseError('Max referral count (' . $referralCount . ') reached. Cyrus murder loop error?', 7);
     }
 
     /**
      * Returns the name of the best authentication method that the server
      * has advertised.
      *
-     * @param string if !=null,authenticate with this method ($userMethod).
+     * @param string $userMethod Only consider this method as available.
      *
-     * @return mixed    Returns a string containing the name of the best
-     *                  supported authentication method or a PEAR_Error object
-     *                  if a failure condition is encountered.
-     * @access private
-     * @since  1.0
+     * @return string  The name of the best supported authentication method or
+     *                 a PEAR_Error object on failure.
      */
     function _getBestAuthMethod($userMethod = null)
     {
-       if( isset($this->_capability['sasl']) ){
-           $serverMethods=$this->_capability['sasl'];
-       }else{
-           // if the server don't send an sasl capability fallback to login auth
-           //return 'LOGIN';
-           return new PEAR_Error("This server don't support any Auth methods SASL problem?");
-       }
+        if (!isset($this->_capability['sasl'])) {
+            return PEAR::raiseError('This server doesn\'t support any authentication methods. SASL problem?');
+        }
 
-        if($userMethod != null ){
-            $methods = array();
-            $methods[] = $userMethod;
-        }else{
+        $serverMethods = $this->_capability['sasl'];
 
+        if ($userMethod) {
+            $methods = array($userMethod);
+        } else {
             $methods = $this->supportedAuthMethods;
         }
-        if( ($methods != null) && ($serverMethods != null)){
-            foreach ( $methods as $method ) {
-                if ( in_array( $method , $serverMethods ) ) {
-                    return $method;
-                }
-            }
-            $serverMethods=implode(',' , $serverMethods );
-            $myMethods=implode(',' ,$this->supportedAuthMethods);
-            return new PEAR_Error("$method NOT supported authentication method!. This server " .
-                "supports these methods= $serverMethods, but I support $myMethods");
-        }else{
-            return new PEAR_Error("This server don't support any Auth methods");
-        }
-    }
 
-    /**
-    * Return the list of extensions the server supports
-    *
-    * @return mixed              array  on success, PEAR_Error on failure
-    */
-    function getExtensions()
-    {
-        if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
-            $msg='Not currently connected';
-            $code=7;
-            return $this->_raiseError($msg,$code);
+        if (!$methods || !$serverMethods) {
+            return PEAR::raiseError(
+                'This server doesn\'t support any authentication methods.'
+            );
         }
 
-        return $this->_capability['extensions'];
-    }
-
-    /**
-    * Return true if tyhe server has that extension
-    *
-    * @param string  the extension to compare
-    * @return mixed              array  on success, PEAR_Error on failure
-    */
-    function hasExtension($extension)
-    {
-        if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
-            $msg='Not currently connected';
-            $code=7;
-            return $this->_raiseError($msg,$code);
-        }
-
-        if(is_array($this->_capability['extensions'] ) ){
-            foreach( $this->_capability['extensions'] as $ext){
-                if( trim( strtolower( $ext ) ) === trim( strtolower( $extension ) ) )
-                    return true;
+        foreach ($methods as $method) {
+            if (in_array($method, $serverMethods)) {
+                return $method;
             }
         }
-        return false;
+
+        return PEAR::raiseError(
+            'No supported authentication method found. The server supports these methods: '
+            . implode(',', $serverMethods)
+            . ', but we only support: '
+            . implode(',', $this->supportedAuthMethods)
+        );
     }
 
     /**
-    * Return the list of auth methods the server supports
-    *
-    * @return mixed              array  on success, PEAR_Error on failure
-    */
-    function getAuthMechs()
-    {
-        if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
-            $msg='Not currently connected';
-            $code=7;
-            return $this->_raiseError($msg,$code);
-        }
-        if(!isset($this->_capability['sasl']) ){
-            $this->_capability['sasl']=array();
-        }
-        return $this->_capability['sasl'];
-    }
-
-    /**
-    * Return true if the server has that extension
-    *
-    * @param string  the extension to compare
-    * @return mixed              array  on success, PEAR_Error on failure
-    */
-    function hasAuthMech($method)
-    {
-        if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
-            $msg='Not currently connected';
-            $code=7;
-            return $this->_raiseError($msg,$code);
-            //return PEAR::raiseError('Not currently connected');
-        }
-
-        if(is_array($this->_capability['sasl'] ) ){
-            foreach( $this->_capability['sasl'] as $ext){
-                if( trim( strtolower( $ext ) ) === trim( strtolower( $method ) ) )
-                    return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-    * Return true if the TLS negotiation was successful
-    *
-    * @access private
-    * @return mixed              true on success, PEAR_Error on failure
-    */
+     * Starts a TLS connection.
+     *
+     * @return boolean  True on success, PEAR_Error on failure.
+     */
     function _startTLS()
     {
-        if (PEAR::isError($res = $this->_doCmd("STARTTLS"))) {
+        if (PEAR::isError($res = $this->_doCmd('STARTTLS'))) {
             return $res;
         }
 
-        if(stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) == false) {
-            $msg='Failed to establish TLS connection';
-            $code=2;
-            return $this->_raiseError($msg,$code);
+        if (!stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
+            return PEAR::raiseError('Failed to establish TLS connection', 2);
         }
 
-        if($this->_debug === true) {
-            echo "STARTTLS Negotiation Successful\n";
-        }
+        $this->_debug('STARTTLS negotiation successful');
 
         // The server should be sending a CAPABILITY response after
         // negotiating TLS. Read it, and ignore if it doesn't.
         $this->_doCmd();
 
-        // RFC says we need to query the server capabilities again now that
-        // we are under encryption
-        if(PEAR::isError($res = $this->_cmdCapability() )) {
-            $msg='Failed to connect, server said: ' . $res->getMessage();
-            $code=2;
-            return $this->_raiseError($msg,$code);
+        // RFC says we need to query the server capabilities again now that we
+        // are under encryption.
+        if (PEAR::isError($res = $this->_cmdCapability())) {
+            return PEAR::raiseError(
+                'Failed to connect, server said: ' . $res->getMessage(), 2
+            );
         }
 
         return true;
     }
 
-    function _getLineLength($string) {
-        if (extension_loaded('mbstring') || @dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX)) {
-          return mb_strlen($string,'latin1');
+    /**
+     * Returns the length of a string.
+     *
+     * @param string $string A string.
+     *
+     * @return integer  The length of the string.
+     */
+    function _getLineLength($string)
+    {
+        if (extension_loaded('mbstring')
+            || @dl(PHP_SHLIB_PREFIX . 'mbstring.' . PHP_SHLIB_SUFFIX)
+        ) {
+            return mb_strlen($string, 'latin1');
         } else {
-          return strlen($string);
+            return strlen($string);
+        }
+    }
+
+    /**
+     * Locale independant strtoupper() implementation.
+     *
+     * @param string $string The string to convert to lowercase.
+     *
+     * @return string  The lowercased string, based on ASCII encoding.
+     */
+    function _toUpper($string)
+    {
+        $language = setlocale(LC_CTYPE, 0);
+        setlocale(LC_CTYPE, 'C');
+        $string = strtoupper($string);
+        setlocale(LC_CTYPE, $language);
+        return $string;
+    }
+
+    /**
+     * Write debug text to the current debug output handler.
+     *
+     * @param string $message Debug message text.
+     *
+     * @return void
+     */
+    function _debug($message)
+    {
+        if ($this->_debug) {
+            if ($this->_debug_handler) {
+                call_user_func_array($this->_debug_handler, array(&$this, $message));
+            } else {
+                echo "$message\n";
+            }
         }
     }
 }
-?>
diff --git a/plugins/managesieve/lib/rcube_sieve.php b/plugins/managesieve/lib/rcube_sieve.php
index 2490aca..a8290b1 100644
--- a/plugins/managesieve/lib/rcube_sieve.php
+++ b/plugins/managesieve/lib/rcube_sieve.php
@@ -16,19 +16,22 @@
 define('SIEVE_ERROR_NOT_EXISTS', 3);	// script not exists
 define('SIEVE_ERROR_INSTALL', 4);	// script installation
 define('SIEVE_ERROR_ACTIVATE', 5);	// script activation
+define('SIEVE_ERROR_DELETE', 6);	// script deletion
+define('SIEVE_ERROR_INTERNAL', 7);	// internal error
 define('SIEVE_ERROR_OTHER', 255);	// other/unknown error
 
 
 class rcube_sieve
 {
-  var $sieve;				// Net_Sieve object
-  var $error = false; 			// error flag 
-  var $list = array(); 			// scripts list 
+    private $sieve;			// Net_Sieve object
+    private $error = false; 		// error flag 
+    private $list = array(); 		// scripts list 
 
-  public $script;			// rcube_sieve_script object
-  private $disabled;			// array of disabled extensions
+    public $script;			// rcube_sieve_script object
+    public $current;			// name of currently loaded script
+    private $disabled;			// array of disabled extensions
 
-  /**
+    /**
     * Object constructor
     *
     * @param  string  Username (to managesieve login)
@@ -38,137 +41,259 @@
     * @param  string  Enable/disable TLS use
     * @param  array   Disabled extensions
     */
-  public function __construct($username, $password='', $host='localhost', $port=2000, $usetls=true, $disabled=array())
+    public function __construct($username, $password='', $host='localhost', $port=2000,
+			    $usetls=true, $disabled=array(), $debug=false)
     {
-      $this->sieve = new Net_Sieve();
+	$this->sieve = new Net_Sieve();
       
-//      $this->sieve->setDebug();
-      if (PEAR::isError($this->sieve->connect($host, $port, NULL, $usetls)))
-        return $this->_set_error(SIEVE_ERROR_CONNECTION);
+        if ($debug)
+    	    $this->sieve->setDebug(true, array($this, 'debug_handler'));
+      
+        if (PEAR::isError($this->sieve->connect($host, $port, NULL, $usetls)))
+    	    return $this->_set_error(SIEVE_ERROR_CONNECTION);
 
-      if (PEAR::isError($this->sieve->login($username, $password)))
-        return $this->_set_error(SIEVE_ERROR_LOGIN);
+        if (PEAR::isError($this->sieve->login($username, $password)))
+    	    return $this->_set_error(SIEVE_ERROR_LOGIN);
 
-      $this->disabled = $disabled;
-      $this->_get_script();
+        $this->disabled = $disabled;
     }
 
-  /**
+    /**
     * Getter for error code
     */
-  public function error()
+    public function error()
     {
-      return $this->error ? $this->error : false;
+	return $this->error ? $this->error : false;
     }
 			    
-  public function save()
+    /**
+    * Saves current script into server
+    */
+    public function save($name = null)
     {
-      $script = $this->script->as_text();
+        if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+	
+	if (!$this->script)
+	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+	
+	if (!$name)
+	    $name = $this->current;
 
-      if (!$script)
-	$script = '/* empty script */';
+        $script = $this->script->as_text();
 
-      if (PEAR::isError($this->sieve->installScript('roundcube', $script)))
-    	return $this->_set_error(SIEVE_ERROR_INSTALL);
+        if (!$script)
+	    $script = '/* empty script */';
 
-      if (PEAR::isError($this->sieve->setActive('roundcube')))
-    	return $this->_set_error(SIEVE_ERROR_ACTIVATE);
+        if (PEAR::isError($this->sieve->installScript($name, $script)))
+    	    return $this->_set_error(SIEVE_ERROR_INSTALL);
 
-      return true;
+        return true;
     }
 
-  public function get_extensions()
+    /**
+    * Saves text script into server
+    */
+    public function save_script($name, $content = null)
     {
-      if ($this->sieve) {
+        if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+	
+        if (!$content)
+	    $content = '/* empty script */';
+
+        if (PEAR::isError($this->sieve->installScript($name, $content)))
+    	    return $this->_set_error(SIEVE_ERROR_INSTALL);
+
+        return true;
+    }
+
+    /**
+    * Activates specified script
+    */
+    public function activate($name = null)
+    {
+	if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+
+	if (!$name)
+	    $name = $this->current;
+
+        if (PEAR::isError($this->sieve->setActive($name)))
+    	    return $this->_set_error(SIEVE_ERROR_ACTIVATE);
+
+        return true;
+    }
+
+    /**
+    * Removes specified script
+    */
+    public function remove($name = null)
+    {
+	if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+
+	if (!$name)
+	    $name = $this->current;
+
+	// script must be deactivated first
+	if ($name == $this->sieve->getActive())
+            if (PEAR::isError($this->sieve->setActive('')))
+    		return $this->_set_error(SIEVE_ERROR_DELETE);
+
+        if (PEAR::isError($this->sieve->removeScript($name)))
+    	    return $this->_set_error(SIEVE_ERROR_DELETE);
+
+	if ($name == $this->current)
+	    $this->current = null;
+
+        return true;
+    }
+
+    /**
+    * Gets list of supported by server Sieve extensions
+    */
+    public function get_extensions()
+    {
+        if (!$this->sieve)
+	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+	
 	$ext = $this->sieve->getExtensions();
+	// we're working on lower-cased names
+	$ext = array_map('strtolower', (array) $ext); 
 
 	if ($this->script) {
-	  $supported = $this->script->get_extensions();
-	  foreach ($ext as $idx => $ext_name)
-	    if (!in_array($ext_name, $supported))
-	      unset($ext[$idx]);
+	    $supported = $this->script->get_extensions();
+	    foreach ($ext as $idx => $ext_name)
+	        if (!in_array($ext_name, $supported))
+		    unset($ext[$idx]);
 	}
 
-        return array_values($ext);
-      }
+    	return array_values($ext);
     }
 
-  private function _get_script()
+    /**
+    * Gets list of scripts from server
+    */
+    public function get_scripts()
     {
-      if (!$this->sieve)
-        return false;
-    
-      $this->list = $this->sieve->listScripts();
+        if (!$this->list) {
 
-      if (PEAR::isError($this->list))
-    	return $this->_set_error(SIEVE_ERROR_OTHER);
+    	    if (!$this->sieve)
+        	return $this->_set_error(SIEVE_ERROR_INTERNAL);
     
-      if (in_array('roundcube', $this->list))
-        {
-          $script = $this->sieve->getScript('roundcube');
+    	    $this->list = $this->sieve->listScripts();
+
+    	    if (PEAR::isError($this->list))
+    		return $this->_set_error(SIEVE_ERROR_OTHER);
+	}
+
+        return $this->list;
+    }
+
+    /**
+    * Returns active script name
+    */
+    public function get_active()
+    {
+	if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+
+	return $this->sieve->getActive();
+    }
     
-          if (PEAR::isError($script))
+    /**
+    * Loads script by name
+    */
+    public function load($name)
+    {
+        if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+
+        if ($this->current == $name)
+    	    return true;
+    
+    	$script = $this->sieve->getScript($name);
+    
+        if (PEAR::isError($script))
     	    return $this->_set_error(SIEVE_ERROR_OTHER);
-	}
-      // import scripts from squirrelmail
-      elseif (in_array('phpscript', $this->list))
-        {
-          $script = $this->sieve->getScript('phpscript');
 
-          $script = $this->_convert_from_squirrel_rules($script);
+	// try to parse from Roundcube format
+        $this->script = new rcube_sieve_script($script, $this->disabled);
 
-          $this->script = new rcube_sieve_script($script, $this->disabled);
-       
-          $this->save();
+        // ... else try Squirrelmail format
+        if (empty($this->script->content) && $name == 'phpscript') {
 
-          $script = $this->sieve->getScript('roundcube');
+    	    $script = $this->sieve->getScript('phpscript');
+    	    $script = $this->_convert_from_squirrel_rules($script);
 
-          if (PEAR::isError($script))
-            return $this->_set_error(SIEVE_ERROR_OTHER);
-        }
-      else
-        {
-	  $this->_set_error(SIEVE_ERROR_NOT_EXISTS);
-          $script = '';
-	}
+    	    $this->script = new rcube_sieve_script($script, $this->disabled);
+    	}
 
-      $this->script = new rcube_sieve_script($script, $this->disabled);
+    	$this->current = $name;
+
+    	return true;
     }
+
+    /**
+    * Creates empty script or copy of other script
+    */
+    public function copy($name, $copy)
+    {
+        if (!$this->sieve)
+    	    return $this->_set_error(SIEVE_ERROR_INTERNAL);
+
+	if ($copy) {
+    	    $content = $this->sieve->getScript($copy);
     
-  private function _convert_from_squirrel_rules($script)
-    {
-      $i = 0;
-      $name = array();
-      // tokenize rules
-      if ($tokens = preg_split('/(#START_SIEVE_RULE.*END_SIEVE_RULE)\n/', $script, -1, PREG_SPLIT_DELIM_CAPTURE))
-        foreach($tokens as $token)
-          {
-            if (preg_match('/^#START_SIEVE_RULE.*/', $token, $matches))
-              {
-	        $name[$i] = "unnamed rule ".($i+1);
-                $content .= "# rule:[".$name[$i]."]\n";
-              }
-            elseif (isset($name[$i]))
-              {
-	        $content .= "if ".$token."\n";
-		$i++;
-              }
-          }
-
-      return $content;
+    	    if (PEAR::isError($content))
+    		return $this->_set_error(SIEVE_ERROR_OTHER);
+	}
+	
+	return $this->save_script($name, $content);
     }
 
 
-  private function _set_error($error)
+    private function _convert_from_squirrel_rules($script)
     {
-      $this->error = $error;
-      return false;
-    }    
+        $i = 0;
+        $name = array();
+
+        // tokenize rules
+        if ($tokens = preg_split('/(#START_SIEVE_RULE.*END_SIEVE_RULE)\n/', $script, -1, PREG_SPLIT_DELIM_CAPTURE))
+    	    foreach($tokens as $token) {
+        	if (preg_match('/^#START_SIEVE_RULE.*/', $token, $matches)) {
+	    	    $name[$i] = "unnamed rule ".($i+1);
+            	    $content .= "# rule:[".$name[$i]."]\n";
+                }
+        	elseif (isset($name[$i])) {
+	    	    $content .= "if $token\n";
+		    $i++;
+                }
+            }
+
+        return $content;
+    }
+
+    private function _set_error($error)
+    {
+	$this->error = $error;
+        return false;
+    }
+
+    /**
+    * This is our own debug handler for connection
+    * @access public
+    */
+    public function debug_handler(&$sieve, $message)
+    {
+        write_log('sieve', preg_replace('/\r\n$/', '', $message));
+    }		        
 }
 
 class rcube_sieve_script
 {
-  var $content = array();	// script rules array   
+  public $content = array();	// script rules array   
 
   private $supported = array(	// extensions supported by class
     'fileinto',
diff --git a/plugins/managesieve/localization/bg_BG.inc b/plugins/managesieve/localization/bg_BG.inc
index 96ce63b..90f34bf 100644
--- a/plugins/managesieve/localization/bg_BG.inc
+++ b/plugins/managesieve/localization/bg_BG.inc
@@ -39,7 +39,7 @@
 $messages['filterconnerror'] = 'Невъзможност за свързване с managesieve сървъра ';
 $messages['filterdeleteerror'] = 'Невъзможност за изтриване на филтър. Сървър грешка';
 $messages['filterdeleted'] = 'Филтърът е изтрит успешно';
-$messages['filterconfirmdelete'] = 'Наистина ли искате да изтриете избрания филтър?';
+$messages['filterdeleteconfirm'] = 'Наистина ли искате да изтриете избрания филтър?';
 $messages['filtersaved'] = 'Филтърът е записан успешно';
 $messages['filtersaveerror'] = 'Филтърът не може да бъде записан. Сървър грешка.';
 $messages['ruledeleteconfirm'] = 'Сигурни ли сте, че искате да изтриете избраното правило?';
diff --git a/plugins/managesieve/localization/cs_CZ.inc b/plugins/managesieve/localization/cs_CZ.inc
index 62f0fdf..033a1a0 100644
--- a/plugins/managesieve/localization/cs_CZ.inc
+++ b/plugins/managesieve/localization/cs_CZ.inc
@@ -50,7 +50,7 @@
 $messages['filterconnerror'] = 'Nebylo možné se připojit k sieve serveru';
 $messages['filterdeleteerror'] = 'Nebylo možné smazat filtr. Server nahlásil chybu';
 $messages['filterdeleted'] = 'Filtr byl smazán';
-$messages['filterconfirmdelete'] = 'Opravdu chcete smazat vybraný filtr?';
+$messages['filterdeleteconfirm'] = 'Opravdu chcete smazat vybraný filtr?';
 $messages['filtersaved'] = 'Filtr byl uložen';
 $messages['filtersaveerror'] = 'Nebylo možné uložit filtr. Server nahlásil chybu.';
 $messages['ruledeleteconfirm'] = 'Jste si jisti, že chcete smazat vybrané pravidlo?';
diff --git a/plugins/managesieve/localization/de_CH.inc b/plugins/managesieve/localization/de_CH.inc
index c4d4d49..c0fe389 100644
--- a/plugins/managesieve/localization/de_CH.inc
+++ b/plugins/managesieve/localization/de_CH.inc
@@ -41,7 +41,7 @@
 $messages['filterconnerror'] = 'Kann nicht zum Sieve-Server verbinden';
 $messages['filterdeleteerror'] = 'Fehler beim des löschen  Filters. Serverfehler';
 $messages['filterdeleted'] = 'Filter erfolgreich gelöscht';
-$messages['filterconfirmdelete'] = 'Möchten Sie den Filter löschen ?';
+$messages['filterdeleteconfirm'] = 'Möchten Sie den Filter löschen ?';
 $messages['filtersaved'] = 'Filter gespeichert';
 $messages['filtersaveerror'] = 'Serverfehler, konnte den Filter nicht speichern.';
 $messages['ruledeleteconfirm'] = 'Sicher, dass Sie die Regel löschen wollen?';
diff --git a/plugins/managesieve/localization/de_DE.inc b/plugins/managesieve/localization/de_DE.inc
index e2caf77..31b5f80 100644
--- a/plugins/managesieve/localization/de_DE.inc
+++ b/plugins/managesieve/localization/de_DE.inc
@@ -42,7 +42,7 @@
 $messages['filterconnerror'] = 'Kann nicht zum Sieve-Server verbinden';
 $messages['filterdeleteerror'] = 'Fehler beim Löschen des Filters. Serverfehler';
 $messages['filterdeleted'] = 'Filter erfolgreich gelöscht';
-$messages['filterconfirmdelete'] = 'Möchten Sie den Filter löschen?';
+$messages['filterdeleteconfirm'] = 'Möchten Sie den Filter löschen?';
 $messages['filtersaved'] = 'Filter gespeichert';
 $messages['filtersaveerror'] = 'Serverfehler, konnte den Filter nicht speichern.';
 $messages['ruledeleteconfirm'] = 'Sicher, dass Sie die Regel löschen wollen?';
diff --git a/plugins/managesieve/localization/en_GB.inc b/plugins/managesieve/localization/en_GB.inc
index c671b83..c62979c 100644
--- a/plugins/managesieve/localization/en_GB.inc
+++ b/plugins/managesieve/localization/en_GB.inc
@@ -42,7 +42,7 @@
 $messages['filterconnerror'] = 'Unable to connect to managesieve server';
 $messages['filterdeleteerror'] = 'Unable to delete filter. Server error occured';
 $messages['filterdeleted'] = 'Filter deleted successfully';
-$messages['filterconfirmdelete'] = 'Do you really want to delete selected filter?';
+$messages['filterdeleteconfirm'] = 'Do you really want to delete selected filter?';
 $messages['filtersaved'] = 'Filter saved successfully';
 $messages['filtersaveerror'] = 'Unable to save filter. Server error occured.';
 $messages['ruledeleteconfirm'] = 'Are you sure, you want to delete selected rule?';
diff --git a/plugins/managesieve/localization/en_US.inc b/plugins/managesieve/localization/en_US.inc
index c671b83..a5bb878 100644
--- a/plugins/managesieve/localization/en_US.inc
+++ b/plugins/managesieve/localization/en_US.inc
@@ -36,18 +36,37 @@
 $labels['vacationdays'] = 'How often send messages (in days):';
 $labels['vacationreason'] = 'Message body (vacation reason):';
 $labels['rulestop'] = 'Stop evaluating rules';
+$labels['filterset'] = 'Filters set';
+$labels['filtersetadd'] = 'Add filters set';
+$labels['filtersetdel'] = 'Delete current filters set';
+$labels['filtersetact'] = 'Activate current filters set';
+$labels['filterdef'] = 'Filter definition';
+$labels['filtersetname'] = 'Filters set name';
+$labels['newfilterset'] = 'New filters set';
+$labels['active'] = 'active';
+$labels['copyfromset'] = 'Copy filters from set';
+$labels['none'] = '- none -';
 
 $messages = array();
 $messages['filterunknownerror'] = 'Unknown server error';
 $messages['filterconnerror'] = 'Unable to connect to managesieve server';
 $messages['filterdeleteerror'] = 'Unable to delete filter. Server error occured';
 $messages['filterdeleted'] = 'Filter deleted successfully';
-$messages['filterconfirmdelete'] = 'Do you really want to delete selected filter?';
 $messages['filtersaved'] = 'Filter saved successfully';
-$messages['filtersaveerror'] = 'Unable to save filter. Server error occured.';
+$messages['filtersaveerror'] = 'Unable to save filter. Server error occured';
+$messages['filterdeleteconfirm'] = 'Do you really want to delete selected filter?';
 $messages['ruledeleteconfirm'] = 'Are you sure, you want to delete selected rule?';
 $messages['actiondeleteconfirm'] = 'Are you sure, you want to delete selected action?';
 $messages['forbiddenchars'] = 'Forbidden characters in field';
 $messages['cannotbeempty'] = 'Field cannot be empty';
+$messages['setactivateerror'] = 'Unable to activate selected filters set. Server error occured';
+$messages['setdeleteerror'] = 'Unable to delete selected filters set. Server error occured';
+$messages['setactivated'] = 'Filters set activated successfully';
+$messages['setdeleted'] = 'Filters set deleted successfully';
+$messages['setdeleteconfirm'] = 'Are you sure, you want to delete selected filters set?';
+$messages['setcreateerror'] = 'Unable to create filters set. Server error occured';
+$messages['setcreated'] = 'Filters set created successfully';
+$messages['emptyname'] = 'Unable to create filters set. Empty set name';
+$messages['nametoolong'] = 'Unable to create filters set. Name too long'
 
 ?>
diff --git a/plugins/managesieve/localization/es_ES.inc b/plugins/managesieve/localization/es_ES.inc
index 9e7e3f5..24e682a 100644
--- a/plugins/managesieve/localization/es_ES.inc
+++ b/plugins/managesieve/localization/es_ES.inc
@@ -43,7 +43,7 @@
 $messages['filterconnerror'] = 'Imposible conectar con el servidor managesieve';
 $messages['filterdeleteerror'] = 'Imposible borrar filtro. Ha ocurrido un error en el servidor';
 $messages['filterdeleted'] = 'Filtro borrado satisfactoriamente';
-$messages['filterconfirmdelete'] = '¿Realmente desea borrar el filtro seleccionado?';
+$messages['filterdeleteconfirm'] = '¿Realmente desea borrar el filtro seleccionado?';
 $messages['filtersaved'] = 'Filtro guardado satisfactoriamente';
 $messages['filtersaveerror'] = 'Imposible guardar ell filtro. Ha ocurrido un error en el servidor';
 $messages['ruledeleteconfirm'] = '¿Está seguro de que desea borrar la regla seleccionada?';
diff --git a/plugins/managesieve/localization/et_EE.inc b/plugins/managesieve/localization/et_EE.inc
index 2915de8..7f89188 100644
--- a/plugins/managesieve/localization/et_EE.inc
+++ b/plugins/managesieve/localization/et_EE.inc
@@ -42,7 +42,7 @@
 $messages['filterconnerror'] = 'Managesieve serveriga ühendumine nurjus';
 $messages['filterdeleteerror'] = 'Filtri kustutamine nurjus. Ilmnes serveri tõrge.';
 $messages['filterdeleted'] = 'Filter edukalt kustutatud';
-$messages['filterconfirmdelete'] = 'Soovid valitud filtri kustutada?';
+$messages['filterdeleteconfirm'] = 'Soovid valitud filtri kustutada?';
 $messages['filtersaved'] = 'Filter edukalt salvestatud';
 $messages['filtersaveerror'] = 'Filtri salvestamine nurjus. Ilmnes serveri tõrge.';
 $messages['ruledeleteconfirm'] = 'Soovid valitud reegli kustutada?';
diff --git a/plugins/managesieve/localization/fi_FI.inc b/plugins/managesieve/localization/fi_FI.inc
index f066ca6..1b51d3b 100644
--- a/plugins/managesieve/localization/fi_FI.inc
+++ b/plugins/managesieve/localization/fi_FI.inc
@@ -38,7 +38,7 @@
 $messages['filterconnerror'] = 'Yhdistäminen palvelimeen epäonnistui';
 $messages['filterdeleteerror'] = 'Suodattimen poistaminen epäonnistui. Palvelin virhe';
 $messages['filterdeleted'] = 'Suodatin poistettu';
-$messages['filterconfirmdelete'] = 'Haluatko varmasti poistaa valitut suodattimet?';
+$messages['filterdeleteconfirm'] = 'Haluatko varmasti poistaa valitut suodattimet?';
 $messages['filtersaved'] = 'Suodatin tallennettu';
 $messages['filtersaveerror'] = 'Suodattimen tallennus epäonnistui. Palvelin virhe';
 $messages['ruledeleteconfirm'] = 'Haluatko poistaa valitut säännöt?';
diff --git a/plugins/managesieve/localization/fr_FR.inc b/plugins/managesieve/localization/fr_FR.inc
index 632db98..e7d0994 100644
--- a/plugins/managesieve/localization/fr_FR.inc
+++ b/plugins/managesieve/localization/fr_FR.inc
@@ -42,7 +42,7 @@
 $messages['filterconnerror'] = 'Connexion au serveur Managesieve impossible';
 $messages['filterdeleteerror'] = 'Suppression du filtre impossible. Le serveur à produit une erreur';
 $messages['filterdeleted'] = 'Le filtre a bien été supprimé';
-$messages['filterconfirmdelete'] = 'Voulez-vous vraiment supprimer le filtre sélectionné?';
+$messages['filterdeleteconfirm'] = 'Voulez-vous vraiment supprimer le filtre sélectionné?';
 $messages['filtersaved'] = 'Le filtre a bien été enregistré';
 $messages['filtersaveerror'] = 'Enregistrement du filtre impossibe. Le serveur à produit une erreur';
 $messages['ruledeleteconfirm'] = 'Voulez-vous vraiment supprimer la règle sélectionnée?';
diff --git a/plugins/managesieve/localization/hu_HU.inc b/plugins/managesieve/localization/hu_HU.inc
index 1647fbe..47a84f1 100644
--- a/plugins/managesieve/localization/hu_HU.inc
+++ b/plugins/managesieve/localization/hu_HU.inc
@@ -43,7 +43,7 @@
 $messages['filterconnerror'] = 'Nem tudok a szűrőszerverhez kapcsolódni';
 $messages['filterdeleteerror'] = 'A szűrőt nem lehet törölni, szerverhiba történt';
 $messages['filterdeleted'] = 'A szűrő törlése sikeres';
-$messages['filterconfirmdelete'] = 'Biztosan törli ezt a szűrőt?';
+$messages['filterdeleteconfirm'] = 'Biztosan törli ezt a szűrőt?';
 $messages['filtersaved'] = 'A szűrő mentése sikeres';
 $messages['filtersaveerror'] = 'A szűrő mentése sikertelen, szerverhiba történt';
 $messages['ruledeleteconfirm'] = 'Biztosan törli ezt a szabályt?';
diff --git a/plugins/managesieve/localization/it_IT.inc b/plugins/managesieve/localization/it_IT.inc
index f7079b3..b8736d2 100644
--- a/plugins/managesieve/localization/it_IT.inc
+++ b/plugins/managesieve/localization/it_IT.inc
@@ -43,7 +43,7 @@
 $messages['filterconnerror'] = 'Collegamento al server managesieve fallito';
 $messages['filterdeleteerror'] = 'Eliminazione del filtro fallita. Si è verificato un errore nel server';
 $messages['filterdeleted'] = 'Filtro eliminato con successo';
-$messages['filterconfirmdelete'] = 'Vuoi veramente eliminare il filtro selezionato?';
+$messages['filterdeleteconfirm'] = 'Vuoi veramente eliminare il filtro selezionato?';
 $messages['filtersaved'] = 'Filtro salvato con successo';
 $messages['filtersaveerror'] = 'Salvataggio del filtro fallito. Si è verificato un errore nel server';
 $messages['ruledeleteconfirm'] = 'Sei sicuro di voler eliminare la regola selezionata?';
diff --git a/plugins/managesieve/localization/nl_NL.inc b/plugins/managesieve/localization/nl_NL.inc
index 83a4e69..8ee3172 100644
--- a/plugins/managesieve/localization/nl_NL.inc
+++ b/plugins/managesieve/localization/nl_NL.inc
@@ -38,7 +38,7 @@
 $messages['filterconnerror'] = 'Kan geen verbinding maken met de managesieve server';
 $messages['filterdeleteerror'] = 'Kan filter niet verwijderen. Er is een fout opgetreden';
 $messages['filterdeleted'] = 'Filter succesvol verwijderd';
-$messages['filterconfirmdelete'] = 'Weet je zeker dat je het geselecteerde filter wilt verwijderen?';
+$messages['filterdeleteconfirm'] = 'Weet je zeker dat je het geselecteerde filter wilt verwijderen?';
 $messages['filtersaved'] = 'Filter succesvol opgeslagen';
 $messages['filtersaveerror'] = 'Kan filter niet opslaan. Er is een fout opgetreden.';
 $messages['ruledeleteconfirm'] = 'Weet je zeker dat je de geselecteerde regel wilt verwijderen?';
diff --git a/plugins/managesieve/localization/pl_PL.inc b/plugins/managesieve/localization/pl_PL.inc
index f309a43..663b37f 100644
--- a/plugins/managesieve/localization/pl_PL.inc
+++ b/plugins/managesieve/localization/pl_PL.inc
@@ -37,18 +37,37 @@
 $labels['vacationdays'] = 'Częstotliwość wysyłania wiadomości (w dniach):';
 $labels['vacationaddresses'] = 'Lista dodatkowych adresów odbiorców (oddzielonych przecinkami):';
 $labels['vacationreason'] = 'Treść (przyczyna nieobecności):';
+$labels['filterset'] = 'Zbiór filtrów';
+$labels['filtersetadd'] = 'Dodaj zbiór filtrów';
+$labels['filtersetdel'] = 'Usuń bierzący zbiór filtrów';
+$labels['filtersetact'] = 'Aktywuj bierzący zbiór filtrów';
+$labels['filterdef'] = 'Definicja filtra';
+$labels['filtersetname'] = 'Nazwa zbioru filtrów';
+$labels['newfilterset'] = 'Nowy zbiór filtrów';
+$labels['active'] = 'aktywny';
+$labels['copyfromset'] = 'Skopiuj filtry ze zbioru';
+$labels['none'] = '- brak -';
 
 $messages = array();
 $messages['filterunknownerror'] = 'Nieznany błąd serwera';
 $messages['filterconnerror'] = 'Nie można nawiązać połączenia z serwerem managesieve';
 $messages['filterdeleteerror'] = 'Nie można usunąć filtra. Wystąpił błąd serwera';
 $messages['filterdeleted'] = 'Filtr został usunięty pomyślnie';
-$messages['filterconfirmdelete'] = 'Czy na pewno chcesz usunąć wybrany filtr?';
+$messages['filterdeleteconfirm'] = 'Czy na pewno chcesz usunąć wybrany filtr?';
 $messages['filtersaved'] = 'Filtr został zapisany pomyślnie';
 $messages['filtersaveerror'] = 'Nie można zapisać filtra. Wystąpił błąd serwera.';
 $messages['ruledeleteconfirm'] = 'Czy na pewno chcesz usunąć wybraną regułę?';
 $messages['actiondeleteconfirm'] = 'Czy na pewno usunąć wybraną akcję?';
 $messages['forbiddenchars'] = 'Pole zawiera niedozwolone znaki';
 $messages['cannotbeempty'] = 'Pole nie może być puste';
+$messages['setactivateerror'] = 'Nie można aktywować wybranego zbioru filtrów. Błąd serwera';
+$messages['setdeleteerror'] = 'Nie można usunąć wybranego zbioru filtrów. Błąd serwera';
+$messages['setactivated'] = 'Zbiór filtrów został aktywowany pomyślnie';
+$messages['setdeleted'] = 'Zbiór filtrów został usunięty pomyślnie';
+$messages['setdeleteconfirm'] = 'Czy na pewno chcesz usunąć wybrany zbiór filtrów?';
+$messages['setcreateerror'] = 'Nie można utworzyć zbioru filtrów. Błąd serwera';
+$messages['setcreated'] = 'Zbiór filtrów został utworzony pomyślnie';
+$messages['emptyname'] = 'Nie można utworzyć zbioru filtrów. Pusta nazwa zbioru';
+$messages['nametoolong'] = 'Nie można utworzyć zbioru filtrów. Nazwa zbyt długa'
 
 ?>
diff --git a/plugins/managesieve/localization/pt_BR.inc b/plugins/managesieve/localization/pt_BR.inc
index 4515deb..b48774e 100644
--- a/plugins/managesieve/localization/pt_BR.inc
+++ b/plugins/managesieve/localization/pt_BR.inc
@@ -42,7 +42,7 @@
 $messages['filterconnerror'] = 'Não foi possível conectar ao servidor managesieve';
 $messages['filterdeleteerror'] = 'Não foi possível excluir filtro. Occorreu um erro de servidor';
 $messages['filterdeleted'] = 'Filtro excluído com sucesso';
-$messages['filterconfirmdelete'] = 'Deseja realmente excluir o filtro selecionado?';
+$messages['filterdeleteconfirm'] = 'Deseja realmente excluir o filtro selecionado?';
 $messages['filtersaved'] = 'Filtro gravado com sucesso';
 $messages['filtersaveerror'] = 'Não foi possível gravar filtro. Occoreu um erro de servidor.';
 $messages['ruledeleteconfirm'] = 'Deseja realmente excluir a regra selecionada?';
diff --git a/plugins/managesieve/localization/ru_RU.inc b/plugins/managesieve/localization/ru_RU.inc
index b402943..46a6db7 100644
--- a/plugins/managesieve/localization/ru_RU.inc
+++ b/plugins/managesieve/localization/ru_RU.inc
@@ -32,17 +32,13 @@
 $labels['del'] = 'Удалить';
 $labels['sender'] = 'Отправитель';
 $labels['recipient'] = 'Получатель';
-$labels['vacationaddresses'] = 'Список дополнительных адресов почты (разделённый запятыми):';
-$labels['vacationdays'] = 'Как часто отправлять сообщение (раз в сколько дней):';
-$labels['vacationreason'] = 'Текст сообщения (причины отсутствия):';
-$labels['rulestop'] = 'Не обрабатывать последующие правила';
 
 $messages = array();
 $messages['filterunknownerror'] = 'Неизвестная ошибка сервера';
 $messages['filterconnerror'] = 'Невозможно подсоединится к серверу фильтров';
 $messages['filterdeleteerror'] = 'Невозможно удалить фильтр. Ошибка сервера';
 $messages['filterdeleted'] = 'Фильтр успешно удалён';
-$messages['filterconfirmdelete'] = 'Вы действительно хотите удалить фильтр?';
+$messages['filterdeleteconfirm'] = 'Вы действительно хотите удалить фильтр?';
 $messages['filtersaved'] = 'Фильтр успешно сохранён';
 $messages['filtersaveerror'] = 'Невозможно сохранить фильтр. Ошибка сервера';
 $messages['ruledeleteconfirm'] = 'Вы уверенны, что хотите удалить это правило?';
diff --git a/plugins/managesieve/localization/sl_SI.inc b/plugins/managesieve/localization/sl_SI.inc
index ee3c6fe..ab9ccad 100644
--- a/plugins/managesieve/localization/sl_SI.inc
+++ b/plugins/managesieve/localization/sl_SI.inc
@@ -42,7 +42,7 @@
 $messages['filterconnerror'] = 'Povezave s strežnikom (managesieve) ni bilo mogoče vzpostaviti';
 $messages['filterdeleteerror'] = 'Pravila ni bilo mogoče izbrisati. Prišlo je do napake.';
 $messages['filterdeleted'] = 'Pravilo je bilo uspešno izbrisano.';
-$messages['filterconfirmdelete'] = 'Ste prepričani, da želite izbrisati izbrano pravilo?';
+$messages['filterdeleteconfirm'] = 'Ste prepričani, da želite izbrisati izbrano pravilo?';
 $messages['filtersaved'] = 'Pravilo je bilo uspešno shranjeno';
 $messages['filtersaveerror'] = 'Pravilo ni bilo shranjeno. Prišlo je do napake.';
 $messages['ruledeleteconfirm'] = 'Ste prepričani, da želite izbrisati izbrano pravilo?';
diff --git a/plugins/managesieve/localization/sv_SE.inc b/plugins/managesieve/localization/sv_SE.inc
index 48d0158..2c5ab69 100644
--- a/plugins/managesieve/localization/sv_SE.inc
+++ b/plugins/managesieve/localization/sv_SE.inc
@@ -43,7 +43,7 @@
 $messages['filterconnerror'] = 'Anslutning till serverns filtertjänst misslyckades';
 $messages['filterdeleteerror'] = 'Filtret kunde inte tas bort på grund av serverfel';
 $messages['filterdeleted'] = 'Filtret är borttaget';
-$messages['filterconfirmdelete'] = 'Vill du ta bort det markerade filtret?';
+$messages['filterdeleteconfirm'] = 'Vill du ta bort det markerade filtret?';
 $messages['filtersaved'] = 'Filtret har sparats';
 $messages['filtersaveerror'] = 'Filtret kunde inte sparas på grund av serverfel';
 $messages['ruledeleteconfirm'] = 'Vill du ta bort filterregeln?';
diff --git a/plugins/managesieve/localization/uk_UA.inc b/plugins/managesieve/localization/uk_UA.inc
index 2cc4436..70b643d 100644
--- a/plugins/managesieve/localization/uk_UA.inc
+++ b/plugins/managesieve/localization/uk_UA.inc
@@ -43,7 +43,7 @@
 $messages['filterconnerror'] = 'Неможливо з\'єднатися з сервером.';
 $messages['filterdeleteerror'] = 'Неможливо видалити фільтр. Помилка сервера.';
 $messages['filterdeleted'] = 'Фільтр успішно видалено.';
-$messages['filterconfirmdelete'] = 'Ви дійсно хочете видалити вибраний фільтр?';
+$messages['filterdeleteconfirm'] = 'Ви дійсно хочете видалити вибраний фільтр?';
 $messages['filtersaved'] = 'Фільтр успішно збережено.';
 $messages['filtersaveerror'] = 'Неможливо зберегти фільтр. Помилка сервера.';
 $messages['ruledeleteconfirm'] = 'Ви дійсно хочете видалити вибране правило?';
diff --git a/plugins/managesieve/localization/zh_CN.inc b/plugins/managesieve/localization/zh_CN.inc
index fe63c6d..a31a67d 100644
--- a/plugins/managesieve/localization/zh_CN.inc
+++ b/plugins/managesieve/localization/zh_CN.inc
@@ -38,7 +38,7 @@
 $messages['filterconnerror'] = '无法连接到 managesieve 服务器';
 $messages['filterdeleteerror'] = '无法删除过滤器。服务器错误';
 $messages['filterdeleted'] = '过滤器已成功删除';
-$messages['filterconfirmdelete'] = '您确定要删除所选择的过滤器吗?';
+$messages['filterdeleteconfirm'] = '您确定要删除所选择的过滤器吗?';
 $messages['filtersaved'] = '过滤器已成功保存。';
 $messages['filtersaveerror'] = '无法保存过滤器。服务器错误';
 $messages['ruledeleteconfirm'] = '您确定要删除所选择的规则吗?';
diff --git a/plugins/managesieve/managesieve.js b/plugins/managesieve/managesieve.js
index 7ff1acf..aac302b 100644
--- a/plugins/managesieve/managesieve.js
+++ b/plugins/managesieve/managesieve.js
@@ -19,16 +19,25 @@
     rcmail.register_command('plugin.managesieve-del', function() { rcmail.managesieve_del() }, true);
     rcmail.register_command('plugin.managesieve-up', function() { rcmail.managesieve_up() }, true);
     rcmail.register_command('plugin.managesieve-down', function() { rcmail.managesieve_down() }, true);
+    rcmail.register_command('plugin.managesieve-set', function() { rcmail.managesieve_set() }, true);
+    rcmail.register_command('plugin.managesieve-setadd', function() { rcmail.managesieve_setadd() }, true);
+    rcmail.register_command('plugin.managesieve-setdel', function() { rcmail.managesieve_setdel() }, true);
+    rcmail.register_command('plugin.managesieve-setact', function() { rcmail.managesieve_setact() }, true);
 
     if (rcmail.env.action == 'plugin.managesieve')
       {
 	if (rcmail.gui_objects.sieveform)
 	  rcmail.enable_command('plugin.managesieve-save', true);
 	else {
-	  rcmail.enable_command('plugin.managesieve-del', 'plugin.managesieve-up', 'plugin.managesieve-down', false);
-          rcmail.enable_command('plugin.managesieve-add', !rcmail.env.sieveconnerror);
+	  rcmail.enable_command('plugin.managesieve-del', 'plugin.managesieve-up',
+	    'plugin.managesieve-down', false);
+          rcmail.enable_command('plugin.managesieve-add', 'plugin.managesieve-setadd', !rcmail.env.sieveconnerror);
+	  rcmail.enable_command('plugin.managesieve-set', rcmail.gui_objects.filtersetslist != null);
+	  rcmail.enable_command('plugin.managesieve-setact',
+	    (rcmail.gui_objects.filtersetslist && rcmail.gui_objects.filtersetslist.value != rcmail.env.active_set));
+	  rcmail.enable_command('plugin.managesieve-setdel',
+	    (rcmail.gui_objects.filtersetslist && rcmail.gui_objects.filtersetslist.length > 1));
 	}
-	
         if (rcmail.gui_objects.filterslist) {
 	    var p = rcmail;
     	    rcmail.filters_list = new rcube_list_widget(rcmail.gui_objects.filterslist, {multiselect:false, draggable:false, keyboard:false});
@@ -53,7 +62,7 @@
     {
     var id = this.filters_list.get_single_selection();
 
-    if (confirm(this.get_label('managesieve.filterconfirmdelete')))
+    if (confirm(this.get_label('managesieve.filterdeleteconfirm')))
       this.http_request('plugin.managesieve',
 	    '_act=delete&_fid='+this.filters_list.rows[id].uid, true);
     };
@@ -203,7 +212,7 @@
 
   rcube_webmail.prototype.managesieve_save = function()
     {
-      if (parent.rcmail && parent.rcmail.filters_list)
+      if (parent.rcmail && parent.rcmail.filters_list && this.gui_objects.sieveform.name != 'filtersetform')
         {
         var id = parent.rcmail.filters_list.get_single_selection();
 	if (id != null)
@@ -378,4 +387,75 @@
 	  }
         }
     }
+
+  // Set change
+  rcube_webmail.prototype.managesieve_set = function()
+    {
+    var script = $(this.gui_objects.filtersetslist).val();
+    location.href = this.env.comm_path+'&_action=plugin.managesieve&_sid='+script;
+    };
+
+  // Set activate
+  rcube_webmail.prototype.managesieve_setact = function()
+    {
+      if (!this.gui_objects.filtersetslist)
+        return false;
+
+      var script = this.gui_objects.filtersetslist.value;
+      this.http_post('plugin.managesieve', '_act=setact&_set='+script);
+    };
+
+  // Set activate flag in sets list after set activation
+  rcube_webmail.prototype.managesieve_reset = function(name)
+    {
+      if (!this.gui_objects.filtersetslist || !name)
+        return false;
+
+      var opts = this.gui_objects.filtersetslist.getElementsByTagName('option');
+      var regx = new RegExp(RegExp.escape(' (' + this.get_label('managesieve.active') + ')'));
+      
+      for (var x=1; x<opts.length; x++)
+        if (opts[x].value != name && opts[x].innerHTML.match(regx))
+	  opts[x].innerHTML = opts[x].innerHTML.replace(regx, '');
+	else if (opts[x].value == name)
+	  opts[x].innerHTML = opts[x].innerHTML + ' (' + this.get_label('managesieve.active') + ')';
+    };
+
+  // Set delete
+  rcube_webmail.prototype.managesieve_setdel = function()
+    {
+      if (!this.gui_objects.filtersetslist)
+        return false;
+
+      if (!confirm(this.get_label('managesieve.setdeleteconfirm')))
+        return false;
+
+      var script = this.gui_objects.filtersetslist.value;
+      this.http_post('plugin.managesieve', '_act=setdel&_set='+script);
+    };
+
+  // Set add
+  rcube_webmail.prototype.managesieve_setadd = function()
+    {
+      this.filters_list.clear_selection();
+      this.enable_command('plugin.managesieve-up', 'plugin.managesieve-down', 'plugin.managesieve-del', false);
+
+      if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
+        {
+        target = window.frames[this.env.contentframe];
+        this.set_busy(true, 'loading');
+        target.location.href = this.env.comm_path+'&_action=plugin.managesieve&_framed=1&_newset=1';
+        }
+    };
+
+
+  rcube_webmail.prototype.managesieve_reload = function(set)
+    {
+      this.env.reload_set = set;
+      window.setTimeout(function() {
+        location.href = rcmail.env.comm_path + '&_action=plugin.managesieve'
+	  + (rcmail.env.reload_set ? '&_sid=' + rcmail.env.reload_set : '')
+	}, 500);
+    };
+
 }
diff --git a/plugins/managesieve/managesieve.php b/plugins/managesieve/managesieve.php
index 0c8c492..92185e0 100644
--- a/plugins/managesieve/managesieve.php
+++ b/plugins/managesieve/managesieve.php
@@ -7,7 +7,7 @@
  * It's clickable interface which operates on text scripts and communicates
  * with server using managesieve protocol. Adds Filters tab in Settings.
  *
- * @version 1.7
+ * @version 2.0
  * @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
  *
  * Configuration (see config.inc.php.dist):
@@ -35,7 +35,7 @@
     $this->add_texts('localization/', array('filters','managefilters'));
 
     // register actions
-    $this->register_action('plugin.managesieve', array($this, 'managesieve_init'));
+    $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
     $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
 
     // include main js script
@@ -52,8 +52,10 @@
     // register UI objects
     $this->rc->output->add_handlers(array(
 	'filterslist' => array($this, 'filters_list'),
+	'filtersetslist' => array($this, 'filtersets_list'),
 	'filterframe' => array($this, 'filter_frame'),
 	'filterform' => array($this, 'filter_form'),
+	'filtersetform' => array($this, 'filterset_form'),
     ));
 
     require_once($this->home . '/lib/Net/Sieve.php');
@@ -65,23 +67,51 @@
 	str_replace('%h', $_SESSION['imap_host'], $this->rc->config->get('managesieve_host', 'localhost')),
 	$this->rc->config->get('managesieve_port', 2000),
 	$this->rc->config->get('managesieve_usetls', false),
-	$this->rc->config->get('managesieve_disabled_extensions'));
+	$this->rc->config->get('managesieve_disabled_extensions'),
+	$this->rc->config->get('managesieve_debug', false)
+    );
 
-    $error = $this->sieve->error();
+    if (!($error = $this->sieve->error())) {
+      
+      $list = $this->sieve->get_scripts();
+      $active = $this->sieve->get_active();
+      $_SESSION['managesieve_active'] = $active;
+      
+      if (!empty($_GET['_sid'])) {
+        $script_name = get_input_value('_sid', RCUBE_INPUT_GET);
+      } else if (!empty($_SESSION['managesieve_current'])) {
+        $script_name = $_SESSION['managesieve_current'];
+      } else {
+        // get active script
+	if ($active) {
+	  $script_name = $active;
+        } else if ($list) {
+          $script_name = $list[0];
+        // create a new (initial) script
+        } else {
+          // if script not exists build default script contents
+          $script_file = $this->rc->config->get('managesieve_default');
+	  $script_name = 'roundcube';
+          if ($script_file && is_readable($script_file))
+	    $content = file_get_contents($script_file);
 
-    if ($error == SIEVE_ERROR_NOT_EXISTS)
-    {
-      // if script not exists build default script contents
-      $script_file = $this->rc->config->get('managesieve_default');
-      if ($script_file && is_readable($script_file))
-	$this->sieve->script->add_text(file_get_contents($script_file)); 
-      // that's not exactly an error
-      $error = false;
+	  // add script and set it active    
+	  if ($this->sieve->save_script($script_name, $content)) 
+            if ($this->sieve->activate($script_name))
+	      $_SESSION['managesieve_active'] = $script_name;
+	}
+      }
+
+      if ($script_name)
+        $this->sieve->load($script_name);
+
+      $error = $this->sieve->error();
     }
-    elseif ($error)
+    
+    // finally set script objects
+    if ($error)
     {
-      switch ($error)
-      {
+      switch ($error) {
 	case SIEVE_ERROR_CONNECTION:
 	case SIEVE_ERROR_LOGIN:
           $this->rc->output->show_message('managesieve.filterconnerror', 'error');  
@@ -90,26 +120,22 @@
           $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
 	break;
       }
-
       // to disable 'Add filter' button set env variable
       $this->rc->output->set_env('filterconnerror', true);
-    }
-
-    // finally set script objects
-    if ($error)
-    {
       $this->script = array();
     }
     else
     {
       $this->script = $this->sieve->script->as_array();
       $this->exts = $this->sieve->get_extensions();
+      $this->rc->output->set_env('active_set', $_SESSION['managesieve_active']);
+      $_SESSION['managesieve_current'] = $this->sieve->current;
     }
     
     return $error;
   }
 
-  function managesieve_init()
+  function managesieve_actions()
   {
     // Init plugin and handle managesieve connection
     $error = $this->managesieve_start();
@@ -134,7 +160,7 @@
             $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
         }
       }
-      elseif ($action=='down' && !$error)
+      else if ($action=='down' && !$error)
       {
         if (isset($this->script[$fid]) && isset($this->script[$fid+1]))
         {
@@ -142,27 +168,56 @@
     		&& $this->sieve->script->update_rule($fid+1, $this->script[$fid]) !== false)
 	    $result = $this->sieve->save();
       
-          if ($result) {
+          if ($result === true) {
 //          $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
 	    $this->rc->output->command('managesieve_updatelist', 'down', '', $fid);
-          } else
+          } else {
             $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
-        }
+          }
+	}
       }
-      elseif ($action=='delete' && !$error)
+      else if ($action=='delete' && !$error)
       {
         if (isset($this->script[$fid]))
         {
           if ($this->sieve->script->delete_rule($fid))
             $result = $this->sieve->save();
 
-          if (!$result)
-            $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
-          else {
+          if ($result === true) {
 	    $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
 	    $this->rc->output->command('managesieve_updatelist', 'delete', '', $fid);
+          } else {
+            $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
           }
-        }
+	}
+      }
+      else if ($action=='setact' && !$error)
+      {
+        $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
+	$result = $this->sieve->activate($script_name);
+	
+	if ($result === true) {
+          $this->rc->output->set_env('active_set', $script_name);
+	  $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
+	  $this->rc->output->command('enable_command', 'plugin.managesieve-setact', false);
+	  $this->rc->output->command('managesieve_reset', $script_name);
+	  $_SESSION['managesieve_active'] = $script_name;
+	} else {
+          $this->rc->output->show_message('managesieve.setactivateerror', 'error');
+	}
+      }
+      else if ($action=='setdel' && !$error)
+      {
+        $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
+	$result = $this->sieve->remove($script_name);
+	
+	if ($result === true) {
+	  $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
+	  $this->rc->output->command('managesieve_reload');
+	  rcube_sess_unset('managesieve_current');
+	} else {
+          $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
+	}
       }
       elseif ($action=='ruleadd')
       {
@@ -192,8 +247,29 @@
     // Init plugin and handle managesieve connection
     $error = $this->managesieve_start();
 
-    // add/edit action
-    if (isset($_POST['_name']))
+    // filters set add action
+    if (!empty($_POST['_newset']))
+    {
+      $name = get_input_value('_name', RCUBE_INPUT_GPC);
+      $copy = get_input_value('_copy', RCUBE_INPUT_GPC);
+
+      if (!$name)
+	$error = 'managesieve.emptyname';
+      else if (mb_strlen($name)>128)
+	$error = 'managesieve.nametoolong';
+      else if (!$this->sieve->copy($name, $copy))
+	$error = 'managesieve.setcreateerror';
+		
+      if (!$error) {
+	$this->rc->output->show_message('managesieve.setcreated', 'confirmation');
+	$this->rc->output->command('parent.managesieve_reload', $name);
+//	rcube_sess_unset('managesieve_current');
+      } else {
+        $this->rc->output->show_message($error, 'error');
+      }
+    }
+    // filter add/edit action
+    else if (isset($_POST['_name']))
     {
       $name = trim(get_input_value('_name', RCUBE_INPUT_POST));
       $fid = trim(get_input_value('_fid', RCUBE_INPUT_POST));
@@ -422,9 +498,12 @@
   private function managesieve_send()
   {
     // Handle form action 
-    if (isset($_GET['_framed']) || isset($_POST['_framed']))
-      $this->rc->output->send('managesieve.managesieveedit');
-    else {
+    if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
+      if (isset($_GET['_newset']) || isset($_POST['_newset']))
+        $this->rc->output->send('managesieve.setedit');
+      else
+        $this->rc->output->send('managesieve.filteredit');
+    } else {
       $this->rc->output->set_pagetitle($this->gettext('filters'));
       $this->rc->output->send('managesieve.managesieve');
     }
@@ -451,7 +530,34 @@
     $this->rc->output->include_script('list.js');
   
     // add some labels to client
-    $this->rc->output->add_label('managesieve.filterconfirmdelete');
+    $this->rc->output->add_label('managesieve.filterdeleteconfirm');
+  
+    return $out;
+  }
+
+  // return the filters list as <SELECT>
+  function filtersets_list($attrib)
+  {
+    // add id to message list table if not specified
+    if (!strlen($attrib['id']))
+      $attrib['id'] = 'rcmfiltersetslist';
+
+    $list = $this->sieve->get_scripts();
+    $active = $this->sieve->get_active();
+  
+    $select = new html_select(array('name' => '_set', 'id' => $attrib['id'], 'onchange' => 'rcmail.managesieve_set()'));
+
+    asort($list, SORT_LOCALE_STRING);
+
+    foreach($list as $set)
+      $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
+    
+    $out = $select->show($this->sieve->current);
+    
+    // set client env
+    $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
+    $this->rc->output->add_label('managesieve.setdeleteconfirm');
+    $this->rc->output->add_label('managesieve.active');
   
     return $out;
   }
@@ -465,9 +571,58 @@
 
     $this->rc->output->set_env('contentframe', $attrib['name']);
     $this->rc->output->set_env('blankpage', $attrib['src'] ? 
-	$this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
+    $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
 
     return html::tag('iframe', $attrib);
+  }
+
+
+  function filterset_form($attrib)
+  {
+    if (!$attrib['id'])
+      $attrib['id'] = 'rcmfiltersetform';
+
+    $out = '<form name="filtersetform" action="./" method="post">'."\n";
+
+    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
+    $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
+    $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
+    $hiddenfields->add(array('name' => '_newset', 'value' => 1));
+
+    $out .= $hiddenfields->show();
+
+    $name = get_input_value('_name', RCUBE_INPUT_GPC);
+    $copy = get_input_value('_copy', RCUBE_INPUT_GPC);
+
+    $table = new html_table(array('cols' => 2));
+
+    // filter set name input
+    $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
+	'class' => ($this->errors['name'] ? 'error' : '')));
+
+    $table->add('title', sprintf('<label for="%s"><b>%s:</b></label>', '_name', Q($this->gettext('filtersetname'))));
+    $table->add(null, $input_name->show($name));
+
+    // filters set list
+    $list = $this->sieve->get_scripts();
+    $active = $this->sieve->get_active();
+  
+    $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
+
+    asort($list, SORT_LOCALE_STRING);
+
+    $select->add($this->gettext('none'), '');
+    foreach($list as $set)
+      $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
+    
+    $table->add('title', '<label>'.$this->gettext('copyfromset').':</label>');
+    $table->add(null, $select->show($copy));
+
+    $out .= $table->show();
+    
+    $this->rc->output->add_gui_object('sieveform', 'filtersetform');
+
+    return $out;
   }
 
 
@@ -818,7 +973,7 @@
 
   private function check_email($email)
   {
-    if (function_exists('check_email'));
+    if (function_exists('check_email')); 
       return check_email($email);
 
     // Check for invalid characters
diff --git a/plugins/managesieve/skins/default/filter_add_act.png b/plugins/managesieve/skins/default/filter_add_act.png
deleted file mode 100644
index d8915dc..0000000
--- a/plugins/managesieve/skins/default/filter_add_act.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_add_pas.png b/plugins/managesieve/skins/default/filter_add_pas.png
deleted file mode 100644
index b5be806..0000000
--- a/plugins/managesieve/skins/default/filter_add_pas.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_add_sel.png b/plugins/managesieve/skins/default/filter_add_sel.png
deleted file mode 100644
index 8cb0593..0000000
--- a/plugins/managesieve/skins/default/filter_add_sel.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_del_act.png b/plugins/managesieve/skins/default/filter_del_act.png
deleted file mode 100644
index 1974417..0000000
--- a/plugins/managesieve/skins/default/filter_del_act.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_del_pas.png b/plugins/managesieve/skins/default/filter_del_pas.png
deleted file mode 100644
index 9f17e38..0000000
--- a/plugins/managesieve/skins/default/filter_del_pas.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_del_sel.png b/plugins/managesieve/skins/default/filter_del_sel.png
deleted file mode 100644
index 483ffc0..0000000
--- a/plugins/managesieve/skins/default/filter_del_sel.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_down_act.png b/plugins/managesieve/skins/default/filter_down_act.png
deleted file mode 100644
index 7a24a4f..0000000
--- a/plugins/managesieve/skins/default/filter_down_act.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_down_pas.png b/plugins/managesieve/skins/default/filter_down_pas.png
deleted file mode 100644
index ac65239..0000000
--- a/plugins/managesieve/skins/default/filter_down_pas.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_down_sel.png b/plugins/managesieve/skins/default/filter_down_sel.png
deleted file mode 100644
index b7a9e67..0000000
--- a/plugins/managesieve/skins/default/filter_down_sel.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_up_act.png b/plugins/managesieve/skins/default/filter_up_act.png
deleted file mode 100644
index fd9689b..0000000
--- a/plugins/managesieve/skins/default/filter_up_act.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_up_pas.png b/plugins/managesieve/skins/default/filter_up_pas.png
deleted file mode 100644
index c60226c..0000000
--- a/plugins/managesieve/skins/default/filter_up_pas.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/filter_up_sel.png b/plugins/managesieve/skins/default/filter_up_sel.png
deleted file mode 100644
index de4c5c3..0000000
--- a/plugins/managesieve/skins/default/filter_up_sel.png
+++ /dev/null
Binary files differ
diff --git a/plugins/managesieve/skins/default/managesieve.css b/plugins/managesieve/skins/default/managesieve.css
index ce24936..d446a3a 100644
--- a/plugins/managesieve/skins/default/managesieve.css
+++ b/plugins/managesieve/skins/default/managesieve.css
@@ -6,7 +6,7 @@
   position: absolute;
   left: 20px;
   width: 220px;
-  top: 130px;
+  top: 120px;
   bottom: 30px;
   border: 1px solid #999999;
   background-color: #F9F9F9;
@@ -32,13 +32,113 @@
 {
   position: absolute;
   left: 20px;
-  top: 95px;
+  top: 85px;
+}
+
+#filtersetsbuttons
+{
+  position: absolute;
+  left: 250px;
+  top: 85px;
+}
+
+#filtersbuttons a,
+#filtersetsbuttons a
+{
+  display: block;
+  float: left;
+}
+
+#filtersbuttons a.button,
+#filtersbuttons a.buttonPas,
+#filtersetsbuttons a.button,
+#filtersetsbuttons a.buttonPas
+{
+  display: block;
+  float: left;
+  width: 32px;
+  height: 32px;
+  padding: 0;
+  margin-right: 3px;
+  overflow: hidden;
+  background: url('managesieve_toolbar.png') 0 0 no-repeat transparent;
+  opacity: 0.99; /* this is needed to make buttons appear correctly in Chrome */
+}
+
+#filtersbuttons a.buttonPas,
+#filtersetsbuttons a.buttonPas
+{
+  filter: alpha(opacity=35);
+  opacity: 0.35;
+}
+
+#filtersbuttons a.add {
+  background-position: 0px 0px;
+}
+
+#filtersbuttons a.addsel {
+  background-position: 0 -32px;
+}
+
+#filtersbuttons a.del {
+  background-position: -32px 0px;
+}
+
+#filtersbuttons a.delsel {
+  background-position: -32px -32px;
+}
+
+#filtersbuttons a.up {
+  background-position: -64px 0px;
+}
+
+#filtersbuttons a.upsel {
+  background-position: -64px -32px;
+}
+
+#filtersbuttons a.down {
+  background-position: -96px 0px;
+}
+
+#filtersbuttons a.downsel {
+  background-position: -96px -32px;
+}
+
+#filtersetsbuttons a.setadd {
+  background-position: -128px 0px;
+}
+
+#filtersetsbuttons a.setaddsel {
+  background-position: -128px -32px;
+}
+
+#filtersetsbuttons a.setdel {
+  background-position: -160px 0px;
+}
+
+#filtersetsbuttons a.setdelsel {
+  background-position: -160px -32px;
+}
+
+#filtersetsbuttons a.setset {
+  background-position: -192px 0px;
+}
+
+#filtersetsbuttons a.setsetsel {
+  background-position: -192px -32px;
+}
+
+#filtersetselect
+{
+  position: absolute;
+  left: 380px;
+  top: 90px;
 }
 
 #filter-box
 {
   position: absolute;
-  top: 95px;
+  top: 120px;
   left: 250px;
   right: 20px;
   bottom: 30px;
@@ -46,7 +146,7 @@
   overflow: hidden;
   /* css hack for IE */
   width: expression((parseInt(document.documentElement.clientWidth)-30-parseInt(document.getElementById('filterslist').offsetLeft)-parseInt(document.getElementById('filterslist').offsetWidth))+'px');
-  height: expression((parseInt(document.documentElement.clientHeight)-120)+'px');
+  height: expression((parseInt(document.documentElement.clientHeight)-155)+'px');
 }
 
 #filter-frame
diff --git a/plugins/managesieve/skins/default/managesieve_toolbar.png b/plugins/managesieve/skins/default/managesieve_toolbar.png
new file mode 100644
index 0000000..3f96a96
--- /dev/null
+++ b/plugins/managesieve/skins/default/managesieve_toolbar.png
Binary files differ
diff --git a/plugins/managesieve/skins/default/templates/managesieveedit.html b/plugins/managesieve/skins/default/templates/filteredit.html
similarity index 97%
rename from plugins/managesieve/skins/default/templates/managesieveedit.html
rename to plugins/managesieve/skins/default/templates/filteredit.html
index 2302073..164b91c 100644
--- a/plugins/managesieve/skins/default/templates/managesieveedit.html
+++ b/plugins/managesieve/skins/default/templates/filteredit.html
@@ -94,6 +94,8 @@
 }
 </script>
 
+<div id="filter-title" class="boxtitle"><roundcube:label name="managesieve.filterdef" /></div>
+
 <div id="filter-form">
 <roundcube:object name="filterform" />
 
diff --git a/plugins/managesieve/skins/default/templates/managesieve.html b/plugins/managesieve/skins/default/templates/managesieve.html
index d5dd6c4..0913ef5 100644
--- a/plugins/managesieve/skins/default/templates/managesieve.html
+++ b/plugins/managesieve/skins/default/templates/managesieve.html
@@ -13,10 +13,20 @@
 <roundcube:include file="/includes/settingstabs.html" />
 
 <div id="filtersbuttons">
-<roundcube:button command="plugin.managesieve-add" imageSel="/this/filter_add_sel.png" imagePas="/this/filter_add_pas.png" imageAct="/this/filter_add_act.png" width="32" height="32" title="managesieve.filteradd" />
-<roundcube:button command="plugin.managesieve-del" imageSel="/this/filter_del_sel.png" imagePas="/this/filter_del_pas.png" imageAct="/this/filter_del_act.png"  width="32" height="32" title="managesieve.filterdel" />
-<roundcube:button command="plugin.managesieve-up" imageSel="/this/filter_up_sel.png" imagePas="/this/filter_up_pas.png" imageAct="/this/filter_up_act.png"  width="32" height="32" title="managesieve.moveup" />
-<roundcube:button command="plugin.managesieve-down" imageSel="/this/filter_down_sel.png" imagePas="/this/filter_down_pas.png" imageAct="/this/filter_down_act.png"  width="32" height="32" title="managesieve.movedown" />
+<roundcube:button command="plugin.managesieve-add" type="link" class="buttonPas add" classSel="button addsel" classAct="button add" title="managesieve.filteradd" content=" " />
+<roundcube:button command="plugin.managesieve-del" type="link" class="buttonPas del" classSel="button delsel" classAct="button del" title="managesieve.filterdel" content=" " />
+<roundcube:button command="plugin.managesieve-up" type="link" class="buttonPas up" classSel="button upsel" classAct="button up" title="managesieve.moveup" content=" " />
+<roundcube:button command="plugin.managesieve-down" type="link" class="buttonPas down" classSel="button downsel" classAct="button down" title="managesieve.movedown" content=" " />
+</div>
+
+<div id="filtersetsbuttons">
+<roundcube:button command="plugin.managesieve-setadd" type="link" class="buttonPas setadd" classSel="button setaddsel" classAct="button setadd" title="managesieve.filtersetadd" content=" " />
+<roundcube:button command="plugin.managesieve-setdel" type="link" class="buttonPas setdel" classSel="button setdelsel" classAct="button setdel" title="managesieve.filtersetdel" content=" " />
+<roundcube:button command="plugin.managesieve-setact" type="link" class="buttonPas setset" classSel="button setsetsel" classAct="button setset" title="managesieve.filtersetact" content=" " />
+</div>
+<div id="filtersetselect">
+<roundcube:label name="managesieve.filterset" />:
+<roundcube:object name="filtersetslist" id="filtersets-select" />
 </div>
 
 <div id="filterslist">
diff --git a/plugins/managesieve/skins/default/templates/setedit.html b/plugins/managesieve/skins/default/templates/setedit.html
new file mode 100644
index 0000000..343fe4e
--- /dev/null
+++ b/plugins/managesieve/skins/default/templates/setedit.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title><roundcube:object name="pagetitle" /></title>
+<roundcube:include file="/includes/links.html" />
+<link rel="stylesheet" type="text/css" href="/this/managesieve.css" />
+</head>
+<body class="iframe">
+
+<div id="filter-title" class="boxtitle"><roundcube:label name="managesieve.newfilterset" /></div>
+
+<div id="filter-form">
+<roundcube:object name="filtersetform" />
+
+<p>
+<roundcube:button command="plugin.managesieve-save" type="input" class="button mainaction" label="save" />
+</p>
+
+</form>
+</div>
+
+
+</body>
+</html>

--
Gitblit v1.9.1