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