PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/php/Net/Sieve.php

https://bitbucket.org/adarshj/convenient_website
PHP | 1165 lines | 546 code | 194 blank | 425 comment | 95 complexity | c6b85b28f42c40bcc63624c874ce2c40 MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-2-Clause, GPL-2.0, LGPL-3.0
  1. <?php
  2. // +-----------------------------------------------------------------------+
  3. // | Copyright (c) 2002-2003, Richard Heyes |
  4. // | All rights reserved. |
  5. // | |
  6. // | Redistribution and use in source and binary forms, with or without |
  7. // | modification, are permitted provided that the following conditions |
  8. // | are met: |
  9. // | |
  10. // | o Redistributions of source code must retain the above copyright |
  11. // | notice, this list of conditions and the following disclaimer. |
  12. // | o Redistributions in binary form must reproduce the above copyright |
  13. // | notice, this list of conditions and the following disclaimer in the |
  14. // | documentation and/or other materials provided with the distribution.|
  15. // | o The names of the authors may not be used to endorse or promote |
  16. // | products derived from this software without specific prior written |
  17. // | permission. |
  18. // | |
  19. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  20. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  21. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
  22. // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
  23. // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
  24. // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
  25. // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
  26. // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
  27. // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
  28. // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
  29. // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
  30. // | |
  31. // +-----------------------------------------------------------------------+
  32. // | Author: Richard Heyes <richard@phpguru.org> |
  33. // | Co-Author: Damian Fernandez Sosa <damlists@cnba.uba.ar> |
  34. // +-----------------------------------------------------------------------+
  35. require_once('Net/Socket.php');
  36. /**
  37. * TODO
  38. *
  39. * o supportsAuthMech()
  40. */
  41. /**
  42. * Disconnected state
  43. * @const NET_SIEVE_STATE_DISCONNECTED
  44. */
  45. define('NET_SIEVE_STATE_DISCONNECTED', 1, true);
  46. /**
  47. * Authorisation state
  48. * @const NET_SIEVE_STATE_AUTHORISATION
  49. */
  50. define('NET_SIEVE_STATE_AUTHORISATION', 2, true);
  51. /**
  52. * Transaction state
  53. * @const NET_SIEVE_STATE_TRANSACTION
  54. */
  55. define('NET_SIEVE_STATE_TRANSACTION', 3, true);
  56. /**
  57. * A class for talking to the timsieved server which
  58. * comes with Cyrus IMAP. the HAVESPACE
  59. * command which appears to be broken (Cyrus 2.0.16).
  60. *
  61. * @author Richard Heyes <richard@php.net>
  62. * @author Damian Fernandez Sosa <damlists@cnba.uba.ar>
  63. * @access public
  64. * @version 0.9.1
  65. * @package Net_Sieve
  66. */
  67. class Net_Sieve
  68. {
  69. /**
  70. * The socket object
  71. * @var object
  72. */
  73. var $_sock;
  74. /**
  75. * Info about the connect
  76. * @var array
  77. */
  78. var $_data;
  79. /**
  80. * Current state of the connection
  81. * @var integer
  82. */
  83. var $_state;
  84. /**
  85. * Constructor error is any
  86. * @var object
  87. */
  88. var $_error;
  89. /**
  90. * To allow class debuging
  91. * @var boolean
  92. */
  93. var $_debug = false;
  94. /**
  95. * The auth methods this class support
  96. * @var array
  97. */
  98. var $supportedAuthMethods=array('DIGEST-MD5', 'CRAM-MD5', 'PLAIN' , 'LOGIN');
  99. //if you have problems using DIGEST-MD5 authentication please commente the line above and discomment the following line
  100. //var $supportedAuthMethods=array( 'CRAM-MD5', 'PLAIN' , 'LOGIN');
  101. //var $supportedAuthMethods=array( 'PLAIN' , 'LOGIN');
  102. /**
  103. * The auth methods this class support
  104. * @var array
  105. */
  106. var $supportedSASLAuthMethods=array('DIGEST-MD5', 'CRAM-MD5');
  107. /**
  108. * Handles posible referral loops
  109. * @var array
  110. */
  111. var $_maxReferralCount = 15;
  112. /**
  113. * Constructor
  114. * Sets up the object, connects to the server and logs in. stores
  115. * any generated error in $this->_error, which can be retrieved
  116. * using the getError() method.
  117. *
  118. * @access public
  119. * @param string $user Login username
  120. * @param string $pass Login password
  121. * @param string $host Hostname of server
  122. * @param string $port Port of server
  123. * @param string $logintype Type of login to perform
  124. * @param string $euser Effective User (if $user=admin, login as $euser)
  125. */
  126. function Net_Sieve($user = null , $pass = null , $host = 'localhost', $port = 2000, $logintype = '', $euser = '', $debug = false)
  127. {
  128. $this->_state = NET_SIEVE_STATE_DISCONNECTED;
  129. $this->_data['user'] = $user;
  130. $this->_data['pass'] = $pass;
  131. $this->_data['host'] = $host;
  132. $this->_data['port'] = $port;
  133. $this->_data['logintype'] = $logintype;
  134. $this->_data['euser'] = $euser;
  135. $this->_sock = &new Net_Socket();
  136. $this->_debug = $debug;
  137. /*
  138. * Include the Auth_SASL package. If the package is not available,
  139. * we disable the authentication methods that depend upon it.
  140. */
  141. if ((@include_once 'Auth/SASL.php') === false) {
  142. if($this->_debug){
  143. echo "AUTH_SASL NOT PRESENT!\n";
  144. }
  145. foreach($this->supportedSASLAuthMethods as $SASLMethod){
  146. $pos = array_search( $SASLMethod, $this->supportedAuthMethods );
  147. if($this->_debug){
  148. echo "DISABLING METHOD $SASLMethod\n";
  149. }
  150. unset($this->supportedAuthMethods[$pos]);
  151. }
  152. }
  153. if( ($user != null) && ($pass != null) ){
  154. $this->_error = $this->_handleConnectAndLogin();
  155. }
  156. }
  157. /**
  158. * Handles the errors the class can find
  159. * on the server
  160. *
  161. * @access private
  162. * @return PEAR_Error
  163. */
  164. function _raiseError($msg, $code)
  165. {
  166. include_once 'PEAR.php';
  167. return PEAR::raiseError($msg, $code);
  168. }
  169. /**
  170. * Handles connect and login.
  171. * on the server
  172. *
  173. * @access private
  174. * @return mixed Indexed array of scriptnames or PEAR_Error on failure
  175. */
  176. function _handleConnectAndLogin(){
  177. if (PEAR::isError($res = $this->connect($this->_data['host'] , $this->_data['port'] ))) {
  178. return $res;
  179. }
  180. if (PEAR::isError($res = $this->login($this->_data['user'], $this->_data['pass'], $this->_data['logintype'] , $this->_data['euser'] ) ) ) {
  181. return $res;
  182. }
  183. return true;
  184. }
  185. /**
  186. * Returns an indexed array of scripts currently
  187. * on the server
  188. *
  189. * @access public
  190. * @return mixed Indexed array of scriptnames or PEAR_Error on failure
  191. */
  192. function listScripts()
  193. {
  194. if (is_array($scripts = $this->_cmdListScripts())) {
  195. $this->_active = $scripts[1];
  196. return $scripts[0];
  197. } else {
  198. return $scripts;
  199. }
  200. }
  201. /**
  202. * Returns the active script
  203. *
  204. * @access public
  205. * @return mixed The active scriptname or PEAR_Error on failure
  206. */
  207. function getActive()
  208. {
  209. if (!empty($this->_active)) {
  210. return $this->_active;
  211. } elseif (is_array($scripts = $this->_cmdListScripts())) {
  212. $this->_active = $scripts[1];
  213. return $scripts[1];
  214. }
  215. }
  216. /**
  217. * Sets the active script
  218. *
  219. * @access public
  220. * @param string $scriptname The name of the script to be set as active
  221. * @return mixed true on success, PEAR_Error on failure
  222. */
  223. function setActive($scriptname)
  224. {
  225. return $this->_cmdSetActive($scriptname);
  226. }
  227. /**
  228. * Retrieves a script
  229. *
  230. * @access public
  231. * @param string $scriptname The name of the script to be retrieved
  232. * @return mixed The script on success, PEAR_Error on failure
  233. */
  234. function getScript($scriptname)
  235. {
  236. return $this->_cmdGetScript($scriptname);
  237. }
  238. /**
  239. * Adds a script to the server
  240. *
  241. * @access public
  242. * @param string $scriptname Name of the script
  243. * @param string $script The script
  244. * @param bool $makeactive Whether to make this the active script
  245. * @return mixed true on success, PEAR_Error on failure
  246. */
  247. function installScript($scriptname, $script, $makeactive = false)
  248. {
  249. if (PEAR::isError($res = $this->_cmdPutScript($scriptname, $script))) {
  250. return $res;
  251. } elseif ($makeactive) {
  252. return $this->_cmdSetActive($scriptname);
  253. } else {
  254. return true;
  255. }
  256. }
  257. /**
  258. * Removes a script from the server
  259. *
  260. * @access public
  261. * @param string $scriptname Name of the script
  262. * @return mixed True on success, PEAR_Error on failure
  263. */
  264. function removeScript($scriptname)
  265. {
  266. return $this->_cmdDeleteScript($scriptname);
  267. }
  268. /**
  269. * Returns any error that may have been generated in the
  270. * constructor
  271. *
  272. * @access public
  273. * @return mixed False if no error, PEAR_Error otherwise
  274. */
  275. function getError()
  276. {
  277. return PEAR::isError($this->_error) ? $this->_error : false;
  278. }
  279. /**
  280. * Handles connecting to the server and checking the
  281. * response is valid.
  282. *
  283. * @access private
  284. * @param string $host Hostname of server
  285. * @param string $port Port of server
  286. * @return mixed True on success, PEAR_Error otherwise
  287. */
  288. function connect($host, $port)
  289. {
  290. if (NET_SIEVE_STATE_DISCONNECTED != $this->_state) {
  291. $msg='Not currently in DISCONNECTED state';
  292. $code=1;
  293. return $this->_raiseError($msg,$code);
  294. }
  295. if (PEAR::isError($res = $this->_sock->connect($host, $port, null, 5))) {
  296. return $res;
  297. }
  298. $this->_state = NET_SIEVE_STATE_AUTHORISATION;
  299. if (PEAR::isError($res = $this->_doCmd())) {
  300. return $res;
  301. }
  302. /*
  303. if(PEAR::isError($res = $this->_cmdCapability() )) {
  304. $msg='Failed to connect, server said: ' . $res->getMessage();
  305. $code=2;
  306. return $this->_raiseError($msg,$code);
  307. }
  308. */
  309. // Get logon greeting/capability and parse
  310. $this->_parseCapability($res);
  311. return true;
  312. }
  313. /**
  314. * Logs into server.
  315. *
  316. * @access public
  317. * @param string $user Login username
  318. * @param string $pass Login password
  319. * @param string $logintype Type of login method to use
  320. * @param string $euser Effective UID (perform on behalf of $euser)
  321. * @param boolean $bypassAuth dont perform auth
  322. * @return mixed True on success, PEAR_Error otherwise
  323. */
  324. function login($user, $pass, $logintype = null , $euser = '', $bypassAuth=false)
  325. {
  326. if (NET_SIEVE_STATE_AUTHORISATION != $this->_state) {
  327. $msg='Not currently in AUTHORISATION state';
  328. $code=1;
  329. return $this->_raiseError($msg,$code);
  330. }
  331. if( $bypassAuth === false ){
  332. if(PEAR::isError($res=$this->_cmdAuthenticate($user , $pass , $logintype, $euser ) ) ){
  333. return $res;
  334. }
  335. }
  336. $this->_state = NET_SIEVE_STATE_TRANSACTION;
  337. return true;
  338. }
  339. /* Handles the authentication using any known method
  340. *
  341. * @param string The userid to authenticate as.
  342. * @param string The password to authenticate with.
  343. * @param string The method to use ( if $usermethod == '' then the class chooses the best method (the stronger is the best ) )
  344. * @param string The effective uid to authenticate as.
  345. *
  346. * @return mixed string or PEAR_Error
  347. *
  348. * @access private
  349. * @since 1.0
  350. */
  351. function _cmdAuthenticate($uid , $pwd , $userMethod = null , $euser = '' )
  352. {
  353. if ( PEAR::isError( $method = $this->_getBestAuthMethod($userMethod) ) ) {
  354. return $method;
  355. }
  356. switch ($method) {
  357. case 'DIGEST-MD5':
  358. $result = $this->_authDigest_MD5( $uid , $pwd , $euser );
  359. return $result;
  360. break;
  361. case 'CRAM-MD5':
  362. $result = $this->_authCRAM_MD5( $uid , $pwd, $euser);
  363. break;
  364. case 'LOGIN':
  365. $result = $this->_authLOGIN( $uid , $pwd , $euser );
  366. break;
  367. case 'PLAIN':
  368. $result = $this->_authPLAIN( $uid , $pwd , $euser );
  369. break;
  370. default :
  371. $result = new PEAR_Error( "$method is not a supported authentication method" );
  372. break;
  373. }
  374. if (PEAR::isError($res = $this->_doCmd() )) {
  375. return $res;
  376. }
  377. return $result;
  378. }
  379. /* Authenticates the user using the PLAIN method.
  380. *
  381. * @param string The userid to authenticate as.
  382. * @param string The password to authenticate with.
  383. * @param string The effective uid to authenticate as.
  384. *
  385. * @return array Returns an array containing the response
  386. *
  387. * @access private
  388. * @since 1.0
  389. */
  390. function _authPLAIN($user, $pass , $euser )
  391. {
  392. if ($euser != '') {
  393. $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode($euser . chr(0) . $user . chr(0) . $pass ) ) ;
  394. } else {
  395. $cmd=sprintf('AUTHENTICATE "PLAIN" "%s"', base64_encode( chr(0) . $user . chr(0) . $pass ) );
  396. }
  397. return $this->_sendCmd( $cmd ) ;
  398. }
  399. /* Authenticates the user using the PLAIN method.
  400. *
  401. * @param string The userid to authenticate as.
  402. * @param string The password to authenticate with.
  403. * @param string The effective uid to authenticate as.
  404. *
  405. * @return array Returns an array containing the response
  406. *
  407. * @access private
  408. * @since 1.0
  409. */
  410. function _authLOGIN($user, $pass , $euser )
  411. {
  412. $this->_sendCmd('AUTHENTICATE "LOGIN"');
  413. $this->_doCmd(sprintf('"%s"', base64_encode($user)));
  414. $this->_doCmd(sprintf('"%s"', base64_encode($pass)));
  415. }
  416. /* Authenticates the user using the CRAM-MD5 method.
  417. *
  418. * @param string The userid to authenticate as.
  419. * @param string The password to authenticate with.
  420. * @param string The cmdID.
  421. *
  422. * @return array Returns an array containing the response
  423. *
  424. * @access private
  425. * @since 1.0
  426. */
  427. function _authCRAM_MD5($uid, $pwd, $euser)
  428. {
  429. if ( PEAR::isError( $challenge = $this->_doCmd( 'AUTHENTICATE "CRAM-MD5"' ) ) ) {
  430. $this->_error=challenge ;
  431. return challenge ;
  432. }
  433. $challenge=trim($challenge);
  434. $challenge = base64_decode( trim($challenge) );
  435. $cram = &Auth_SASL::factory('crammd5');
  436. if ( PEAR::isError($resp=$cram->getResponse( $uid , $pwd , $challenge ) ) ) {
  437. $this->_error=$resp;
  438. return $resp;
  439. }
  440. $auth_str = base64_encode( $resp );
  441. if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str ) ) ) {
  442. $this->_error=$error;
  443. return $error;
  444. }
  445. }
  446. /* Authenticates the user using the DIGEST-MD5 method.
  447. *
  448. * @param string The userid to authenticate as.
  449. * @param string The password to authenticate with.
  450. * @param string The efective user
  451. *
  452. * @return array Returns an array containing the response
  453. *
  454. * @access private
  455. * @since 1.0
  456. */
  457. function _authDigest_MD5($uid, $pwd, $euser)
  458. {
  459. if ( PEAR::isError( $challenge = $this->_doCmd('AUTHENTICATE "DIGEST-MD5"') ) ) {
  460. $this->_error=challenge ;
  461. return challenge ;
  462. }
  463. $challenge = base64_decode( $challenge );
  464. $digest = &Auth_SASL::factory('digestmd5');
  465. if(PEAR::isError($param=$digest->getResponse($uid, $pwd, $challenge, "localhost", "sieve" , $euser) )) {
  466. return $param;
  467. }
  468. $auth_str = base64_encode($param);
  469. if ( PEAR::isError($error = $this->_sendStringResponse( $auth_str ) ) ) {
  470. $this->_error=$error;
  471. return $error;
  472. }
  473. if ( PEAR::isError( $challenge = $this->_doCmd() ) ) {
  474. $this->_error=$challenge ;
  475. return $challenge ;
  476. }
  477. if( strtoupper(substr($challenge,0,2))== 'OK' ){
  478. return true;
  479. }
  480. /*
  481. * We don't use the protocol's third step because SIEVE doesn't allow
  482. * subsequent authentication, so we just silently ignore it.
  483. */
  484. if ( PEAR::isError($error = $this->_sendStringResponse( '' ) ) ) {
  485. $this->_error=$error;
  486. return $error;
  487. }
  488. if (PEAR::isError($res = $this->_doCmd() )) {
  489. return $res;
  490. }
  491. }
  492. /**
  493. * Removes a script from the server
  494. *
  495. * @access private
  496. * @param string $scriptname Name of the script to delete
  497. * @return mixed True on success, PEAR_Error otherwise
  498. */
  499. function _cmdDeleteScript($scriptname)
  500. {
  501. if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
  502. $msg='Not currently in AUTHORISATION state';
  503. $code=1;
  504. return $this->_raiseError($msg,$code);
  505. }
  506. if (PEAR::isError($res = $this->_doCmd(sprintf('DELETESCRIPT "%s"', $scriptname) ) )) {
  507. return $res;
  508. }
  509. return true;
  510. }
  511. /**
  512. * Retrieves the contents of the named script
  513. *
  514. * @access private
  515. * @param string $scriptname Name of the script to retrieve
  516. * @return mixed The script if successful, PEAR_Error otherwise
  517. */
  518. function _cmdGetScript($scriptname)
  519. {
  520. if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
  521. $msg='Not currently in AUTHORISATION state';
  522. $code=1;
  523. return $this->_raiseError($msg,$code);
  524. }
  525. if (PEAR::isError($res = $this->_doCmd(sprintf('GETSCRIPT "%s"', $scriptname) ) ) ) {
  526. return $res;
  527. }
  528. return preg_replace('/{[0-9]+}\r\n/', '', $res);
  529. }
  530. /**
  531. * Sets the ACTIVE script, ie the one that gets run on new mail
  532. * by the server
  533. *
  534. * @access private
  535. * @param string $scriptname The name of the script to mark as active
  536. * @return mixed True on success, PEAR_Error otherwise
  537. */
  538. function _cmdSetActive($scriptname)
  539. {
  540. if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
  541. $msg='Not currently in AUTHORISATION state';
  542. $code=1;
  543. return $this->_raiseError($msg,$code);
  544. }
  545. if (PEAR::isError($res = $this->_doCmd(sprintf('SETACTIVE "%s"', $scriptname) ) ) ) {
  546. return $res;
  547. }
  548. $this->_activeScript = $scriptname;
  549. return true;
  550. }
  551. /**
  552. * Sends the LISTSCRIPTS command
  553. *
  554. * @access private
  555. * @return mixed Two item array of scripts, and active script on success,
  556. * PEAR_Error otherwise.
  557. */
  558. function _cmdListScripts()
  559. {
  560. if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
  561. $msg='Not currently in AUTHORISATION state';
  562. $code=1;
  563. return $this->_raiseError($msg,$code);
  564. }
  565. $scripts = array();
  566. $activescript = null;
  567. if (PEAR::isError($res = $this->_doCmd('LISTSCRIPTS'))) {
  568. return $res;
  569. }
  570. $res = explode("\r\n", $res);
  571. foreach ($res as $value) {
  572. if (preg_match('/^"(.*)"( ACTIVE)?$/i', $value, $matches)) {
  573. $scripts[] = $matches[1];
  574. if (!empty($matches[2])) {
  575. $activescript = $matches[1];
  576. }
  577. }
  578. }
  579. return array($scripts, $activescript);
  580. }
  581. /**
  582. * Sends the PUTSCRIPT command to add a script to
  583. * the server.
  584. *
  585. * @access private
  586. * @param string $scriptname Name of the new script
  587. * @param string $scriptdata The new script
  588. * @return mixed True on success, PEAR_Error otherwise
  589. */
  590. function _cmdPutScript($scriptname, $scriptdata)
  591. {
  592. if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
  593. $msg='Not currently in TRANSACTION state';
  594. $code=1;
  595. return $this->_raiseError($msg,$code);
  596. }
  597. if (PEAR::isError($res = $this->_doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, strlen($scriptdata),$scriptdata ) ))) {
  598. return $res;
  599. }
  600. return true;
  601. }
  602. /**
  603. * Sends the LOGOUT command and terminates the connection
  604. *
  605. * @access private
  606. * @return mixed True on success, PEAR_Error otherwise
  607. */
  608. function _cmdLogout($sendLogoutCMD=true)
  609. {
  610. if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
  611. $msg='Not currently connected';
  612. $code=1;
  613. return $this->_raiseError($msg,$code);
  614. //return PEAR::raiseError('Not currently connected');
  615. }
  616. if($sendLogoutCMD){
  617. if (PEAR::isError($res = $this->_doCmd('LOGOUT'))) {
  618. return $res;
  619. }
  620. }
  621. $this->_sock->disconnect();
  622. $this->_state = NET_SIEVE_STATE_DISCONNECTED;
  623. return true;
  624. }
  625. /**
  626. * Sends the CAPABILITY command
  627. *
  628. * @access private
  629. * @return mixed True on success, PEAR_Error otherwise
  630. */
  631. function _cmdCapability()
  632. {
  633. if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
  634. $msg='Not currently connected';
  635. $code=1;
  636. return $this->_raiseError($msg,$code);
  637. }
  638. if (PEAR::isError($res = $this->_doCmd('CAPABILITY'))) {
  639. return $res;
  640. }
  641. $this->_parseCapability($res);
  642. return true;
  643. }
  644. /**
  645. * Checks if the server has space to store the script
  646. * by the server
  647. *
  648. * @access public
  649. * @param string $scriptname The name of the script to mark as active
  650. * @return mixed True on success, PEAR_Error otherwise
  651. */
  652. function haveSpace($scriptname,$quota)
  653. {
  654. if (NET_SIEVE_STATE_TRANSACTION != $this->_state) {
  655. $msg='Not currently in TRANSACTION state';
  656. $code=1;
  657. return $this->_raiseError($msg,$code);
  658. }
  659. if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE "%s" %s', $scriptname, $quota) ) ) ) {
  660. //if (PEAR::isError($res = $this->_doCmd(sprintf('HAVESPACE %d "%s"', $quota,$scriptname ) ) ) ) {
  661. return $res;
  662. }
  663. return true;
  664. }
  665. /**
  666. * Parses the response from the capability command. Storesq
  667. * the result in $this->_capability
  668. *
  669. * @access private
  670. */
  671. function _parseCapability($data)
  672. {
  673. $data = preg_split('/\r?\n/', $data, -1, PREG_SPLIT_NO_EMPTY);
  674. for ($i = 0; $i < count($data); $i++) {
  675. if (preg_match('/^"([a-z]+)" ("(.*)")?$/i', $data[$i], $matches)) {
  676. switch (strtolower($matches[1])) {
  677. case 'implementation':
  678. $this->_capability['implementation'] = $matches[3];
  679. break;
  680. case 'sasl':
  681. $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]);
  682. break;
  683. case 'sieve':
  684. $this->_capability['extensions'] = preg_split('/\s+/', $matches[3]);
  685. break;
  686. case 'starttls':
  687. $this->_capability['starttls'] = true;
  688. }
  689. }
  690. }
  691. }
  692. /**
  693. * Sends a command to the server
  694. *
  695. * @access private
  696. * @param string $cmd The command to send
  697. */
  698. function _sendCmd($cmd)
  699. {
  700. $status = $this->_sock->getStatus();
  701. if (PEAR::isError($status) || $status['eof']) {
  702. return new PEAR_Error( 'Failed to write to socket: (connection lost!) ' );
  703. }
  704. if ( PEAR::isError( $error = $this->_sock->write( $cmd . "\r\n" ) ) ) {
  705. return new PEAR_Error( 'Failed to write to socket: ' . $error->getMessage() );
  706. }
  707. if( $this->_debug ){
  708. // C: means this data was sent by the client (this class)
  709. echo "C:$cmd\n";
  710. }
  711. return true;
  712. }
  713. /**
  714. * Sends a string response to the server
  715. *
  716. * @access private
  717. * @param string $cmd The command to send
  718. */
  719. function _sendStringResponse($str)
  720. {
  721. $response='{' . strlen($str) . "+}\r\n" . $str ;
  722. return $this->_sendCmd($response);
  723. }
  724. function _recvLn()
  725. {
  726. $lastline='';
  727. if (PEAR::isError( $lastline = $this->_sock->gets( 8192 ) ) ) {
  728. return new PEAR_Error('Failed to write to socket: ' . $lastline->getMessage() );
  729. }
  730. $lastline=rtrim($lastline);
  731. if($this->_debug){
  732. // S: means this data was sent by the IMAP Server
  733. echo "S:$lastline\n" ;
  734. }
  735. /* if( $lastline === '' ){
  736. return new PEAR_Error('Failed to receive from the socket: ' );
  737. }
  738. */
  739. return $lastline;
  740. }
  741. /**
  742. * Send a command and retrieves a response from the server.
  743. *
  744. *
  745. * @access private
  746. * @param string $cmd The command to send
  747. * @return mixed Reponse string if an OK response, PEAR_Error if a NO response
  748. */
  749. function _doCmd($cmd = '' )
  750. {
  751. $referralCount=0;
  752. while($referralCount < $this->_maxReferralCount ){
  753. if($cmd != '' ){
  754. if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
  755. return $error;
  756. }
  757. }
  758. $response = '';
  759. while (true) {
  760. if(PEAR::isError( $line=$this->_recvLn() )){
  761. return $line;
  762. }
  763. if ('ok' === strtolower(substr($line, 0, 2))) {
  764. $response .= $line;
  765. return rtrim($response);
  766. } elseif ('no' === strtolower(substr($line, 0, 2))) {
  767. // Check for string literal error message
  768. if (preg_match('/^no {([0-9]+)\+?}/i', $line, $matches)) {
  769. $line .= str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
  770. if($this->_debug){
  771. echo "S:$line\n";
  772. }
  773. }
  774. $msg=trim($response . substr($line, 2));
  775. $code=3;
  776. return $this->_raiseError($msg,$code);
  777. //return PEAR::raiseError(trim($response . substr($line, 2)));
  778. } elseif ('bye' === strtolower(substr($line, 0, 3))) {
  779. if(PEAR::isError($error = $this->disconnect(false) ) ){
  780. $msg="Can't handle bye, The error was= " . $error->getMessage() ;
  781. $code=4;
  782. return $this->_raiseError($msg,$code);
  783. //return PEAR::raiseError("Can't handle bye, The error was= " . $error->getMessage() );
  784. }
  785. //if (preg_match('/^bye \(referral "([^"]+)/i', $line, $matches)) {
  786. if (preg_match('/^bye \(referral "(sieve:\/\/)?([^"]+)/i', $line, $matches)) {
  787. // Check for referral, then follow it. Otherwise, carp an error.
  788. //$this->_data['host'] = $matches[1];
  789. $this->_data['host'] = $matches[2];
  790. if (PEAR::isError($error = $this->_handleConnectAndLogin() ) ){
  791. $msg="Can't follow referral to " . $this->_data['host'] . ", The error was= " . $error->getMessage() ;
  792. $code=5;
  793. return $this->_raiseError($msg,$code);
  794. //return PEAR::raiseError("Can't follow referral to " . $this->_data['host'] . ", The error was= " . $error->getMessage() );
  795. }
  796. break;
  797. // Retry the command
  798. if(PEAR::isError($error = $this->_sendCmd($cmd) )) {
  799. return $error;
  800. }
  801. continue;
  802. }
  803. $msg=trim($response . $line);
  804. $code=6;
  805. return $this->_raiseError($msg,$code);
  806. //return PEAR::raiseError(trim($response . $line));
  807. } elseif (preg_match('/^{([0-9]+)\+?}/i', $line, $matches)) {
  808. // Matches String Responses.
  809. //$line = str_replace("\r\n", ' ', $this->_sock->read($matches[1] + 2 ));
  810. $line = $this->_sock->read($matches[1] + 2 );
  811. if($this->_debug){
  812. echo "S:$line\n";
  813. }
  814. return $line;
  815. }
  816. $response .= $line . "\r\n";
  817. $referralCount++;
  818. }
  819. }
  820. $msg="Max referral count reached ($referralCount times) Cyrus murder loop error?";
  821. $code=7;
  822. return $this->_raiseError($msg,$code);
  823. //return PEAR::raiseError("Max referral count reached ($referralCount times) Cyrus murder loop error?" );
  824. }
  825. /**
  826. * Sets the bebug state
  827. *
  828. * @access public
  829. * @return void
  830. */
  831. function setDebug($debug=true)
  832. {
  833. $this->_debug=$debug;
  834. }
  835. /**
  836. * Disconnect from the Sieve server
  837. *
  838. * @access public
  839. * @param string $scriptname The name of the script to be set as active
  840. * @return mixed true on success, PEAR_Error on failure
  841. */
  842. function disconnect($sendLogoutCMD=true)
  843. {
  844. return $this->_cmdLogout($sendLogoutCMD);
  845. }
  846. /**
  847. * Returns the name of the best authentication method that the server
  848. * has advertised.
  849. *
  850. * @param string if !=null,authenticate with this method ($userMethod).
  851. *
  852. * @return mixed Returns a string containing the name of the best
  853. * supported authentication method or a PEAR_Error object
  854. * if a failure condition is encountered.
  855. * @access private
  856. * @since 1.0
  857. */
  858. function _getBestAuthMethod($userMethod = null)
  859. {
  860. if( isset($this->_capability['sasl']) ){
  861. $serverMethods=$this->_capability['sasl'];
  862. }else{
  863. // if the server don't send an sasl capability fallback to login auth
  864. //return 'LOGIN';
  865. return new PEAR_Error("This server don't support any Auth methods SASL problem?");
  866. }
  867. if($userMethod != null ){
  868. $methods = array();
  869. $methods[] = $userMethod;
  870. }else{
  871. $methods = $this->supportedAuthMethods;
  872. }
  873. if( ($methods != null) && ($serverMethods != null)){
  874. foreach ( $methods as $method ) {
  875. if ( in_array( $method , $serverMethods ) ) {
  876. return $method;
  877. }
  878. }
  879. $serverMethods=implode(',' , $serverMethods );
  880. $myMethods=implode(',' ,$this->supportedAuthMethods);
  881. return new PEAR_Error("$method NOT supported authentication method!. This server " .
  882. "supports these methods= $serverMethods, but I support $myMethods");
  883. }else{
  884. return new PEAR_Error("This server don't support any Auth methods");
  885. }
  886. }
  887. /**
  888. * Return the list of extensions the server supports
  889. *
  890. * @access public
  891. * @return mixed array on success, PEAR_Error on failure
  892. */
  893. function getExtensions()
  894. {
  895. if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
  896. $msg='Not currently connected';
  897. $code=7;
  898. return $this->_raiseError($msg,$code);
  899. //return PEAR::raiseError('Not currently connected');
  900. }
  901. return $this->_capability['extensions'];
  902. }
  903. /**
  904. * Return true if tyhe server has that extension
  905. *
  906. * @access public
  907. * @param string the extension to compare
  908. * @return mixed array on success, PEAR_Error on failure
  909. */
  910. function hasExtension($extension)
  911. {
  912. if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
  913. $msg='Not currently connected';
  914. $code=7;
  915. return $this->_raiseError($msg,$code);
  916. //return PEAR::raiseError('Not currently connected');
  917. }
  918. if(is_array($this->_capability['extensions'] ) ){
  919. foreach( $this->_capability['extensions'] as $ext){
  920. if( trim( strtolower( $ext ) ) === trim( strtolower( $extension ) ) )
  921. return true;
  922. }
  923. }
  924. return false;
  925. }
  926. /**
  927. * Return the list of auth methods the server supports
  928. *
  929. * @access public
  930. * @return mixed array on success, PEAR_Error on failure
  931. */
  932. function getAuthMechs()
  933. {
  934. if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
  935. $msg='Not currently connected';
  936. $code=7;
  937. return $this->_raiseError($msg,$code);
  938. //return PEAR::raiseError('Not currently connected');
  939. }
  940. if(!isset($this->_capability['sasl']) ){
  941. $this->_capability['sasl']=array();
  942. }
  943. return $this->_capability['sasl'];
  944. }
  945. /**
  946. * Return true if tyhe server has that extension
  947. *
  948. * @access public
  949. * @param string the extension to compare
  950. * @return mixed array on success, PEAR_Error on failure
  951. */
  952. function hasAuthMech($method)
  953. {
  954. if (NET_SIEVE_STATE_DISCONNECTED === $this->_state) {
  955. $msg='Not currently connected';
  956. $code=7;
  957. return $this->_raiseError($msg,$code);
  958. //return PEAR::raiseError('Not currently connected');
  959. }
  960. if(is_array($this->_capability['sasl'] ) ){
  961. foreach( $this->_capability['sasl'] as $ext){
  962. if( trim( strtolower( $ext ) ) === trim( strtolower( $method ) ) )
  963. return true;
  964. }
  965. }
  966. return false;
  967. }
  968. }
  969. ?>