rcube_sieve.php 12.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
<?php

/**
 * Classes for managesieve operations (using PEAR::Net_Sieve)
 *
 * Copyright (C) The Roundcube Dev Team
 * Copyright (C) Kolab Systems AG
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

// Managesieve Protocol: RFC5804

class rcube_sieve
{
    private $sieve;                 // Net_Sieve object
    private $error      = false;    // error flag
    private $errorLines = [];       // array of line numbers within sieve script which raised an error
    private $list       = [];       // scripts list
    private $exts;                  // array of supported extensions
    private $active;                // active script name

    public $script;                 // rcube_sieve_script object
    public $current;                // name of currently loaded script

    const ERROR_CONNECTION = 1;
    const ERROR_LOGIN      = 2;
    const ERROR_NOT_EXISTS = 3;    // script not exists
    const ERROR_INSTALL    = 4;    // script installation
    const ERROR_ACTIVATE   = 5;    // script activation
    const ERROR_DELETE     = 6;    // script deletion
    const ERROR_INTERNAL   = 7;    // internal error
    const ERROR_DEACTIVATE = 8;    // script activation
    const ERROR_OTHER      = 255;  // other/unknown error


    /**
     * Object constructor
     *
     * @param string  Username (for managesieve login)
     * @param string  Password (for managesieve login)
     * @param string  Managesieve server hostname/address
     * @param string  Managesieve server port number
     * @param string  Managesieve authentication method 
     * @param boolean Enable/disable TLS use
     * @param array   Disabled extensions
     * @param boolean Enable/disable debugging
     * @param string  Proxy authentication identifier
     * @param string  Proxy authentication password
     * @param array   List of options to pass to stream_context_create().
     */
    public function __construct($username, $password = '', $host = 'localhost', $port = 4190,
        $auth_type = null, $usetls = true, $disabled = [], $debug = false,
        $auth_cid = null, $auth_pw = null, $options = [], $gssapi_principal = null,
        $gssapi_cname = null)
    {
        $this->sieve = new Net_Sieve();

        if ($debug) {
            $this->sieve->setDebug(true, [$this, 'debug_handler']);
        }

        if (isset($gssapi_principal)) {
            $this->sieve->setServicePrincipal($gssapi_principal);
        }

        if (isset($gssapi_cname)) {
            $this->sieve->setServiceCN($gssapi_cname);
        }

        $result = $this->sieve->connect($host, $port, $options, $usetls);

        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_CONNECTION);
        }

        $authz = null;

        if (!empty($auth_cid)) {
            $authz    = $username;
            $username = $auth_cid;
        }

        if (!empty($auth_pw)) {
            $password = $auth_pw;
        }

        $result = $this->sieve->login($username, $password, $auth_type ? strtoupper($auth_type) : null, $authz);

        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_LOGIN);
        }

        $this->exts = $this->get_extensions();

        // disable features by config
        if (!empty($disabled)) {
            // we're working on lower-cased names
            $disabled = array_map('strtolower', (array) $disabled);
            foreach ($disabled as $ext) {
                if (($idx = array_search($ext, $this->exts)) !== false) {
                    unset($this->exts[$idx]);
                }
            }
        }
    }

    public function __destruct()
    {
        $this->sieve->disconnect();
    }

    /**
     * Getter for error code
     */
    public function error()
    {
        return $this->error ?: false;
    }

    /**
     * Saves current script into server
     */
    public function save($name = null)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        if (!$this->script) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        if (!$name) {
            $name = $this->current;
        }

        $script = $this->script->as_text();

        if (!$script) {
            $script = '/* empty script */';
        }

        $result = $this->sieve->installScript($name, $script);
        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_INSTALL);
        }

        return true;
    }

    /**
     * Saves text script into server
     */
    public function save_script($name, $content = null)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        if (!$content) {
            $content = '/* empty script */';
        }

        $result = $this->sieve->installScript($name, $content);

        if (is_a($result, 'PEAR_Error')) {
            $rawErrorMessage = $result->getMessage();
            $errMessages = preg_split("/$name:/", $rawErrorMessage);

            if (count($errMessages) > 0) {
                foreach ($errMessages as $singleError) {
                    $res = preg_match('/line (\d+):(.*)/i', $singleError, $matches);

                    if ($res === 1 ) {
                        if (count($matches) > 2) {
                            $this->errorLines[] = ['line' => $matches[1], 'msg' => $matches[2]];
                        }
                        else {
                            $this->errorLines[] = ['line' => $matches[1], 'msg' => null];
                        }
                    }
                }
            }

            return $this->_set_error(self::ERROR_INSTALL);
        }

        return true;
    }

    /**
     * Returns the current error line within the saved sieve script
     */
    public function get_error_lines()
    {
        return $this->errorLines;
    }

    /**
     * Activates specified script
     */
    public function activate($name = null)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        if (!$name) {
            $name = $this->current;
        }

        $result = $this->sieve->setActive($name);

        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_ACTIVATE);
        }

        $this->active = $name;

        return true;
    }

    /**
     * De-activates specified script
     */
    public function deactivate()
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        $result = $this->sieve->setActive('');

        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_DEACTIVATE);
        }

        $this->active = null;

        return true;
    }

    /**
     * Removes specified script
     */
    public function remove($name = null)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        if (!$name) {
            $name = $this->current;
        }

        // script must be deactivated first
        if ($name == $this->sieve->getActive()) {
            $result = $this->sieve->setActive('');

            if (is_a($result, 'PEAR_Error')) {
                return $this->_set_error(self::ERROR_DELETE);
            }

            $this->active = null;
        }

        $result = $this->sieve->removeScript($name);

        if (is_a($result, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_DELETE);
        }

        if ($name == $this->current) {
            $this->current = null;
        }

        $this->list = null;

        return true;
    }

    /**
     * Gets list of supported by server Sieve extensions
     */
    public function get_extensions()
    {
        if ($this->exts) {
            return $this->exts;
        }

        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        $ext = $this->sieve->getExtensions();

        if (is_a($ext, 'PEAR_Error')) {
            return [];
        }

        // we're working on lower-cased names
        $ext = array_map('strtolower', (array) $ext);

        if ($this->script) {
            $supported = $this->script->get_extensions();
            $ext       = array_values(array_intersect($ext, $supported));
        }

        return $ext;
    }

    /**
     * Gets list of scripts from server
     */
    public function get_scripts()
    {
        if (!$this->list) {
            if (!$this->sieve) {
                return $this->_set_error(self::ERROR_INTERNAL);
            }

            $active = null;
            $list   = $this->sieve->listScripts($active);

            if (is_a($list, 'PEAR_Error')) {
                return $this->_set_error(self::ERROR_OTHER);
            }

            $this->list   = $list;
            $this->active = $active;
        }

        return $this->list;
    }

    /**
     * Returns active script name
     */
    public function get_active()
    {
        if ($this->active !== null) {
            return $this->active;
        }

        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        return $this->active = $this->sieve->getActive();
    }

    /**
     * Loads script by name
     */
    public function load($name)
    {
        if ($this->current === $name) {
            return true;
        }

        $script = $this->get_script($name);

        if ($script === false) {
            return false;
        }

        // try to parse to Roundcube format
        $this->script = $this->_parse($script);

        $this->current = $name;

        return true;
    }

    /**
     * Loads script from text content
     */
    public function load_script($script)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        // try to parse to Roundcube format
        $this->script = $this->_parse($script);
    }

    /**
     * Creates rcube_sieve_script object from text script
     */
    private function _parse($txt)
    {
        // parse
        $script = new rcube_sieve_script($txt, $this->exts);

        // fix/convert to Roundcube format
        if (!empty($script->content)) {
            // replace all elsif with if+stop, we support only ifs
            foreach ($script->content as $idx => $rule) {
                if (empty($rule['type']) || !preg_match('/^(if|elsif|else)$/', $rule['type'])) {
                    continue;
                }

                $script->content[$idx]['type'] = 'if';

                // 'stop' not found?
                foreach ($rule['actions'] as $action) {
                    if (preg_match('/^(stop|vacation)$/', $action['type'])) {
                        continue 2;
                    }
                }

                if (!empty($script->content[$idx+1]) && $script->content[$idx+1]['type'] != 'if') {
                    $script->content[$idx]['actions'][] = ['type' => 'stop'];
                }
            }
        }

        return $script;
    }

    /**
     * Gets specified script as text
     */
    public function get_script($name)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        $content = $this->sieve->getScript($name);

        if (is_a($content, 'PEAR_Error')) {
            return $this->_set_error(self::ERROR_OTHER);
        }

        return $content;
    }

    /**
     * Creates empty script or a copy of another script
     */
    public function copy($name, $copy)
    {
        if (!$this->sieve) {
            return $this->_set_error(self::ERROR_INTERNAL);
        }

        $content = '';

        if ($copy) {
            $content = $this->sieve->getScript($copy);

            if (is_a($content, 'PEAR_Error')) {
                return $this->_set_error(self::ERROR_OTHER);
            }
        }

        return $this->save_script($name, $content);
    }

    private function _set_error($error)
    {
        $this->error = $error;
        return false;
    }

    /**
     * This is our own debug handler for connection
     */
    public function debug_handler($sieve, $message)
    {
        rcube::write_log('sieve', preg_replace('/\r\n$/', '', $message));
    }
}