Source for file Sieve.php
Documentation is available at Sieve.php
// +-----------------------------------------------------------------------+
// | Copyright (c) 2002-2003, Richard Heyes |
// | Copyright (c) 2006, Anish Mistry |
// | All rights reserved. |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | 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 |
// | 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> |
// +-----------------------------------------------------------------------+
require_once('Net/Socket.php');
* @const NET_SIEVE_STATE_DISCONNECTED
define('NET_SIEVE_STATE_DISCONNECTED', 1 , true );
* @const NET_SIEVE_STATE_AUTHORISATION
define('NET_SIEVE_STATE_AUTHORISATION', 2 , true );
* @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. the HAVESPACE
* command which appears to be broken (Cyrus 2.0.16).
* SIEVE: RFC3028 http://www.ietf.org/rfc/rfc3028.txt
* @author Richard Heyes <richard@php.net>
* @author Damian Fernandez Sosa <damlists@cnba.uba.ar>
* @author Anish Mistry <amistry@am-productions.biz>
* Current state of the connection
* Constructor error is any
* To allow class debuging
* Allows picking up of an already established connection
var $_bypassAuth = false;
* The auth methods this class support
//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
* Handles posible referral loops
var $_maxReferralCount = 15;
* 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
function Net_Sieve($user = null , $pass = null , $host = 'localhost', $port = 2000 , $logintype = '', $euser = '', $debug = false , $bypassAuth = false )
$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->_bypassAuth = $bypassAuth;
* 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 ) {
echo "AUTH_SASL NOT PRESENT!\n";
echo " DISABLING METHOD $SASLMethod\n";
if( ($user != null ) && ($pass != null ) ){
$this->_error = $this->_handleConnectAndLogin ();
* Handles the errors the class can find
function _raiseError ($msg, $code)
return PEAR ::raiseError ($msg, $code);
* Handles connect and login.
* @return mixed Indexed array of scriptnames or PEAR_Error on failure
function _handleConnectAndLogin ()
if($this->_bypassAuth === false ) {
if (PEAR ::isError ($res = $this->connect ($this->_data['host'] , $this->_data['port'] ))) {
if (PEAR ::isError ($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'] , $this->_data['euser'] , $this->_bypassAuth) ) ) {
* Returns an indexed array of scripts currently
* @return mixed Indexed array of scriptnames or PEAR_Error on failure
if (is_array($scripts = $this->_cmdListScripts ())) {
$this->_active = $scripts[1 ];
* Returns the active script
* @return mixed The active scriptname or PEAR_Error on failure
if (!empty ($this->_active)) {
} elseif (is_array($scripts = $this->_cmdListScripts ())) {
$this->_active = $scripts[1 ];
* @param string $scriptname The name of the script to be set as active
* @return mixed true on success, PEAR_Error on failure
return $this->_cmdSetActive ($scriptname);
* @param string $scriptname The name of the script to be retrieved
* @return mixed The script on success, PEAR_Error on failure
return $this->_cmdGetScript ($scriptname);
* Adds a script to the server
* @param string $scriptname Name of the script
* @param string $script The script
* @param bool $makeactive Whether to make this the active script
* @return mixed true on success, PEAR_Error on failure
function installScript($scriptname, $script, $makeactive = false )
if (PEAR ::isError ($res = $this->_cmdPutScript ($scriptname, $script))) {
return $this->_cmdSetActive ($scriptname);
* Removes a script from the server
* @param string $scriptname Name of the script
* @return mixed True on success, PEAR_Error on failure
return $this->_cmdDeleteScript ($scriptname);
* Returns any error that may have been generated in the
* @return mixed False if no error, PEAR_Error otherwise
return PEAR ::isError ($this->_error) ? $this->_error : false;
* Handles connecting to the server and checking the
* @param string $host Hostname of server
* @param string $port Port of server
* @param array $options List of options to pass to connect
* @return mixed True on success, PEAR_Error otherwise
function connect ($host, $port, $options = null )
$msg= 'Not currently in DISCONNECTED state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_sock->connect ($host, $port, false , 5 , $options))) {
if($this->_bypassAuth === false ) {
if (PEAR ::isError ($res = $this->_doCmd ())) {
// 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 ();
return $this->_raiseError ($msg,$code);
// Get logon greeting/capability and parse
$this->_parseCapability ($res);
// 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())) {
* @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 )
$msg= 'Not currently in AUTHORISATION state';
return $this->_raiseError ($msg,$code);
if( $bypassAuth === false ){
if(PEAR ::isError ($res= $this->_cmdAuthenticate ($user , $pass , $logintype, $euser ) ) ){
/* Handles the authentication using any known method
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The method to use ( if $usermethod == '' then the class chooses the best method (the stronger is the best ) )
* @param string The effective uid to authenticate as.
* @return mixed string or PEAR_Error
function _cmdAuthenticate ($uid , $pwd , $userMethod = null , $euser = '' )
if ( PEAR ::isError ( $method = $this->_getBestAuthMethod ($userMethod) ) ) {
$result = $this->_authDigest_MD5 ( $uid , $pwd , $euser );
$result = $this->_authCRAM_MD5 ( $uid , $pwd, $euser);
$result = $this->_authLOGIN ( $uid , $pwd , $euser );
$result = $this->_authPLAIN ( $uid , $pwd , $euser );
$result = new PEAR_Error ( " $method is not a supported authentication method" );
if (PEAR ::isError ($res = $this->_doCmd () )) {
/* Authenticates the user using the PLAIN method.
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The effective uid to authenticate as.
* @return array Returns an array containing the response
function _authPLAIN ($user, $pass , $euser )
return $this->_sendCmd ( $cmd ) ;
/* Authenticates the user using the PLAIN method.
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The effective uid to authenticate as.
* @return array Returns an array containing the response
function _authLOGIN ($user, $pass , $euser )
$this->_sendCmd ('AUTHENTICATE "LOGIN"');
/* Authenticates the user using the CRAM-MD5 method.
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The cmdID.
* @return array Returns an array containing the response
function _authCRAM_MD5 ($uid, $pwd, $euser)
if ( PEAR ::isError ( $challenge = $this->_doCmd ( 'AUTHENTICATE "CRAM-MD5"' ) ) ) {
$this->_error=challenge ;
$challenge= trim($challenge);
$cram = &Auth_SASL ::factory ('crammd5');
if ( PEAR ::isError ($resp= $cram->getResponse ( $uid , $pwd , $challenge ) ) ) {
if ( PEAR ::isError ($error = $this->_sendStringResponse ( $auth_str ) ) ) {
/* Authenticates the user using the DIGEST-MD5 method.
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The efective user
* @return array Returns an array containing the response
function _authDigest_MD5 ($uid, $pwd, $euser)
if ( PEAR ::isError ( $challenge = $this->_doCmd ('AUTHENTICATE "DIGEST-MD5"') ) ) {
$this->_error=challenge ;
$digest = &Auth_SASL ::factory ('digestmd5');
if(PEAR ::isError ($param= $digest->getResponse ($uid, $pwd, $challenge, "localhost", "sieve" , $euser) )) {
if ( PEAR ::isError ($error = $this->_sendStringResponse ( $auth_str ) ) ) {
if ( PEAR ::isError ( $challenge = $this->_doCmd () ) ) {
$this->_error= $challenge ;
* 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 ( '' ) ) ) {
if (PEAR ::isError ($res = $this->_doCmd () )) {
* Removes a script from the server
* @param string $scriptname Name of the script to delete
* @return mixed True on success, PEAR_Error otherwise
function _cmdDeleteScript ($scriptname)
$msg= 'Not currently in AUTHORISATION state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd (sprintf('DELETESCRIPT "%s"', $scriptname) ) )) {
* Retrieves the contents of the named script
* @param string $scriptname Name of the script to retrieve
* @return mixed The script if successful, PEAR_Error otherwise
function _cmdGetScript ($scriptname)
$msg= 'Not currently in AUTHORISATION state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd (sprintf('GETSCRIPT "%s"', $scriptname) ) ) ) {
* Sets the ACTIVE script, ie the one that gets run on new mail
* @param string $scriptname The name of the script to mark as active
* @return mixed True on success, PEAR_Error otherwise
function _cmdSetActive ($scriptname)
$msg= 'Not currently in AUTHORISATION state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd (sprintf('SETACTIVE "%s"', $scriptname) ) ) ) {
$this->_activeScript = $scriptname;
* Sends the LISTSCRIPTS command
* @return mixed Two item array of scripts, and active script on success,
function _cmdListScripts ()
$msg= 'Not currently in AUTHORISATION state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd ('LISTSCRIPTS'))) {
foreach ($res as $value) {
if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
$scripts[] = $matches[1 ];
if (!empty ($matches[2 ])) {
$activescript = $matches[1 ];
return array ($scripts, $activescript);
* Sends the PUTSCRIPT command to add a script to
* @param string $scriptname Name of the new script
* @param string $scriptdata The new script
* @return mixed True on success, PEAR_Error otherwise
function _cmdPutScript ($scriptname, $scriptdata)
$msg= 'Not currently in TRANSACTION state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd (sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, strlen($scriptdata),$scriptdata ) ))) {
* Sends the LOGOUT command and terminates the connection
* @return mixed True on success, PEAR_Error otherwise
function _cmdLogout ($sendLogoutCMD=true )
$msg= 'Not currently connected';
return $this->_raiseError ($msg,$code);
//return PEAR::raiseError('Not currently connected');
if (PEAR ::isError ($res = $this->_doCmd ('LOGOUT'))) {
$this->_sock->disconnect ();
* Sends the CAPABILITY command
* @return mixed True on success, PEAR_Error otherwise
function _cmdCapability ()
$msg= 'Not currently connected';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd ('CAPABILITY'))) {
$this->_parseCapability ($res);
* Checks if the server has space to store the script
* @param string $scriptname The name of the script to mark as active
* @return mixed True on success, PEAR_Error otherwise
$msg= 'Not currently in TRANSACTION state';
return $this->_raiseError ($msg,$code);
if (PEAR ::isError ($res = $this->_doCmd (sprintf('HAVESPACE "%s" %s', $scriptname, $quota) ) ) ) {
//if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE %d "%s"', $quota,$scriptname ) ) ) ) {
* Parses the response from the capability command. Storesq
* the result in $this->_capability
function _parseCapability ($data)
$data = preg_split('/\r?\n/', $data, -1 , PREG_SPLIT_NO_EMPTY );
for ($i = 0; $i < count($data); $i++ ) {
if (preg_match('/^"([a-z]+)"( "(.*)")?$/i', $data[$i], $matches)) {
$this->_capability['implementation'] = $matches[3 ];
$this->_capability['sasl'] = preg_split('/\s+/', $matches[3 ]);
$this->_capability['extensions'] = preg_split('/\s+/', $matches[3 ]);
$this->_capability['starttls'] = true;
* Sends a command to the server
* @param string $cmd The command to send
$status = $this->_sock->getStatus ();
if (PEAR ::isError ($status) || $status['eof']) {
return new PEAR_Error ( '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 () );
// C: means this data was sent by the client (this class)
* Sends a string response to the server
* @param string $cmd The command to send
function _sendStringResponse ($str)
$response= '{' . strlen($str) . "+}\r\n" . $str ;
return $this->_sendCmd ($response);
if (PEAR ::isError ( $lastline = $this->_sock->gets ( 8192 ) ) ) {
return new PEAR_Error ('Failed to write to socket: ' . $lastline->getMessage () );
$lastline= rtrim($lastline);
// S: means this data was sent by the IMAP Server
/* if( $lastline === '' ){
return new PEAR_Error('Failed to receive from the socket: ' );
* Send a command and retrieves a response from the server.
* @param string $cmd The command to send
* @return mixed Reponse string if an OK response, PEAR_Error if a NO response
function _doCmd ($cmd = '' )
while ($referralCount < $this->_maxReferralCount ){
if(PEAR ::isError ($error = $this->_sendCmd ($cmd) )) {
if(PEAR ::isError ( $line= $this->_recvLn () )){
// 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 ));
return $this->_raiseError ($msg,$code);
if(PEAR ::isError ($error = $this->disconnect(false ) ) ){
$msg= "Can't handle bye, The error was= " . $error->getMessage () ;
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 () ;
return $this->_raiseError ($msg,$code);
if(PEAR ::isError ($error = $this->_sendCmd ($cmd) )) {
$msg= trim($response . $line);
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 ));
$line = $this->_sock->read ($matches[1 ] + 2 );
$response .= $line . "\r\n";
$msg=" Max referral count reached ($referralCount times) Cyrus murder loop error?";
return $this->_raiseError ($msg,$code);
* 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
return $this->_cmdLogout ($sendLogoutCMD);
* Returns the name of the best authentication method that the server
* @param string if !=null,authenticate with this method ($userMethod).
* @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.
function _getBestAuthMethod ($userMethod = null )
if( isset ($this->_capability['sasl']) ){
$serverMethods= $this->_capability['sasl'];
// if the server don't send an sasl capability fallback to login auth
return new PEAR_Error ("This server don't support any Auth methods SASL problem?");
if($userMethod != null ){
$methods[] = $userMethod;
if( ($methods != null ) && ($serverMethods != null )){
foreach ( $methods as $method ) {
if ( in_array( $method , $serverMethods ) ) {
$serverMethods= implode(',' , $serverMethods );
return new PEAR_Error (" $method NOT supported authentication method!. This server " .
" supports these methods= $serverMethods, but I support $myMethods" );
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
$msg= 'Not currently connected';
return $this->_raiseError ($msg,$code);
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
$msg= 'Not currently connected';
return $this->_raiseError ($msg,$code);
if(is_array($this->_capability['extensions'] ) ){
foreach( $this->_capability['extensions'] as $ext){
* Return the list of auth methods the server supports
* @return mixed array on success, PEAR_Error on failure
$msg= 'Not currently connected';
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
$msg= 'Not currently connected';
return $this->_raiseError ($msg,$code);
//return PEAR::raiseError('Not currently connected');
if(is_array($this->_capability['sasl'] ) ){
foreach( $this->_capability['sasl'] as $ext){
* Return true if the TLS negotiation was successful
* @return mixed true on success, PEAR_Error on failure
if (PEAR ::isError ($res = $this->_doCmd ("STARTTLS"))) {
$msg= 'Failed to establish TLS connection';
return $this->_raiseError ($msg,$code);
if($this->_debug === true ) {
echo "STARTTLS Negotiation Successful\n";
// RFC says we need to query the server capabilities again
if(PEAR ::isError ($res = $this->_cmdCapability () )) {
$msg= 'Failed to connect, server said: ' . $res->getMessage ();
return $this->_raiseError ($msg,$code);
Documentation generated on Mon, 11 Mar 2019 14:36:32 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|