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