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

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