4 * Managesieve (Sieve Filters)
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.
11 * @author Aleksander Machniak <alec@alec.pl>
13 * Configuration (see config.inc.php.dist)
15 * Copyright (C) 2008-2011, The Roundcube Dev Team
16 * Copyright (C) 2011, Kolab Systems AG
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.
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.
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.
31 * $Id: managesieve.php 5452 2011-11-18 14:44:48Z alec $
34 class managesieve extends rcube_plugin
36 public $task = 'mail|settings';
42 private $tips = array();
43 private $script = array();
44 private $exts = array();
46 private $active = array();
47 private $headers = array(
48 'subject' => 'Subject',
52 private $addr_headers = array(
54 "from", "to", "cc", "bcc", "sender", "resent-from", "resent-to",
55 // Additional (RFC 822 / RFC 2822)
56 "reply-to", "resent-reply-to", "resent-sender", "resent-cc", "resent-bcc",
57 // Non-standard (RFC 2076, draft-palme-mailext-headers-08.txt)
58 "for-approval", "for-handling", "for-comment", "apparently-to", "errors-to",
59 "delivered-to", "return-receipt-to", "x-admin", "read-receipt-to",
60 "x-confirm-reading-to", "return-receipt-requested",
61 "registered-mail-reply-requested-by", "mail-followup-to", "mail-reply-to",
62 "abuse-reports-to", "x-complaints-to", "x-report-abuse-to",
67 const VERSION = '5.0';
68 const PROGNAME = 'Roundcube (Managesieve)';
73 $this->rc = rcmail::get_instance();
76 $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
77 $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
79 if ($this->rc->task == 'settings') {
82 else if ($this->rc->task == 'mail') {
83 // register message hook
84 $this->add_hook('message_headers_output', array($this, 'mail_headers'));
86 // inject Create Filter popup stuff
87 if (empty($this->rc->action) || $this->rc->action == 'show') {
88 $this->mail_task_handler();
94 * Initializes plugin's UI (localization, js script)
96 private function init_ui()
98 if ($this->ui_initialized)
102 $this->add_texts('localization/', array('filters','managefilters'));
103 $this->include_script('managesieve.js');
105 $this->ui_initialized = true;
109 * Add UI elements to the 'mailbox view' and 'show message' UI.
111 function mail_task_handler()
113 // use jQuery for popup window
114 $this->require_plugin('jqueryui');
116 // include js script and localization
120 $skin = $this->rc->config->get('skin');
121 if (!file_exists($this->home."/skins/$skin/managesieve_mail.css"))
123 $this->include_stylesheet("skins/$skin/managesieve_mail.css");
125 // add 'Create filter' item to message menu
126 $this->api->add_content(html::tag('li', null,
127 $this->api->output->button(array(
128 'command' => 'managesieve-create',
129 'label' => 'managesieve.filtercreate',
131 'classact' => 'filterlink active',
132 'class' => 'filterlink',
135 // register some labels/messages
136 $this->rc->output->add_label('managesieve.newfilter', 'managesieve.usedata',
137 'managesieve.nodata', 'managesieve.nextstep', 'save');
139 $this->rc->session->remove('managesieve_current');
143 * Get message headers for popup window
145 function mail_headers($args)
147 $headers = $args['headers'];
150 if ($headers->subject)
151 $ret[] = array('Subject', $this->rc->imap->decode_header($headers->subject));
153 // @TODO: List-Id, others?
154 foreach (array('From', 'To') as $h) {
155 $hl = strtolower($h);
157 $list = $this->rc->imap->decode_address_list($headers->$hl);
158 foreach ($list as $item) {
159 if ($item['mailto']) {
160 $ret[] = array($h, $item['mailto']);
166 if ($this->rc->action == 'preview')
167 $this->rc->output->command('parent.set_env', array('sieve_headers' => $ret));
169 $this->rc->output->set_env('sieve_headers', $ret);
176 * Loads configuration, initializes plugin (including sieve connection)
178 function managesieve_start()
180 $this->load_config();
182 // register UI objects
183 $this->rc->output->add_handlers(array(
184 'filterslist' => array($this, 'filters_list'),
185 'filtersetslist' => array($this, 'filtersets_list'),
186 'filterframe' => array($this, 'filter_frame'),
187 'filterform' => array($this, 'filter_form'),
188 'filtersetform' => array($this, 'filterset_form'),
191 // Add include path for internal classes
192 $include_path = $this->home . '/lib' . PATH_SEPARATOR;
193 $include_path .= ini_get('include_path');
194 set_include_path($include_path);
196 $host = rcube_parse_host($this->rc->config->get('managesieve_host', 'localhost'));
197 $port = $this->rc->config->get('managesieve_port', 2000);
199 $host = rcube_idn_to_ascii($host);
201 $plugin = $this->rc->plugins->exec_hook('managesieve_connect', array(
202 'user' => $_SESSION['username'],
203 'password' => $this->rc->decrypt($_SESSION['password']),
206 'auth_type' => $this->rc->config->get('managesieve_auth_type'),
207 'usetls' => $this->rc->config->get('managesieve_usetls', false),
208 'disabled' => $this->rc->config->get('managesieve_disabled_extensions'),
209 'debug' => $this->rc->config->get('managesieve_debug', false),
210 'auth_cid' => $this->rc->config->get('managesieve_auth_cid'),
211 'auth_pw' => $this->rc->config->get('managesieve_auth_pw'),
214 // try to connect to managesieve server and to fetch the script
215 $this->sieve = new rcube_sieve(
220 $plugin['auth_type'],
228 if (!($error = $this->sieve->error())) {
229 // Get list of scripts
230 $list = $this->list_scripts();
232 if (!empty($_GET['_set']) || !empty($_POST['_set'])) {
233 $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
235 else if (!empty($_SESSION['managesieve_current'])) {
236 $script_name = $_SESSION['managesieve_current'];
239 // get (first) active script
240 if (!empty($this->active[0])) {
241 $script_name = $this->active[0];
244 $script_name = $list[0];
246 // create a new (initial) script
248 // if script not exists build default script contents
249 $script_file = $this->rc->config->get('managesieve_default');
250 $script_name = $this->rc->config->get('managesieve_script_name');
252 if (empty($script_name))
253 $script_name = 'roundcube';
255 if ($script_file && is_readable($script_file))
256 $content = file_get_contents($script_file);
258 // add script and set it active
259 if ($this->sieve->save_script($script_name, $content)) {
260 $this->activate_script($script_name);
261 $this->list[] = $script_name;
267 $this->sieve->load($script_name);
270 $error = $this->sieve->error();
273 // finally set script objects
276 case SIEVE_ERROR_CONNECTION:
277 case SIEVE_ERROR_LOGIN:
278 $this->rc->output->show_message('managesieve.filterconnerror', 'error');
281 $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
285 raise_error(array('code' => 403, 'type' => 'php',
286 'file' => __FILE__, 'line' => __LINE__,
287 'message' => "Unable to connect to managesieve on $host:$port"), true, false);
289 // to disable 'Add filter' button set env variable
290 $this->rc->output->set_env('filterconnerror', true);
291 $this->script = array();
294 $this->exts = $this->sieve->get_extensions();
295 $this->script = $this->sieve->script->as_array();
296 $this->rc->output->set_env('currentset', $this->sieve->current);
297 $_SESSION['managesieve_current'] = $this->sieve->current;
303 function managesieve_actions()
307 $error = $this->managesieve_start();
309 // Handle user requests
310 if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
311 $fid = (int) get_input_value('_fid', RCUBE_INPUT_POST);
313 if ($action == 'delete' && !$error) {
314 if (isset($this->script[$fid])) {
315 if ($this->sieve->script->delete_rule($fid))
316 $result = $this->save_script();
318 if ($result === true) {
319 $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
320 $this->rc->output->command('managesieve_updatelist', 'del', array('id' => $fid));
322 $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
326 else if ($action == 'move' && !$error) {
327 if (isset($this->script[$fid])) {
328 $to = (int) get_input_value('_to', RCUBE_INPUT_POST);
329 $rule = $this->script[$fid];
332 unset($this->script[$fid]);
333 $this->script = array_values($this->script);
335 // add at target position
336 if ($to >= count($this->script)) {
337 $this->script[] = $rule;
341 foreach ($this->script as $idx => $r) {
346 $this->script = $script;
349 $this->sieve->script->content = $this->script;
350 $result = $this->save_script();
352 if ($result === true) {
353 $result = $this->list_rules();
355 $this->rc->output->show_message('managesieve.moved', 'confirmation');
356 $this->rc->output->command('managesieve_updatelist', 'list',
357 array('list' => $result, 'clear' => true, 'set' => $to));
359 $this->rc->output->show_message('managesieve.moveerror', 'error');
363 else if ($action == 'act' && !$error) {
364 if (isset($this->script[$fid])) {
365 $rule = $this->script[$fid];
366 $disabled = $rule['disabled'] ? true : false;
367 $rule['disabled'] = !$disabled;
368 $result = $this->sieve->script->update_rule($fid, $rule);
370 if ($result !== false)
371 $result = $this->save_script();
373 if ($result === true) {
374 if ($rule['disabled'])
375 $this->rc->output->show_message('managesieve.deactivated', 'confirmation');
377 $this->rc->output->show_message('managesieve.activated', 'confirmation');
378 $this->rc->output->command('managesieve_updatelist', 'update',
379 array('id' => $fid, 'disabled' => $rule['disabled']));
381 if ($rule['disabled'])
382 $this->rc->output->show_message('managesieve.deactivateerror', 'error');
384 $this->rc->output->show_message('managesieve.activateerror', 'error');
388 else if ($action == 'setact' && !$error) {
389 $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
390 $result = $this->activate_script($script_name);
391 $kep14 = $this->rc->config->get('managesieve_kolab_master');
393 if ($result === true) {
394 $this->rc->output->set_env('active_sets', $this->active);
395 $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
396 $this->rc->output->command('managesieve_updatelist', 'setact',
397 array('name' => $script_name, 'active' => true, 'all' => !$kep14));
399 $this->rc->output->show_message('managesieve.setactivateerror', 'error');
402 else if ($action == 'deact' && !$error) {
403 $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
404 $result = $this->deactivate_script($script_name);
406 if ($result === true) {
407 $this->rc->output->set_env('active_sets', $this->active);
408 $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
409 $this->rc->output->command('managesieve_updatelist', 'setact',
410 array('name' => $script_name, 'active' => false));
412 $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
415 else if ($action == 'setdel' && !$error) {
416 $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
417 $result = $this->remove_script($script_name);
419 if ($result === true) {
420 $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
421 $this->rc->output->command('managesieve_updatelist', 'setdel',
422 array('name' => $script_name));
423 $this->rc->session->remove('managesieve_current');
425 $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
428 else if ($action == 'setget') {
429 $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
430 $script = $this->sieve->get_script($script_name);
432 if (PEAR::isError($script))
435 $browser = new rcube_browser;
437 // send download headers
438 header("Content-Type: application/octet-stream");
439 header("Content-Length: ".strlen($script));
442 header("Content-Type: application/force-download");
443 if ($browser->ie && $browser->ver < 7)
444 $filename = rawurlencode(abbreviate_string($script_name, 55));
445 else if ($browser->ie)
446 $filename = rawurlencode($script_name);
448 $filename = addcslashes($script_name, '\\"');
450 header("Content-Disposition: attachment; filename=\"$filename.txt\"");
454 else if ($action == 'list') {
455 $result = $this->list_rules();
457 $this->rc->output->command('managesieve_updatelist', 'list', array('list' => $result));
459 else if ($action == 'ruleadd') {
460 $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
461 $id = $this->genid();
462 $content = $this->rule_div($fid, $id, false);
464 $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
466 else if ($action == 'actionadd') {
467 $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
468 $id = $this->genid();
469 $content = $this->action_div($fid, $id, false);
471 $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
474 $this->rc->output->send();
476 else if ($this->rc->task == 'mail') {
477 // Initialize the form
478 $rules = get_input_value('r', RCUBE_INPUT_GET);
479 if (!empty($rules)) {
481 foreach ($rules as $rule) {
482 list($header, $value) = explode(':', $rule, 2);
484 'type' => 'contains',
493 'join' => count($tests) > 1 ? 'allof' : 'anyof',
497 0 => array('type' => 'fileinto'),
498 1 => array('type' => 'stop'),
504 $this->managesieve_send();
507 function managesieve_save()
510 $this->add_texts('localization/', array('filters','managefilters'));
512 // include main js script
513 if ($this->api->output->type == 'html') {
514 $this->include_script('managesieve.js');
517 // Init plugin and handle managesieve connection
518 $error = $this->managesieve_start();
520 // filters set add action
521 if (!empty($_POST['_newset'])) {
523 $name = get_input_value('_name', RCUBE_INPUT_POST, true);
524 $copy = get_input_value('_copy', RCUBE_INPUT_POST, true);
525 $from = get_input_value('_from', RCUBE_INPUT_POST);
526 $exceptions = $this->rc->config->get('managesieve_filename_exceptions');
527 $kolab = $this->rc->config->get('managesieve_kolab_master');
528 $name_uc = mb_strtolower($name);
529 $list = $this->list_scripts();
532 $this->errors['name'] = $this->gettext('cannotbeempty');
534 else if (mb_strlen($name) > 128) {
535 $this->errors['name'] = $this->gettext('nametoolong');
537 else if (!empty($exceptions) && in_array($name, (array)$exceptions)) {
538 $this->errors['name'] = $this->gettext('namereserved');
540 else if (!empty($kolab) && in_array($name_uc, array('MASTER', 'USER', 'MANAGEMENT'))) {
541 $this->errors['name'] = $this->gettext('namereserved');
543 else if (in_array($name, $list)) {
544 $this->errors['name'] = $this->gettext('setexist');
546 else if ($from == 'file') {
548 if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
549 $file = file_get_contents($_FILES['_file']['tmp_name']);
550 $file = preg_replace('/\r/', '', $file);
551 // for security don't save script directly
552 // check syntax before, like this...
553 $this->sieve->load_script($file);
554 if (!$this->save_script($name)) {
555 $this->errors['file'] = $this->gettext('setcreateerror');
558 else { // upload failed
559 $err = $_FILES['_file']['error'];
561 if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
562 $msg = rcube_label(array('name' => 'filesizeerror',
563 'vars' => array('size' =>
564 show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
567 $this->errors['file'] = $this->gettext('fileuploaderror');
571 else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
572 $error = 'managesieve.setcreateerror';
575 if (!$error && empty($this->errors)) {
576 // Find position of the new script on the list
578 asort($list, SORT_LOCALE_STRING);
579 $list = array_values($list);
580 $index = array_search($name, $list);
582 $this->rc->output->show_message('managesieve.setcreated', 'confirmation');
583 $this->rc->output->command('parent.managesieve_updatelist', 'setadd',
584 array('name' => $name, 'index' => $index));
586 $this->rc->output->command('display_message', $msg, 'error');
588 $this->rc->output->show_message($error, 'error');
591 // filter add/edit action
592 else if (isset($_POST['_name'])) {
593 $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
594 $fid = trim(get_input_value('_fid', RCUBE_INPUT_POST));
595 $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
598 $headers = get_input_value('_header', RCUBE_INPUT_POST);
599 $cust_headers = get_input_value('_custom_header', RCUBE_INPUT_POST);
600 $ops = get_input_value('_rule_op', RCUBE_INPUT_POST);
601 $sizeops = get_input_value('_rule_size_op', RCUBE_INPUT_POST);
602 $sizeitems = get_input_value('_rule_size_item', RCUBE_INPUT_POST);
603 $sizetargets = get_input_value('_rule_size_target', RCUBE_INPUT_POST);
604 $targets = get_input_value('_rule_target', RCUBE_INPUT_POST, true);
605 $mods = get_input_value('_rule_mod', RCUBE_INPUT_POST);
606 $mod_types = get_input_value('_rule_mod_type', RCUBE_INPUT_POST);
607 $body_trans = get_input_value('_rule_trans', RCUBE_INPUT_POST);
608 $body_types = get_input_value('_rule_trans_type', RCUBE_INPUT_POST, true);
609 $comparators = get_input_value('_rule_comp', RCUBE_INPUT_POST);
610 $act_types = get_input_value('_action_type', RCUBE_INPUT_POST, true);
611 $mailboxes = get_input_value('_action_mailbox', RCUBE_INPUT_POST, true);
612 $act_targets = get_input_value('_action_target', RCUBE_INPUT_POST, true);
613 $area_targets = get_input_value('_action_target_area', RCUBE_INPUT_POST, true);
614 $reasons = get_input_value('_action_reason', RCUBE_INPUT_POST, true);
615 $addresses = get_input_value('_action_addresses', RCUBE_INPUT_POST, true);
616 $days = get_input_value('_action_days', RCUBE_INPUT_POST);
617 $subject = get_input_value('_action_subject', RCUBE_INPUT_POST, true);
618 $flags = get_input_value('_action_flags', RCUBE_INPUT_POST);
620 // we need a "hack" for radiobuttons
621 foreach ($sizeitems as $item)
624 $this->form['disabled'] = $_POST['_disabled'] ? true : false;
625 $this->form['join'] = $join=='allof' ? true : false;
626 $this->form['name'] = $name;
627 $this->form['tests'] = array();
628 $this->form['actions'] = array();
631 $this->errors['name'] = $this->gettext('cannotbeempty');
633 foreach($this->script as $idx => $rule)
634 if($rule['name'] == $name && $idx != $fid) {
635 $this->errors['name'] = $this->gettext('ruleexist');
642 if ($join == 'any') {
643 $this->form['tests'][0]['test'] = 'true';
646 foreach ($headers as $idx => $header) {
647 $header = $this->strip_value($header);
648 $target = $this->strip_value($targets[$idx], true);
649 $operator = $this->strip_value($ops[$idx]);
650 $comparator = $this->strip_value($comparators[$idx]);
652 if ($header == 'size') {
653 $sizeop = $this->strip_value($sizeops[$idx]);
654 $sizeitem = $this->strip_value($items[$idx]);
655 $sizetarget = $this->strip_value($sizetargets[$idx]);
657 $this->form['tests'][$i]['test'] = 'size';
658 $this->form['tests'][$i]['type'] = $sizeop;
659 $this->form['tests'][$i]['arg'] = $sizetarget;
661 if ($sizetarget == '')
662 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
663 else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) {
664 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
665 $this->form['tests'][$i]['item'] = $sizeitem;
668 $this->form['tests'][$i]['arg'] .= $m[1];
670 else if ($header == 'body') {
671 $trans = $this->strip_value($body_trans[$idx]);
672 $trans_type = $this->strip_value($body_types[$idx], true);
674 if (preg_match('/^not/', $operator))
675 $this->form['tests'][$i]['not'] = true;
676 $type = preg_replace('/^not/', '', $operator);
678 if ($type == 'exists') {
679 $this->errors['tests'][$i]['op'] = true;
682 $this->form['tests'][$i]['test'] = 'body';
683 $this->form['tests'][$i]['type'] = $type;
684 $this->form['tests'][$i]['arg'] = $target;
686 if ($target == '' && $type != 'exists')
687 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
688 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
689 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
691 $this->form['tests'][$i]['part'] = $trans;
692 if ($trans == 'content') {
693 $this->form['tests'][$i]['content'] = $trans_type;
697 $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
698 $mod = $this->strip_value($mods[$idx]);
699 $mod_type = $this->strip_value($mod_types[$idx]);
701 if (preg_match('/^not/', $operator))
702 $this->form['tests'][$i]['not'] = true;
703 $type = preg_replace('/^not/', '', $operator);
705 if ($header == '...') {
706 $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
708 if (!count($headers))
709 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
711 foreach ($headers as $hr)
712 if (!preg_match('/^[a-z0-9-]+$/i', $hr))
713 $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
716 if (empty($this->errors['tests'][$i]['header']))
717 $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
720 if ($type == 'exists') {
721 $this->form['tests'][$i]['test'] = 'exists';
722 $this->form['tests'][$i]['arg'] = $header == '...' ? $cust_header : $header;
726 $header = $header == '...' ? $cust_header : $header;
728 if ($mod == 'address' || $mod == 'envelope') {
730 if (empty($this->errors['tests'][$i]['header'])) {
731 foreach ((array)$header as $hdr) {
732 if (!in_array(strtolower(trim($hdr)), $this->addr_headers))
740 $this->form['tests'][$i]['type'] = $type;
741 $this->form['tests'][$i]['test'] = $test;
742 $this->form['tests'][$i]['arg1'] = $header;
743 $this->form['tests'][$i]['arg2'] = $target;
746 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
747 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
748 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
751 $this->form['tests'][$i]['part'] = $mod_type;
756 if ($header != 'size' && $comparator) {
757 if (preg_match('/^(value|count)/', $this->form['tests'][$i]['type']))
758 $comparator = 'i;ascii-numeric';
760 $this->form['tests'][$i]['comparator'] = $comparator;
769 foreach($act_types as $idx => $type) {
770 $type = $this->strip_value($type);
771 $target = $this->strip_value($act_targets[$idx]);
776 case 'fileinto_copy':
777 $mailbox = $this->strip_value($mailboxes[$idx]);
778 $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
779 if ($type == 'fileinto_copy') {
781 $this->form['actions'][$i]['copy'] = true;
787 $target = $this->strip_value($area_targets[$idx]);
788 $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
790 // if ($target == '')
791 // $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
795 case 'redirect_copy':
796 $this->form['actions'][$i]['target'] = $target;
798 if ($this->form['actions'][$i]['target'] == '')
799 $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
800 else if (!check_email($this->form['actions'][$i]['target']))
801 $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
803 if ($type == 'redirect_copy') {
805 $this->form['actions'][$i]['copy'] = true;
813 if (empty($flags[$idx])) {
814 $this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
817 foreach ($flags[$idx] as $flag) {
818 $_target[] = $this->strip_value($flag);
821 $this->form['actions'][$i]['target'] = $_target;
825 $reason = $this->strip_value($reasons[$idx]);
826 $this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason);
827 $this->form['actions'][$i]['days'] = $days[$idx];
828 $this->form['actions'][$i]['subject'] = $subject[$idx];
829 $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
830 // @TODO: vacation :mime, :from, :handle
832 if ($this->form['actions'][$i]['addresses']) {
833 foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
834 $address = trim($address);
836 unset($this->form['actions'][$i]['addresses'][$aidx]);
837 else if(!check_email($address)) {
838 $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
841 $this->form['actions'][$i]['addresses'][$aidx] = $address;
845 if ($this->form['actions'][$i]['reason'] == '')
846 $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
847 if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
848 $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
852 $this->form['actions'][$i]['type'] = $type;
856 if (!$this->errors && !$error) {
858 if (!isset($this->script[$fid])) {
859 $fid = $this->sieve->script->add_rule($this->form);
862 $fid = $this->sieve->script->update_rule($fid, $this->form);
865 $save = $this->save_script();
867 if ($save && $fid !== false) {
868 $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
869 if ($this->rc->task != 'mail') {
870 $this->rc->output->command('parent.managesieve_updatelist',
871 isset($new) ? 'add' : 'update',
873 'name' => Q($this->form['name']),
875 'disabled' => $this->form['disabled']
879 $this->rc->output->command('managesieve_dialog_close');
880 $this->rc->output->send('iframe');
884 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
885 // $this->rc->output->send();
890 $this->managesieve_send();
893 private function managesieve_send()
895 // Handle form action
896 if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
897 if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
898 $this->rc->output->send('managesieve.setedit');
901 $this->rc->output->send('managesieve.filteredit');
904 $this->rc->output->set_pagetitle($this->gettext('filters'));
905 $this->rc->output->send('managesieve.managesieve');
909 // return the filters list as HTML table
910 function filters_list($attrib)
912 // add id to message list table if not specified
913 if (!strlen($attrib['id']))
914 $attrib['id'] = 'rcmfilterslist';
916 // define list of cols to be displayed
917 $a_show_cols = array('name');
919 $result = $this->list_rules();
921 // create XHTML table
922 $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
925 $this->rc->output->add_gui_object('filterslist', $attrib['id']);
926 $this->rc->output->include_script('list.js');
928 // add some labels to client
929 $this->rc->output->add_label('managesieve.filterdeleteconfirm');
934 // return the filters list as <SELECT>
935 function filtersets_list($attrib, $no_env = false)
937 // add id to message list table if not specified
938 if (!strlen($attrib['id']))
939 $attrib['id'] = 'rcmfiltersetslist';
941 $list = $this->list_scripts();
944 asort($list, SORT_LOCALE_STRING);
947 if (!empty($attrib['type']) && $attrib['type'] == 'list') {
948 // define list of cols to be displayed
949 $a_show_cols = array('name');
952 foreach ($list as $idx => $set) {
953 $scripts['S'.$idx] = $set;
957 'class' => !in_array($set, $this->active) ? 'disabled' : '',
962 // create XHTML table
963 $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
965 $this->rc->output->set_env('filtersets', $scripts);
966 $this->rc->output->include_script('list.js');
969 $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
970 'onchange' => $this->rc->task != 'mail' ? 'rcmail.managesieve_set()' : ''));
973 foreach ($list as $set)
974 $select->add($set, $set);
977 $out = $select->show($this->sieve->current);
982 $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
983 $this->rc->output->add_label('managesieve.setdeleteconfirm');
989 function filter_frame($attrib)
992 $attrib['id'] = 'rcmfilterframe';
994 $attrib['name'] = $attrib['id'];
996 $this->rc->output->set_env('contentframe', $attrib['name']);
997 $this->rc->output->set_env('blankpage', $attrib['src'] ?
998 $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
1000 return html::tag('iframe', $attrib);
1003 function filterset_form($attrib)
1006 $attrib['id'] = 'rcmfiltersetform';
1008 $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
1010 $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1011 $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1012 $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1013 $hiddenfields->add(array('name' => '_newset', 'value' => 1));
1015 $out .= $hiddenfields->show();
1017 $name = get_input_value('_name', RCUBE_INPUT_POST);
1018 $copy = get_input_value('_copy', RCUBE_INPUT_POST);
1019 $selected = get_input_value('_from', RCUBE_INPUT_POST);
1021 // filter set name input
1022 $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
1023 'class' => ($this->errors['name'] ? 'error' : '')));
1025 $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
1026 '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
1028 $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
1029 $out .= '<input type="radio" id="from_none" name="_from" value="none"'
1030 .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
1031 $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
1034 $list = $this->list_scripts();
1035 $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
1037 if (is_array($list)) {
1038 asort($list, SORT_LOCALE_STRING);
1041 $copy = $_SESSION['managesieve_current'];
1043 foreach ($list as $set) {
1044 $select->add($set, $set);
1047 $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
1048 .($selected=='set' ? ' checked="checked"' : '').'></input>';
1049 $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
1050 $out .= $select->show($copy);
1053 // script upload box
1054 $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
1055 'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : '')));
1057 $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
1058 .($selected=='file' ? ' checked="checked"' : '').'></input>';
1059 $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
1060 $out .= $upload->show();
1061 $out .= '</fieldset>';
1063 $this->rc->output->add_gui_object('sieveform', 'filtersetform');
1065 if ($this->errors['name'])
1066 $this->add_tip('_name', $this->errors['name'], true);
1067 if ($this->errors['file'])
1068 $this->add_tip('_file', $this->errors['file'], true);
1070 $this->print_tips();
1076 function filter_form($attrib)
1079 $attrib['id'] = 'rcmfilterform';
1081 $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
1082 $scr = isset($this->form) ? $this->form : $this->script[$fid];
1084 $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1085 $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1086 $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1087 $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
1089 $out = '<form name="filterform" action="./" method="post">'."\n";
1090 $out .= $hiddenfields->show();
1093 if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
1096 // filter name input
1097 $field_id = '_name';
1098 $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
1099 'class' => ($this->errors['name'] ? 'error' : '')));
1101 if ($this->errors['name'])
1102 $this->add_tip($field_id, $this->errors['name'], true);
1105 $input_name = $input_name->show($scr['name']);
1107 $input_name = $input_name->show();
1109 $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s\n",
1110 $field_id, Q($this->gettext('filtername')), $input_name);
1112 // filter set selector
1113 if ($this->rc->task == 'mail') {
1114 $out .= sprintf("\n <label for=\"%s\"><b>%s:</b></label> %s\n",
1115 $field_id, Q($this->gettext('filterset')),
1116 $this->filtersets_list(array('id' => 'sievescriptname'), true));
1119 $out .= '<br /><br /><fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
1121 // any, allof, anyof radio buttons
1122 $field_id = '_allof';
1123 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
1124 'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
1126 if (isset($scr) && !$any)
1127 $input_join = $input_join->show($scr['join'] ? 'allof' : '');
1129 $input_join = $input_join->show();
1131 $out .= sprintf("%s<label for=\"%s\">%s</label> \n",
1132 $input_join, $field_id, Q($this->gettext('filterallof')));
1134 $field_id = '_anyof';
1135 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
1136 'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
1138 if (isset($scr) && !$any)
1139 $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
1141 $input_join = $input_join->show('anyof'); // default
1143 $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1144 $input_join, $field_id, Q($this->gettext('filteranyof')));
1147 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
1148 'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
1150 $input_join = $input_join->show($any ? 'any' : '');
1152 $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1153 $input_join, $field_id, Q($this->gettext('filterany')));
1155 $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
1157 $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
1158 for ($x=0; $x<$rows_num; $x++)
1159 $out .= $this->rule_div($fid, $x);
1162 $out .= "</fieldset>\n";
1165 $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
1167 $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
1169 $out .= '<div id="actions">';
1170 for ($x=0; $x<$rows_num; $x++)
1171 $out .= $this->action_div($fid, $x);
1174 $out .= "</fieldset>\n";
1176 $this->print_tips();
1178 if ($scr['disabled']) {
1179 $this->rc->output->set_env('rule_disabled', true);
1181 $this->rc->output->add_label(
1182 'managesieve.ruledeleteconfirm',
1183 'managesieve.actiondeleteconfirm'
1185 $this->rc->output->add_gui_object('sieveform', 'filterform');
1190 function rule_div($fid, $id, $div=true)
1192 $rule = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
1193 $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
1196 $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
1197 'onchange' => 'rule_header_select(' .$id .')'));
1198 foreach($this->headers as $name => $val)
1199 $select_header->add(Q($this->gettext($name)), Q($val));
1200 if (in_array('body', $this->exts))
1201 $select_header->add(Q($this->gettext('body')), 'body');
1202 $select_header->add(Q($this->gettext('size')), 'size');
1203 $select_header->add(Q($this->gettext('...')), '...');
1205 // TODO: list arguments
1208 if ((isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope')))
1209 && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers)
1211 $aout .= $select_header->show($rule['arg1']);
1213 else if ((isset($rule['test']) && $rule['test'] == 'exists')
1214 && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers)
1216 $aout .= $select_header->show($rule['arg']);
1218 else if (isset($rule['test']) && $rule['test'] == 'size')
1219 $aout .= $select_header->show('size');
1220 else if (isset($rule['test']) && $rule['test'] == 'body')
1221 $aout .= $select_header->show('body');
1222 else if (isset($rule['test']) && $rule['test'] != 'true')
1223 $aout .= $select_header->show('...');
1225 $aout .= $select_header->show();
1227 if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) {
1228 if (is_array($rule['arg1']))
1229 $custom = implode(', ', $rule['arg1']);
1230 else if (!in_array($rule['arg1'], $this->headers))
1231 $custom = $rule['arg1'];
1233 else if (isset($rule['test']) && $rule['test'] == 'exists') {
1234 if (is_array($rule['arg']))
1235 $custom = implode(', ', $rule['arg']);
1236 else if (!in_array($rule['arg'], $this->headers))
1237 $custom = $rule['arg'];
1240 $tout = '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
1241 <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
1242 . $this->error_class($id, 'test', 'header', 'custom_header_i')
1243 .' value="' .Q($custom). '" size="15" /> </div>' . "\n";
1245 // matching type select (operator)
1246 $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
1247 'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
1248 'class' => 'operator_selector',
1249 'onchange' => 'rule_op_select('.$id.')'));
1250 $select_op->add(Q($this->gettext('filtercontains')), 'contains');
1251 $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
1252 $select_op->add(Q($this->gettext('filteris')), 'is');
1253 $select_op->add(Q($this->gettext('filterisnot')), 'notis');
1254 $select_op->add(Q($this->gettext('filterexists')), 'exists');
1255 $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
1256 $select_op->add(Q($this->gettext('filtermatches')), 'matches');
1257 $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
1258 if (in_array('regex', $this->exts)) {
1259 $select_op->add(Q($this->gettext('filterregex')), 'regex');
1260 $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
1262 if (in_array('relational', $this->exts)) {
1263 $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
1264 $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
1265 $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
1266 $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
1267 $select_op->add(Q($this->gettext('countequals')), 'count-eq');
1268 $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
1269 $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
1270 $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
1271 $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
1272 $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
1273 $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
1274 $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
1277 // target input (TODO: lists)
1279 if (in_array($rule['test'], array('header', 'address', 'envelope'))) {
1280 $test = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
1281 $target = $rule['arg2'];
1283 else if ($rule['test'] == 'body') {
1284 $test = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
1285 $target = $rule['arg'];
1287 else if ($rule['test'] == 'size') {
1290 if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) {
1291 $sizetarget = $matches[1];
1292 $sizeitem = $matches[2];
1295 $sizetarget = $rule['arg'];
1296 $sizeitem = $rule['item'];
1300 $test = ($rule['not'] ? 'not' : '').$rule['test'];
1304 $tout .= $select_op->show($test);
1305 $tout .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
1306 value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
1307 . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
1309 $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
1310 $select_size_op->add(Q($this->gettext('filterover')), 'over');
1311 $select_size_op->add(Q($this->gettext('filterunder')), 'under');
1313 $tout .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
1314 $tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
1315 $tout .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" '
1316 . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
1317 <input type="radio" name="_rule_size_item['.$id.']" value=""'
1318 . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
1319 <input type="radio" name="_rule_size_item['.$id.']" value="K"'
1320 . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
1321 <input type="radio" name="_rule_size_item['.$id.']" value="M"'
1322 . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
1323 <input type="radio" name="_rule_size_item['.$id.']" value="G"'
1324 . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
1327 // Advanced modifiers (address, envelope)
1328 $select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id,
1329 'onchange' => 'rule_mod_select(' .$id .')'));
1330 $select_mod->add(Q($this->gettext('none')), '');
1331 $select_mod->add(Q($this->gettext('address')), 'address');
1332 if (in_array('envelope', $this->exts))
1333 $select_mod->add(Q($this->gettext('envelope')), 'envelope');
1335 $select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id));
1336 $select_type->add(Q($this->gettext('allparts')), 'all');
1337 $select_type->add(Q($this->gettext('domain')), 'domain');
1338 $select_type->add(Q($this->gettext('localpart')), 'localpart');
1339 if (in_array('subaddress', $this->exts)) {
1340 $select_type->add(Q($this->gettext('user')), 'user');
1341 $select_type->add(Q($this->gettext('detail')), 'detail');
1344 $need_mod = $rule['test'] != 'size' && $rule['test'] != 'body';
1345 $mout = '<div id="rule_mod' .$id. '" class="adv" style="display:' . ($need_mod ? 'block' : 'none') .'">';
1347 $mout .= Q($this->gettext('modifier')) . ' ';
1348 $mout .= $select_mod->show($rule['test']);
1350 $mout .= ' <span id="rule_mod_type' . $id . '"';
1351 $mout .= ' style="display:' . (in_array($rule['test'], array('address', 'envelope')) ? 'inline' : 'none') .'">';
1352 $mout .= Q($this->gettext('modtype')) . ' ';
1353 $mout .= $select_type->show($rule['part']);
1357 // Advanced modifiers (body transformations)
1358 $select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id,
1359 'onchange' => 'rule_trans_select(' .$id .')'));
1360 $select_mod->add(Q($this->gettext('text')), 'text');
1361 $select_mod->add(Q($this->gettext('undecoded')), 'raw');
1362 $select_mod->add(Q($this->gettext('contenttype')), 'content');
1364 $mout .= '<div id="rule_trans' .$id. '" class="adv" style="display:' . ($rule['test'] == 'body' ? 'block' : 'none') .'">';
1366 $mout .= Q($this->gettext('modifier')) . ' ';
1367 $mout .= $select_mod->show($rule['part']);
1368 $mout .= '<input type="text" name="_rule_trans_type[]" id="rule_trans_type'.$id
1369 . '" value="'.(is_array($rule['content']) ? implode(',', $rule['content']) : $rule['content'])
1370 .'" size="20" style="display:' . ($rule['part'] == 'content' ? 'inline' : 'none') .'"'
1371 . $this->error_class($id, 'test', 'part', 'rule_trans_type') .' />';
1375 // Advanced modifiers (body transformations)
1376 $select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id));
1377 $select_comp->add(Q($this->gettext('default')), '');
1378 $select_comp->add(Q($this->gettext('octet')), 'i;octet');
1379 $select_comp->add(Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
1380 if (in_array('comparator-i;ascii-numeric', $this->exts)) {
1381 $select_comp->add(Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
1384 $mout .= '<div id="rule_comp' .$id. '" class="adv" style="display:' . ($rule['test'] != 'size' ? 'block' : 'none') .'">';
1386 $mout .= Q($this->gettext('comparator')) . ' ';
1387 $mout .= $select_comp->show($rule['comparator']);
1391 // Build output table
1392 $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
1393 $out .= '<table><tr>';
1394 $out .= '<td class="advbutton">';
1395 $out .= '<a href="#" id="ruleadv' . $id .'" title="'. Q($this->gettext('advancedopts')). '"
1396 onclick="rule_adv_switch(' . $id .', this)" class="show"> </a>';
1398 $out .= '<td class="rowactions">' . $aout . '</td>';
1399 $out .= '<td class="rowtargets">' . $tout . "\n";
1400 $out .= '<div id="rule_advanced' .$id. '" style="display:none">' . $mout . '</div>';
1404 $out .= '<td class="rowbuttons">';
1405 $out .= '<a href="#" id="ruleadd' . $id .'" title="'. Q($this->gettext('add')). '"
1406 onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
1407 $out .= '<a href="#" id="ruledel' . $id .'" title="'. Q($this->gettext('del')). '"
1408 onclick="rcmail.managesieve_ruledel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1410 $out .= '</tr></table>';
1412 $out .= $div ? "</div>\n" : '';
1417 function action_div($fid, $id, $div=true)
1419 $action = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
1420 $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
1422 $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
1424 $out .= '<table><tr><td class="rowactions">';
1427 $select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id,
1428 'onchange' => 'action_type_select(' .$id .')'));
1429 if (in_array('fileinto', $this->exts))
1430 $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
1431 if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
1432 $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
1433 $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
1434 if (in_array('copy', $this->exts))
1435 $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
1436 if (in_array('reject', $this->exts))
1437 $select_action->add(Q($this->gettext('messagediscard')), 'reject');
1438 else if (in_array('ereject', $this->exts))
1439 $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
1440 if (in_array('vacation', $this->exts))
1441 $select_action->add(Q($this->gettext('messagereply')), 'vacation');
1442 $select_action->add(Q($this->gettext('messagedelete')), 'discard');
1443 if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
1444 $select_action->add(Q($this->gettext('setflags')), 'setflag');
1445 $select_action->add(Q($this->gettext('addflags')), 'addflag');
1446 $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
1448 $select_action->add(Q($this->gettext('rulestop')), 'stop');
1450 $select_type = $action['type'];
1451 if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
1452 $select_type .= '_copy';
1455 $out .= $select_action->show($select_type);
1458 // actions target inputs
1459 $out .= '<td class="rowtargets">';
1461 $out .= '<input type="text" name="_action_target['.$id.']" id="action_target' .$id. '" '
1462 .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="35" '
1463 .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1464 . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1465 $out .= '<textarea name="_action_target_area['.$id.']" id="action_target_area' .$id. '" '
1466 .'rows="3" cols="35" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1467 .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1468 . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1472 $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1473 $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1474 .'<textarea name="_action_reason['.$id.']" id="action_reason' .$id. '" '
1475 .'rows="3" cols="35" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1476 . Q($action['reason'], 'strict', false) . "</textarea>\n";
1477 $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
1478 .'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
1479 .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
1480 . $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
1481 $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1482 .'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
1483 .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
1484 . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1485 $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1486 .'<input type="text" name="_action_days['.$id.']" id="action_days'.$id.'" '
1487 .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1488 . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1494 'answered' => '\\Answered',
1495 'flagged' => '\\Flagged',
1496 'deleted' => '\\Deleted',
1497 'draft' => '\\Draft',
1499 $flags_target = (array)$action['target'];
1501 $out .= '<div id="action_flags' .$id.'" style="display:'
1502 . (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
1503 . $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
1504 foreach ($flags as $fidx => $flag) {
1505 $out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
1506 . (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
1507 . Q($this->gettext('flag'.$fidx)) .'<br>';
1512 if ($action['type'] == 'fileinto')
1513 $mailbox = $this->mod_mailbox($action['target'], 'out');
1517 $this->rc->imap_connect();
1518 $select = rcmail_mailbox_select(array(
1519 'realnames' => false,
1521 'id' => 'action_mailbox' . $id,
1522 'name' => "_action_mailbox[$id]",
1523 'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
1525 $out .= $select->show($mailbox);
1529 $out .= '<td class="rowbuttons">';
1530 $out .= '<a href="#" id="actionadd' . $id .'" title="'. Q($this->gettext('add')). '"
1531 onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
1532 $out .= '<a href="#" id="actiondel' . $id .'" title="'. Q($this->gettext('del')). '"
1533 onclick="rcmail.managesieve_actiondel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1536 $out .= '</tr></table>';
1538 $out .= $div ? "</div>\n" : '';
1543 private function genid()
1545 $result = intval(rcube_timer());
1549 private function strip_value($str, $allow_html=false)
1552 $str = strip_tags($str);
1557 private function error_class($id, $type, $target, $elem_prefix='')
1560 if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1561 ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1563 $this->add_tip($elem_prefix.$id, $str, true);
1564 return ' class="error"';
1570 private function add_tip($id, $str, $error=false)
1573 $str = html::span('sieve error', $str);
1575 $this->tips[] = array($id, $str);
1578 private function print_tips()
1580 if (empty($this->tips))
1583 $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1584 $this->rc->output->add_script($script, 'foot');
1588 * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
1589 * with delimiter replacement.
1591 * @param string $mailbox Mailbox name
1592 * @param string $mode Conversion direction ('in'|'out')
1594 * @return string Mailbox name
1596 private function mod_mailbox($mailbox, $mode = 'out')
1598 $delimiter = $_SESSION['imap_delimiter'];
1599 $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
1600 $mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1602 if ($mode == 'out') {
1603 $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
1604 if ($replace_delimiter && $replace_delimiter != $delimiter)
1605 $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
1608 $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
1609 if ($replace_delimiter && $replace_delimiter != $delimiter)
1610 $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);
1617 * List sieve scripts
1619 * @return array Scripts list
1621 public function list_scripts()
1623 if ($this->list !== null) {
1627 $this->list = $this->sieve->get_scripts();
1629 // Handle active script(s) and list of scripts according to Kolab's KEP:14
1630 if ($this->rc->config->get('managesieve_kolab_master')) {
1632 // Skip protected names
1633 foreach ((array)$this->list as $idx => $name) {
1634 $_name = strtoupper($name);
1635 if ($_name == 'MASTER')
1636 $master_script = $name;
1637 else if ($_name == 'MANAGEMENT')
1638 $management_script = $name;
1639 else if($_name == 'USER')
1640 $user_script = $name;
1644 unset($this->list[$idx]);
1647 // get active script(s), read USER script
1649 $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1650 $filename_regex = '/'.preg_quote($extension, '/').'$/';
1651 $_SESSION['managesieve_user_script'] = $user_script;
1653 $this->sieve->load($user_script);
1655 foreach ($this->sieve->script->as_array() as $rules) {
1656 foreach ($rules['actions'] as $action) {
1657 if ($action['type'] == 'include' && empty($action['global'])) {
1658 $name = preg_replace($filename_regex, '', $action['target']);
1659 $this->active[] = $name;
1664 // create USER script if it doesn't exist
1666 $content = "# USER Management Script\n"
1668 ."# This script includes the various active sieve scripts\n"
1669 ."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n"
1671 ."# For more information, see http://wiki.kolab.org/KEP:14#USER\n"
1673 if ($this->sieve->save_script('USER', $content)) {
1674 $_SESSION['managesieve_user_script'] = 'USER';
1675 if (empty($this->master_file))
1676 $this->sieve->activate('USER');
1680 else if (!empty($this->list)) {
1681 // Get active script name
1682 if ($active = $this->sieve->get_active()) {
1683 $this->active = array($active);
1691 * Removes sieve script
1693 * @param string $name Script name
1695 * @return bool True on success, False on failure
1697 public function remove_script($name)
1699 $result = $this->sieve->remove($name);
1702 if ($result && $this->rc->config->get('managesieve_kolab_master')) {
1703 $this->deactivate_script($name);
1710 * Activates sieve script
1712 * @param string $name Script name
1714 * @return bool True on success, False on failure
1716 public function activate_script($name)
1719 if ($this->rc->config->get('managesieve_kolab_master')) {
1720 $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1721 $user_script = $_SESSION['managesieve_user_script'];
1723 // if the script is not active...
1724 if ($user_script && ($key = array_search($name, $this->active)) === false) {
1725 // ...rewrite USER file adding appropriate include command
1726 if ($this->sieve->load($user_script)) {
1727 $script = $this->sieve->script->as_array();
1729 $regexp = '/' . preg_quote($extension, '/') . '$/';
1731 // Create new include entry
1735 'target' => $name.$extension,
1736 'type' => 'include',
1740 // get all active scripts for sorting
1741 foreach ($script as $rid => $rules) {
1742 foreach ($rules['actions'] as $aid => $action) {
1743 if ($action['type'] == 'include' && empty($action['global'])) {
1744 $target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target'];
1751 // Sort and find current script position
1752 asort($list, SORT_LOCALE_STRING);
1753 $list = array_values($list);
1754 $index = array_search($name, $list);
1756 // add rule at the end of the script
1757 if ($index === false || $index == count($list)-1) {
1758 $this->sieve->script->add_rule($rule);
1760 // add rule at index position
1763 foreach ($script as $rid => $rules) {
1764 if ($rid == $index) {
1767 $script2[] = $rules;
1769 $this->sieve->script->content = $script2;
1772 $result = $this->sieve->save();
1774 $this->active[] = $name;
1780 $result = $this->sieve->activate($name);
1782 $this->active = array($name);
1789 * Deactivates sieve script
1791 * @param string $name Script name
1793 * @return bool True on success, False on failure
1795 public function deactivate_script($name)
1798 if ($this->rc->config->get('managesieve_kolab_master')) {
1799 $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1800 $user_script = $_SESSION['managesieve_user_script'];
1802 // if the script is active...
1803 if ($user_script && ($key = array_search($name, $this->active)) !== false) {
1804 // ...rewrite USER file removing appropriate include command
1805 if ($this->sieve->load($user_script)) {
1806 $script = $this->sieve->script->as_array();
1807 $name = $name.$extension;
1809 foreach ($script as $rid => $rules) {
1810 foreach ($rules['actions'] as $aid => $action) {
1811 if ($action['type'] == 'include' && empty($action['global'])
1812 && $action['target'] == $name
1820 if ($rid < count($script)) {
1821 $this->sieve->script->delete_rule($rid);
1822 $result = $this->sieve->save();
1824 unset($this->active[$key]);
1831 $result = $this->sieve->deactivate();
1833 $this->active = array();
1840 * Saves current script (adding some variables)
1842 public function save_script($name = null)
1845 if ($this->rc->config->get('managesieve_kolab_master')) {
1846 $this->sieve->script->set_var('EDITOR', self::PROGNAME);
1847 $this->sieve->script->set_var('EDITOR_VERSION', self::VERSION);
1850 return $this->sieve->save($name);
1854 * Returns list of rules from the current script
1856 * @return array List of rules
1858 public function list_rules()
1863 foreach ($this->script as $idx => $filter) {
1864 if ($filter['type'] != 'if') {
1867 $fname = $filter['name'] ? $filter['name'] : "#$i";
1870 'name' => Q($fname),
1871 'class' => $filter['disabled'] ? 'disabled' : '',