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