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
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License version 2
19 * as published by the Free Software Foundation.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
26 * You should have received a copy of the GNU General Public License along
27 * with this program; if not, write to the Free Software Foundation, Inc.,
28 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 * $Id: managesieve.php 4983 2011-07-28 07:31:16Z alec $
33 class managesieve extends rcube_plugin
35 public $task = 'settings';
41 private $tips = array();
42 private $script = array();
43 private $exts = array();
44 private $headers = array(
45 'subject' => 'Subject',
53 // add Tab label/title
54 $this->add_texts('localization/', array('filters','managefilters'));
57 $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
58 $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
60 // include main js script
61 $this->include_script('managesieve.js');
64 function managesieve_start()
66 $this->rc = rcmail::get_instance();
69 // register UI objects
70 $this->rc->output->add_handlers(array(
71 'filterslist' => array($this, 'filters_list'),
72 'filtersetslist' => array($this, 'filtersets_list'),
73 'filterframe' => array($this, 'filter_frame'),
74 'filterform' => array($this, 'filter_form'),
75 'filtersetform' => array($this, 'filterset_form'),
78 // Add include path for internal classes
79 $include_path = $this->home . '/lib' . PATH_SEPARATOR;
80 $include_path .= ini_get('include_path');
81 set_include_path($include_path);
83 $host = rcube_parse_host($this->rc->config->get('managesieve_host', 'localhost'));
84 $port = $this->rc->config->get('managesieve_port', 2000);
86 $host = rcube_idn_to_ascii($host);
88 // try to connect to managesieve server and to fetch the script
89 $this->sieve = new rcube_sieve($_SESSION['username'],
90 $this->rc->decrypt($_SESSION['password']), $host, $port,
91 $this->rc->config->get('managesieve_auth_type'),
92 $this->rc->config->get('managesieve_usetls', false),
93 $this->rc->config->get('managesieve_disabled_extensions'),
94 $this->rc->config->get('managesieve_debug', false),
95 $this->rc->config->get('managesieve_auth_cid'),
96 $this->rc->config->get('managesieve_auth_pw')
99 if (!($error = $this->sieve->error())) {
101 $list = $this->sieve->get_scripts();
102 $active = $this->sieve->get_active();
103 $_SESSION['managesieve_active'] = $active;
105 if (!empty($_GET['_set'])) {
106 $script_name = get_input_value('_set', RCUBE_INPUT_GET);
108 else if (!empty($_SESSION['managesieve_current'])) {
109 $script_name = $_SESSION['managesieve_current'];
114 $script_name = $active;
117 $script_name = $list[0];
119 // create a new (initial) script
121 // if script not exists build default script contents
122 $script_file = $this->rc->config->get('managesieve_default');
123 $script_name = 'roundcube';
124 if ($script_file && is_readable($script_file))
125 $content = file_get_contents($script_file);
127 // add script and set it active
128 if ($this->sieve->save_script($script_name, $content))
129 if ($this->sieve->activate($script_name))
130 $_SESSION['managesieve_active'] = $script_name;
135 $this->sieve->load($script_name);
137 $error = $this->sieve->error();
140 // finally set script objects
143 case SIEVE_ERROR_CONNECTION:
144 case SIEVE_ERROR_LOGIN:
145 $this->rc->output->show_message('managesieve.filterconnerror', 'error');
148 $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
152 raise_error(array('code' => 403, 'type' => 'php',
153 'file' => __FILE__, 'line' => __LINE__,
154 'message' => "Unable to connect to managesieve on $host:$port"), true, false);
156 // to disable 'Add filter' button set env variable
157 $this->rc->output->set_env('filterconnerror', true);
158 $this->script = array();
161 $this->script = $this->sieve->script->as_array();
162 $this->exts = $this->sieve->get_extensions();
163 $this->rc->output->set_env('active_set', $_SESSION['managesieve_active']);
164 $_SESSION['managesieve_current'] = $this->sieve->current;
170 function managesieve_actions()
172 // Init plugin and handle managesieve connection
173 $error = $this->managesieve_start();
175 // Handle user requests
176 if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
177 $fid = (int) get_input_value('_fid', RCUBE_INPUT_GET);
179 if ($action == 'up' && !$error) {
180 if ($fid && isset($this->script[$fid]) && isset($this->script[$fid-1])) {
181 if ($this->sieve->script->update_rule($fid, $this->script[$fid-1]) !== false
182 && $this->sieve->script->update_rule($fid-1, $this->script[$fid]) !== false) {
183 $result = $this->sieve->save();
187 // $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
188 $this->rc->output->command('managesieve_updatelist', 'up', '', $fid);
190 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
193 else if ($action == 'down' && !$error) {
194 if (isset($this->script[$fid]) && isset($this->script[$fid+1])) {
195 if ($this->sieve->script->update_rule($fid, $this->script[$fid+1]) !== false
196 && $this->sieve->script->update_rule($fid+1, $this->script[$fid]) !== false) {
197 $result = $this->sieve->save();
200 if ($result === true) {
201 // $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
202 $this->rc->output->command('managesieve_updatelist', 'down', '', $fid);
204 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
208 else if ($action == 'delete' && !$error) {
209 if (isset($this->script[$fid])) {
210 if ($this->sieve->script->delete_rule($fid))
211 $result = $this->sieve->save();
213 if ($result === true) {
214 $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
215 $this->rc->output->command('managesieve_updatelist', 'delete', '', $fid);
217 $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
221 else if ($action == 'setact' && !$error) {
222 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
223 $result = $this->sieve->activate($script_name);
225 if ($result === true) {
226 $this->rc->output->set_env('active_set', $script_name);
227 $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
228 $this->rc->output->command('managesieve_reset');
229 $_SESSION['managesieve_active'] = $script_name;
231 $this->rc->output->show_message('managesieve.setactivateerror', 'error');
234 else if ($action == 'deact' && !$error) {
235 $result = $this->sieve->deactivate();
237 if ($result === true) {
238 $this->rc->output->set_env('active_set', '');
239 $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
240 $this->rc->output->command('managesieve_reset');
241 $_SESSION['managesieve_active'] = '';
243 $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
246 else if ($action == 'setdel' && !$error) {
247 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
248 $result = $this->sieve->remove($script_name);
250 if ($result === true) {
251 $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
252 $this->rc->output->command('managesieve_reload');
253 $this->rc->session->remove('managesieve_current');
255 $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
258 else if ($action == 'setget') {
259 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
260 $script = $this->sieve->get_script($script_name);
262 if (PEAR::isError($script))
265 $browser = new rcube_browser;
267 // send download headers
268 header("Content-Type: application/octet-stream");
269 header("Content-Length: ".strlen($script));
272 header("Content-Type: application/force-download");
273 if ($browser->ie && $browser->ver < 7)
274 $filename = rawurlencode(abbreviate_string($script_name, 55));
275 else if ($browser->ie)
276 $filename = rawurlencode($script_name);
278 $filename = addcslashes($script_name, '\\"');
280 header("Content-Disposition: attachment; filename=\"$filename.txt\"");
284 elseif ($action == 'ruleadd') {
285 $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
286 $id = $this->genid();
287 $content = $this->rule_div($fid, $id, false);
289 $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
291 elseif ($action == 'actionadd') {
292 $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
293 $id = $this->genid();
294 $content = $this->action_div($fid, $id, false);
296 $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
299 $this->rc->output->send();
302 $this->managesieve_send();
305 function managesieve_save()
307 // Init plugin and handle managesieve connection
308 $error = $this->managesieve_start();
310 // filters set add action
311 if (!empty($_POST['_newset'])) {
312 $name = get_input_value('_name', RCUBE_INPUT_POST);
313 $copy = get_input_value('_copy', RCUBE_INPUT_POST);
314 $from = get_input_value('_from', RCUBE_INPUT_POST);
317 $error = 'managesieve.emptyname';
318 else if (mb_strlen($name)>128)
319 $error = 'managesieve.nametoolong';
320 else if ($from == 'file') {
322 if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
323 $file = file_get_contents($_FILES['_file']['tmp_name']);
324 $file = preg_replace('/\r/', '', $file);
325 // for security don't save script directly
326 // check syntax before, like this...
327 $this->sieve->load_script($file);
328 if (!$this->sieve->save($name)) {
329 $error = 'managesieve.setcreateerror';
332 else { // upload failed
333 $err = $_FILES['_file']['error'];
336 if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
337 $msg = rcube_label(array('name' => 'filesizeerror',
338 'vars' => array('size' =>
339 show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
342 $error = 'fileuploaderror';
346 else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
347 $error = 'managesieve.setcreateerror';
351 $this->rc->output->show_message('managesieve.setcreated', 'confirmation');
352 $this->rc->output->command('parent.managesieve_reload', $name);
354 $this->rc->output->command('display_message', $msg, 'error');
356 $this->rc->output->show_message($error, 'error');
359 // filter add/edit action
360 else if (isset($_POST['_name'])) {
361 $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
362 $fid = trim(get_input_value('_fid', RCUBE_INPUT_POST));
363 $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
366 $headers = $_POST['_header'];
367 $cust_headers = $_POST['_custom_header'];
368 $ops = $_POST['_rule_op'];
369 $sizeops = $_POST['_rule_size_op'];
370 $sizeitems = $_POST['_rule_size_item'];
371 $sizetargets = $_POST['_rule_size_target'];
372 $targets = $_POST['_rule_target'];
373 $act_types = $_POST['_action_type'];
374 $mailboxes = $_POST['_action_mailbox'];
375 $act_targets = $_POST['_action_target'];
376 $area_targets = $_POST['_action_target_area'];
377 $reasons = $_POST['_action_reason'];
378 $addresses = $_POST['_action_addresses'];
379 $days = $_POST['_action_days'];
380 $subject = $_POST['_action_subject'];
381 $flags = $_POST['_action_flags'];
383 // we need a "hack" for radiobuttons
384 foreach ($sizeitems as $item)
387 $this->form['disabled'] = $_POST['_disabled'] ? true : false;
388 $this->form['join'] = $join=='allof' ? true : false;
389 $this->form['name'] = $name;
390 $this->form['tests'] = array();
391 $this->form['actions'] = array();
394 $this->errors['name'] = $this->gettext('cannotbeempty');
396 foreach($this->script as $idx => $rule)
397 if($rule['name'] == $name && $idx != $fid) {
398 $this->errors['name'] = $this->gettext('ruleexist');
405 if ($join == 'any') {
406 $this->form['tests'][0]['test'] = 'true';
409 foreach ($headers as $idx => $header) {
410 $header = $this->strip_value($header);
411 $target = $this->strip_value($targets[$idx], true);
412 $op = $this->strip_value($ops[$idx]);
415 if (in_array($header, $this->headers)) {
416 if (preg_match('/^not/', $op))
417 $this->form['tests'][$i]['not'] = true;
418 $type = preg_replace('/^not/', '', $op);
420 if ($type == 'exists') {
421 $this->form['tests'][$i]['test'] = 'exists';
422 $this->form['tests'][$i]['arg'] = $header;
425 $this->form['tests'][$i]['type'] = $type;
426 $this->form['tests'][$i]['test'] = 'header';
427 $this->form['tests'][$i]['arg1'] = $header;
428 $this->form['tests'][$i]['arg2'] = $target;
431 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
432 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
433 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
439 $sizeop = $this->strip_value($sizeops[$idx]);
440 $sizeitem = $this->strip_value($items[$idx]);
441 $sizetarget = $this->strip_value($sizetargets[$idx]);
443 $this->form['tests'][$i]['test'] = 'size';
444 $this->form['tests'][$i]['type'] = $sizeop;
445 $this->form['tests'][$i]['arg'] = $sizetarget.$sizeitem;
447 if ($sizetarget == '')
448 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
449 else if (!preg_match('/^[0-9]+(K|M|G)*$/i', $sizetarget))
450 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
453 $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
455 if (preg_match('/^not/', $op))
456 $this->form['tests'][$i]['not'] = true;
457 $type = preg_replace('/^not/', '', $op);
459 if ($cust_header == '')
460 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
462 $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
464 if (!count($headers))
465 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
467 foreach ($headers as $hr)
468 if (!preg_match('/^[a-z0-9-]+$/i', $hr))
469 $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
473 if (empty($this->errors['tests'][$i]['header']))
474 $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
476 if ($type == 'exists') {
477 $this->form['tests'][$i]['test'] = 'exists';
478 $this->form['tests'][$i]['arg'] = $cust_header;
481 $this->form['tests'][$i]['test'] = 'header';
482 $this->form['tests'][$i]['type'] = $type;
483 $this->form['tests'][$i]['arg1'] = $cust_header;
484 $this->form['tests'][$i]['arg2'] = $target;
487 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
488 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
489 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
499 foreach($act_types as $idx => $type) {
500 $type = $this->strip_value($type);
501 $target = $this->strip_value($act_targets[$idx]);
506 case 'fileinto_copy':
507 $mailbox = $this->strip_value($mailboxes[$idx]);
508 $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
509 if ($type == 'fileinto_copy') {
511 $this->form['actions'][$i]['copy'] = true;
517 $target = $this->strip_value($area_targets[$idx]);
518 $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
520 // if ($target == '')
521 // $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
525 case 'redirect_copy':
526 $this->form['actions'][$i]['target'] = $target;
528 if ($this->form['actions'][$i]['target'] == '')
529 $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
530 else if (!check_email($this->form['actions'][$i]['target']))
531 $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
533 if ($type == 'redirect_copy') {
535 $this->form['actions'][$i]['copy'] = true;
543 if (empty($flags[$idx])) {
544 $this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
547 foreach ($flags[$idx] as $flag) {
548 $_target[] = $this->strip_value($flag);
551 $this->form['actions'][$i]['target'] = $_target;
555 $reason = $this->strip_value($reasons[$idx]);
556 $this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason);
557 $this->form['actions'][$i]['days'] = $days[$idx];
558 $this->form['actions'][$i]['subject'] = $subject[$idx];
559 $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
560 // @TODO: vacation :mime, :from, :handle
562 if ($this->form['actions'][$i]['addresses']) {
563 foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
564 $address = trim($address);
566 unset($this->form['actions'][$i]['addresses'][$aidx]);
567 else if(!check_email($address)) {
568 $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
571 $this->form['actions'][$i]['addresses'][$aidx] = $address;
575 if ($this->form['actions'][$i]['reason'] == '')
576 $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
577 if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
578 $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
582 $this->form['actions'][$i]['type'] = $type;
586 if (!$this->errors) {
588 if (!isset($this->script[$fid])) {
589 $fid = $this->sieve->script->add_rule($this->form);
592 $fid = $this->sieve->script->update_rule($fid, $this->form);
595 $save = $this->sieve->save();
597 if ($save && $fid !== false) {
598 $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
599 $this->rc->output->add_script(
600 sprintf("rcmail.managesieve_updatelist('%s', '%s', %d, %d);",
601 isset($new) ? 'add' : 'update', Q($this->form['name']),
602 $fid, $this->form['disabled']),
606 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
607 // $this->rc->output->send();
612 $this->managesieve_send();
615 private function managesieve_send()
617 // Handle form action
618 if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
619 if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
620 $this->rc->output->send('managesieve.setedit');
623 $this->rc->output->send('managesieve.filteredit');
626 $this->rc->output->set_pagetitle($this->gettext('filters'));
627 $this->rc->output->send('managesieve.managesieve');
631 // return the filters list as HTML table
632 function filters_list($attrib)
634 // add id to message list table if not specified
635 if (!strlen($attrib['id']))
636 $attrib['id'] = 'rcmfilterslist';
638 // define list of cols to be displayed
639 $a_show_cols = array('managesieve.filtername');
641 foreach($this->script as $idx => $filter)
643 'managesieve.filtername' => $filter['name'],
645 'class' => $filter['disabled'] ? 'disabled' : '',
648 // create XHTML table
649 $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
652 $this->rc->output->add_gui_object('filterslist', $attrib['id']);
653 $this->rc->output->include_script('list.js');
655 // add some labels to client
656 $this->rc->output->add_label('managesieve.filterdeleteconfirm');
661 // return the filters list as <SELECT>
662 function filtersets_list($attrib)
664 // add id to message list table if not specified
665 if (!strlen($attrib['id']))
666 $attrib['id'] = 'rcmfiltersetslist';
668 $list = $this->sieve->get_scripts();
669 $active = $this->sieve->get_active();
671 $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
672 'onchange' => 'rcmail.managesieve_set()'));
675 asort($list, SORT_LOCALE_STRING);
677 foreach ($list as $set)
678 $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
681 $out = $select->show($this->sieve->current);
684 $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
685 $this->rc->output->add_label(
686 'managesieve.setdeleteconfirm',
687 'managesieve.active',
688 'managesieve.filtersetact',
689 'managesieve.filtersetdeact'
695 function filter_frame($attrib)
698 $attrib['id'] = 'rcmfilterframe';
700 $attrib['name'] = $attrib['id'];
702 $this->rc->output->set_env('contentframe', $attrib['name']);
703 $this->rc->output->set_env('blankpage', $attrib['src'] ?
704 $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
706 return html::tag('iframe', $attrib);
709 function filterset_form($attrib)
712 $attrib['id'] = 'rcmfiltersetform';
714 $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
716 $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
717 $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
718 $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
719 $hiddenfields->add(array('name' => '_newset', 'value' => 1));
721 $out .= $hiddenfields->show();
723 $name = get_input_value('_name', RCUBE_INPUT_POST);
724 $copy = get_input_value('_copy', RCUBE_INPUT_POST);
725 $selected = get_input_value('_from', RCUBE_INPUT_POST);
727 // filter set name input
728 $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
729 'class' => ($this->errors['name'] ? 'error' : '')));
731 $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
732 '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
734 $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
735 $out .= '<input type="radio" id="from_none" name="_from" value="none"'
736 .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
737 $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
740 $list = $this->sieve->get_scripts();
741 $active = $this->sieve->get_active();
743 $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
745 if (is_array($list)) {
746 asort($list, SORT_LOCALE_STRING);
748 foreach ($list as $set)
749 $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
751 $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
752 .($selected=='set' ? ' checked="checked"' : '').'></input>';
753 $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
754 $out .= $select->show($copy);
758 $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
759 'type' => 'file', 'class' => ($this->errors['name'] ? 'error' : '')));
761 $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
762 .($selected=='file' ? ' checked="checked"' : '').'></input>';
763 $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
764 $out .= $upload->show();
765 $out .= '</fieldset>';
767 $this->rc->output->add_gui_object('sieveform', 'filtersetform');
773 function filter_form($attrib)
776 $attrib['id'] = 'rcmfilterform';
778 $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
779 $scr = isset($this->form) ? $this->form : $this->script[$fid];
781 $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
782 $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
783 $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
784 $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
786 $out = '<form name="filterform" action="./" method="post">'."\n";
787 $out .= $hiddenfields->show();
790 if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
795 $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
796 'class' => ($this->errors['name'] ? 'error' : '')));
798 if ($this->errors['name'])
799 $this->add_tip($field_id, $this->errors['name'], true);
802 $input_name = $input_name->show($scr['name']);
804 $input_name = $input_name->show();
806 $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s<br /><br />\n",
807 $field_id, Q($this->gettext('filtername')), $input_name);
809 $out .= '<fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
811 // any, allof, anyof radio buttons
812 $field_id = '_allof';
813 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
814 'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
816 if (isset($scr) && !$any)
817 $input_join = $input_join->show($scr['join'] ? 'allof' : '');
819 $input_join = $input_join->show();
821 $out .= sprintf("%s<label for=\"%s\">%s</label> \n",
822 $input_join, $field_id, Q($this->gettext('filterallof')));
824 $field_id = '_anyof';
825 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
826 'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
828 if (isset($scr) && !$any)
829 $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
831 $input_join = $input_join->show('anyof'); // default
833 $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
834 $input_join, $field_id, Q($this->gettext('filteranyof')));
837 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
838 'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
840 $input_join = $input_join->show($any ? 'any' : '');
842 $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
843 $input_join, $field_id, Q($this->gettext('filterany')));
845 $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
847 $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
848 for ($x=0; $x<$rows_num; $x++)
849 $out .= $this->rule_div($fid, $x);
852 $out .= "</fieldset>\n";
855 $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
857 $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
859 $out .= '<div id="actions">';
860 for ($x=0; $x<$rows_num; $x++)
861 $out .= $this->action_div($fid, $x);
864 $out .= "</fieldset>\n";
868 if ($scr['disabled']) {
869 $this->rc->output->set_env('rule_disabled', true);
871 $this->rc->output->add_label(
872 'managesieve.ruledeleteconfirm',
873 'managesieve.actiondeleteconfirm'
875 $this->rc->output->add_gui_object('sieveform', 'filterform');
880 function rule_div($fid, $id, $div=true)
882 $rule = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
883 $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
885 $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
887 $out .= '<table><tr><td class="rowactions">';
890 $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
891 'onchange' => 'rule_header_select(' .$id .')'));
892 foreach($this->headers as $name => $val)
893 $select_header->add(Q($this->gettext($name)), Q($val));
894 $select_header->add(Q($this->gettext('size')), 'size');
895 $select_header->add(Q($this->gettext('...')), '...');
897 // TODO: list arguments
899 if ((isset($rule['test']) && $rule['test'] == 'header')
900 && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers))
901 $out .= $select_header->show($rule['arg1']);
902 else if ((isset($rule['test']) && $rule['test'] == 'exists')
903 && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers))
904 $out .= $select_header->show($rule['arg']);
905 else if (isset($rule['test']) && $rule['test'] == 'size')
906 $out .= $select_header->show('size');
907 else if (isset($rule['test']) && $rule['test'] != 'true')
908 $out .= $select_header->show('...');
910 $out .= $select_header->show();
912 $out .= '</td><td class="rowtargets">';
914 if ((isset($rule['test']) && $rule['test'] == 'header')
915 && (is_array($rule['arg1']) || !in_array($rule['arg1'], $this->headers)))
916 $custom = is_array($rule['arg1']) ? implode(', ', $rule['arg1']) : $rule['arg1'];
917 else if ((isset($rule['test']) && $rule['test'] == 'exists')
918 && (is_array($rule['arg']) || !in_array($rule['arg'], $this->headers)))
919 $custom = is_array($rule['arg']) ? implode(', ', $rule['arg']) : $rule['arg'];
921 $out .= '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
922 <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
923 . $this->error_class($id, 'test', 'header', 'custom_header_i')
924 .' value="' .Q($custom). '" size="20" /> </div>' . "\n";
926 // matching type select (operator)
927 $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
928 'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
929 'onchange' => 'rule_op_select('.$id.')'));
930 $select_op->add(Q($this->gettext('filtercontains')), 'contains');
931 $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
932 $select_op->add(Q($this->gettext('filteris')), 'is');
933 $select_op->add(Q($this->gettext('filterisnot')), 'notis');
934 $select_op->add(Q($this->gettext('filterexists')), 'exists');
935 $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
936 $select_op->add(Q($this->gettext('filtermatches')), 'matches');
937 $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
938 if (in_array('regex', $this->exts)) {
939 $select_op->add(Q($this->gettext('filterregex')), 'regex');
940 $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
942 if (in_array('relational', $this->exts)) {
943 $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
944 $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
945 $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
946 $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
947 $select_op->add(Q($this->gettext('countequals')), 'count-eq');
948 $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
949 $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
950 $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
951 $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
952 $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
953 $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
954 $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
957 // target input (TODO: lists)
959 if ($rule['test'] == 'header') {
960 $out .= $select_op->show(($rule['not'] ? 'not' : '').$rule['type']);
961 $target = $rule['arg2'];
963 else if ($rule['test'] == 'size') {
964 $out .= $select_op->show();
965 if (preg_match('/^([0-9]+)(K|M|G)*$/', $rule['arg'], $matches)) {
966 $sizetarget = $matches[1];
967 $sizeitem = $matches[2];
971 $out .= $select_op->show(($rule['not'] ? 'not' : '').$rule['test']);
975 $out .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
976 value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
977 . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
979 $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
980 $select_size_op->add(Q($this->gettext('filterunder')), 'under');
981 $select_size_op->add(Q($this->gettext('filterover')), 'over');
983 $out .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
984 $out .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
985 $out .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" '
986 . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
987 <input type="radio" name="_rule_size_item['.$id.']" value=""'
988 . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
989 <input type="radio" name="_rule_size_item['.$id.']" value="K"'
990 . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
991 <input type="radio" name="_rule_size_item['.$id.']" value="M"'
992 . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
993 <input type="radio" name="_rule_size_item['.$id.']" value="G"'
994 . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
999 $out .= '<td class="rowbuttons">';
1000 $out .= '<input type="button" id="ruleadd' . $id .'" value="'. Q($this->gettext('add')). '"
1001 onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button" /> ';
1002 $out .= '<input type="button" id="ruledel' . $id .'" value="'. Q($this->gettext('del')). '"
1003 onclick="rcmail.managesieve_ruledel(' . $id .')" class="button' . ($rows_num<2 ? ' disabled' : '') .'"'
1004 . ($rows_num<2 ? ' disabled="disabled"' : '') .' />';
1005 $out .= '</td></tr></table>';
1007 $out .= $div ? "</div>\n" : '';
1012 function action_div($fid, $id, $div=true)
1014 $action = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
1015 $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
1017 $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
1019 $out .= '<table><tr><td class="rowactions">';
1022 $select_action = new html_select(array('name' => "_action_type[]", 'id' => 'action_type'.$id,
1023 'onchange' => 'action_type_select(' .$id .')'));
1024 if (in_array('fileinto', $this->exts))
1025 $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
1026 if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
1027 $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
1028 $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
1029 if (in_array('copy', $this->exts))
1030 $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
1031 if (in_array('reject', $this->exts))
1032 $select_action->add(Q($this->gettext('messagediscard')), 'reject');
1033 else if (in_array('ereject', $this->exts))
1034 $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
1035 if (in_array('vacation', $this->exts))
1036 $select_action->add(Q($this->gettext('messagereply')), 'vacation');
1037 $select_action->add(Q($this->gettext('messagedelete')), 'discard');
1038 if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
1039 $select_action->add(Q($this->gettext('setflags')), 'setflag');
1040 $select_action->add(Q($this->gettext('addflags')), 'addflag');
1041 $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
1043 $select_action->add(Q($this->gettext('rulestop')), 'stop');
1045 $select_type = $action['type'];
1046 if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
1047 $select_type .= '_copy';
1050 $out .= $select_action->show($select_type);
1053 // actions target inputs
1054 $out .= '<td class="rowtargets">';
1056 $out .= '<input type="text" name="_action_target[]" id="action_target' .$id. '" '
1057 .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="40" '
1058 .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1059 . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1060 $out .= '<textarea name="_action_target_area[]" id="action_target_area' .$id. '" '
1061 .'rows="3" cols="40" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1062 .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1063 . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1067 $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1068 $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1069 .'<textarea name="_action_reason[]" id="action_reason' .$id. '" '
1070 .'rows="3" cols="45" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1071 . Q($action['reason'], 'strict', false) . "</textarea>\n";
1072 $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
1073 .'<input type="text" name="_action_subject[]" id="action_subject'.$id.'" '
1074 .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="50" '
1075 . $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
1076 $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1077 .'<input type="text" name="_action_addresses[]" id="action_addr'.$id.'" '
1078 .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="50" '
1079 . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1080 $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1081 .'<input type="text" name="_action_days[]" id="action_days'.$id.'" '
1082 .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1083 . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1089 'answered' => '\\Answered',
1090 'flagged' => '\\Flagged',
1091 'deleted' => '\\Deleted',
1092 'draft' => '\\Draft',
1094 $flags_target = (array)$action['target'];
1096 $out .= '<div id="action_flags' .$id.'" style="display:'
1097 . (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
1098 . $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
1099 foreach ($flags as $fidx => $flag) {
1100 $out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
1101 . (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
1102 . Q($this->gettext('flag'.$fidx)) .'<br>';
1107 if ($action['type'] == 'fileinto')
1108 $mailbox = $this->mod_mailbox($action['target'], 'out');
1112 $this->rc->imap_connect();
1113 $select = rcmail_mailbox_select(array(
1114 'realnames' => false,
1116 'id' => 'action_mailbox' . $id,
1117 'name' => '_action_mailbox[]',
1118 'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
1120 $out .= $select->show($mailbox);
1124 $out .= '<td class="rowbuttons">';
1125 $out .= '<input type="button" id="actionadd' . $id .'" value="'. Q($this->gettext('add')). '"
1126 onclick="rcmail.managesieve_actionadd(' . $id .')" class="button" /> ';
1127 $out .= '<input type="button" id="actiondel' . $id .'" value="'. Q($this->gettext('del')). '"
1128 onclick="rcmail.managesieve_actiondel(' . $id .')" class="button' . ($rows_num<2 ? ' disabled' : '') .'"'
1129 . ($rows_num<2 ? ' disabled="disabled"' : '') .' />';
1132 $out .= '</tr></table>';
1134 $out .= $div ? "</div>\n" : '';
1139 private function genid()
1141 $result = intval(rcube_timer());
1145 private function strip_value($str, $allow_html=false)
1148 $str = strip_tags($str);
1153 private function error_class($id, $type, $target, $elem_prefix='')
1156 if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1157 ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1159 $this->add_tip($elem_prefix.$id, $str, true);
1160 return ' class="error"';
1166 private function add_tip($id, $str, $error=false)
1169 $str = html::span('sieve error', $str);
1171 $this->tips[] = array($id, $str);
1174 private function print_tips()
1176 if (empty($this->tips))
1179 $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1180 $this->rc->output->add_script($script, 'foot');
1184 * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
1185 * with delimiter replacement.
1187 * @param string $mailbox Mailbox name
1188 * @param string $mode Conversion direction ('in'|'out')
1190 * @return string Mailbox name
1192 private function mod_mailbox($mailbox, $mode = 'out')
1194 $delimiter = $_SESSION['imap_delimiter'];
1195 $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
1196 $mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1198 if ($mode == 'out') {
1199 $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
1200 if ($replace_delimiter && $replace_delimiter != $delimiter)
1201 $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
1204 $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
1205 if ($replace_delimiter && $replace_delimiter != $delimiter)
1206 $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);