2
// +-----------------------------------------------------------------------+
3
// | Copyright (c) 2002-2003, Richard Heyes |
4
// | Copyright (c) 2006, Anish Mistry |
5
// | All rights reserved. |
7
// | Redistribution and use in source and binary forms, with or without |
8
// | modification, are permitted provided that the following conditions |
11
// | o Redistributions of source code must retain the above copyright |
12
// | notice, this list of conditions and the following disclaimer. |
13
// | o Redistributions in binary form must reproduce the above copyright |
14
// | notice, this list of conditions and the following disclaimer in the |
15
// | documentation and/or other materials provided with the distribution.|
16
// | o The names of the authors may not be used to endorse or promote |
17
// | products derived from this software without specific prior written |
20
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
21
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
22
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
23
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
24
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
25
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
26
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
27
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
28
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
29
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
30
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
32
// +-----------------------------------------------------------------------+
33
// | Author: Richard Heyes <richard@phpguru.org> |
34
// | Co-Author: Damian Fernandez Sosa <damlists@cnba.uba.ar> |
35
// | Co-Author: Anish Mistry <amistry@am-productions.biz> |
36
// +-----------------------------------------------------------------------+
38
require_once('Net/Socket.php');
43
* o supportsAuthMech()
48
* @const NET_SIEVE_STATE_DISCONNECTED
50
define('NET_SIEVE_STATE_DISCONNECTED', 1, true);
54
* @const NET_SIEVE_STATE_AUTHORISATION
56
define('NET_SIEVE_STATE_AUTHORISATION', 2, true);
60
* @const NET_SIEVE_STATE_TRANSACTION
62
define('NET_SIEVE_STATE_TRANSACTION', 3, true);
65
* A class for talking to the timsieved server which
66
* comes with Cyrus IMAP.
68
* SIEVE: RFC3028 http://www.ietf.org/rfc/rfc3028.txt
69
* MANAGE-SIEVE: http://www.ietf.org/internet-drafts/draft-martin-managesieve-07.txt
71
* @author Richard Heyes <richard@php.net>
72
* @author Damian Fernandez Sosa <damlists@cnba.uba.ar>
73
* @author Anish Mistry <amistry@am-productions.biz>
88
* Info about the connect
94
* Current state of the connection
100
* Constructor error is any
106
* To allow class debuging
112
* Allows picking up of an already established connection
115
var $_bypassAuth = false;
118
* Whether to use TLS if available
124
* The auth methods this class support
127
var $supportedAuthMethods=array('DIGEST-MD5', 'CRAM-MD5', 'PLAIN' , 'LOGIN');
128
//if you have problems using DIGEST-MD5 authentication please comment the line above and uncomment the following line
129
//var $supportedAuthMethods=array( 'CRAM-MD5', 'PLAIN' , 'LOGIN');
131
//var $supportedAuthMethods=array( 'PLAIN' , 'LOGIN');
134
* The auth methods this class support
137
var $supportedSASLAuthMethods=array('DIGEST-MD5', 'CRAM-MD5');
140
* Handles posible referral loops
143
var $_maxReferralCount = 15;
147
* Sets up the object, connects to the server and logs in. stores
148
* any generated error in $this->_error, which can be retrieved
149
* using the getError() method.
151
* @param string $user Login username
152
* @param string $pass Login password
153
* @param string $host Hostname of server
154
* @param string $port Port of server
155
* @param string $logintype Type of login to perform
156
* @param string $euser Effective User (if $user=admin, login as $euser)
157
* @param string $bypassAuth Skip the authentication phase. Useful if the socket
159
* @param boolean $useTLS Use TLS if available
161
function Net_Sieve($user = null , $pass = null , $host = 'localhost', $port = 2000, $logintype = '', $euser = '', $debug = false, $bypassAuth = false, $useTLS = true)
163
$this->_state = NET_SIEVE_STATE_DISCONNECTED;
164
$this->_data['user'] = $user;
165
$this->_data['pass'] = $pass;
166
$this->_data['host'] = $host;
167
$this->_data['port'] = $port;
168
$this->_data['logintype'] = $logintype;
169
$this->_data['euser'] = $euser;
170
$this->_sock = &new Net_Socket();
171
$this->_debug = $debug;
172
$this->_bypassAuth = $bypassAuth;
173
$this->_useTLS = $useTLS;
175
* Include the Auth_SASL package. If the package is not available,
176
* we disable the authentication methods that depend upon it.
178
if ((@include_once 'Auth/SASL.php') === false) {
180
echo "AUTH_SASL NOT PRESENT!\n";
182
foreach($this->supportedSASLAuthMethods as $SASLMethod){
183
$pos = array_search( $SASLMethod, $this->supportedAuthMethods );
185
echo "DISABLING METHOD $SASLMethod\n";
187
unset($this->supportedAuthMethods[$pos]);
190
if( ($user != null) && ($pass != null) ){
191
$this->_error = $this->_handleConnectAndLogin();
196
* Handles the errors the class can find
200
* @param mixed $msg Text error message or PEAR error object
201
* @param integer $code Numeric error code
204
function _raiseError($msg, $code)
206
include_once 'PEAR.php';
207
return PEAR::raiseError($msg, $code);
211
* Handles connect and login.
215
* @return mixed Indexed array of scriptnames or PEAR_Error on failure
217
function _handleConnectAndLogin()
219
if (PEAR::isError($res = $this->connect($this->_data['host'] , $this->_data['port'], null, $this->_useTLS ))) {
222
if($this->_bypassAuth === false) {
223
if (PEAR::isError($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'] , $this->_data['euser'] , $this->_bypassAuth) ) ) {
231
* Returns an indexed array of scripts currently
234
* @return mixed Indexed array of scriptnames or PEAR_Error on failure
236
function listScripts()
238
if (is_array($scripts = $this->_cmdListScripts())) {
239
$this->_active = $scripts[1];
247
* Returns the active script
249
* @return mixed The active scriptname or PEAR_Error on failure
253
if (!empty($this->_active)) {
254
return $this->_active;
256
} elseif (is_array($scripts = $this->_cmdListScripts())) {
257
$this->_active = $scripts[1];
263
* Sets the active script
265
* @param string $scriptname The name of the script to be set as active
266
* @return mixed true on success, PEAR_Error on failure
268
function setActive($scriptname)
270
return $this->_cmdSetActive($scriptname);
276
* @param string $scriptname The name of the script to be retrieved
277
* @return mixed The script on success, PEAR_Error on failure
279
function getScript($scriptname)
281
return $this->_cmdGetScript($scriptname);
285
* Adds a script to the server
287
* @param string $scriptname Name of the script
288
* @param string $script The script
289
* @param boolean $makeactive Whether to make this the active script
290
* @return mixed true on success, PEAR_Error on failure
292
function installScript($scriptname, $script, $makeactive = false)
294
if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
297
} elseif ($makeactive) {
298
return $this->_cmdSetActive($scriptname);
306
* Removes a script from the server
308
* @param string $scriptname Name of the script
309
* @return mixed True on success, PEAR_Error on failure
311
function removeScript($scriptname)
313
return $this->_cmdDeleteScript($scriptname);
317
* Returns any error that may have been generated in the
320
* @return mixed False if no error, PEAR_Error otherwise
324
return PEAR::isError($this->_error) ? $this->_error : false;
328
* Handles connecting to the server and checking the
332
* @param string $host Hostname of server
333
* @param string $port Port of server
334
* @param array $options List of options to pass to connect
335
* @param boolean $useTLS Use TLS if available
336
* @return mixed True on success, PEAR_Error otherwise
338
function connect($host, $port, $options = null, $useTLS = true)
340
if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
341
$msg='Not currently in DISCONNECTED state';
343
return $this->_raiseError($msg,$code);
346
if (PEAR::isError($res = $this->_sock->connect($host, $port, false, 5, $options))) {
350
if($this->_bypassAuth === false) {
351
$this->_state = NET_SIEVE_STATE_AUTHORISATION;
352
if (PEAR::isError($res = $this->_doCmd())) {
356
$this->_state = NET_SIEVE_STATE_TRANSACTION;
359
// Explicitly ask for the capabilities in case the connection
360
// is picked up from an existing connection.
361
if(PEAR::isError($res = $this->_cmdCapability() )) {
362
$msg='Failed to connect, server said: ' . $res->getMessage();
364
return $this->_raiseError($msg,$code);
367
// Get logon greeting/capability and parse
368
$this->_parseCapability($res);
370
if($useTLS === true) {
371
// check if we can enable TLS via STARTTLS
372
if(isset($this->_capability['starttls']) && function_exists('stream_socket_enable_crypto') === true) {
373
if (PEAR::isError($res = $this->_startTLS())) {
385
* @param string $user Login username
386
* @param string $pass Login password
387
* @param string $logintype Type of login method to use
388
* @param string $euser Effective UID (perform on behalf of $euser)
389
* @param boolean $bypassAuth Do not perform authentication
390
* @return mixed True on success, PEAR_Error otherwise
392
function login($user, $pass, $logintype = null , $euser = '', $bypassAuth = false)
394
if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
395
$msg='Not currently in AUTHORISATION state';
397
return $this->_raiseError($msg,$code);
400
if( $bypassAuth === false ){
401
if(PEAR::isError($res=$this->_cmdAuthenticate($user , $pass , $logintype, $euser ) ) ){
405
$this->_state = NET_SIEVE_STATE_TRANSACTION;
410
* Handles the authentication using any known method
412
* @param string $uid The userid to authenticate as.
413
* @param string $pwd The password to authenticate with.
414
* @param string $userMethod The method to use ( if $userMethod == '' then the class chooses the best method (the stronger is the best ) )
415
* @param string $euser The effective uid to authenticate as.
417
* @return mixed string or PEAR_Error
422
function _cmdAuthenticate($uid , $pwd , $userMethod = null , $euser = '' )
424
if ( PEAR::isError( $method = $this->_getBestAuthMethod($userMethod) ) ) {
429
$result = $this->_authDigest_MD5( $uid , $pwd , $euser );
433
$result = $this->_authCRAM_MD5( $uid , $pwd, $euser);
436
$result = $this->_authLOGIN( $uid , $pwd , $euser );
439
$result = $this->_authPLAIN( $uid , $pwd , $euser );
442
$result = new PEAR_Error( "$method is not a supported authentication method" );
446
if (PEAR::isError($res = $this->_doCmd() )) {
453
* Authenticates the user using the PLAIN method.
455
* @param string $user The userid to authenticate as.
456
* @param string $pass The password to authenticate with.
457
* @param string $euser The effective uid to authenticate as.
459
* @return array Returns an array containing the response
464
function _authPLAIN($user, $pass , $euser )
467
$cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode($euser . chr(0) . $user . chr(0) . $pass ) ) ;
469
$cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode( chr(0) . $user . chr(0) . $pass ) );
471
return $this->_sendCmd( $cmd ) ;
475
* Authenticates the user using the PLAIN method.
477
* @param string $user The userid to authenticate as.
478
* @param string $pass The password to authenticate with.
479
* @param string $euser The effective uid to authenticate as.
481
* @return array Returns an array containing the response
486
function _authLOGIN($user, $pass , $euser )
488
$this->_sendCmd('AUTHENTICATE "LOGIN"');
489
$this->_doCmd(sprintf('"%s"', base64_encode($user)));
490
$this->_doCmd(sprintf('"%s"', base64_encode($pass)));
494
* Authenticates the user using the CRAM-MD5 method.
496
* @param string $uid The userid to authenticate as.
497
* @param string $pwd The password to authenticate with.
498
* @param string $euser The effective uid to authenticate as.
500
* @return array Returns an array containing the response
505
function _authCRAM_MD5($uid, $pwd, $euser)
507
if ( PEAR::isError( $challenge = $this->_doCmd( 'AUTHENTICATE "CRAM-MD5"' ) ) ) {
508
$this->_error=$challenge;
511
$challenge=trim($challenge);
512
$challenge = base64_decode( trim($challenge) );
513
$cram = &Auth_SASL::factory('crammd5');
514
if ( PEAR::isError($resp=$cram->getResponse( $uid , $pwd , $challenge ) ) ) {
518
$auth_str = base64_encode( $resp );
519
if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str ) ) ) {
520
$this->_error=$error;
527
* Authenticates the user using the DIGEST-MD5 method.
529
* @param string $uid The userid to authenticate as.
530
* @param string $pwd The password to authenticate with.
531
* @param string $euser The effective uid to authenticate as.
533
* @return array Returns an array containing the response
538
function _authDigest_MD5($uid, $pwd, $euser)
540
if ( PEAR::isError( $challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"') ) ) {
541
$this->_error= $challenge;
544
$challenge = base64_decode( $challenge );
545
$digest = &Auth_SASL::factory('digestmd5');
547
if(PEAR::isError($param=$digest->getResponse($uid, $pwd, $challenge, "localhost", "sieve" , $euser) )) {
550
$auth_str = base64_encode($param);
552
if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str ) ) ) {
553
$this->_error=$error;
557
if ( PEAR::isError( $challenge = $this->_doCmd() ) ) {
558
$this->_error=$challenge ;
562
if( strtoupper(substr($challenge,0,2))== 'OK' ){
567
* We don't use the protocol's third step because SIEVE doesn't allow
568
* subsequent authentication, so we just silently ignore it.
570
if ( PEAR::isError($error = $this->_sendStringResponse( '' ) ) ) {
571
$this->_error=$error;
575
if (PEAR::isError($res = $this->_doCmd() )) {
581
* Removes a script from the server
584
* @param string $scriptname Name of the script to delete
585
* @return mixed True on success, PEAR_Error otherwise
587
function _cmdDeleteScript($scriptname)
589
if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
590
$msg='Not currently in AUTHORISATION state';
592
return $this->_raiseError($msg,$code);
594
if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname) ) )) {
601
* Retrieves the contents of the named script
604
* @param string $scriptname Name of the script to retrieve
605
* @return mixed The script if successful, PEAR_Error otherwise
607
function _cmdGetScript($scriptname)
609
if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
610
$msg='Not currently in AUTHORISATION state';
612
return $this->_raiseError($msg,$code);
615
if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname) ) ) ) {
619
return preg_replace('/{[0-9]+}\r\n/', '', $res);
623
* Sets the ACTIVE script, ie the one that gets run on new mail
627
* @param string $scriptname The name of the script to mark as active
628
* @return mixed True on success, PEAR_Error otherwise
630
function _cmdSetActive($scriptname)
632
if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
633
$msg='Not currently in AUTHORISATION state';
635
return $this->_raiseError($msg,$code);
638
if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname) ) ) ) {
642
$this->_activeScript = $scriptname;
647
* Sends the LISTSCRIPTS command
650
* @return mixed Two item array of scripts, and active script on success,
651
* PEAR_Error otherwise.
653
function _cmdListScripts()
655
if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
656
$msg='Not currently in AUTHORISATION state';
658
return $this->_raiseError($msg,$code);
662
$activescript = null;
664
if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
668
$res = explode("\r\n", $res);
670
foreach ($res as $value) {
671
if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
672
$scripts[] = $matches[1];
673
if (!empty($matches[2])) {
674
$activescript = $matches[1];
679
return array($scripts, $activescript);
683
* Sends the PUTSCRIPT command to add a script to
687
* @param string $scriptname Name of the new script
688
* @param string $scriptdata The new script
689
* @return mixed True on success, PEAR_Error otherwise
691
function _cmdPutScript($scriptname, $scriptdata)
693
if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
694
$msg='Not currently in TRANSACTION state';
696
return $this->_raiseError($msg,$code);
699
$stringLength = $this->_getLineLength($scriptdata);
701
if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata) ))) {
709
* Sends the LOGOUT command and terminates the connection
712
* @param boolean $sendLogoutCMD True to send LOGOUT command before disconnecting
713
* @return mixed True on success, PEAR_Error otherwise
715
function _cmdLogout($sendLogoutCMD=true)
717
if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
718
$msg='Not currently connected';
720
return $this->_raiseError($msg,$code);
721
//return PEAR::raiseError('Not currently connected');
725
if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
730
$this->_sock->disconnect();
731
$this->_state = NET_SIEVE_STATE_DISCONNECTED;
736
* Sends the CAPABILITY command
739
* @return mixed True on success, PEAR_Error otherwise
741
function _cmdCapability()
743
if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
744
$msg='Not currently connected';
746
return $this->_raiseError($msg,$code);
749
if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
752
$this->_parseCapability($res);
757
* Checks if the server has space to store the script
760
* @param string $scriptname The name of the script to mark as active
761
* @param integer $size The size of the script
762
* @return mixed True on success, PEAR_Error otherwise
764
function haveSpace($scriptname,$size)
766
if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
767
$msg='Not currently in TRANSACTION state';
769
return $this->_raiseError($msg,$code);
772
if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %d', $scriptname, $size) ) ) ) {
780
* Parses the response from the capability command. Stores
781
* the result in $this->_capability
784
* @param string $data The response from the capability command
786
function _parseCapability($data)
788
$data = preg_split('/\r?\n/', $data, -1, PREG_SPLIT_NO_EMPTY);
790
for ($i = 0; $i < count($data); $i++) {
791
if (preg_match('/^"([a-z]+)"( "(.*)")?$/i', $data[$i], $matches)) {
792
switch (strtolower($matches[1])) {
793
case 'implementation':
794
$this->_capability['implementation'] = $matches[3];
798
$this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
802
$this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
806
$this->_capability['starttls'] = true;
814
* Sends a command to the server
817
* @param string $cmd The command to send
819
function _sendCmd($cmd)
821
$status = $this->_sock->getStatus();
822
if (PEAR::isError($status) || $status['eof']) {
823
return new PEAR_Error( 'Failed to write to socket: (connection lost!) ' );
825
if ( PEAR::isError( $error = $this->_sock->write( $cmd . "\r\n" ) ) ) {
826
return new PEAR_Error( 'Failed to write to socket: ' . $error->getMessage() );
830
// C: means this data was sent by the client (this class)
837
* Sends a string response to the server
840
* @param string $cmd The command to send
842
function _sendStringResponse($str)
844
$response='{' . $this->_getLineLength($str) . "+}\r\n" . $str ;
845
return $this->_sendCmd($response);
851
if (PEAR::isError( $lastline = $this->_sock->gets( 8192 ) ) ) {
852
return new PEAR_Error( 'Failed to write to socket: ' . $lastline->getMessage() );
854
$lastline=rtrim($lastline);
856
// S: means this data was sent by the IMAP Server
857
echo "S:$lastline\n" ;
860
if( $lastline === '' ) {
861
return new PEAR_Error( 'Failed to receive from the socket' );
868
* Send a command and retrieves a response from the server.
872
* @param string $cmd The command to send
873
* @return mixed Reponse string if an OK response, PEAR_Error if a NO response
875
function _doCmd($cmd = '' )
878
while($referralCount < $this->_maxReferralCount ){
881
if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
888
if(PEAR::isError( $line=$this->_recvLn() )){
891
if ('ok' === strtolower(substr($line, 0, 2))) {
893
return rtrim($response);
895
} elseif ('no' === strtolower(substr($line, 0, 2))) {
896
// Check for string literal error message
897
if (preg_match('/^no {([0-9]+)\+?}/i', $line, $matches)) {
898
$line .= str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
903
$msg=trim($response . substr($line, 2));
905
return $this->_raiseError($msg,$code);
906
} elseif ('bye' === strtolower(substr($line, 0, 3))) {
908
if(PEAR::isError($error = $this->disconnect(false) ) ){
909
$msg="Can't handle bye, The error was= " . $error->getMessage() ;
911
return $this->_raiseError($msg,$code);
913
//if (preg_match('/^bye \(referral "([^"]+)/i', $line, $matches)) {
914
if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
915
// Check for referral, then follow it. Otherwise, carp an error.
916
// Replace the old host with the referral host preserving any protocol prefix
917
$this->_data['host'] = preg_replace('/\w+(?!(\w|\:\/\/)).*/',$matches[2],$this->_data['host']);
918
if (PEAR::isError($error = $this->_handleConnectAndLogin() ) ){
919
$msg="Can't follow referral to " . $this->_data['host'] . ", The error was= " . $error->getMessage() ;
921
return $this->_raiseError($msg,$code);
925
if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
930
$msg=trim($response . $line);
932
return $this->_raiseError($msg,$code);
933
} elseif (preg_match('/^{([0-9]+)\+?}/i', $line, $matches)) {
934
// Matches String Responses.
935
//$line = str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
936
$str_size = $matches[1] + 2;
939
while ($line_length < $str_size) {
940
$line .= $this->_sock->read($str_size - $line_length);
941
$line_length = $this->_getLineLength($line);
946
if($this->_state != NET_SIEVE_STATE_AUTHORISATION) {
947
// receive the pending OK only if we aren't authenticating
948
// since string responses during authentication don't need an
954
$response .= $line . "\r\n";
958
$msg="Max referral count reached ($referralCount times) Cyrus murder loop error?";
960
return $this->_raiseError($msg,$code);
964
* Sets the debug state
966
* @param boolean $debug
969
function setDebug($debug = true)
971
$this->_debug = $debug;
975
* Disconnect from the Sieve server
977
* @param string $scriptname The name of the script to be set as active
978
* @return mixed true on success, PEAR_Error on failure
980
function disconnect($sendLogoutCMD=true)
982
return $this->_cmdLogout($sendLogoutCMD);
986
* Returns the name of the best authentication method that the server
989
* @param string if !=null,authenticate with this method ($userMethod).
991
* @return mixed Returns a string containing the name of the best
992
* supported authentication method or a PEAR_Error object
993
* if a failure condition is encountered.
997
function _getBestAuthMethod($userMethod = null)
999
if( isset($this->_capability['sasl']) ){
1000
$serverMethods=$this->_capability['sasl'];
1002
// if the server don't send an sasl capability fallback to login auth
1004
return new PEAR_Error("This server don't support any Auth methods SASL problem?");
1007
if($userMethod != null ){
1009
$methods[] = $userMethod;
1012
$methods = $this->supportedAuthMethods;
1014
if( ($methods != null) && ($serverMethods != null)){
1015
foreach ( $methods as $method ) {
1016
if ( in_array( $method , $serverMethods ) ) {
1020
$serverMethods=implode(',' , $serverMethods );
1021
$myMethods=implode(',' ,$this->supportedAuthMethods);
1022
return new PEAR_Error("$method NOT supported authentication method!. This server " .
1023
"supports these methods= $serverMethods, but I support $myMethods");
1025
return new PEAR_Error("This server don't support any Auth methods");
1030
* Return the list of extensions the server supports
1032
* @return mixed array on success, PEAR_Error on failure
1034
function getExtensions()
1036
if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1037
$msg='Not currently connected';
1039
return $this->_raiseError($msg,$code);
1042
return $this->_capability['extensions'];
1046
* Return true if tyhe server has that extension
1048
* @param string the extension to compare
1049
* @return mixed array on success, PEAR_Error on failure
1051
function hasExtension($extension)
1053
if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1054
$msg='Not currently connected';
1056
return $this->_raiseError($msg,$code);
1059
if(is_array($this->_capability['extensions'] ) ){
1060
foreach( $this->_capability['extensions'] as $ext){
1061
if( trim( strtolower( $ext ) ) === trim( strtolower( $extension ) ) )
1069
* Return the list of auth methods the server supports
1071
* @return mixed array on success, PEAR_Error on failure
1073
function getAuthMechs()
1075
if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1076
$msg='Not currently connected';
1078
return $this->_raiseError($msg,$code);
1080
if(!isset($this->_capability['sasl']) ){
1081
$this->_capability['sasl']=array();
1083
return $this->_capability['sasl'];
1087
* Return true if the server has that extension
1089
* @param string the extension to compare
1090
* @return mixed array on success, PEAR_Error on failure
1092
function hasAuthMech($method)
1094
if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
1095
$msg='Not currently connected';
1097
return $this->_raiseError($msg,$code);
1098
//return PEAR::raiseError('Not currently connected');
1101
if(is_array($this->_capability['sasl'] ) ){
1102
foreach( $this->_capability['sasl'] as $ext){
1103
if( trim( strtolower( $ext ) ) === trim( strtolower( $method ) ) )
1111
* Return true if the TLS negotiation was successful
1114
* @return mixed true on success, PEAR_Error on failure
1116
function _startTLS()
1118
if (PEAR::isError($res = $this->_doCmd("STARTTLS"))) {
1122
if(stream_socket_enable_crypto($this->_sock->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) == false) {
1123
$msg='Failed to establish TLS connection';
1125
return $this->_raiseError($msg,$code);
1128
if($this->_debug === true) {
1129
echo "STARTTLS Negotiation Successful\n";
1132
// RFC says we need to query the server capabilities again
1133
if(PEAR::isError($res = $this->_cmdCapability() )) {
1134
$msg='Failed to connect, server said: ' . $res->getMessage();
1136
return $this->_raiseError($msg,$code);
1141
function _getLineLength($string) {
1142
if (extension_loaded('mbstring') || @dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX)) {
1143
return mb_strlen($string,'latin1');
1145
return strlen($string);