source: github/plugins/managesieve/managesieve.php @ c9dcb83

Last change on this file since c9dcb83 was c9dcb83, checked in by Aleksander Machniak <alec@…>, 11 months ago

Fixed PHP warning, added check for allowed characters in variable name

  • Property mode set to 100644
File size: 81.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            $varnames       = get_input_value('_action_varname', RCUBE_INPUT_POST);
619            $varvalues      = get_input_value('_action_varvalue', RCUBE_INPUT_POST);
620            $varmods        = get_input_value('_action_varmods', RCUBE_INPUT_POST);
621
622            // we need a "hack" for radiobuttons
623            foreach ($sizeitems as $item)
624                $items[] = $item;
625
626            $this->form['disabled'] = $_POST['_disabled'] ? true : false;
627            $this->form['join']     = $join=='allof' ? true : false;
628            $this->form['name']     = $name;
629            $this->form['tests']    = array();
630            $this->form['actions']  = array();
631
632            if ($name == '')
633                $this->errors['name'] = $this->gettext('cannotbeempty');
634            else {
635                foreach($this->script as $idx => $rule)
636                    if($rule['name'] == $name && $idx != $fid) {
637                        $this->errors['name'] = $this->gettext('ruleexist');
638                        break;
639                    }
640            }
641
642            $i = 0;
643            // rules
644            if ($join == 'any') {
645                $this->form['tests'][0]['test'] = 'true';
646            }
647            else {
648                foreach ($headers as $idx => $header) {
649                    $header     = $this->strip_value($header);
650                    $target     = $this->strip_value($targets[$idx], true);
651                    $operator   = $this->strip_value($ops[$idx]);
652                    $comparator = $this->strip_value($comparators[$idx]);
653
654                    if ($header == 'size') {
655                        $sizeop     = $this->strip_value($sizeops[$idx]);
656                        $sizeitem   = $this->strip_value($items[$idx]);
657                        $sizetarget = $this->strip_value($sizetargets[$idx]);
658
659                        $this->form['tests'][$i]['test'] = 'size';
660                        $this->form['tests'][$i]['type'] = $sizeop;
661                        $this->form['tests'][$i]['arg']  = $sizetarget;
662
663                        if ($sizetarget == '')
664                            $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
665                        else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) {
666                            $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
667                            $this->form['tests'][$i]['item'] = $sizeitem;
668                        }
669                        else
670                            $this->form['tests'][$i]['arg'] .= $m[1];
671                    }
672                    else if ($header == 'body') {
673                        $trans      = $this->strip_value($body_trans[$idx]);
674                        $trans_type = $this->strip_value($body_types[$idx], true);
675
676                        if (preg_match('/^not/', $operator))
677                            $this->form['tests'][$i]['not'] = true;
678                        $type = preg_replace('/^not/', '', $operator);
679
680                        if ($type == 'exists') {
681                            $this->errors['tests'][$i]['op'] = true;
682                        }
683
684                        $this->form['tests'][$i]['test'] = 'body';
685                        $this->form['tests'][$i]['type'] = $type;
686                        $this->form['tests'][$i]['arg']  = $target;
687
688                        if ($target == '' && $type != 'exists')
689                            $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
690                        else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
691                            $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
692
693                        $this->form['tests'][$i]['part'] = $trans;
694                        if ($trans == 'content') {
695                            $this->form['tests'][$i]['content'] = $trans_type;
696                        }
697                    }
698                    else {
699                        $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
700                        $mod      = $this->strip_value($mods[$idx]);
701                        $mod_type = $this->strip_value($mod_types[$idx]);
702
703                        if (preg_match('/^not/', $operator))
704                            $this->form['tests'][$i]['not'] = true;
705                        $type = preg_replace('/^not/', '', $operator);
706
707                        if ($header == '...') {
708                            $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
709
710                            if (!count($headers))
711                                $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
712                            else {
713                                foreach ($headers as $hr) {
714                                    // RFC2822: printable ASCII except colon
715                                    if (!preg_match('/^[\x21-\x39\x41-\x7E]+$/i', $hr)) {
716                                        $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
717                                    }
718                                }
719                            }
720
721                            if (empty($this->errors['tests'][$i]['header']))
722                                $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
723                        }
724
725                        if ($type == 'exists') {
726                            $this->form['tests'][$i]['test'] = 'exists';
727                            $this->form['tests'][$i]['arg'] = $header == '...' ? $cust_header : $header;
728                        }
729                        else {
730                            $test   = 'header';
731                            $header = $header == '...' ? $cust_header : $header;
732
733                            if ($mod == 'address' || $mod == 'envelope') {
734                                $found = false;
735                                if (empty($this->errors['tests'][$i]['header'])) {
736                                    foreach ((array)$header as $hdr) {
737                                        if (!in_array(strtolower(trim($hdr)), $this->addr_headers))
738                                            $found = true;
739                                    }
740                                }
741                                if (!$found)
742                                    $test = $mod;
743                            }
744
745                            $this->form['tests'][$i]['type'] = $type;
746                            $this->form['tests'][$i]['test'] = $test;
747                            $this->form['tests'][$i]['arg1'] = $header;
748                            $this->form['tests'][$i]['arg2'] = $target;
749
750                            if ($target == '')
751                                $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
752                            else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
753                                $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
754
755                            if ($mod) {
756                                $this->form['tests'][$i]['part'] = $mod_type;
757                            }
758                        }
759                    }
760
761                    if ($header != 'size' && $comparator) {
762                        if (preg_match('/^(value|count)/', $this->form['tests'][$i]['type']))
763                            $comparator = 'i;ascii-numeric';
764
765                        $this->form['tests'][$i]['comparator'] = $comparator;
766                    }
767
768                    $i++;
769                }
770            }
771
772            $i = 0;
773            // actions
774            foreach($act_types as $idx => $type) {
775                $type   = $this->strip_value($type);
776                $target = $this->strip_value($act_targets[$idx]);
777
778                switch ($type) {
779
780                case 'fileinto':
781                case 'fileinto_copy':
782                    $mailbox = $this->strip_value($mailboxes[$idx]);
783                    $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
784                    if ($type == 'fileinto_copy') {
785                        $type = 'fileinto';
786                        $this->form['actions'][$i]['copy'] = true;
787                    }
788                    break;
789
790                case 'reject':
791                case 'ereject':
792                    $target = $this->strip_value($area_targets[$idx]);
793                    $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
794
795 //                 if ($target == '')
796//                      $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
797                    break;
798
799                case 'redirect':
800                case 'redirect_copy':
801                    $this->form['actions'][$i]['target'] = $target;
802
803                    if ($this->form['actions'][$i]['target'] == '')
804                        $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
805                    else if (!check_email($this->form['actions'][$i]['target']))
806                        $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
807
808                    if ($type == 'redirect_copy') {
809                        $type = 'redirect';
810                        $this->form['actions'][$i]['copy'] = true;
811                    }
812                    break;
813
814                case 'addflag':
815                case 'setflag':
816                case 'removeflag':
817                    $_target = array();
818                    if (empty($flags[$idx])) {
819                        $this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
820                    }
821                    else {
822                        foreach ($flags[$idx] as $flag) {
823                            $_target[] = $this->strip_value($flag);
824                        }
825                    }
826                    $this->form['actions'][$i]['target'] = $_target;
827                    break;
828
829                case 'vacation':
830                    $reason = $this->strip_value($reasons[$idx]);
831                    $this->form['actions'][$i]['reason']    = str_replace("\r\n", "\n", $reason);
832                    $this->form['actions'][$i]['days']      = $days[$idx];
833                    $this->form['actions'][$i]['subject']   = $subject[$idx];
834                    $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
835// @TODO: vacation :mime, :from, :handle
836
837                    if ($this->form['actions'][$i]['addresses']) {
838                        foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
839                            $address = trim($address);
840                            if (!$address)
841                                unset($this->form['actions'][$i]['addresses'][$aidx]);
842                            else if(!check_email($address)) {
843                                $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
844                                break;
845                            } else
846                                $this->form['actions'][$i]['addresses'][$aidx] = $address;
847                        }
848                    }
849
850                    if ($this->form['actions'][$i]['reason'] == '')
851                        $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
852                    if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
853                        $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
854                    break;
855
856                case 'set':
857                    $this->form['actions'][$i]['name'] = $varnames[$idx];
858                    $this->form['actions'][$i]['value'] = $varvalues[$idx];
859                    foreach ((array)$varmods[$idx] as $v_m) {
860                        $this->form['actions'][$i][$v_m] = true;
861                    }
862
863                    if (empty($varnames[$idx])) {
864                        $this->errors['actions'][$i]['name'] = $this->gettext('cannotbeempty');
865                    }
866                    else if (!preg_match('/^[0-9a-z_]+$/i', $varnames[$idx])) {
867                        $this->errors['actions'][$i]['name'] = $this->gettext('forbiddenchars');
868                    }
869
870                    if (!isset($varvalues[$idx]) || $varvalues[$idx] === '') {
871                        $this->errors['actions'][$i]['value'] = $this->gettext('cannotbeempty');
872                    }
873                    break;
874                }
875
876                $this->form['actions'][$i]['type'] = $type;
877                $i++;
878            }
879
880            if (!$this->errors && !$error) {
881                // zapis skryptu
882                if (!isset($this->script[$fid])) {
883                    $fid = $this->sieve->script->add_rule($this->form);
884                    $new = true;
885                } else
886                    $fid = $this->sieve->script->update_rule($fid, $this->form);
887
888                if ($fid !== false)
889                    $save = $this->save_script();
890
891                if ($save && $fid !== false) {
892                    $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
893                    if ($this->rc->task != 'mail') {
894                        $this->rc->output->command('parent.managesieve_updatelist',
895                            isset($new) ? 'add' : 'update',
896                            array(
897                                'name' => Q($this->form['name']),
898                                'id' => $fid,
899                                'disabled' => $this->form['disabled']
900                        ));
901                    }
902                    else {
903                        $this->rc->output->command('managesieve_dialog_close');
904                        $this->rc->output->send('iframe');
905                    }
906                }
907                else {
908                    $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
909//                  $this->rc->output->send();
910                }
911            }
912        }
913
914        $this->managesieve_send();
915    }
916
917    private function managesieve_send()
918    {
919        // Handle form action
920        if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
921            if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
922                $this->rc->output->send('managesieve.setedit');
923            }
924            else {
925                $this->rc->output->send('managesieve.filteredit');
926            }
927        } else {
928            $this->rc->output->set_pagetitle($this->gettext('filters'));
929            $this->rc->output->send('managesieve.managesieve');
930        }
931    }
932
933    // return the filters list as HTML table
934    function filters_list($attrib)
935    {
936        // add id to message list table if not specified
937        if (!strlen($attrib['id']))
938            $attrib['id'] = 'rcmfilterslist';
939
940        // define list of cols to be displayed
941        $a_show_cols = array('name');
942
943        $result = $this->list_rules();
944
945        // create XHTML table
946        $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
947
948        // set client env
949        $this->rc->output->add_gui_object('filterslist', $attrib['id']);
950        $this->rc->output->include_script('list.js');
951
952        // add some labels to client
953        $this->rc->output->add_label('managesieve.filterdeleteconfirm');
954
955        return $out;
956    }
957
958    // return the filters list as <SELECT>
959    function filtersets_list($attrib, $no_env = false)
960    {
961        // add id to message list table if not specified
962        if (!strlen($attrib['id']))
963            $attrib['id'] = 'rcmfiltersetslist';
964
965        $list = $this->list_scripts();
966
967        if ($list) {
968            asort($list, SORT_LOCALE_STRING);
969        }
970
971        if (!empty($attrib['type']) && $attrib['type'] == 'list') {
972            // define list of cols to be displayed
973            $a_show_cols = array('name');
974
975            if ($list) {
976                foreach ($list as $idx => $set) {
977                    $scripts['S'.$idx] = $set;
978                    $result[] = array(
979                        'name' => Q($set),
980                        'id' => 'S'.$idx,
981                        'class' => !in_array($set, $this->active) ? 'disabled' : '',
982                    );
983                }
984            }
985
986            // create XHTML table
987            $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
988
989            $this->rc->output->set_env('filtersets', $scripts);
990            $this->rc->output->include_script('list.js');
991        }
992        else {
993            $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
994                'onchange' => $this->rc->task != 'mail' ? 'rcmail.managesieve_set()' : ''));
995
996            if ($list) {
997                foreach ($list as $set)
998                    $select->add($set, $set);
999            }
1000
1001            $out = $select->show($this->sieve->current);
1002        }
1003
1004        // set client env
1005        if (!$no_env) {
1006            $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
1007            $this->rc->output->add_label('managesieve.setdeleteconfirm');
1008        }
1009
1010        return $out;
1011    }
1012
1013    function filter_frame($attrib)
1014    {
1015        if (!$attrib['id'])
1016            $attrib['id'] = 'rcmfilterframe';
1017
1018        $attrib['name'] = $attrib['id'];
1019
1020        $this->rc->output->set_env('contentframe', $attrib['name']);
1021        $this->rc->output->set_env('blankpage', $attrib['src'] ?
1022        $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
1023
1024        return html::tag('iframe', $attrib);
1025    }
1026
1027    function filterset_form($attrib)
1028    {
1029        if (!$attrib['id'])
1030            $attrib['id'] = 'rcmfiltersetform';
1031
1032        $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
1033
1034        $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1035        $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1036        $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1037        $hiddenfields->add(array('name' => '_newset', 'value' => 1));
1038
1039        $out .= $hiddenfields->show();
1040
1041        $name     = get_input_value('_name', RCUBE_INPUT_POST);
1042        $copy     = get_input_value('_copy', RCUBE_INPUT_POST);
1043        $selected = get_input_value('_from', RCUBE_INPUT_POST);
1044
1045        // filter set name input
1046        $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
1047            'class' => ($this->errors['name'] ? 'error' : '')));
1048
1049        $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
1050            '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
1051
1052        $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
1053        $out .= '<input type="radio" id="from_none" name="_from" value="none"'
1054            .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
1055        $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
1056
1057        // filters set list
1058        $list   = $this->list_scripts();
1059        $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
1060
1061        if (is_array($list)) {
1062            asort($list, SORT_LOCALE_STRING);
1063
1064            if (!$copy)
1065                $copy = $_SESSION['managesieve_current'];
1066
1067            foreach ($list as $set) {
1068                $select->add($set, $set);
1069            }
1070
1071            $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
1072                .($selected=='set' ? ' checked="checked"' : '').'></input>';
1073            $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
1074            $out .= $select->show($copy);
1075        }
1076
1077        // script upload box
1078        $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
1079            'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : '')));
1080
1081        $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
1082            .($selected=='file' ? ' checked="checked"' : '').'></input>';
1083        $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
1084        $out .= $upload->show();
1085        $out .= '</fieldset>';
1086
1087        $this->rc->output->add_gui_object('sieveform', 'filtersetform');
1088
1089        if ($this->errors['name'])
1090            $this->add_tip('_name', $this->errors['name'], true);
1091        if ($this->errors['file'])
1092            $this->add_tip('_file', $this->errors['file'], true);
1093
1094        $this->print_tips();
1095
1096        return $out;
1097    }
1098
1099
1100    function filter_form($attrib)
1101    {
1102        if (!$attrib['id'])
1103            $attrib['id'] = 'rcmfilterform';
1104
1105        $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
1106        $scr = isset($this->form) ? $this->form : $this->script[$fid];
1107
1108        $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1109        $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1110        $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1111        $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
1112
1113        $out = '<form name="filterform" action="./" method="post">'."\n";
1114        $out .= $hiddenfields->show();
1115
1116        // 'any' flag
1117        if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
1118            $any = true;
1119
1120        // filter name input
1121        $field_id = '_name';
1122        $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
1123            'class' => ($this->errors['name'] ? 'error' : '')));
1124
1125        if ($this->errors['name'])
1126            $this->add_tip($field_id, $this->errors['name'], true);
1127
1128        if (isset($scr))
1129            $input_name = $input_name->show($scr['name']);
1130        else
1131            $input_name = $input_name->show();
1132
1133        $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s\n",
1134            $field_id, Q($this->gettext('filtername')), $input_name);
1135
1136        // filter set selector
1137        if ($this->rc->task == 'mail') {
1138            $out .= sprintf("\n&nbsp;<label for=\"%s\"><b>%s:</b></label> %s\n",
1139                $field_id, Q($this->gettext('filterset')),
1140                $this->filtersets_list(array('id' => 'sievescriptname'), true));
1141        }
1142
1143        $out .= '<br /><br /><fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
1144
1145        // any, allof, anyof radio buttons
1146        $field_id = '_allof';
1147        $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
1148            'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
1149
1150        if (isset($scr) && !$any)
1151            $input_join = $input_join->show($scr['join'] ? 'allof' : '');
1152        else
1153            $input_join = $input_join->show();
1154
1155        $out .= sprintf("%s<label for=\"%s\">%s</label>&nbsp;\n",
1156            $input_join, $field_id, Q($this->gettext('filterallof')));
1157
1158        $field_id = '_anyof';
1159        $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
1160            'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
1161
1162        if (isset($scr) && !$any)
1163            $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
1164        else
1165            $input_join = $input_join->show('anyof'); // default
1166
1167        $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1168            $input_join, $field_id, Q($this->gettext('filteranyof')));
1169
1170        $field_id = '_any';
1171        $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
1172            'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
1173
1174        $input_join = $input_join->show($any ? 'any' : '');
1175
1176        $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1177            $input_join, $field_id, Q($this->gettext('filterany')));
1178
1179        $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
1180
1181        $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
1182        for ($x=0; $x<$rows_num; $x++)
1183            $out .= $this->rule_div($fid, $x);
1184        $out .= "</div>\n";
1185
1186        $out .= "</fieldset>\n";
1187
1188        // actions
1189        $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
1190
1191        $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
1192
1193        $out .= '<div id="actions">';
1194        for ($x=0; $x<$rows_num; $x++)
1195            $out .= $this->action_div($fid, $x);
1196        $out .= "</div>\n";
1197
1198        $out .= "</fieldset>\n";
1199
1200        $this->print_tips();
1201
1202        if ($scr['disabled']) {
1203            $this->rc->output->set_env('rule_disabled', true);
1204        }
1205        $this->rc->output->add_label(
1206            'managesieve.ruledeleteconfirm',
1207            'managesieve.actiondeleteconfirm'
1208        );
1209        $this->rc->output->add_gui_object('sieveform', 'filterform');
1210
1211        return $out;
1212    }
1213
1214    function rule_div($fid, $id, $div=true)
1215    {
1216        $rule     = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
1217        $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
1218
1219        // headers select
1220        $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
1221            'onchange' => 'rule_header_select(' .$id .')'));
1222        foreach($this->headers as $name => $val)
1223            $select_header->add(Q($this->gettext($name)), Q($val));
1224        if (in_array('body', $this->exts))
1225            $select_header->add(Q($this->gettext('body')), 'body');
1226        $select_header->add(Q($this->gettext('size')), 'size');
1227        $select_header->add(Q($this->gettext('...')), '...');
1228
1229        // TODO: list arguments
1230        $aout = '';
1231
1232        if ((isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope')))
1233            && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers)
1234        ) {
1235            $aout .= $select_header->show($rule['arg1']);
1236        }
1237        else if ((isset($rule['test']) && $rule['test'] == 'exists')
1238            && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers)
1239        ) {
1240            $aout .= $select_header->show($rule['arg']);
1241        }
1242        else if (isset($rule['test']) && $rule['test'] == 'size')
1243            $aout .= $select_header->show('size');
1244        else if (isset($rule['test']) && $rule['test'] == 'body')
1245            $aout .= $select_header->show('body');
1246        else if (isset($rule['test']) && $rule['test'] != 'true')
1247            $aout .= $select_header->show('...');
1248        else
1249            $aout .= $select_header->show();
1250
1251        if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) {
1252            if (is_array($rule['arg1']))
1253                $custom = implode(', ', $rule['arg1']);
1254            else if (!in_array($rule['arg1'], $this->headers))
1255                $custom = $rule['arg1'];
1256        }
1257        else if (isset($rule['test']) && $rule['test'] == 'exists') {
1258            if (is_array($rule['arg']))
1259                $custom = implode(', ', $rule['arg']);
1260            else if (!in_array($rule['arg'], $this->headers))
1261                $custom = $rule['arg'];
1262        }
1263
1264        $tout = '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
1265            <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
1266            . $this->error_class($id, 'test', 'header', 'custom_header_i')
1267            .' value="' .Q($custom). '" size="15" />&nbsp;</div>' . "\n";
1268
1269        // matching type select (operator)
1270        $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
1271            'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
1272            'class' => 'operator_selector',
1273            'onchange' => 'rule_op_select('.$id.')'));
1274        $select_op->add(Q($this->gettext('filtercontains')), 'contains');
1275        $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
1276        $select_op->add(Q($this->gettext('filteris')), 'is');
1277        $select_op->add(Q($this->gettext('filterisnot')), 'notis');
1278        $select_op->add(Q($this->gettext('filterexists')), 'exists');
1279        $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
1280        $select_op->add(Q($this->gettext('filtermatches')), 'matches');
1281        $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
1282        if (in_array('regex', $this->exts)) {
1283            $select_op->add(Q($this->gettext('filterregex')), 'regex');
1284            $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
1285        }
1286        if (in_array('relational', $this->exts)) {
1287            $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
1288            $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
1289            $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
1290            $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
1291            $select_op->add(Q($this->gettext('countequals')), 'count-eq');
1292            $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
1293            $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
1294            $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
1295            $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
1296            $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
1297            $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
1298            $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
1299        }
1300
1301        // target input (TODO: lists)
1302
1303        if (in_array($rule['test'], array('header', 'address', 'envelope'))) {
1304            $test   = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
1305            $target = $rule['arg2'];
1306        }
1307        else if ($rule['test'] == 'body') {
1308            $test   = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
1309            $target = $rule['arg'];
1310        }
1311        else if ($rule['test'] == 'size') {
1312            $test   = '';
1313            $target = '';
1314            if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) {
1315                $sizetarget = $matches[1];
1316                $sizeitem = $matches[2];
1317            }
1318            else {
1319                $sizetarget = $rule['arg'];
1320                $sizeitem = $rule['item'];
1321            }
1322        }
1323        else {
1324            $test   = ($rule['not'] ? 'not' : '').$rule['test'];
1325            $target =  '';
1326        }
1327
1328        $tout .= $select_op->show($test);
1329        $tout .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
1330            value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
1331            . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
1332
1333        $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
1334        $select_size_op->add(Q($this->gettext('filterover')), 'over');
1335        $select_size_op->add(Q($this->gettext('filterunder')), 'under');
1336
1337        $tout .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
1338        $tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
1339        $tout .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" ' 
1340            . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
1341            <input type="radio" name="_rule_size_item['.$id.']" value=""'
1342                . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
1343            <input type="radio" name="_rule_size_item['.$id.']" value="K"'
1344                . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
1345            <input type="radio" name="_rule_size_item['.$id.']" value="M"'
1346                . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
1347            <input type="radio" name="_rule_size_item['.$id.']" value="G"'
1348                . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
1349        $tout .= '</div>';
1350
1351        // Advanced modifiers (address, envelope)
1352        $select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id,
1353            'onchange' => 'rule_mod_select(' .$id .')'));
1354        $select_mod->add(Q($this->gettext('none')), '');
1355        $select_mod->add(Q($this->gettext('address')), 'address');
1356        if (in_array('envelope', $this->exts))
1357            $select_mod->add(Q($this->gettext('envelope')), 'envelope');
1358
1359        $select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id));
1360        $select_type->add(Q($this->gettext('allparts')), 'all');
1361        $select_type->add(Q($this->gettext('domain')), 'domain');
1362        $select_type->add(Q($this->gettext('localpart')), 'localpart');
1363        if (in_array('subaddress', $this->exts)) {
1364            $select_type->add(Q($this->gettext('user')), 'user');
1365            $select_type->add(Q($this->gettext('detail')), 'detail');
1366        }
1367
1368        $need_mod = $rule['test'] != 'size' && $rule['test'] != 'body';
1369        $mout = '<div id="rule_mod' .$id. '" class="adv" style="display:' . ($need_mod ? 'block' : 'none') .'">';
1370        $mout .= ' <span>';
1371        $mout .= Q($this->gettext('modifier')) . ' ';
1372        $mout .= $select_mod->show($rule['test']);
1373        $mout .= '</span>';
1374        $mout .= ' <span id="rule_mod_type' . $id . '"';
1375        $mout .= ' style="display:' . (in_array($rule['test'], array('address', 'envelope')) ? 'inline' : 'none') .'">';
1376        $mout .= Q($this->gettext('modtype')) . ' ';
1377        $mout .= $select_type->show($rule['part']);
1378        $mout .= '</span>';
1379        $mout .= '</div>';
1380
1381        // Advanced modifiers (body transformations)
1382        $select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id,
1383            'onchange' => 'rule_trans_select(' .$id .')'));
1384        $select_mod->add(Q($this->gettext('text')), 'text');
1385        $select_mod->add(Q($this->gettext('undecoded')), 'raw');
1386        $select_mod->add(Q($this->gettext('contenttype')), 'content');
1387
1388        $mout .= '<div id="rule_trans' .$id. '" class="adv" style="display:' . ($rule['test'] == 'body' ? 'block' : 'none') .'">';
1389        $mout .= ' <span>';
1390        $mout .= Q($this->gettext('modifier')) . ' ';
1391        $mout .= $select_mod->show($rule['part']);
1392        $mout .= '<input type="text" name="_rule_trans_type[]" id="rule_trans_type'.$id
1393            . '" value="'.(is_array($rule['content']) ? implode(',', $rule['content']) : $rule['content'])
1394            .'" size="20" style="display:' . ($rule['part'] == 'content' ? 'inline' : 'none') .'"'
1395            . $this->error_class($id, 'test', 'part', 'rule_trans_type') .' />';
1396        $mout .= '</span>';
1397        $mout .= '</div>';
1398
1399        // Advanced modifiers (body transformations)
1400        $select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id));
1401        $select_comp->add(Q($this->gettext('default')), '');
1402        $select_comp->add(Q($this->gettext('octet')), 'i;octet');
1403        $select_comp->add(Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
1404        if (in_array('comparator-i;ascii-numeric', $this->exts)) {
1405            $select_comp->add(Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
1406        }
1407
1408        $mout .= '<div id="rule_comp' .$id. '" class="adv" style="display:' . ($rule['test'] != 'size' ? 'block' : 'none') .'">';
1409        $mout .= ' <span>';
1410        $mout .= Q($this->gettext('comparator')) . ' ';
1411        $mout .= $select_comp->show($rule['comparator']);
1412        $mout .= '</span>';
1413        $mout .= '</div>';
1414
1415        // Build output table
1416        $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
1417        $out .= '<table><tr>';
1418        $out .= '<td class="advbutton">';
1419        $out .= '<a href="#" id="ruleadv' . $id .'" title="'. Q($this->gettext('advancedopts')). '"
1420            onclick="rule_adv_switch(' . $id .', this)" class="show">&nbsp;&nbsp;</a>';
1421        $out .= '</td>';
1422        $out .= '<td class="rowactions">' . $aout . '</td>';
1423        $out .= '<td class="rowtargets">' . $tout . "\n";
1424        $out .= '<div id="rule_advanced' .$id. '" style="display:none">' . $mout . '</div>';
1425        $out .= '</td>';
1426
1427        // add/del buttons
1428        $out .= '<td class="rowbuttons">';
1429        $out .= '<a href="#" id="ruleadd' . $id .'" title="'. Q($this->gettext('add')). '"
1430            onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
1431        $out .= '<a href="#" id="ruledel' . $id .'" title="'. Q($this->gettext('del')). '"
1432            onclick="rcmail.managesieve_ruledel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1433        $out .= '</td>';
1434        $out .= '</tr></table>';
1435
1436        $out .= $div ? "</div>\n" : '';
1437
1438        return $out;
1439    }
1440
1441    function action_div($fid, $id, $div=true)
1442    {
1443        $action   = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
1444        $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
1445
1446        $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
1447
1448        $out .= '<table><tr><td class="rowactions">';
1449
1450        // action select
1451        $select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id,
1452            'onchange' => 'action_type_select(' .$id .')'));
1453        if (in_array('fileinto', $this->exts))
1454            $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
1455        if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
1456            $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
1457        $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
1458        if (in_array('copy', $this->exts))
1459            $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
1460        if (in_array('reject', $this->exts))
1461            $select_action->add(Q($this->gettext('messagediscard')), 'reject');
1462        else if (in_array('ereject', $this->exts))
1463            $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
1464        if (in_array('vacation', $this->exts))
1465            $select_action->add(Q($this->gettext('messagereply')), 'vacation');
1466        $select_action->add(Q($this->gettext('messagedelete')), 'discard');
1467        if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
1468            $select_action->add(Q($this->gettext('setflags')), 'setflag');
1469            $select_action->add(Q($this->gettext('addflags')), 'addflag');
1470            $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
1471        }
1472        if (in_array('variables', $this->exts)) {
1473            $select_action->add(Q($this->gettext('setvariable')), 'set');
1474        }
1475        $select_action->add(Q($this->gettext('rulestop')), 'stop');
1476
1477        $select_type = $action['type'];
1478        if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
1479            $select_type .= '_copy';
1480        }
1481
1482        $out .= $select_action->show($select_type);
1483        $out .= '</td>';
1484
1485        // actions target inputs
1486        $out .= '<td class="rowtargets">';
1487        // shared targets
1488        $out .= '<input type="text" name="_action_target['.$id.']" id="action_target' .$id. '" '
1489            .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="35" '
1490            .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1491            . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1492        $out .= '<textarea name="_action_target_area['.$id.']" id="action_target_area' .$id. '" '
1493            .'rows="3" cols="35" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1494            .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1495            . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1496            . "</textarea>\n";
1497
1498        // vacation
1499        $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1500        $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1501            .'<textarea name="_action_reason['.$id.']" id="action_reason' .$id. '" '
1502            .'rows="3" cols="35" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1503            . Q($action['reason'], 'strict', false) . "</textarea>\n";
1504        $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
1505            .'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
1506            .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
1507            . $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
1508        $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1509            .'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
1510            .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
1511            . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1512        $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1513            .'<input type="text" name="_action_days['.$id.']" id="action_days'.$id.'" '
1514            .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1515            . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1516        $out .= '</div>';
1517
1518        // flags
1519        $flags = array(
1520            'read'      => '\\Seen',
1521            'answered'  => '\\Answered',
1522            'flagged'   => '\\Flagged',
1523            'deleted'   => '\\Deleted',
1524            'draft'     => '\\Draft',
1525        );
1526        $flags_target = (array)$action['target'];
1527
1528        $out .= '<div id="action_flags' .$id.'" style="display:' 
1529            . (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
1530            . $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
1531        foreach ($flags as $fidx => $flag) {
1532            $out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
1533                . (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
1534                . Q($this->gettext('flag'.$fidx)) .'<br>';
1535        }
1536        $out .= '</div>';
1537
1538        // set variable
1539        $set_modifiers = array(
1540            'lower',
1541            'upper',
1542            'lowerfirst',
1543            'upperfirst',
1544            'quotewildcard',
1545            'length'
1546        );
1547
1548        $out .= '<div id="action_set' .$id.'" style="display:' .($action['type']=='set' ? 'inline' : 'none') .'">';
1549        $out .= '<span class="label">' .Q($this->gettext('setvarname')) . '</span><br />'
1550            .'<input type="text" name="_action_varname['.$id.']" id="action_varname'.$id.'" '
1551            .'value="' . Q($action['name']) . '" size="35" '
1552            . $this->error_class($id, 'action', 'name', 'action_varname') .' />';
1553        $out .= '<br /><span class="label">' .Q($this->gettext('setvarvalue')) . '</span><br />'
1554            .'<input type="text" name="_action_varvalue['.$id.']" id="action_varvalue'.$id.'" '
1555            .'value="' . Q($action['value']) . '" size="35" '
1556            . $this->error_class($id, 'action', 'value', 'action_varvalue') .' />';
1557        $out .= '<br /><span class="label">' .Q($this->gettext('setvarmodifiers')) . '</span><br />';
1558        foreach ($set_modifiers as $j => $s_m) {
1559            $s_m_id = 'action_varmods' . $id . $s_m;
1560            $out .= sprintf('<input type="checkbox" name="_action_varmods[%s][]" value="%s" id="%s"%s />%s<br>',
1561                $id, $s_m, $s_m_id,
1562                (array_key_exists($s_m, (array)$action) && $action[$s_m] ? ' checked="checked"' : ''),
1563                Q($this->gettext('var' . $s_m)));
1564        }
1565        $out .= '</div>';
1566
1567        // mailbox select
1568        if ($action['type'] == 'fileinto')
1569            $mailbox = $this->mod_mailbox($action['target'], 'out');
1570        else
1571            $mailbox = '';
1572
1573        $select = rcmail_mailbox_select(array(
1574            'realnames' => false,
1575            'maxlength' => 100,
1576            'id' => 'action_mailbox' . $id,
1577            'name' => "_action_mailbox[$id]",
1578            'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
1579        ));
1580        $out .= $select->show($mailbox);
1581        $out .= '</td>';
1582
1583        // add/del buttons
1584        $out .= '<td class="rowbuttons">';
1585        $out .= '<a href="#" id="actionadd' . $id .'" title="'. Q($this->gettext('add')). '"
1586            onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
1587        $out .= '<a href="#" id="actiondel' . $id .'" title="'. Q($this->gettext('del')). '"
1588            onclick="rcmail.managesieve_actiondel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1589        $out .= '</td>';
1590
1591        $out .= '</tr></table>';
1592
1593        $out .= $div ? "</div>\n" : '';
1594
1595        return $out;
1596    }
1597
1598    private function genid()
1599    {
1600        $result = preg_replace('/[^0-9]/', '', microtime(true));
1601        return $result;
1602    }
1603
1604    private function strip_value($str, $allow_html=false)
1605    {
1606        if (!$allow_html)
1607            $str = strip_tags($str);
1608
1609        return trim($str);
1610    }
1611
1612    private function error_class($id, $type, $target, $elem_prefix='')
1613    {
1614        // TODO: tooltips
1615        if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1616            ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1617        ) {
1618            $this->add_tip($elem_prefix.$id, $str, true);
1619            return ' class="error"';
1620        }
1621
1622        return '';
1623    }
1624
1625    private function add_tip($id, $str, $error=false)
1626    {
1627        if ($error)
1628            $str = html::span('sieve error', $str);
1629
1630        $this->tips[] = array($id, $str);
1631    }
1632
1633    private function print_tips()
1634    {
1635        if (empty($this->tips))
1636            return;
1637
1638        $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1639        $this->rc->output->add_script($script, 'foot');
1640    }
1641
1642    /**
1643     * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
1644     * with delimiter replacement.
1645     *
1646     * @param string $mailbox Mailbox name
1647     * @param string $mode    Conversion direction ('in'|'out')
1648     *
1649     * @return string Mailbox name
1650     */
1651    private function mod_mailbox($mailbox, $mode = 'out')
1652    {
1653        $delimiter         = $_SESSION['imap_delimiter'];
1654        $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
1655        $mbox_encoding     = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1656
1657        if ($mode == 'out') {
1658            $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
1659            if ($replace_delimiter && $replace_delimiter != $delimiter)
1660                $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
1661        }
1662        else {
1663            $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
1664            if ($replace_delimiter && $replace_delimiter != $delimiter)
1665                $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);
1666        }
1667
1668        return $mailbox;
1669    }
1670
1671    /**
1672     * List sieve scripts
1673     *
1674     * @return array Scripts list
1675     */
1676    public function list_scripts()
1677    {
1678        if ($this->list !== null) {
1679            return $this->list;
1680        }
1681
1682        $this->list = $this->sieve->get_scripts();
1683
1684        // Handle active script(s) and list of scripts according to Kolab's KEP:14
1685        if ($this->rc->config->get('managesieve_kolab_master')) {
1686
1687            // Skip protected names
1688            foreach ((array)$this->list as $idx => $name) {
1689                $_name = strtoupper($name);
1690                if ($_name == 'MASTER')
1691                    $master_script = $name;
1692                else if ($_name == 'MANAGEMENT')
1693                    $management_script = $name;
1694                else if($_name == 'USER')
1695                    $user_script = $name;
1696                else
1697                    continue;
1698
1699                unset($this->list[$idx]);
1700            }
1701
1702            // get active script(s), read USER script
1703            if ($user_script) {
1704                $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1705                $filename_regex = '/'.preg_quote($extension, '/').'$/';
1706                $_SESSION['managesieve_user_script'] = $user_script;
1707
1708                $this->sieve->load($user_script);
1709
1710                foreach ($this->sieve->script->as_array() as $rules) {
1711                    foreach ($rules['actions'] as $action) {
1712                        if ($action['type'] == 'include' && empty($action['global'])) {
1713                            $name = preg_replace($filename_regex, '', $action['target']);
1714                            $this->active[] = $name;
1715                        }
1716                    }
1717                }
1718            }
1719            // create USER script if it doesn't exist
1720            else {
1721                $content = "# USER Management Script\n"
1722                    ."#\n"
1723                    ."# This script includes the various active sieve scripts\n"
1724                    ."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n"
1725                    ."#\n"
1726                    ."# For more information, see http://wiki.kolab.org/KEP:14#USER\n"
1727                    ."#\n";
1728                if ($this->sieve->save_script('USER', $content)) {
1729                    $_SESSION['managesieve_user_script'] = 'USER';
1730                    if (empty($this->master_file))
1731                        $this->sieve->activate('USER');
1732                }
1733            }
1734        }
1735        else if (!empty($this->list)) {
1736            // Get active script name
1737            if ($active = $this->sieve->get_active()) {
1738                $this->active = array($active);
1739            }
1740        }
1741
1742        return $this->list;
1743    }
1744
1745    /**
1746     * Removes sieve script
1747     *
1748     * @param string $name Script name
1749     *
1750     * @return bool True on success, False on failure
1751     */
1752    public function remove_script($name)
1753    {
1754        $result = $this->sieve->remove($name);
1755
1756        // Kolab's KEP:14
1757        if ($result && $this->rc->config->get('managesieve_kolab_master')) {
1758            $this->deactivate_script($name);
1759        }
1760
1761        return $result;
1762    }
1763
1764    /**
1765     * Activates sieve script
1766     *
1767     * @param string $name Script name
1768     *
1769     * @return bool True on success, False on failure
1770     */
1771    public function activate_script($name)
1772    {
1773        // Kolab's KEP:14
1774        if ($this->rc->config->get('managesieve_kolab_master')) {
1775            $extension   = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1776            $user_script = $_SESSION['managesieve_user_script'];
1777
1778            // if the script is not active...
1779            if ($user_script && ($key = array_search($name, $this->active)) === false) {
1780                // ...rewrite USER file adding appropriate include command
1781                if ($this->sieve->load($user_script)) {
1782                    $script = $this->sieve->script->as_array();
1783                    $list   = array();
1784                    $regexp = '/' . preg_quote($extension, '/') . '$/';
1785
1786                    // Create new include entry
1787                    $rule = array(
1788                        'actions' => array(
1789                            0 => array(
1790                                'target'   => $name.$extension,
1791                                'type'     => 'include',
1792                                'personal' => true,
1793                    )));
1794
1795                    // get all active scripts for sorting
1796                    foreach ($script as $rid => $rules) {
1797                        foreach ($rules['actions'] as $aid => $action) {
1798                            if ($action['type'] == 'include' && empty($action['global'])) {
1799                                $target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target'];
1800                                $list[] = $target;
1801                            }
1802                        }
1803                    }
1804                    $list[] = $name;
1805
1806                    // Sort and find current script position
1807                    asort($list, SORT_LOCALE_STRING);
1808                    $list = array_values($list);
1809                    $index = array_search($name, $list);
1810
1811                    // add rule at the end of the script
1812                    if ($index === false || $index == count($list)-1) {
1813                        $this->sieve->script->add_rule($rule);
1814                    }
1815                    // add rule at index position
1816                    else {
1817                        $script2 = array();
1818                        foreach ($script as $rid => $rules) {
1819                            if ($rid == $index) {
1820                                $script2[] = $rule;
1821                            }
1822                            $script2[] = $rules;
1823                        }
1824                        $this->sieve->script->content = $script2;
1825                    }
1826
1827                    $result = $this->sieve->save();
1828                    if ($result) {
1829                        $this->active[] = $name;
1830                    }
1831                }
1832            }
1833        }
1834        else {
1835            $result = $this->sieve->activate($name);
1836            if ($result)
1837                $this->active = array($name);
1838        }
1839
1840        return $result;
1841    }
1842
1843    /**
1844     * Deactivates sieve script
1845     *
1846     * @param string $name Script name
1847     *
1848     * @return bool True on success, False on failure
1849     */
1850    public function deactivate_script($name)
1851    {
1852        // Kolab's KEP:14
1853        if ($this->rc->config->get('managesieve_kolab_master')) {
1854            $extension   = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1855            $user_script = $_SESSION['managesieve_user_script'];
1856
1857            // if the script is active...
1858            if ($user_script && ($key = array_search($name, $this->active)) !== false) {
1859                // ...rewrite USER file removing appropriate include command
1860                if ($this->sieve->load($user_script)) {
1861                    $script = $this->sieve->script->as_array();
1862                    $name   = $name.$extension;
1863
1864                    foreach ($script as $rid => $rules) {
1865                        foreach ($rules['actions'] as $aid => $action) {
1866                            if ($action['type'] == 'include' && empty($action['global'])
1867                                && $action['target'] == $name
1868                            ) {
1869                                break 2;
1870                            }
1871                        }
1872                    }
1873
1874                    // Entry found
1875                    if ($rid < count($script)) {
1876                        $this->sieve->script->delete_rule($rid);
1877                        $result = $this->sieve->save();
1878                        if ($result) {
1879                            unset($this->active[$key]);
1880                        }
1881                    }
1882                }
1883            }
1884        }
1885        else {
1886            $result = $this->sieve->deactivate();
1887            if ($result)
1888                $this->active = array();
1889        }
1890
1891        return $result;
1892    }
1893
1894    /**
1895     * Saves current script (adding some variables)
1896     */
1897    public function save_script($name = null)
1898    {
1899        // Kolab's KEP:14
1900        if ($this->rc->config->get('managesieve_kolab_master')) {
1901            $this->sieve->script->set_var('EDITOR', self::PROGNAME);
1902            $this->sieve->script->set_var('EDITOR_VERSION', self::VERSION);
1903        }
1904
1905        return $this->sieve->save($name);
1906    }
1907
1908    /**
1909     * Returns list of rules from the current script
1910     *
1911     * @return array List of rules
1912     */
1913    public function list_rules()
1914    {
1915        $result = array();
1916        $i      = 1;
1917
1918        foreach ($this->script as $idx => $filter) {
1919            if ($filter['type'] != 'if') {
1920                continue;
1921            }
1922            $fname = $filter['name'] ? $filter['name'] : "#$i";
1923            $result[] = array(
1924                'id'    => $idx,
1925                'name'  => Q($fname),
1926                'class' => $filter['disabled'] ? 'disabled' : '',
1927            );
1928            $i++;
1929        }
1930
1931        return $result;
1932    }
1933}
Note: See TracBrowser for help on using the repository browser.