source: subversion/trunk/plugins/managesieve/managesieve.php @ 5441

Last change on this file since 5441 was 5441, checked in by alec, 19 months ago
  • Added 'address' and 'envelope' tests support
  • Added 'body' extension support (RFC5173)
  • Added 'subaddress' extension support (RFC5233)
  • Added comparators support
  • Changed Sender/Recipient? labels to From/To?
  • Fixed importing rule names from Ingo
  • Fixed handling of extensions disabled in config
  • Property svn:keywords set to Id
File size: 78.5 KB
Line 
1<?php
2
3/**
4 * Managesieve (Sieve Filters)
5 *
6 * Plugin that adds a possibility to manage Sieve filters in Thunderbird's style.
7 * It's clickable interface which operates on text scripts and communicates
8 * with server using managesieve protocol. Adds Filters tab in Settings.
9 *
10 * @version 5.0
11 * @author Aleksander Machniak <alec@alec.pl>
12 *
13 * Configuration (see config.inc.php.dist)
14 *
15 * Copyright (C) 2008-2011, The Roundcube Dev Team
16 * Copyright (C) 2011, Kolab Systems AG
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License version 2
20 * as published by the Free Software Foundation.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License along
28 * with this program; if not, write to the Free Software Foundation, Inc.,
29 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 *
31 * $Id$
32 */
33
34class managesieve extends rcube_plugin
35{
36    public $task = 'mail|settings';
37
38    private $rc;
39    private $sieve;
40    private $errors;
41    private $form;
42    private $tips = array();
43    private $script = array();
44    private $exts = array();
45    private $list;
46    private $active = array();
47    private $headers = array(
48        'subject' => 'Subject',
49        'from'    => 'From',
50        'to'      => 'To',
51    );
52    private $addr_headers = array(
53        // Required
54        "from", "to", "cc", "bcc", "sender", "resent-from", "resent-to",
55        // Additional (RFC 822 / RFC 2822)
56        "reply-to", "resent-reply-to", "resent-sender", "resent-cc", "resent-bcc",
57        // Non-standard (RFC 2076, draft-palme-mailext-headers-08.txt)
58        "for-approval", "for-handling", "for-comment", "apparently-to", "errors-to",
59        "delivered-to", "return-receipt-to", "x-admin", "read-receipt-to",
60        "x-confirm-reading-to", "return-receipt-requested",
61        "registered-mail-reply-requested-by", "mail-followup-to", "mail-reply-to",
62        "abuse-reports-to", "x-complaints-to", "x-report-abuse-to",
63        // Undocumented
64        "x-beenthere",
65    );
66
67    const VERSION = '5.0';
68    const PROGNAME = 'Roundcube (Managesieve)';
69
70
71    function init()
72    {
73        $this->rc = rcmail::get_instance();
74
75        // register actions
76        $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
77        $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
78
79        if ($this->rc->task == 'settings') {
80            $this->init_ui();
81        }
82        else if ($this->rc->task == 'mail') {
83            // register message hook
84            $this->add_hook('message_headers_output', array($this, 'mail_headers'));
85
86            // inject Create Filter popup stuff
87            if (empty($this->rc->action) || $this->rc->action == 'show') {
88                $this->mail_task_handler();
89            }
90        }
91    }
92
93    /**
94     * Initializes plugin's UI (localization, js script)
95     */
96    private function init_ui()
97    {
98        if ($this->ui_initialized)
99            return;
100
101        // load localization
102        $this->add_texts('localization/', array('filters','managefilters'));
103        $this->include_script('managesieve.js');
104
105        $this->ui_initialized = true;
106    }
107
108    /**
109     * Add UI elements to the 'mailbox view' and 'show message' UI.
110     */
111    function mail_task_handler()
112    {
113        // use jQuery for popup window
114        $this->require_plugin('jqueryui'); 
115
116        // include js script and localization
117        $this->init_ui();
118
119        // include styles
120        $skin = $this->rc->config->get('skin');
121        if (!file_exists($this->home."/skins/$skin/managesieve_mail.css"))
122            $skin = 'default';
123        $this->include_stylesheet("skins/$skin/managesieve_mail.css");
124
125        // add 'Create filter' item to message menu
126        $this->api->add_content(html::tag('li', null, 
127            $this->api->output->button(array(
128                'command'  => 'managesieve-create',
129                'label'    => 'managesieve.filtercreate',
130                'type'     => 'link',
131                'classact' => 'filterlink active',
132                'class'    => 'filterlink',
133            ))), 'messagemenu');
134
135        // register some labels/messages
136        $this->rc->output->add_label('managesieve.newfilter', 'managesieve.usedata',
137            'managesieve.nodata', 'managesieve.nextstep', 'save');
138
139        $this->rc->session->remove('managesieve_current');
140    }
141
142    /**
143     * Get message headers for popup window
144     */
145    function mail_headers($args)
146    {
147        $headers = $args['headers'];
148        $ret     = array();
149
150        if ($headers->subject)
151            $ret[] = array('Subject', $this->rc->imap->decode_header($headers->subject));
152
153        // @TODO: List-Id, others?
154        foreach (array('From', 'To') as $h) {
155            $hl = strtolower($h);
156            if ($headers->$hl) {
157                $list = $this->rc->imap->decode_address_list($headers->$hl);
158                foreach ($list as $item) {
159                    if ($item['mailto']) {
160                        $ret[] = array($h, $item['mailto']);
161                    }
162                }
163            }
164        }
165
166        if ($this->rc->action == 'preview')
167            $this->rc->output->command('parent.set_env', array('sieve_headers' => $ret));
168        else
169            $this->rc->output->set_env('sieve_headers', $ret);
170
171
172        return $args;
173    }
174
175    /**
176     * Loads configuration, initializes plugin (including sieve connection)
177     */
178    function managesieve_start()
179    {
180        $this->load_config();
181
182        // register UI objects
183        $this->rc->output->add_handlers(array(
184            'filterslist'    => array($this, 'filters_list'),
185            'filtersetslist' => array($this, 'filtersets_list'),
186            'filterframe'    => array($this, 'filter_frame'),
187            'filterform'     => array($this, 'filter_form'),
188            'filtersetform'  => array($this, 'filterset_form'),
189        ));
190
191        // Add include path for internal classes
192        $include_path = $this->home . '/lib' . PATH_SEPARATOR;
193        $include_path .= ini_get('include_path');
194        set_include_path($include_path);
195
196        $host = rcube_parse_host($this->rc->config->get('managesieve_host', 'localhost'));
197        $port = $this->rc->config->get('managesieve_port', 2000);
198
199        $host = rcube_idn_to_ascii($host);
200
201        $plugin = $this->rc->plugins->exec_hook('managesieve_connect', array(
202            'user'      => $_SESSION['username'],
203            'password'  => $this->rc->decrypt($_SESSION['password']),
204            'host'      => $host,
205            'port'      => $port,
206            'auth_type' => $this->rc->config->get('managesieve_auth_type'),
207            'usetls'    => $this->rc->config->get('managesieve_usetls', false),
208            'disabled'  => $this->rc->config->get('managesieve_disabled_extensions'),
209            'debug'     => $this->rc->config->get('managesieve_debug', false),
210            'auth_cid'  => $this->rc->config->get('managesieve_auth_cid'),
211            'auth_pw'   => $this->rc->config->get('managesieve_auth_pw'),
212        ));
213
214        // try to connect to managesieve server and to fetch the script
215        $this->sieve = new rcube_sieve(
216            $plugin['user'],
217            $plugin['password'],
218            $plugin['host'],
219            $plugin['port'],
220            $plugin['auth_type'],
221            $plugin['usetls'],
222            $plugin['disabled'],
223            $plugin['debug'],
224            $plugin['auth_cid'],
225            $plugin['auth_pw']
226        );
227
228        if (!($error = $this->sieve->error())) {
229            // Get list of scripts
230            $list = $this->list_scripts();
231
232            if (!empty($_GET['_set']) || !empty($_POST['_set'])) {
233                $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
234            }
235            else if (!empty($_SESSION['managesieve_current'])) {
236                $script_name = $_SESSION['managesieve_current'];
237            }
238            else {
239                // get (first) active script
240                if (!empty($this->active[0])) {
241                    $script_name = $this->active[0];
242                }
243                else if ($list) {
244                    $script_name = $list[0];
245                }
246                // create a new (initial) script
247                else {
248                    // if script not exists build default script contents
249                    $script_file = $this->rc->config->get('managesieve_default');
250                    $script_name = $this->rc->config->get('managesieve_script_name');
251
252                    if (empty($script_name))
253                        $script_name = 'roundcube';
254
255                    if ($script_file && is_readable($script_file))
256                        $content = file_get_contents($script_file);
257
258                    // add script and set it active
259                    if ($this->sieve->save_script($script_name, $content)) {
260                        $this->activate_script($script_name);
261                        $this->list[] = $script_name;
262                    }
263                }
264            }
265
266            if ($script_name) {
267                $this->sieve->load($script_name);
268            }
269
270            $error = $this->sieve->error();
271        }
272
273        // finally set script objects
274        if ($error) {
275            switch ($error) {
276                case SIEVE_ERROR_CONNECTION:
277                case SIEVE_ERROR_LOGIN:
278                    $this->rc->output->show_message('managesieve.filterconnerror', 'error');
279                    break;
280                default:
281                    $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
282                    break;
283            }
284
285            raise_error(array('code' => 403, 'type' => 'php',
286                'file' => __FILE__, 'line' => __LINE__,
287                'message' => "Unable to connect to managesieve on $host:$port"), true, false);
288
289            // to disable 'Add filter' button set env variable
290            $this->rc->output->set_env('filterconnerror', true);
291            $this->script = array();
292        }
293        else {
294            $this->exts = $this->sieve->get_extensions();
295            $this->script = $this->sieve->script->as_array();
296            $this->rc->output->set_env('currentset', $this->sieve->current);
297            $_SESSION['managesieve_current'] = $this->sieve->current;
298        }
299
300        return $error;
301    }
302
303    function managesieve_actions()
304    {
305        $this->init_ui();
306
307        $error = $this->managesieve_start();
308
309        // Handle user requests
310        if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
311            $fid = (int) get_input_value('_fid', RCUBE_INPUT_POST);
312
313            if ($action == 'delete' && !$error) {
314                if (isset($this->script[$fid])) {
315                    if ($this->sieve->script->delete_rule($fid))
316                        $result = $this->save_script();
317
318                    if ($result === true) {
319                        $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
320                        $this->rc->output->command('managesieve_updatelist', 'del', array('id' => $fid));
321                    } else {
322                        $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
323                    }
324                }
325            }
326            else if ($action == 'move' && !$error) {
327                if (isset($this->script[$fid])) {
328                    $to   = (int) get_input_value('_to', RCUBE_INPUT_POST);
329                    $rule = $this->script[$fid];
330
331                    // remove rule
332                    unset($this->script[$fid]);
333                    $this->script = array_values($this->script);
334
335                    // add at target position
336                    if ($to >= count($this->script)) {
337                        $this->script[] = $rule;
338                    }
339                    else {
340                        $script = array();
341                        foreach ($this->script as $idx => $r) {
342                            if ($idx == $to)
343                                $script[] = $rule;
344                            $script[] = $r;
345                        }
346                        $this->script = $script;
347                    }
348
349                    $this->sieve->script->content = $this->script;
350                    $result = $this->save_script();
351
352                    if ($result === true) {
353                        $result = $this->list_rules();
354
355                        $this->rc->output->show_message('managesieve.moved', 'confirmation');
356                        $this->rc->output->command('managesieve_updatelist', 'list',
357                            array('list' => $result, 'clear' => true, 'set' => $to));
358                    } else {
359                        $this->rc->output->show_message('managesieve.moveerror', 'error');
360                    }
361                }
362            }
363            else if ($action == 'act' && !$error) {
364                if (isset($this->script[$fid])) {
365                    $rule     = $this->script[$fid];
366                    $disabled = $rule['disabled'] ? true : false;
367                    $rule['disabled'] = !$disabled;
368                    $result = $this->sieve->script->update_rule($fid, $rule);
369
370                    if ($result !== false)
371                        $result = $this->save_script();
372
373                    if ($result === true) {
374                        if ($rule['disabled'])
375                            $this->rc->output->show_message('managesieve.deactivated', 'confirmation');
376                        else
377                            $this->rc->output->show_message('managesieve.activated', 'confirmation');
378                        $this->rc->output->command('managesieve_updatelist', 'update',
379                            array('id' => $fid, 'disabled' => $rule['disabled']));
380                    } else {
381                        if ($rule['disabled'])
382                            $this->rc->output->show_message('managesieve.deactivateerror', 'error');
383                        else
384                            $this->rc->output->show_message('managesieve.activateerror', 'error');
385                    }
386                }
387            }
388            else if ($action == 'setact' && !$error) {
389                $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
390                $result = $this->activate_script($script_name);
391                $kep14  = $this->rc->config->get('managesieve_kolab_master');
392
393                if ($result === true) {
394                    $this->rc->output->set_env('active_sets', $this->active);
395                    $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
396                    $this->rc->output->command('managesieve_updatelist', 'setact',
397                        array('name' => $script_name, 'active' => true, 'all' => !$kep14));
398                } else {
399                    $this->rc->output->show_message('managesieve.setactivateerror', 'error');
400                }
401            }
402            else if ($action == 'deact' && !$error) {
403                $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
404                $result = $this->deactivate_script($script_name);
405
406                if ($result === true) {
407                    $this->rc->output->set_env('active_sets', $this->active);
408                    $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
409                    $this->rc->output->command('managesieve_updatelist', 'setact',
410                        array('name' => $script_name, 'active' => false));
411                } else {
412                    $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
413                }
414            }
415            else if ($action == 'setdel' && !$error) {
416                $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
417                $result = $this->remove_script($script_name);
418
419                if ($result === true) {
420                    $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
421                    $this->rc->output->command('managesieve_updatelist', 'setdel',
422                        array('name' => $script_name));
423                    $this->rc->session->remove('managesieve_current');
424                } else {
425                    $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
426                }
427            }
428            else if ($action == 'setget') {
429                $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
430                $script = $this->sieve->get_script($script_name);
431
432                if (PEAR::isError($script))
433                    exit;
434
435                $browser = new rcube_browser;
436
437                // send download headers
438                header("Content-Type: application/octet-stream");
439                header("Content-Length: ".strlen($script));
440
441                if ($browser->ie)
442                    header("Content-Type: application/force-download");
443                if ($browser->ie && $browser->ver < 7)
444                    $filename = rawurlencode(abbreviate_string($script_name, 55));
445                else if ($browser->ie)
446                    $filename = rawurlencode($script_name);
447                else
448                    $filename = addcslashes($script_name, '\\"');
449
450                header("Content-Disposition: attachment; filename=\"$filename.txt\"");
451                echo $script;
452                exit;
453            }
454            else if ($action == 'list') {
455                $result = $this->list_rules();
456
457                $this->rc->output->command('managesieve_updatelist', 'list', array('list' => $result));
458            }
459            else if ($action == 'ruleadd') {
460                $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
461                $id = $this->genid();
462                $content = $this->rule_div($fid, $id, false);
463
464                $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
465            }
466            else if ($action == 'actionadd') {
467                $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
468                $id = $this->genid();
469                $content = $this->action_div($fid, $id, false);
470
471                $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
472            }
473
474            $this->rc->output->send();
475        }
476        else if ($this->rc->task == 'mail') {
477            // Initialize the form
478            $rules = get_input_value('r', RCUBE_INPUT_GET);
479            if (!empty($rules)) {
480                $i = 0;
481                foreach ($rules as $rule) {
482                    list($header, $value) = explode(':', $rule, 2);
483                    $tests[$i] = array(
484                        'type' => 'contains',
485                        'test' => 'header',
486                        'arg1' => $header,
487                        'arg2' => $value,
488                    );
489                    $i++;
490                }
491
492                $this->form = array(
493                    'join'  => count($tests) > 1 ? 'allof' : 'anyof',
494                    'name'  => '',
495                    'tests' => $tests,
496                    'actions' => array(
497                        0 => array('type' => 'fileinto'),
498                        1 => array('type' => 'stop'),
499                    ),
500                );
501            }
502        }
503
504        $this->managesieve_send();
505    }
506
507    function managesieve_save()
508    {
509        // load localization
510        $this->add_texts('localization/', array('filters','managefilters'));
511
512        // include main js script
513        if ($this->api->output->type == 'html') {
514            $this->include_script('managesieve.js');
515        }
516
517        // Init plugin and handle managesieve connection
518        $error = $this->managesieve_start();
519
520        // filters set add action
521        if (!empty($_POST['_newset'])) {
522
523            $name       = get_input_value('_name', RCUBE_INPUT_POST, true);
524            $copy       = get_input_value('_copy', RCUBE_INPUT_POST, true);
525            $from       = get_input_value('_from', RCUBE_INPUT_POST);
526            $exceptions = $this->rc->config->get('managesieve_filename_exceptions');
527            $kolab      = $this->rc->config->get('managesieve_kolab_master');
528            $name_uc    = mb_strtolower($name);
529            $list       = $this->list_scripts();
530
531            if (!$name) {
532                $this->errors['name'] = $this->gettext('cannotbeempty');
533            }
534            else if (mb_strlen($name) > 128) {
535                $this->errors['name'] = $this->gettext('nametoolong');
536            }
537            else if (!empty($exceptions) && in_array($name, (array)$exceptions)) {
538                $this->errors['name'] = $this->gettext('namereserved');
539            }
540            else if (!empty($kolab) && in_array($name_uc, array('MASTER', 'USER', 'MANAGEMENT'))) {
541                $this->errors['name'] = $this->gettext('namereserved');
542            }
543            else if (in_array($name, $list)) {
544                $this->errors['name'] = $this->gettext('setexist');
545            }
546            else if ($from == 'file') {
547                // from file
548                if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
549                    $file = file_get_contents($_FILES['_file']['tmp_name']);
550                    $file = preg_replace('/\r/', '', $file);
551                    // for security don't save script directly
552                    // check syntax before, like this...
553                    $this->sieve->load_script($file);
554                    if (!$this->save_script($name)) {
555                        $this->errors['file'] = $this->gettext('setcreateerror');
556                    }
557                }
558                else {  // upload failed
559                    $err = $_FILES['_file']['error'];
560
561                    if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
562                        $msg = rcube_label(array('name' => 'filesizeerror',
563                            'vars' => array('size' =>
564                                show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
565                    }
566                    else {
567                        $this->errors['file'] = $this->gettext('fileuploaderror');
568                    }
569                }
570            }
571            else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
572                $error = 'managesieve.setcreateerror';
573            }
574
575            if (!$error && empty($this->errors)) {
576                // Find position of the new script on the list
577                $list[] = $name;
578                asort($list, SORT_LOCALE_STRING);
579                $list  = array_values($list);
580                $index = array_search($name, $list);
581
582                $this->rc->output->show_message('managesieve.setcreated', 'confirmation');
583                $this->rc->output->command('parent.managesieve_updatelist', 'setadd',
584                    array('name' => $name, 'index' => $index));
585            } else if ($msg) {
586                $this->rc->output->command('display_message', $msg, 'error');
587            } else if ($error) {
588                $this->rc->output->show_message($error, 'error');
589            }
590        }
591        // filter add/edit action
592        else if (isset($_POST['_name'])) {
593            $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
594            $fid  = trim(get_input_value('_fid', RCUBE_INPUT_POST));
595            $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
596
597            // and arrays
598            $headers        = get_input_value('_header', RCUBE_INPUT_POST);
599            $cust_headers   = get_input_value('_custom_header', RCUBE_INPUT_POST);
600            $ops            = get_input_value('_rule_op', RCUBE_INPUT_POST);
601            $sizeops        = get_input_value('_rule_size_op', RCUBE_INPUT_POST);
602            $sizeitems      = get_input_value('_rule_size_item', RCUBE_INPUT_POST);
603            $sizetargets    = get_input_value('_rule_size_target', RCUBE_INPUT_POST);
604            $targets        = get_input_value('_rule_target', RCUBE_INPUT_POST, true);
605            $mods           = get_input_value('_rule_mod', RCUBE_INPUT_POST);
606            $mod_types      = get_input_value('_rule_mod_type', RCUBE_INPUT_POST);
607            $body_trans     = get_input_value('_rule_trans', RCUBE_INPUT_POST);
608            $body_types     = get_input_value('_rule_trans_type', RCUBE_INPUT_POST, true);
609            $comparators    = get_input_value('_rule_comp', RCUBE_INPUT_POST);
610            $act_types      = get_input_value('_action_type', RCUBE_INPUT_POST, true);
611            $mailboxes      = get_input_value('_action_mailbox', RCUBE_INPUT_POST, true);
612            $act_targets    = get_input_value('_action_target', RCUBE_INPUT_POST, true);
613            $area_targets   = get_input_value('_action_target_area', RCUBE_INPUT_POST, true);
614            $reasons        = get_input_value('_action_reason', RCUBE_INPUT_POST, true);
615            $addresses      = get_input_value('_action_addresses', RCUBE_INPUT_POST, true);
616            $days           = get_input_value('_action_days', RCUBE_INPUT_POST);
617            $subject        = get_input_value('_action_subject', RCUBE_INPUT_POST, true);
618            $flags          = get_input_value('_action_flags', RCUBE_INPUT_POST);
619
620            // we need a "hack" for radiobuttons
621            foreach ($sizeitems as $item)
622                $items[] = $item;
623
624            $this->form['disabled'] = $_POST['_disabled'] ? true : false;
625            $this->form['join']     = $join=='allof' ? true : false;
626            $this->form['name']     = $name;
627            $this->form['tests']    = array();
628            $this->form['actions']  = array();
629
630            if ($name == '')
631                $this->errors['name'] = $this->gettext('cannotbeempty');
632            else {
633                foreach($this->script as $idx => $rule)
634                    if($rule['name'] == $name && $idx != $fid) {
635                        $this->errors['name'] = $this->gettext('ruleexist');
636                        break;
637                    }
638            }
639
640            $i = 0;
641            // rules
642            if ($join == 'any') {
643                $this->form['tests'][0]['test'] = 'true';
644            }
645            else {
646                foreach ($headers as $idx => $header) {
647                    $header     = $this->strip_value($header);
648                    $target     = $this->strip_value($targets[$idx], true);
649                    $operator   = $this->strip_value($ops[$idx]);
650                    $comparator = $this->strip_value($comparators[$idx]);
651
652                    if ($header == 'size') {
653                        $sizeop     = $this->strip_value($sizeops[$idx]);
654                        $sizeitem   = $this->strip_value($items[$idx]);
655                        $sizetarget = $this->strip_value($sizetargets[$idx]);
656
657                        $this->form['tests'][$i]['test'] = 'size';
658                        $this->form['tests'][$i]['type'] = $sizeop;
659                        $this->form['tests'][$i]['arg']  = $sizetarget;
660
661                        if ($sizetarget == '')
662                            $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
663                        else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) {
664                            $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
665                            $this->form['tests'][$i]['item'] = $sizeitem;
666                        }
667                        else
668                            $this->form['tests'][$i]['arg'] .= $m[1];
669                    }
670                    else if ($header == 'body') {
671                        $trans      = $this->strip_value($body_trans[$idx]);
672                        $trans_type = $this->strip_value($body_types[$idx], true);
673
674                        if (preg_match('/^not/', $operator))
675                            $this->form['tests'][$i]['not'] = true;
676                        $type = preg_replace('/^not/', '', $operator);
677
678                        if ($type == 'exists') {
679                            $this->errors['tests'][$i]['op'] = true;
680                        }
681
682                        $this->form['tests'][$i]['test'] = 'body';
683                        $this->form['tests'][$i]['type'] = $type;
684                        $this->form['tests'][$i]['arg']  = $target;
685
686                        if ($target == '' && $type != 'exists')
687                            $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
688                        else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
689                            $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
690
691                        $this->form['tests'][$i]['part'] = $trans;
692                        if ($trans == 'content') {
693                            $this->form['tests'][$i]['content'] = $trans_type;
694                        }
695                    }
696                    else {
697                        $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
698                        $mod      = $this->strip_value($mods[$idx]);
699                        $mod_type = $this->strip_value($mod_types[$idx]);
700
701                        if (preg_match('/^not/', $operator))
702                            $this->form['tests'][$i]['not'] = true;
703                        $type = preg_replace('/^not/', '', $operator);
704
705                        if ($header == '...') {
706                            $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
707
708                            if (!count($headers))
709                                $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
710                            else {
711                                foreach ($headers as $hr)
712                                    if (!preg_match('/^[a-z0-9-]+$/i', $hr))
713                                        $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
714                            }
715
716                            if (empty($this->errors['tests'][$i]['header']))
717                                $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
718                        }
719
720                        if ($type == 'exists') {
721                            $this->form['tests'][$i]['test'] = 'exists';
722                            $this->form['tests'][$i]['arg'] = $header == '...' ? $cust_header : $header;
723                        }
724                        else {
725                            $test   = 'header';
726                            $header = $header == '...' ? $cust_header : $header;
727
728                            if ($mod == 'address' || $mod == 'envelope') {
729                                $found = false;
730                                if (empty($this->errors['tests'][$i]['header'])) {
731                                    foreach ((array)$header as $hdr) {
732                                        if (!in_array(strtolower(trim($hdr)), $this->addr_headers))
733                                            $found = true;
734                                    }
735                                }
736                                if (!$found)
737                                    $test = $mod;
738                            }
739
740                            $this->form['tests'][$i]['type'] = $type;
741                            $this->form['tests'][$i]['test'] = $test;
742                            $this->form['tests'][$i]['arg1'] = $header;
743                            $this->form['tests'][$i]['arg2'] = $target;
744
745                            if ($target == '')
746                                $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
747                            else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
748                                $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
749
750                            if ($mod) {
751                                $this->form['tests'][$i]['part'] = $mod_type;
752                            }
753                        }
754                    }
755
756                    if ($header != 'size' && $comparator) {
757                        if (preg_match('/^(value|count)/', $this->form['tests'][$i]['type']))
758                            $comparator = 'i;ascii-numeric';
759
760                        $this->form['tests'][$i]['comparator'] = $comparator;
761                    }
762
763                    $i++;
764                }
765            }
766
767            $i = 0;
768            // actions
769            foreach($act_types as $idx => $type) {
770                $type   = $this->strip_value($type);
771                $target = $this->strip_value($act_targets[$idx]);
772
773                switch ($type) {
774
775                case 'fileinto':
776                case 'fileinto_copy':
777                    $mailbox = $this->strip_value($mailboxes[$idx]);
778                    $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
779                    if ($type == 'fileinto_copy') {
780                        $type = 'fileinto';
781                        $this->form['actions'][$i]['copy'] = true;
782                    }
783                    break;
784
785                case 'reject':
786                case 'ereject':
787                    $target = $this->strip_value($area_targets[$idx]);
788                    $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
789
790 //                 if ($target == '')
791//                      $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
792                    break;
793
794                case 'redirect':
795                case 'redirect_copy':
796                    $this->form['actions'][$i]['target'] = $target;
797
798                    if ($this->form['actions'][$i]['target'] == '')
799                        $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
800                    else if (!check_email($this->form['actions'][$i]['target']))
801                        $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
802
803                    if ($type == 'redirect_copy') {
804                        $type = 'redirect';
805                        $this->form['actions'][$i]['copy'] = true;
806                    }
807                    break;
808
809                case 'addflag':
810                case 'setflag':
811                case 'removeflag':
812                    $_target = array();
813                    if (empty($flags[$idx])) {
814                        $this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
815                    }
816                    else {
817                        foreach ($flags[$idx] as $flag) {
818                            $_target[] = $this->strip_value($flag);
819                        }
820                    }
821                    $this->form['actions'][$i]['target'] = $_target;
822                    break;
823
824                case 'vacation':
825                    $reason = $this->strip_value($reasons[$idx]);
826                    $this->form['actions'][$i]['reason']    = str_replace("\r\n", "\n", $reason);
827                    $this->form['actions'][$i]['days']      = $days[$idx];
828                    $this->form['actions'][$i]['subject']   = $subject[$idx];
829                    $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
830// @TODO: vacation :mime, :from, :handle
831
832                    if ($this->form['actions'][$i]['addresses']) {
833                        foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
834                            $address = trim($address);
835                            if (!$address)
836                                unset($this->form['actions'][$i]['addresses'][$aidx]);
837                            else if(!check_email($address)) {
838                                $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
839                                break;
840                            } else
841                                $this->form['actions'][$i]['addresses'][$aidx] = $address;
842                        }
843                    }
844
845                    if ($this->form['actions'][$i]['reason'] == '')
846                        $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
847                    if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
848                        $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
849                    break;
850                }
851
852                $this->form['actions'][$i]['type'] = $type;
853                $i++;
854            }
855
856            if (!$this->errors && !$error) {
857                // zapis skryptu
858                if (!isset($this->script[$fid])) {
859                    $fid = $this->sieve->script->add_rule($this->form);
860                    $new = true;
861                } else
862                    $fid = $this->sieve->script->update_rule($fid, $this->form);
863
864                if ($fid !== false)
865                    $save = $this->save_script();
866
867                if ($save && $fid !== false) {
868                    $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
869                    if ($this->rc->task != 'mail') {
870                        $this->rc->output->command('parent.managesieve_updatelist',
871                            isset($new) ? 'add' : 'update',
872                            array(
873                                'name' => Q($this->form['name']),
874                                'id' => $fid,
875                                'disabled' => $this->form['disabled']
876                        ));
877                    }
878                    else {
879                        $this->rc->output->command('managesieve_dialog_close');
880                        $this->rc->output->send('iframe');
881                    }
882                }
883                else {
884                    $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
885//                  $this->rc->output->send();
886                }
887            }
888        }
889
890        $this->managesieve_send();
891    }
892
893    private function managesieve_send()
894    {
895        // Handle form action
896        if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
897            if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
898                $this->rc->output->send('managesieve.setedit');
899            }
900            else {
901                $this->rc->output->send('managesieve.filteredit');
902            }
903        } else {
904            $this->rc->output->set_pagetitle($this->gettext('filters'));
905            $this->rc->output->send('managesieve.managesieve');
906        }
907    }
908
909    // return the filters list as HTML table
910    function filters_list($attrib)
911    {
912        // add id to message list table if not specified
913        if (!strlen($attrib['id']))
914            $attrib['id'] = 'rcmfilterslist';
915
916        // define list of cols to be displayed
917        $a_show_cols = array('name');
918
919        $result = $this->list_rules();
920
921        // create XHTML table
922        $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
923
924        // set client env
925        $this->rc->output->add_gui_object('filterslist', $attrib['id']);
926        $this->rc->output->include_script('list.js');
927
928        // add some labels to client
929        $this->rc->output->add_label('managesieve.filterdeleteconfirm');
930
931        return $out;
932    }
933
934    // return the filters list as <SELECT>
935    function filtersets_list($attrib, $no_env = false)
936    {
937        // add id to message list table if not specified
938        if (!strlen($attrib['id']))
939            $attrib['id'] = 'rcmfiltersetslist';
940
941        $list = $this->list_scripts();
942
943        if ($list) {
944            asort($list, SORT_LOCALE_STRING);
945        }
946
947        if (!empty($attrib['type']) && $attrib['type'] == 'list') {
948            // define list of cols to be displayed
949            $a_show_cols = array('name');
950
951            if ($list) {
952                foreach ($list as $idx => $set) {
953                    $scripts['S'.$idx] = $set;
954                    $result[] = array(
955                        'name' => Q($set),
956                        'id' => 'S'.$idx,
957                        'class' => !in_array($set, $this->active) ? 'disabled' : '',
958                    );
959                }
960            }
961
962            // create XHTML table
963            $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
964
965            $this->rc->output->set_env('filtersets', $scripts);
966            $this->rc->output->include_script('list.js');
967        }
968        else {
969            $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
970                'onchange' => $this->rc->task != 'mail' ? 'rcmail.managesieve_set()' : ''));
971
972            if ($list) {
973                foreach ($list as $set)
974                    $select->add($set, $set);
975            }
976
977            $out = $select->show($this->sieve->current);
978        }
979
980        // set client env
981        if (!$no_env) {
982            $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
983            $this->rc->output->add_label('managesieve.setdeleteconfirm');
984        }
985
986        return $out;
987    }
988
989    function filter_frame($attrib)
990    {
991        if (!$attrib['id'])
992            $attrib['id'] = 'rcmfilterframe';
993
994        $attrib['name'] = $attrib['id'];
995
996        $this->rc->output->set_env('contentframe', $attrib['name']);
997        $this->rc->output->set_env('blankpage', $attrib['src'] ?
998        $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
999
1000        return html::tag('iframe', $attrib);
1001    }
1002
1003    function filterset_form($attrib)
1004    {
1005        if (!$attrib['id'])
1006            $attrib['id'] = 'rcmfiltersetform';
1007
1008        $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
1009
1010        $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1011        $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1012        $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1013        $hiddenfields->add(array('name' => '_newset', 'value' => 1));
1014
1015        $out .= $hiddenfields->show();
1016
1017        $name     = get_input_value('_name', RCUBE_INPUT_POST);
1018        $copy     = get_input_value('_copy', RCUBE_INPUT_POST);
1019        $selected = get_input_value('_from', RCUBE_INPUT_POST);
1020
1021        // filter set name input
1022        $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
1023            'class' => ($this->errors['name'] ? 'error' : '')));
1024
1025        $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
1026            '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
1027
1028        $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
1029        $out .= '<input type="radio" id="from_none" name="_from" value="none"'
1030            .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
1031        $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
1032
1033        // filters set list
1034        $list   = $this->list_scripts();
1035        $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
1036
1037        if (is_array($list)) {
1038            asort($list, SORT_LOCALE_STRING);
1039
1040            if (!$copy)
1041                $copy = $_SESSION['managesieve_current'];
1042
1043            foreach ($list as $set) {
1044                $select->add($set, $set);
1045            }
1046
1047            $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
1048                .($selected=='set' ? ' checked="checked"' : '').'></input>';
1049            $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
1050            $out .= $select->show($copy);
1051        }
1052
1053        // script upload box
1054        $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
1055            'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : '')));
1056
1057        $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
1058            .($selected=='file' ? ' checked="checked"' : '').'></input>';
1059        $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
1060        $out .= $upload->show();
1061        $out .= '</fieldset>';
1062
1063        $this->rc->output->add_gui_object('sieveform', 'filtersetform');
1064
1065        if ($this->errors['name'])
1066            $this->add_tip('_name', $this->errors['name'], true);
1067        if ($this->errors['file'])
1068            $this->add_tip('_file', $this->errors['file'], true);
1069
1070        $this->print_tips();
1071
1072        return $out;
1073    }
1074
1075
1076    function filter_form($attrib)
1077    {
1078        if (!$attrib['id'])
1079            $attrib['id'] = 'rcmfilterform';
1080
1081        $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
1082        $scr = isset($this->form) ? $this->form : $this->script[$fid];
1083
1084        $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1085        $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1086        $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1087        $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
1088
1089        $out = '<form name="filterform" action="./" method="post">'."\n";
1090        $out .= $hiddenfields->show();
1091
1092        // 'any' flag
1093        if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
1094            $any = true;
1095
1096        // filter name input
1097        $field_id = '_name';
1098        $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
1099            'class' => ($this->errors['name'] ? 'error' : '')));
1100
1101        if ($this->errors['name'])
1102            $this->add_tip($field_id, $this->errors['name'], true);
1103
1104        if (isset($scr))
1105            $input_name = $input_name->show($scr['name']);
1106        else
1107            $input_name = $input_name->show();
1108
1109        $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s\n",
1110            $field_id, Q($this->gettext('filtername')), $input_name);
1111
1112        // filter set selector
1113        if ($this->rc->task == 'mail') {
1114            $out .= sprintf("\n&nbsp;<label for=\"%s\"><b>%s:</b></label> %s\n",
1115                $field_id, Q($this->gettext('filterset')),
1116                $this->filtersets_list(array('id' => 'sievescriptname'), true));
1117        }
1118
1119        $out .= '<br /><br /><fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
1120
1121        // any, allof, anyof radio buttons
1122        $field_id = '_allof';
1123        $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
1124            'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
1125
1126        if (isset($scr) && !$any)
1127            $input_join = $input_join->show($scr['join'] ? 'allof' : '');
1128        else
1129            $input_join = $input_join->show();
1130
1131        $out .= sprintf("%s<label for=\"%s\">%s</label>&nbsp;\n",
1132            $input_join, $field_id, Q($this->gettext('filterallof')));
1133
1134        $field_id = '_anyof';
1135        $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
1136            'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
1137
1138        if (isset($scr) && !$any)
1139            $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
1140        else
1141            $input_join = $input_join->show('anyof'); // default
1142
1143        $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1144            $input_join, $field_id, Q($this->gettext('filteranyof')));
1145
1146        $field_id = '_any';
1147        $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
1148            'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
1149
1150        $input_join = $input_join->show($any ? 'any' : '');
1151
1152        $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1153            $input_join, $field_id, Q($this->gettext('filterany')));
1154
1155        $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
1156
1157        $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
1158        for ($x=0; $x<$rows_num; $x++)
1159            $out .= $this->rule_div($fid, $x);
1160        $out .= "</div>\n";
1161
1162        $out .= "</fieldset>\n";
1163
1164        // actions
1165        $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
1166
1167        $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
1168
1169        $out .= '<div id="actions">';
1170        for ($x=0; $x<$rows_num; $x++)
1171            $out .= $this->action_div($fid, $x);
1172        $out .= "</div>\n";
1173
1174        $out .= "</fieldset>\n";
1175
1176        $this->print_tips();
1177
1178        if ($scr['disabled']) {
1179            $this->rc->output->set_env('rule_disabled', true);
1180        }
1181        $this->rc->output->add_label(
1182            'managesieve.ruledeleteconfirm',
1183            'managesieve.actiondeleteconfirm'
1184        );
1185        $this->rc->output->add_gui_object('sieveform', 'filterform');
1186
1187        return $out;
1188    }
1189
1190    function rule_div($fid, $id, $div=true)
1191    {
1192        $rule     = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
1193        $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
1194
1195        // headers select
1196        $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
1197            'onchange' => 'rule_header_select(' .$id .')'));
1198        foreach($this->headers as $name => $val)
1199            $select_header->add(Q($this->gettext($name)), Q($val));
1200        if (in_array('body', $this->exts))
1201            $select_header->add(Q($this->gettext('body')), 'body');
1202        $select_header->add(Q($this->gettext('size')), 'size');
1203        $select_header->add(Q($this->gettext('...')), '...');
1204
1205        // TODO: list arguments
1206        $aout = '';
1207
1208        if ((isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope')))
1209            && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers)
1210        ) {
1211            $aout .= $select_header->show($rule['arg1']);
1212        }
1213        else if ((isset($rule['test']) && $rule['test'] == 'exists')
1214            && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers)
1215        ) {
1216            $aout .= $select_header->show($rule['arg']);
1217        }
1218        else if (isset($rule['test']) && $rule['test'] == 'size')
1219            $aout .= $select_header->show('size');
1220        else if (isset($rule['test']) && $rule['test'] == 'body')
1221            $aout .= $select_header->show('body');
1222        else if (isset($rule['test']) && $rule['test'] != 'true')
1223            $aout .= $select_header->show('...');
1224        else
1225            $aout .= $select_header->show();
1226
1227        if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) {
1228            if (is_array($rule['arg1']))
1229                $custom = implode(', ', $rule['arg1']);
1230            else if (!in_array($rule['arg1'], $this->headers))
1231                $custom = $rule['arg1'];
1232        }
1233        else if (isset($rule['test']) && $rule['test'] == 'exists') {
1234            if (is_array($rule['arg']))
1235                $custom = implode(', ', $rule['arg']);
1236            else if (!in_array($rule['arg'], $this->headers))
1237                $custom = $rule['arg'];
1238        }
1239
1240        $tout = '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
1241            <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
1242            . $this->error_class($id, 'test', 'header', 'custom_header_i')
1243            .' value="' .Q($custom). '" size="15" />&nbsp;</div>' . "\n";
1244
1245        // matching type select (operator)
1246        $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
1247            'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
1248            'class' => 'operator_selector',
1249            'onchange' => 'rule_op_select('.$id.')'));
1250        $select_op->add(Q($this->gettext('filtercontains')), 'contains');
1251        $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
1252        $select_op->add(Q($this->gettext('filteris')), 'is');
1253        $select_op->add(Q($this->gettext('filterisnot')), 'notis');
1254        $select_op->add(Q($this->gettext('filterexists')), 'exists');
1255        $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
1256        $select_op->add(Q($this->gettext('filtermatches')), 'matches');
1257        $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
1258        if (in_array('regex', $this->exts)) {
1259            $select_op->add(Q($this->gettext('filterregex')), 'regex');
1260            $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
1261        }
1262        if (in_array('relational', $this->exts)) {
1263            $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
1264            $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
1265            $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
1266            $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
1267            $select_op->add(Q($this->gettext('countequals')), 'count-eq');
1268            $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
1269            $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
1270            $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
1271            $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
1272            $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
1273            $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
1274            $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
1275        }
1276
1277        // target input (TODO: lists)
1278
1279        if (in_array($rule['test'], array('header', 'address', 'envelope'))) {
1280            $tout .= $select_op->show(($rule['not'] ? 'not' : '').$rule['type']);
1281            $target = $rule['arg2'];
1282        }
1283        else if ($rule['test'] == 'size') {
1284            $tout .= $select_op->show();
1285            if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) {
1286                $sizetarget = $matches[1];
1287                $sizeitem = $matches[2];
1288            }
1289            else {
1290                $sizetarget = $rule['arg'];
1291                $sizeitem = $rule['item'];
1292            }
1293        }
1294        else {
1295            $tout .= $select_op->show(($rule['not'] ? 'not' : '').$rule['test']);
1296            $target = $rule['test'] == 'body' ? $rule['arg'] : '';
1297        }
1298
1299        $tout .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
1300            value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
1301            . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
1302
1303        $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
1304        $select_size_op->add(Q($this->gettext('filterover')), 'over');
1305        $select_size_op->add(Q($this->gettext('filterunder')), 'under');
1306
1307        $tout .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
1308        $tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
1309        $tout .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" ' 
1310            . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
1311            <input type="radio" name="_rule_size_item['.$id.']" value=""'
1312                . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
1313            <input type="radio" name="_rule_size_item['.$id.']" value="K"'
1314                . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
1315            <input type="radio" name="_rule_size_item['.$id.']" value="M"'
1316                . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
1317            <input type="radio" name="_rule_size_item['.$id.']" value="G"'
1318                . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
1319        $tout .= '</div>';
1320
1321        // Advanced modifiers (address, envelope)
1322        $select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id,
1323            'onchange' => 'rule_mod_select(' .$id .')'));
1324        $select_mod->add(Q($this->gettext('none')), '');
1325        $select_mod->add(Q($this->gettext('address')), 'address');
1326        if (in_array('envelope', $this->exts))
1327            $select_mod->add(Q($this->gettext('envelope')), 'envelope');
1328
1329        $select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id));
1330        $select_type->add(Q($this->gettext('allparts')), 'all');
1331        $select_type->add(Q($this->gettext('domain')), 'domain');
1332        $select_type->add(Q($this->gettext('localpart')), 'localpart');
1333        if (in_array('subaddress', $this->exts)) {
1334            $select_type->add(Q($this->gettext('user')), 'user');
1335            $select_type->add(Q($this->gettext('detail')), 'detail');
1336        }
1337
1338        $need_mod = $rule['test'] != 'size' && $rule['test'] != 'body';
1339        $mout = '<div id="rule_mod' .$id. '" class="adv" style="display:' . ($need_mod ? 'block' : 'none') .'">';
1340        $mout .= ' <span>';
1341        $mout .= Q($this->gettext('modifier')) . ' ';
1342        $mout .= $select_mod->show($rule['test']);
1343        $mout .= '</span>';
1344        $mout .= ' <span id="rule_mod_type' . $id . '"';
1345        $mout .= ' style="display:' . (in_array($rule['test'], array('address', 'envelope')) ? 'inline' : 'none') .'">';
1346        $mout .= Q($this->gettext('modtype')) . ' ';
1347        $mout .= $select_type->show($rule['part']);
1348        $mout .= '</span>';
1349        $mout .= '</div>';
1350
1351        // Advanced modifiers (body transformations)
1352        $select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id,
1353            'onchange' => 'rule_trans_select(' .$id .')'));
1354        $select_mod->add(Q($this->gettext('text')), 'text');
1355        $select_mod->add(Q($this->gettext('undecoded')), 'raw');
1356        $select_mod->add(Q($this->gettext('contenttype')), 'content');
1357
1358        $mout .= '<div id="rule_trans' .$id. '" class="adv" style="display:' . ($rule['test'] == 'body' ? 'block' : 'none') .'">';
1359        $mout .= ' <span>';
1360        $mout .= Q($this->gettext('modifier')) . ' ';
1361        $mout .= $select_mod->show($rule['part']);
1362        $mout .= '<input type="text" name="_rule_trans_type[]" id="rule_trans_type'.$id
1363            . '" value="'.(is_array($rule['content']) ? implode(',', $rule['content']) : $rule['content'])
1364            .'" size="20" style="display:' . ($rule['part'] == 'content' ? 'inline' : 'none') .'"'
1365            . $this->error_class($id, 'test', 'part', 'rule_trans_type') .' />';
1366        $mout .= '</span>';
1367        $mout .= '</div>';
1368
1369        // Advanced modifiers (body transformations)
1370        $select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id));
1371        $select_comp->add(Q($this->gettext('default')), '');
1372        $select_comp->add(Q($this->gettext('octet')), 'i;octet');
1373        $select_comp->add(Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
1374        if (in_array('comparator-i;ascii-numeric', $this->exts)) {
1375            $select_comp->add(Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
1376        }
1377
1378        $mout .= '<div id="rule_comp' .$id. '" class="adv" style="display:' . ($rule['test'] != 'size' ? 'block' : 'none') .'">';
1379        $mout .= ' <span>';
1380        $mout .= Q($this->gettext('comparator')) . ' ';
1381        $mout .= $select_comp->show($rule['comparator']);
1382        $mout .= '</span>';
1383        $mout .= '</div>';
1384
1385        // Build output table
1386        $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
1387        $out .= '<table><tr>';
1388        $out .= '<td class="advbutton">';
1389        $out .= '<a href="#" id="ruleadv' . $id .'" title="'. Q($this->gettext('advancedopts')). '"
1390            onclick="rule_adv_switch(' . $id .', this)" class="show">&nbsp;&nbsp;</a>';
1391        $out .= '</td>';
1392        $out .= '<td class="rowactions">' . $aout . '</td>';
1393        $out .= '<td class="rowtargets">' . $tout . "\n";
1394        $out .= '<div id="rule_advanced' .$id. '" style="display:none">' . $mout . '</div>';
1395        $out .= '</td>';
1396
1397        // add/del buttons
1398        $out .= '<td class="rowbuttons">';
1399        $out .= '<a href="#" id="ruleadd' . $id .'" title="'. Q($this->gettext('add')). '"
1400            onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
1401        $out .= '<a href="#" id="ruledel' . $id .'" title="'. Q($this->gettext('del')). '"
1402            onclick="rcmail.managesieve_ruledel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1403        $out .= '</td>';
1404        $out .= '</tr></table>';
1405
1406        $out .= $div ? "</div>\n" : '';
1407
1408        return $out;
1409    }
1410
1411    function action_div($fid, $id, $div=true)
1412    {
1413        $action   = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
1414        $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
1415
1416        $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
1417
1418        $out .= '<table><tr><td class="rowactions">';
1419
1420        // action select
1421        $select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id,
1422            'onchange' => 'action_type_select(' .$id .')'));
1423        if (in_array('fileinto', $this->exts))
1424            $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
1425        if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
1426            $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
1427        $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
1428        if (in_array('copy', $this->exts))
1429            $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
1430        if (in_array('reject', $this->exts))
1431            $select_action->add(Q($this->gettext('messagediscard')), 'reject');
1432        else if (in_array('ereject', $this->exts))
1433            $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
1434        if (in_array('vacation', $this->exts))
1435            $select_action->add(Q($this->gettext('messagereply')), 'vacation');
1436        $select_action->add(Q($this->gettext('messagedelete')), 'discard');
1437        if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
1438            $select_action->add(Q($this->gettext('setflags')), 'setflag');
1439            $select_action->add(Q($this->gettext('addflags')), 'addflag');
1440            $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
1441        }
1442        $select_action->add(Q($this->gettext('rulestop')), 'stop');
1443
1444        $select_type = $action['type'];
1445        if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
1446            $select_type .= '_copy';
1447        }
1448
1449        $out .= $select_action->show($select_type);
1450        $out .= '</td>';
1451
1452        // actions target inputs
1453        $out .= '<td class="rowtargets">';
1454        // shared targets
1455        $out .= '<input type="text" name="_action_target['.$id.']" id="action_target' .$id. '" '
1456            .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="35" '
1457            .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1458            . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1459        $out .= '<textarea name="_action_target_area['.$id.']" id="action_target_area' .$id. '" '
1460            .'rows="3" cols="35" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1461            .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1462            . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1463            . "</textarea>\n";
1464
1465        // vacation
1466        $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1467        $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1468            .'<textarea name="_action_reason['.$id.']" id="action_reason' .$id. '" '
1469            .'rows="3" cols="35" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1470            . Q($action['reason'], 'strict', false) . "</textarea>\n";
1471        $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
1472            .'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
1473            .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
1474            . $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
1475        $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1476            .'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
1477            .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
1478            . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1479        $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1480            .'<input type="text" name="_action_days['.$id.']" id="action_days'.$id.'" '
1481            .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1482            . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1483        $out .= '</div>';
1484
1485        // flags
1486        $flags = array(
1487            'read'      => '\\Seen',
1488            'answered'  => '\\Answered',
1489            'flagged'   => '\\Flagged',
1490            'deleted'   => '\\Deleted',
1491            'draft'     => '\\Draft',
1492        );
1493        $flags_target = (array)$action['target'];
1494
1495        $out .= '<div id="action_flags' .$id.'" style="display:' 
1496            . (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
1497            . $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
1498        foreach ($flags as $fidx => $flag) {
1499            $out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
1500                . (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
1501                . Q($this->gettext('flag'.$fidx)) .'<br>';
1502        }
1503        $out .= '</div>';
1504
1505        // mailbox select
1506        if ($action['type'] == 'fileinto')
1507            $mailbox = $this->mod_mailbox($action['target'], 'out');
1508        else
1509            $mailbox = '';
1510
1511        $this->rc->imap_connect();
1512        $select = rcmail_mailbox_select(array(
1513            'realnames' => false,
1514            'maxlength' => 100,
1515            'id' => 'action_mailbox' . $id,
1516            'name' => "_action_mailbox[$id]",
1517            'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
1518        ));
1519        $out .= $select->show($mailbox);
1520        $out .= '</td>';
1521
1522        // add/del buttons
1523        $out .= '<td class="rowbuttons">';
1524        $out .= '<a href="#" id="actionadd' . $id .'" title="'. Q($this->gettext('add')). '"
1525            onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
1526        $out .= '<a href="#" id="actiondel' . $id .'" title="'. Q($this->gettext('del')). '"
1527            onclick="rcmail.managesieve_actiondel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1528        $out .= '</td>';
1529
1530        $out .= '</tr></table>';
1531
1532        $out .= $div ? "</div>\n" : '';
1533
1534        return $out;
1535    }
1536
1537    private function genid()
1538    {
1539        $result = intval(rcube_timer());
1540        return $result;
1541    }
1542
1543    private function strip_value($str, $allow_html=false)
1544    {
1545        if (!$allow_html)
1546            $str = strip_tags($str);
1547
1548        return trim($str);
1549    }
1550
1551    private function error_class($id, $type, $target, $elem_prefix='')
1552    {
1553        // TODO: tooltips
1554        if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1555            ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1556        ) {
1557            $this->add_tip($elem_prefix.$id, $str, true);
1558            return ' class="error"';
1559        }
1560
1561        return '';
1562    }
1563
1564    private function add_tip($id, $str, $error=false)
1565    {
1566        if ($error)
1567            $str = html::span('sieve error', $str);
1568
1569        $this->tips[] = array($id, $str);
1570    }
1571
1572    private function print_tips()
1573    {
1574        if (empty($this->tips))
1575            return;
1576
1577        $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1578        $this->rc->output->add_script($script, 'foot');
1579    }
1580
1581    /**
1582     * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
1583     * with delimiter replacement.
1584     *
1585     * @param string $mailbox Mailbox name
1586     * @param string $mode    Conversion direction ('in'|'out')
1587     *
1588     * @return string Mailbox name
1589     */
1590    private function mod_mailbox($mailbox, $mode = 'out')
1591    {
1592        $delimiter         = $_SESSION['imap_delimiter'];
1593        $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
1594        $mbox_encoding     = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1595
1596        if ($mode == 'out') {
1597            $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
1598            if ($replace_delimiter && $replace_delimiter != $delimiter)
1599                $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
1600        }
1601        else {
1602            $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
1603            if ($replace_delimiter && $replace_delimiter != $delimiter)
1604                $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);
1605        }
1606
1607        return $mailbox;
1608    }
1609
1610    /**
1611     * List sieve scripts
1612     *
1613     * @return array Scripts list
1614     */
1615    public function list_scripts()
1616    {
1617        if ($this->list !== null) {
1618            return $this->list;
1619        }
1620
1621        $this->list = $this->sieve->get_scripts();
1622
1623        // Handle active script(s) and list of scripts according to Kolab's KEP:14
1624        if ($this->rc->config->get('managesieve_kolab_master')) {
1625
1626            // Skip protected names
1627            foreach ((array)$this->list as $idx => $name) {
1628                $_name = strtoupper($name);
1629                if ($_name == 'MASTER')
1630                    $master_script = $name;
1631                else if ($_name == 'MANAGEMENT')
1632                    $management_script = $name;
1633                else if($_name == 'USER')
1634                    $user_script = $name;
1635                else
1636                    continue;
1637
1638                unset($this->list[$idx]);
1639            }
1640
1641            // get active script(s), read USER script
1642            if ($user_script) {
1643                $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1644                $filename_regex = '/'.preg_quote($extension, '/').'$/';
1645                $_SESSION['managesieve_user_script'] = $user_script;
1646
1647                $this->sieve->load($user_script);
1648
1649                foreach ($this->sieve->script->as_array() as $rules) {
1650                    foreach ($rules['actions'] as $action) {
1651                        if ($action['type'] == 'include' && empty($action['global'])) {
1652                            $name = preg_replace($filename_regex, '', $action['target']);
1653                            $this->active[] = $name;
1654                        }
1655                    }
1656                }
1657            }
1658            // create USER script if it doesn't exist
1659            else {
1660                $content = "# USER Management Script\n"
1661                    ."#\n"
1662                    ."# This script includes the various active sieve scripts\n"
1663                    ."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n"
1664                    ."#\n"
1665                    ."# For more information, see http://wiki.kolab.org/KEP:14#USER\n"
1666                    ."#\n";
1667                if ($this->sieve->save_script('USER', $content)) {
1668                    $_SESSION['managesieve_user_script'] = 'USER';
1669                    if (empty($this->master_file))
1670                        $this->sieve->activate('USER');
1671                }
1672            }
1673        }
1674        else if (!empty($this->list)) {
1675            // Get active script name
1676            if ($active = $this->sieve->get_active()) {
1677                $this->active = array($active);
1678            }
1679        }
1680
1681        return $this->list;
1682    }
1683
1684    /**
1685     * Removes sieve script
1686     *
1687     * @param string $name Script name
1688     *
1689     * @return bool True on success, False on failure
1690     */
1691    public function remove_script($name)
1692    {
1693        $result = $this->sieve->remove($name);
1694
1695        // Kolab's KEP:14
1696        if ($result && $this->rc->config->get('managesieve_kolab_master')) {
1697            $this->deactivate_script($name);
1698        }
1699
1700        return $result;
1701    }
1702
1703    /**
1704     * Activates sieve script
1705     *
1706     * @param string $name Script name
1707     *
1708     * @return bool True on success, False on failure
1709     */
1710    public function activate_script($name)
1711    {
1712        // Kolab's KEP:14
1713        if ($this->rc->config->get('managesieve_kolab_master')) {
1714            $extension   = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1715            $user_script = $_SESSION['managesieve_user_script'];
1716
1717            // if the script is not active...
1718            if ($user_script && ($key = array_search($name, $this->active)) === false) {
1719                // ...rewrite USER file adding appropriate include command
1720                if ($this->sieve->load($user_script)) {
1721                    $script = $this->sieve->script->as_array();
1722                    $list   = array();
1723                    $regexp = '/' . preg_quote($extension, '/') . '$/';
1724
1725                    // Create new include entry
1726                    $rule = array(
1727                        'actions' => array(
1728                            0 => array(
1729                                'target'   => $name.$extension,
1730                                'type'     => 'include',
1731                                'personal' => true,
1732                    )));
1733
1734                    // get all active scripts for sorting
1735                    foreach ($script as $rid => $rules) {
1736                        foreach ($rules['actions'] as $aid => $action) {
1737                            if ($action['type'] == 'include' && empty($action['global'])) {
1738                                $target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target'];
1739                                $list[] = $target;
1740                            }
1741                        }
1742                    }
1743                    $list[] = $name;
1744
1745                    // Sort and find current script position
1746                    asort($list, SORT_LOCALE_STRING);
1747                    $list = array_values($list);
1748                    $index = array_search($name, $list);
1749
1750                    // add rule at the end of the script
1751                    if ($index === false || $index == count($list)-1) {
1752                        $this->sieve->script->add_rule($rule);
1753                    }
1754                    // add rule at index position
1755                    else {
1756                        $script2 = array();
1757                        foreach ($script as $rid => $rules) {
1758                            if ($rid == $index) {
1759                                $script2[] = $rule;
1760                            }
1761                            $script2[] = $rules;
1762                        }
1763                        $this->sieve->script->content = $script2;
1764                    }
1765
1766                    $result = $this->sieve->save();
1767                    if ($result) {
1768                        $this->active[] = $name;
1769                    }
1770                }
1771            }
1772        }
1773        else {
1774            $result = $this->sieve->activate($name);
1775            if ($result)
1776                $this->active = array($name);
1777        }
1778
1779        return $result;
1780    }
1781
1782    /**
1783     * Deactivates sieve script
1784     *
1785     * @param string $name Script name
1786     *
1787     * @return bool True on success, False on failure
1788     */
1789    public function deactivate_script($name)
1790    {
1791        // Kolab's KEP:14
1792        if ($this->rc->config->get('managesieve_kolab_master')) {
1793            $extension   = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1794            $user_script = $_SESSION['managesieve_user_script'];
1795
1796            // if the script is active...
1797            if ($user_script && ($key = array_search($name, $this->active)) !== false) {
1798                // ...rewrite USER file removing appropriate include command
1799                if ($this->sieve->load($user_script)) {
1800                    $script = $this->sieve->script->as_array();
1801                    $name   = $name.$extension;
1802
1803                    foreach ($script as $rid => $rules) {
1804                        foreach ($rules['actions'] as $aid => $action) {
1805                            if ($action['type'] == 'include' && empty($action['global'])
1806                                && $action['target'] == $name
1807                            ) {
1808                                break 2;
1809                            }
1810                        }
1811                    }
1812
1813                    // Entry found
1814                    if ($rid < count($script)) {
1815                        $this->sieve->script->delete_rule($rid);
1816                        $result = $this->sieve->save();
1817                        if ($result) {
1818                            unset($this->active[$key]);
1819                        }
1820                    }
1821                }
1822            }
1823        }
1824        else {
1825            $result = $this->sieve->deactivate();
1826            if ($result)
1827                $this->active = array();
1828        }
1829
1830        return $result;
1831    }
1832
1833    /**
1834     * Saves current script (adding some variables)
1835     */
1836    public function save_script($name = null)
1837    {
1838        // Kolab's KEP:14
1839        if ($this->rc->config->get('managesieve_kolab_master')) {
1840            $this->sieve->script->set_var('EDITOR', self::PROGNAME);
1841            $this->sieve->script->set_var('EDITOR_VERSION', self::VERSION);
1842        }
1843
1844        return $this->sieve->save($name);
1845    }
1846
1847    /**
1848     * Returns list of rules from the current script
1849     *
1850     * @return array List of rules
1851     */
1852    public function list_rules()
1853    {
1854        $result = array();
1855        $i      = 1;
1856
1857        foreach ($this->script as $idx => $filter) {
1858            if ($filter['type'] != 'if') {
1859                continue;
1860            }
1861            $fname = $filter['name'] ? $filter['name'] : "#$i";
1862            $result[] = array(
1863                'id'    => $idx,
1864                'name'  => Q($fname),
1865                'class' => $filter['disabled'] ? 'disabled' : '',
1866            );
1867            $i++;
1868        }
1869
1870        return $result;
1871    }
1872}
Note: See TracBrowser for help on using the repository browser.