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 'A.L.E.C' Machniak <alec@alec.pl>
13 * Configuration (see config.inc.php.dist)
15 * $Id: managesieve.php 4555 2011-02-16 10:48:11Z alec $
18 class managesieve extends rcube_plugin
20 public $task = 'settings';
26 private $tips = array();
27 private $script = array();
28 private $exts = array();
29 private $headers = array(
30 'subject' => 'Subject',
38 // add Tab label/title
39 $this->add_texts('localization/', array('filters','managefilters'));
42 $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
43 $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
45 // include main js script
46 $this->include_script('managesieve.js');
49 function managesieve_start()
51 $this->rc = rcmail::get_instance();
54 // register UI objects
55 $this->rc->output->add_handlers(array(
56 'filterslist' => array($this, 'filters_list'),
57 'filtersetslist' => array($this, 'filtersets_list'),
58 'filterframe' => array($this, 'filter_frame'),
59 'filterform' => array($this, 'filter_form'),
60 'filtersetform' => array($this, 'filterset_form'),
63 require_once($this->home . '/lib/Net/Sieve.php');
64 require_once($this->home . '/lib/rcube_sieve.php');
66 $host = rcube_parse_host($this->rc->config->get('managesieve_host', 'localhost'));
67 $port = $this->rc->config->get('managesieve_port', 2000);
69 $host = rcube_idn_to_ascii($host);
71 // try to connect to managesieve server and to fetch the script
72 $this->sieve = new rcube_sieve($_SESSION['username'],
73 $this->rc->decrypt($_SESSION['password']), $host, $port,
74 $this->rc->config->get('managesieve_auth_type'),
75 $this->rc->config->get('managesieve_usetls', false),
76 $this->rc->config->get('managesieve_disabled_extensions'),
77 $this->rc->config->get('managesieve_debug', false),
78 $this->rc->config->get('managesieve_auth_cid'),
79 $this->rc->config->get('managesieve_auth_pw')
82 if (!($error = $this->sieve->error())) {
84 $list = $this->sieve->get_scripts();
85 $active = $this->sieve->get_active();
86 $_SESSION['managesieve_active'] = $active;
88 if (!empty($_GET['_set'])) {
89 $script_name = get_input_value('_set', RCUBE_INPUT_GET);
91 else if (!empty($_SESSION['managesieve_current'])) {
92 $script_name = $_SESSION['managesieve_current'];
97 $script_name = $active;
100 $script_name = $list[0];
102 // create a new (initial) script
104 // if script not exists build default script contents
105 $script_file = $this->rc->config->get('managesieve_default');
106 $script_name = 'roundcube';
107 if ($script_file && is_readable($script_file))
108 $content = file_get_contents($script_file);
110 // add script and set it active
111 if ($this->sieve->save_script($script_name, $content))
112 if ($this->sieve->activate($script_name))
113 $_SESSION['managesieve_active'] = $script_name;
118 $this->sieve->load($script_name);
120 $error = $this->sieve->error();
123 // finally set script objects
126 case SIEVE_ERROR_CONNECTION:
127 case SIEVE_ERROR_LOGIN:
128 $this->rc->output->show_message('managesieve.filterconnerror', 'error');
131 $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
135 raise_error(array('code' => 403, 'type' => 'php',
136 'file' => __FILE__, 'line' => __LINE__,
137 'message' => "Unable to connect to managesieve on $host:$port"), true, false);
139 // to disable 'Add filter' button set env variable
140 $this->rc->output->set_env('filterconnerror', true);
141 $this->script = array();
144 $this->script = $this->sieve->script->as_array();
145 $this->exts = $this->sieve->get_extensions();
146 $this->rc->output->set_env('active_set', $_SESSION['managesieve_active']);
147 $_SESSION['managesieve_current'] = $this->sieve->current;
153 function managesieve_actions()
155 // Init plugin and handle managesieve connection
156 $error = $this->managesieve_start();
158 // Handle user requests
159 if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
160 $fid = (int) get_input_value('_fid', RCUBE_INPUT_GET);
162 if ($action == 'up' && !$error) {
163 if ($fid && isset($this->script[$fid]) && isset($this->script[$fid-1])) {
164 if ($this->sieve->script->update_rule($fid, $this->script[$fid-1]) !== false
165 && $this->sieve->script->update_rule($fid-1, $this->script[$fid]) !== false) {
166 $result = $this->sieve->save();
170 // $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
171 $this->rc->output->command('managesieve_updatelist', 'up', '', $fid);
173 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
176 else if ($action == 'down' && !$error) {
177 if (isset($this->script[$fid]) && isset($this->script[$fid+1])) {
178 if ($this->sieve->script->update_rule($fid, $this->script[$fid+1]) !== false
179 && $this->sieve->script->update_rule($fid+1, $this->script[$fid]) !== false) {
180 $result = $this->sieve->save();
183 if ($result === true) {
184 // $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
185 $this->rc->output->command('managesieve_updatelist', 'down', '', $fid);
187 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
191 else if ($action == 'delete' && !$error) {
192 if (isset($this->script[$fid])) {
193 if ($this->sieve->script->delete_rule($fid))
194 $result = $this->sieve->save();
196 if ($result === true) {
197 $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
198 $this->rc->output->command('managesieve_updatelist', 'delete', '', $fid);
200 $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
204 else if ($action == 'setact' && !$error) {
205 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
206 $result = $this->sieve->activate($script_name);
208 if ($result === true) {
209 $this->rc->output->set_env('active_set', $script_name);
210 $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
211 $this->rc->output->command('managesieve_reset');
212 $_SESSION['managesieve_active'] = $script_name;
214 $this->rc->output->show_message('managesieve.setactivateerror', 'error');
217 else if ($action == 'deact' && !$error) {
218 $result = $this->sieve->deactivate();
220 if ($result === true) {
221 $this->rc->output->set_env('active_set', '');
222 $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
223 $this->rc->output->command('managesieve_reset');
224 $_SESSION['managesieve_active'] = '';
226 $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
229 else if ($action == 'setdel' && !$error) {
230 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
231 $result = $this->sieve->remove($script_name);
233 if ($result === true) {
234 $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
235 $this->rc->output->command('managesieve_reload');
236 $this->rc->session->remove('managesieve_current');
238 $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
241 else if ($action == 'setget') {
242 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
243 $script = $this->sieve->get_script($script_name);
245 if (PEAR::isError($script))
248 $browser = new rcube_browser;
250 // send download headers
251 header("Content-Type: application/octet-stream");
252 header("Content-Length: ".strlen($script));
255 header("Content-Type: application/force-download");
256 if ($browser->ie && $browser->ver < 7)
257 $filename = rawurlencode(abbreviate_string($script_name, 55));
258 else if ($browser->ie)
259 $filename = rawurlencode($script_name);
261 $filename = addcslashes($script_name, '\\"');
263 header("Content-Disposition: attachment; filename=\"$filename.txt\"");
267 elseif ($action == 'ruleadd') {
268 $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
269 $id = $this->genid();
270 $content = $this->rule_div($fid, $id, false);
272 $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
274 elseif ($action == 'actionadd') {
275 $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
276 $id = $this->genid();
277 $content = $this->action_div($fid, $id, false);
279 $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
282 $this->rc->output->send();
285 $this->managesieve_send();
288 function managesieve_save()
290 // Init plugin and handle managesieve connection
291 $error = $this->managesieve_start();
293 // filters set add action
294 if (!empty($_POST['_newset'])) {
295 $name = get_input_value('_name', RCUBE_INPUT_POST);
296 $copy = get_input_value('_copy', RCUBE_INPUT_POST);
297 $from = get_input_value('_from', RCUBE_INPUT_POST);
300 $error = 'managesieve.emptyname';
301 else if (mb_strlen($name)>128)
302 $error = 'managesieve.nametoolong';
303 else if ($from == 'file') {
305 if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
306 $file = file_get_contents($_FILES['_file']['tmp_name']);
307 $file = preg_replace('/\r/', '', $file);
308 // for security don't save script directly
309 // check syntax before, like this...
310 $this->sieve->load_script($file);
311 if (!$this->sieve->save($name)) {
312 $error = 'managesieve.setcreateerror';
315 else { // upload failed
316 $err = $_FILES['_file']['error'];
319 if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
320 $msg = rcube_label(array('name' => 'filesizeerror',
321 'vars' => array('size' =>
322 show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
325 $error = 'fileuploaderror';
329 else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
330 $error = 'managesieve.setcreateerror';
334 $this->rc->output->show_message('managesieve.setcreated', 'confirmation');
335 $this->rc->output->command('parent.managesieve_reload', $name);
337 $this->rc->output->command('display_message', $msg, 'error');
339 $this->rc->output->show_message($error, 'error');
342 // filter add/edit action
343 else if (isset($_POST['_name'])) {
344 $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
345 $fid = trim(get_input_value('_fid', RCUBE_INPUT_POST));
346 $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
349 $headers = $_POST['_header'];
350 $cust_headers = $_POST['_custom_header'];
351 $ops = $_POST['_rule_op'];
352 $sizeops = $_POST['_rule_size_op'];
353 $sizeitems = $_POST['_rule_size_item'];
354 $sizetargets = $_POST['_rule_size_target'];
355 $targets = $_POST['_rule_target'];
356 $act_types = $_POST['_action_type'];
357 $mailboxes = $_POST['_action_mailbox'];
358 $act_targets = $_POST['_action_target'];
359 $area_targets = $_POST['_action_target_area'];
360 $reasons = $_POST['_action_reason'];
361 $addresses = $_POST['_action_addresses'];
362 $days = $_POST['_action_days'];
364 // we need a "hack" for radiobuttons
365 foreach ($sizeitems as $item)
368 $this->form['disabled'] = $_POST['_disabled'] ? true : false;
369 $this->form['join'] = $join=='allof' ? true : false;
370 $this->form['name'] = $name;
371 $this->form['tests'] = array();
372 $this->form['actions'] = array();
375 $this->errors['name'] = $this->gettext('cannotbeempty');
377 foreach($this->script as $idx => $rule)
378 if($rule['name'] == $name && $idx != $fid) {
379 $this->errors['name'] = $this->gettext('ruleexist');
385 if ($join == 'any') {
386 $this->form['tests'][0]['test'] = 'true';
389 foreach ($headers as $idx => $header) {
390 $header = $this->strip_value($header);
391 $target = $this->strip_value($targets[$idx], true);
392 $op = $this->strip_value($ops[$idx]);
395 if (in_array($header, $this->headers)) {
396 if (preg_match('/^not/', $op))
397 $this->form['tests'][$i]['not'] = true;
398 $type = preg_replace('/^not/', '', $op);
400 if ($type == 'exists') {
401 $this->form['tests'][$i]['test'] = 'exists';
402 $this->form['tests'][$i]['arg'] = $header;
405 $this->form['tests'][$i]['type'] = $type;
406 $this->form['tests'][$i]['test'] = 'header';
407 $this->form['tests'][$i]['arg1'] = $header;
408 $this->form['tests'][$i]['arg2'] = $target;
411 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
412 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
413 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
419 $sizeop = $this->strip_value($sizeops[$idx]);
420 $sizeitem = $this->strip_value($items[$idx]);
421 $sizetarget = $this->strip_value($sizetargets[$idx]);
423 $this->form['tests'][$i]['test'] = 'size';
424 $this->form['tests'][$i]['type'] = $sizeop;
425 $this->form['tests'][$i]['arg'] = $sizetarget.$sizeitem;
427 if ($sizetarget == '')
428 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
429 else if (!preg_match('/^[0-9]+(K|M|G)*$/i', $sizetarget))
430 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
433 $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
435 if (preg_match('/^not/', $op))
436 $this->form['tests'][$i]['not'] = true;
437 $type = preg_replace('/^not/', '', $op);
439 if ($cust_header == '')
440 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
442 $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
444 if (!count($headers))
445 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
447 foreach ($headers as $hr)
448 if (!preg_match('/^[a-z0-9-]+$/i', $hr))
449 $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
453 if (empty($this->errors['tests'][$i]['header']))
454 $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
456 if ($type == 'exists') {
457 $this->form['tests'][$i]['test'] = 'exists';
458 $this->form['tests'][$i]['arg'] = $cust_header;
461 $this->form['tests'][$i]['test'] = 'header';
462 $this->form['tests'][$i]['type'] = $type;
463 $this->form['tests'][$i]['arg1'] = $cust_header;
464 $this->form['tests'][$i]['arg2'] = $target;
467 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
468 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
469 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
479 foreach($act_types as $idx => $type) {
480 $type = $this->strip_value($type);
481 $target = $this->strip_value($act_targets[$idx]);
485 case 'fileinto_copy':
486 $mailbox = $this->strip_value($mailboxes[$idx]);
487 $this->form['actions'][$i]['target'] = $mailbox;
488 if ($type == 'fileinto_copy') {
490 $this->form['actions'][$i]['copy'] = true;
495 $target = $this->strip_value($area_targets[$idx]);
496 $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
498 // if ($target == '')
499 // $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
502 case 'redirect_copy':
503 $this->form['actions'][$i]['target'] = $target;
505 if ($this->form['actions'][$i]['target'] == '')
506 $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
507 else if (!check_email($this->form['actions'][$i]['target']))
508 $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
510 if ($type == 'redirect_copy') {
512 $this->form['actions'][$i]['copy'] = true;
516 $reason = $this->strip_value($reasons[$idx]);
517 $this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason);
518 $this->form['actions'][$i]['days'] = $days[$idx];
519 $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
520 // @TODO: vacation :subject, :mime, :from, :handle
522 if ($this->form['actions'][$i]['addresses']) {
523 foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
524 $address = trim($address);
526 unset($this->form['actions'][$i]['addresses'][$aidx]);
527 else if(!check_email($address)) {
528 $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
531 $this->form['actions'][$i]['addresses'][$aidx] = $address;
535 if ($this->form['actions'][$i]['reason'] == '')
536 $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
537 if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
538 $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
542 $this->form['actions'][$i]['type'] = $type;
546 if (!$this->errors) {
548 if (!isset($this->script[$fid])) {
549 $fid = $this->sieve->script->add_rule($this->form);
552 $fid = $this->sieve->script->update_rule($fid, $this->form);
555 $save = $this->sieve->save();
557 if ($save && $fid !== false) {
558 $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
559 $this->rc->output->add_script(
560 sprintf("rcmail.managesieve_updatelist('%s', '%s', %d, %d);",
561 isset($new) ? 'add' : 'update', Q($this->form['name']),
562 $fid, $this->form['disabled']),
566 $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
567 // $this->rc->output->send();
572 $this->managesieve_send();
575 private function managesieve_send()
577 // Handle form action
578 if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
579 if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
580 $this->rc->output->send('managesieve.setedit');
583 $this->rc->output->send('managesieve.filteredit');
586 $this->rc->output->set_pagetitle($this->gettext('filters'));
587 $this->rc->output->send('managesieve.managesieve');
591 // return the filters list as HTML table
592 function filters_list($attrib)
594 // add id to message list table if not specified
595 if (!strlen($attrib['id']))
596 $attrib['id'] = 'rcmfilterslist';
598 // define list of cols to be displayed
599 $a_show_cols = array('managesieve.filtername');
601 foreach($this->script as $idx => $filter)
603 'managesieve.filtername' => $filter['name'],
605 'class' => $filter['disabled'] ? 'disabled' : '',
608 // create XHTML table
609 $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
612 $this->rc->output->add_gui_object('filterslist', $attrib['id']);
613 $this->rc->output->include_script('list.js');
615 // add some labels to client
616 $this->rc->output->add_label('managesieve.filterdeleteconfirm');
621 // return the filters list as <SELECT>
622 function filtersets_list($attrib)
624 // add id to message list table if not specified
625 if (!strlen($attrib['id']))
626 $attrib['id'] = 'rcmfiltersetslist';
628 $list = $this->sieve->get_scripts();
629 $active = $this->sieve->get_active();
631 $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
632 'onchange' => 'rcmail.managesieve_set()'));
635 asort($list, SORT_LOCALE_STRING);
637 foreach ($list as $set)
638 $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
641 $out = $select->show($this->sieve->current);
644 $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
645 $this->rc->output->add_label(
646 'managesieve.setdeleteconfirm',
647 'managesieve.active',
648 'managesieve.filtersetact',
649 'managesieve.filtersetdeact'
655 function filter_frame($attrib)
658 $attrib['id'] = 'rcmfilterframe';
660 $attrib['name'] = $attrib['id'];
662 $this->rc->output->set_env('contentframe', $attrib['name']);
663 $this->rc->output->set_env('blankpage', $attrib['src'] ?
664 $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
666 return html::tag('iframe', $attrib);
669 function filterset_form($attrib)
672 $attrib['id'] = 'rcmfiltersetform';
674 $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
676 $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
677 $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
678 $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
679 $hiddenfields->add(array('name' => '_newset', 'value' => 1));
681 $out .= $hiddenfields->show();
683 $name = get_input_value('_name', RCUBE_INPUT_POST);
684 $copy = get_input_value('_copy', RCUBE_INPUT_POST);
685 $selected = get_input_value('_from', RCUBE_INPUT_POST);
687 // filter set name input
688 $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
689 'class' => ($this->errors['name'] ? 'error' : '')));
691 $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
692 '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
694 $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
695 $out .= '<input type="radio" id="from_none" name="_from" value="none"'
696 .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
697 $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
700 $list = $this->sieve->get_scripts();
701 $active = $this->sieve->get_active();
703 $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
705 if (is_array($list)) {
706 asort($list, SORT_LOCALE_STRING);
708 foreach ($list as $set)
709 $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
711 $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
712 .($selected=='set' ? ' checked="checked"' : '').'></input>';
713 $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
714 $out .= $select->show($copy);
718 $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
719 'type' => 'file', 'class' => ($this->errors['name'] ? 'error' : '')));
721 $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
722 .($selected=='file' ? ' checked="checked"' : '').'></input>';
723 $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
724 $out .= $upload->show();
725 $out .= '</fieldset>';
727 $this->rc->output->add_gui_object('sieveform', 'filtersetform');
733 function filter_form($attrib)
736 $attrib['id'] = 'rcmfilterform';
738 $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
739 $scr = isset($this->form) ? $this->form : $this->script[$fid];
741 $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
742 $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
743 $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
744 $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
746 $out = '<form name="filterform" action="./" method="post">'."\n";
747 $out .= $hiddenfields->show();
750 if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
755 $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
756 'class' => ($this->errors['name'] ? 'error' : '')));
758 if ($this->errors['name'])
759 $this->add_tip($field_id, $this->errors['name'], true);
762 $input_name = $input_name->show($scr['name']);
764 $input_name = $input_name->show();
766 $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s<br /><br />\n",
767 $field_id, Q($this->gettext('filtername')), $input_name);
769 $out .= '<fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
771 // any, allof, anyof radio buttons
772 $field_id = '_allof';
773 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
774 'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
776 if (isset($scr) && !$any)
777 $input_join = $input_join->show($scr['join'] ? 'allof' : '');
779 $input_join = $input_join->show();
781 $out .= sprintf("%s<label for=\"%s\">%s</label> \n",
782 $input_join, $field_id, Q($this->gettext('filterallof')));
784 $field_id = '_anyof';
785 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
786 'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
788 if (isset($scr) && !$any)
789 $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
791 $input_join = $input_join->show('anyof'); // default
793 $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
794 $input_join, $field_id, Q($this->gettext('filteranyof')));
797 $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
798 'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
800 $input_join = $input_join->show($any ? 'any' : '');
802 $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
803 $input_join, $field_id, Q($this->gettext('filterany')));
805 $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
807 $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
808 for ($x=0; $x<$rows_num; $x++)
809 $out .= $this->rule_div($fid, $x);
812 $out .= "</fieldset>\n";
815 $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
817 $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
819 $out .= '<div id="actions">';
820 for ($x=0; $x<$rows_num; $x++)
821 $out .= $this->action_div($fid, $x);
824 $out .= "</fieldset>\n";
828 if ($scr['disabled']) {
829 $this->rc->output->set_env('rule_disabled', true);
831 $this->rc->output->add_label(
832 'managesieve.ruledeleteconfirm',
833 'managesieve.actiondeleteconfirm'
835 $this->rc->output->add_gui_object('sieveform', 'filterform');
840 function rule_div($fid, $id, $div=true)
842 $rule = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
843 $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
845 $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
847 $out .= '<table><tr><td class="rowactions">';
850 $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
851 'onchange' => 'header_select(' .$id .')'));
852 foreach($this->headers as $name => $val)
853 $select_header->add(Q($this->gettext($name)), Q($val));
854 $select_header->add(Q($this->gettext('size')), 'size');
855 $select_header->add(Q($this->gettext('...')), '...');
857 // TODO: list arguments
859 if ((isset($rule['test']) && $rule['test'] == 'header')
860 && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers))
861 $out .= $select_header->show($rule['arg1']);
862 else if ((isset($rule['test']) && $rule['test'] == 'exists')
863 && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers))
864 $out .= $select_header->show($rule['arg']);
865 else if (isset($rule['test']) && $rule['test'] == 'size')
866 $out .= $select_header->show('size');
867 else if (isset($rule['test']) && $rule['test'] != 'true')
868 $out .= $select_header->show('...');
870 $out .= $select_header->show();
872 $out .= '</td><td class="rowtargets">';
874 if ((isset($rule['test']) && $rule['test'] == 'header')
875 && (is_array($rule['arg1']) || !in_array($rule['arg1'], $this->headers)))
876 $custom = is_array($rule['arg1']) ? implode(', ', $rule['arg1']) : $rule['arg1'];
877 else if ((isset($rule['test']) && $rule['test'] == 'exists')
878 && (is_array($rule['arg']) || !in_array($rule['arg'], $this->headers)))
879 $custom = is_array($rule['arg']) ? implode(', ', $rule['arg']) : $rule['arg'];
881 $out .= '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
882 <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
883 . $this->error_class($id, 'test', 'header', 'custom_header_i')
884 .' value="' .Q($custom). '" size="20" /> </div>' . "\n";
886 // matching type select (operator)
887 $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
888 'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
889 'onchange' => 'rule_op_select('.$id.')'));
890 $select_op->add(Q($this->gettext('filtercontains')), 'contains');
891 $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
892 $select_op->add(Q($this->gettext('filteris')), 'is');
893 $select_op->add(Q($this->gettext('filterisnot')), 'notis');
894 $select_op->add(Q($this->gettext('filterexists')), 'exists');
895 $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
896 // $select_op->add(Q($this->gettext('filtermatches')), 'matches');
897 // $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
898 if (in_array('relational', $this->exts)) {
899 $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
900 $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
901 $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
902 $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
903 $select_op->add(Q($this->gettext('countequals')), 'count-eq');
904 $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
905 $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
906 $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
907 $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
908 $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
909 $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
910 $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
913 // target input (TODO: lists)
915 if ($rule['test'] == 'header') {
916 $out .= $select_op->show(($rule['not'] ? 'not' : '').$rule['type']);
917 $target = $rule['arg2'];
919 else if ($rule['test'] == 'size') {
920 $out .= $select_op->show();
921 if (preg_match('/^([0-9]+)(K|M|G)*$/', $rule['arg'], $matches)) {
922 $sizetarget = $matches[1];
923 $sizeitem = $matches[2];
927 $out .= $select_op->show(($rule['not'] ? 'not' : '').$rule['test']);
931 $out .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
932 value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
933 . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
935 $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
936 $select_size_op->add(Q($this->gettext('filterunder')), 'under');
937 $select_size_op->add(Q($this->gettext('filterover')), 'over');
939 $out .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
940 $out .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
941 $out .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" '
942 . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
943 <input type="radio" name="_rule_size_item['.$id.']" value=""'
944 . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
945 <input type="radio" name="_rule_size_item['.$id.']" value="K"'
946 . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
947 <input type="radio" name="_rule_size_item['.$id.']" value="M"'
948 . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
949 <input type="radio" name="_rule_size_item['.$id.']" value="G"'
950 . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
955 $out .= '<td class="rowbuttons">';
956 $out .= '<input type="button" id="ruleadd' . $id .'" value="'. Q($this->gettext('add')). '"
957 onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button" /> ';
958 $out .= '<input type="button" id="ruledel' . $id .'" value="'. Q($this->gettext('del')). '"
959 onclick="rcmail.managesieve_ruledel(' . $id .')" class="button' . ($rows_num<2 ? ' disabled' : '') .'"'
960 . ($rows_num<2 ? ' disabled="disabled"' : '') .' />';
961 $out .= '</td></tr></table>';
963 $out .= $div ? "</div>\n" : '';
968 function action_div($fid, $id, $div=true)
970 $action = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
971 $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
973 $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
975 $out .= '<table><tr><td class="rowactions">';
978 $select_action = new html_select(array('name' => "_action_type[]", 'id' => 'action_type'.$id,
979 'onchange' => 'action_type_select(' .$id .')'));
980 if (in_array('fileinto', $this->exts))
981 $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
982 if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
983 $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
984 $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
985 if (in_array('copy', $this->exts))
986 $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
987 if (in_array('reject', $this->exts))
988 $select_action->add(Q($this->gettext('messagediscard')), 'reject');
989 else if (in_array('ereject', $this->exts))
990 $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
991 if (in_array('vacation', $this->exts))
992 $select_action->add(Q($this->gettext('messagereply')), 'vacation');
993 $select_action->add(Q($this->gettext('messagedelete')), 'discard');
994 $select_action->add(Q($this->gettext('rulestop')), 'stop');
996 $select_type = $action['type'];
997 if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
998 $select_type .= '_copy';
1001 $out .= $select_action->show($select_type);
1004 // actions target inputs
1005 $out .= '<td class="rowtargets">';
1007 $out .= '<input type="text" name="_action_target[]" id="action_target' .$id. '" '
1008 .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="40" '
1009 .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1010 . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1011 $out .= '<textarea name="_action_target_area[]" id="action_target_area' .$id. '" '
1012 .'rows="3" cols="40" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1013 .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1014 . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1018 $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1019 $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1020 .'<textarea name="_action_reason[]" id="action_reason' .$id. '" '
1021 .'rows="3" cols="40" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1022 . Q($action['reason'], 'strict', false) . "</textarea>\n";
1023 $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1024 .'<input type="text" name="_action_addresses[]" id="action_addr'.$id.'" '
1025 .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="40" '
1026 . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1027 $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1028 .'<input type="text" name="_action_days[]" id="action_days'.$id.'" '
1029 .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1030 . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1034 $out .= '<select id="action_mailbox' .$id. '" name="_action_mailbox[]" style="display:'
1035 .(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none'). '">';
1037 $this->rc->imap_connect();
1039 $a_folders = $this->rc->imap->list_mailboxes();
1040 $delimiter = $this->rc->imap->get_hierarchy_delimiter();
1042 // set mbox encoding
1043 $mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1045 if ($action['type'] == 'fileinto')
1046 $mailbox = $action['target'];
1050 foreach ($a_folders as $folder) {
1051 $utf7folder = $this->rc->imap->mod_mailbox($folder);
1052 $names = explode($delimiter, rcube_charset_convert($folder, 'UTF7-IMAP'));
1053 $name = $names[sizeof($names)-1];
1055 if ($replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter'))
1056 $utf7folder = str_replace($delimiter, $replace_delimiter, $utf7folder);
1058 // convert to Sieve implementation encoding
1059 $utf7folder = $this->mbox_encode($utf7folder, $mbox_encoding);
1061 if ($folder_class = rcmail_folder_classname($name))
1062 $foldername = $this->gettext($folder_class);
1064 $foldername = $name;
1066 $out .= sprintf('<option value="%s"%s>%s%s</option>'."\n",
1067 htmlspecialchars($utf7folder),
1068 ($mailbox == $utf7folder ? ' selected="selected"' : ''),
1069 str_repeat(' ', 4 * (sizeof($names)-1)),
1070 Q(abbreviate_string($foldername, 40 - (2 * sizeof($names)-1))));
1072 $out .= '</select>';
1076 $out .= '<td class="rowbuttons">';
1077 $out .= '<input type="button" id="actionadd' . $id .'" value="'. Q($this->gettext('add')). '"
1078 onclick="rcmail.managesieve_actionadd(' . $id .')" class="button" /> ';
1079 $out .= '<input type="button" id="actiondel' . $id .'" value="'. Q($this->gettext('del')). '"
1080 onclick="rcmail.managesieve_actiondel(' . $id .')" class="button' . ($rows_num<2 ? ' disabled' : '') .'"'
1081 . ($rows_num<2 ? ' disabled="disabled"' : '') .' />';
1084 $out .= '</tr></table>';
1086 $out .= $div ? "</div>\n" : '';
1091 private function genid()
1093 $result = intval(rcube_timer());
1097 private function strip_value($str, $allow_html=false)
1100 $str = strip_tags($str);
1105 private function error_class($id, $type, $target, $elem_prefix='')
1108 if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1109 ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1111 $this->add_tip($elem_prefix.$id, $str, true);
1112 return ' class="error"';
1118 private function mbox_encode($text, $encoding)
1120 return rcube_charset_convert($text, 'UTF7-IMAP', $encoding);
1123 private function add_tip($id, $str, $error=false)
1126 $str = html::span('sieve error', $str);
1128 $this->tips[] = array($id, $str);
1131 private function print_tips()
1133 if (empty($this->tips))
1136 $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1137 $this->rc->output->add_script($script, 'foot');