source: github/plugins/managesieve/managesieve.php @ 041c93c

HEADdev-browser-capabilitiespdo
Last change on this file since 041c93c was 041c93c, checked in by Aleksander Machniak <alec@…>, 12 months ago

Removed $Id$

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