Aleksander Machniak
2012-09-20 cd97f0ad1190f4fe1f65542389b517936bf32b5d
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);
2e7bd6 628             $notifyaddrs    = get_input_value('_action_notifyaddress', RCUBE_INPUT_POST);
PS 629             $notifybodies   = get_input_value('_action_notifybody', RCUBE_INPUT_POST);
630             $notifymessages = get_input_value('_action_notifymessage', RCUBE_INPUT_POST);
631             $notifyfrom     = get_input_value('_action_notifyfrom', RCUBE_INPUT_POST);
3c9959 632             $notifyimp      = get_input_value('_action_notifyimportance', RCUBE_INPUT_POST);
48e9c1 633
T 634             // we need a "hack" for radiobuttons
635             foreach ($sizeitems as $item)
636                 $items[] = $item;
637
638             $this->form['disabled'] = $_POST['_disabled'] ? true : false;
639             $this->form['join']     = $join=='allof' ? true : false;
640             $this->form['name']     = $name;
641             $this->form['tests']    = array();
642             $this->form['actions']  = array();
643
644             if ($name == '')
645                 $this->errors['name'] = $this->gettext('cannotbeempty');
646             else {
647                 foreach($this->script as $idx => $rule)
648                     if($rule['name'] == $name && $idx != $fid) {
649                         $this->errors['name'] = $this->gettext('ruleexist');
650                         break;
651                     }
652             }
653
654             $i = 0;
655             // rules
656             if ($join == 'any') {
657                 $this->form['tests'][0]['test'] = 'true';
658             }
659             else {
660                 foreach ($headers as $idx => $header) {
661                     $header     = $this->strip_value($header);
662                     $target     = $this->strip_value($targets[$idx], true);
663                     $operator   = $this->strip_value($ops[$idx]);
664                     $comparator = $this->strip_value($comparators[$idx]);
665
666                     if ($header == 'size') {
667                         $sizeop     = $this->strip_value($sizeops[$idx]);
668                         $sizeitem   = $this->strip_value($items[$idx]);
669                         $sizetarget = $this->strip_value($sizetargets[$idx]);
670
671                         $this->form['tests'][$i]['test'] = 'size';
672                         $this->form['tests'][$i]['type'] = $sizeop;
673                         $this->form['tests'][$i]['arg']  = $sizetarget;
674
675                         if ($sizetarget == '')
676                             $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
677                         else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) {
678                             $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
679                             $this->form['tests'][$i]['item'] = $sizeitem;
680                         }
681                         else
682                             $this->form['tests'][$i]['arg'] .= $m[1];
683                     }
684                     else if ($header == 'body') {
685                         $trans      = $this->strip_value($body_trans[$idx]);
686                         $trans_type = $this->strip_value($body_types[$idx], true);
687
688                         if (preg_match('/^not/', $operator))
689                             $this->form['tests'][$i]['not'] = true;
690                         $type = preg_replace('/^not/', '', $operator);
691
692                         if ($type == 'exists') {
693                             $this->errors['tests'][$i]['op'] = true;
694                         }
695
696                         $this->form['tests'][$i]['test'] = 'body';
697                         $this->form['tests'][$i]['type'] = $type;
698                         $this->form['tests'][$i]['arg']  = $target;
699
700                         if ($target == '' && $type != 'exists')
701                             $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
702                         else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
703                             $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
704
705                         $this->form['tests'][$i]['part'] = $trans;
706                         if ($trans == 'content') {
707                             $this->form['tests'][$i]['content'] = $trans_type;
708                         }
709                     }
710                     else {
711                         $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
712                         $mod      = $this->strip_value($mods[$idx]);
713                         $mod_type = $this->strip_value($mod_types[$idx]);
714
715                         if (preg_match('/^not/', $operator))
716                             $this->form['tests'][$i]['not'] = true;
717                         $type = preg_replace('/^not/', '', $operator);
718
719                         if ($header == '...') {
720                             $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
721
722                             if (!count($headers))
723                                 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
724                             else {
7dc7eb 725                                 foreach ($headers as $hr) {
AM 726                                     // RFC2822: printable ASCII except colon
727                                     if (!preg_match('/^[\x21-\x39\x41-\x7E]+$/i', $hr)) {
48e9c1 728                                         $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
7dc7eb 729                                     }
AM 730                                 }
48e9c1 731                             }
T 732
733                             if (empty($this->errors['tests'][$i]['header']))
734                                 $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
735                         }
736
737                         if ($type == 'exists') {
738                             $this->form['tests'][$i]['test'] = 'exists';
739                             $this->form['tests'][$i]['arg'] = $header == '...' ? $cust_header : $header;
740                         }
741                         else {
742                             $test   = 'header';
743                             $header = $header == '...' ? $cust_header : $header;
744
745                             if ($mod == 'address' || $mod == 'envelope') {
746                                 $found = false;
747                                 if (empty($this->errors['tests'][$i]['header'])) {
748                                     foreach ((array)$header as $hdr) {
749                                         if (!in_array(strtolower(trim($hdr)), $this->addr_headers))
750                                             $found = true;
751                                     }
752                                 }
753                                 if (!$found)
754                                     $test = $mod;
755                             }
756
757                             $this->form['tests'][$i]['type'] = $type;
758                             $this->form['tests'][$i]['test'] = $test;
759                             $this->form['tests'][$i]['arg1'] = $header;
760                             $this->form['tests'][$i]['arg2'] = $target;
761
762                             if ($target == '')
763                                 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
764                             else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
765                                 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
766
767                             if ($mod) {
768                                 $this->form['tests'][$i]['part'] = $mod_type;
769                             }
770                         }
771                     }
772
773                     if ($header != 'size' && $comparator) {
774                         if (preg_match('/^(value|count)/', $this->form['tests'][$i]['type']))
775                             $comparator = 'i;ascii-numeric';
776
777                         $this->form['tests'][$i]['comparator'] = $comparator;
778                     }
779
780                     $i++;
781                 }
782             }
783
784             $i = 0;
785             // actions
786             foreach($act_types as $idx => $type) {
787                 $type   = $this->strip_value($type);
788                 $target = $this->strip_value($act_targets[$idx]);
789
790                 switch ($type) {
791
792                 case 'fileinto':
793                 case 'fileinto_copy':
794                     $mailbox = $this->strip_value($mailboxes[$idx]);
795                     $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
796                     if ($type == 'fileinto_copy') {
797                         $type = 'fileinto';
798                         $this->form['actions'][$i]['copy'] = true;
799                     }
800                     break;
801
802                 case 'reject':
803                 case 'ereject':
804                     $target = $this->strip_value($area_targets[$idx]);
805                     $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
806
807  //                 if ($target == '')
808 //                      $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
809                     break;
810
811                 case 'redirect':
812                 case 'redirect_copy':
813                     $this->form['actions'][$i]['target'] = $target;
814
815                     if ($this->form['actions'][$i]['target'] == '')
816                         $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
817                     else if (!check_email($this->form['actions'][$i]['target']))
818                         $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
819
820                     if ($type == 'redirect_copy') {
821                         $type = 'redirect';
822                         $this->form['actions'][$i]['copy'] = true;
823                     }
824                     break;
825
826                 case 'addflag':
827                 case 'setflag':
828                 case 'removeflag':
829                     $_target = array();
830                     if (empty($flags[$idx])) {
831                         $this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
832                     }
833                     else {
834                         foreach ($flags[$idx] as $flag) {
835                             $_target[] = $this->strip_value($flag);
836                         }
837                     }
838                     $this->form['actions'][$i]['target'] = $_target;
839                     break;
840
841                 case 'vacation':
842                     $reason = $this->strip_value($reasons[$idx]);
843                     $this->form['actions'][$i]['reason']    = str_replace("\r\n", "\n", $reason);
844                     $this->form['actions'][$i]['days']      = $days[$idx];
845                     $this->form['actions'][$i]['subject']   = $subject[$idx];
846                     $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
847 // @TODO: vacation :mime, :from, :handle
848
849                     if ($this->form['actions'][$i]['addresses']) {
850                         foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
851                             $address = trim($address);
852                             if (!$address)
853                                 unset($this->form['actions'][$i]['addresses'][$aidx]);
854                             else if(!check_email($address)) {
855                                 $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
856                                 break;
857                             } else
858                                 $this->form['actions'][$i]['addresses'][$aidx] = $address;
859                         }
860                     }
861
862                     if ($this->form['actions'][$i]['reason'] == '')
863                         $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
864                     if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
865                         $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
ebb204 866                     break;
AM 867
868                 case 'set':
c9dcb8 869                     $this->form['actions'][$i]['name'] = $varnames[$idx];
AM 870                     $this->form['actions'][$i]['value'] = $varvalues[$idx];
871                     foreach ((array)$varmods[$idx] as $v_m) {
872                         $this->form['actions'][$i][$v_m] = true;
873                     }
874
ebb204 875                     if (empty($varnames[$idx])) {
AM 876                         $this->errors['actions'][$i]['name'] = $this->gettext('cannotbeempty');
877                     }
c9dcb8 878                     else if (!preg_match('/^[0-9a-z_]+$/i', $varnames[$idx])) {
AM 879                         $this->errors['actions'][$i]['name'] = $this->gettext('forbiddenchars');
880                     }
881
882                     if (!isset($varvalues[$idx]) || $varvalues[$idx] === '') {
ebb204 883                         $this->errors['actions'][$i]['value'] = $this->gettext('cannotbeempty');
AM 884                     }
2e7bd6 885                     break;
PS 886
887                 case 'notify':
888                     if (empty($notifyaddrs[$idx])) {
889                         $this->errors['actions'][$i]['address'] = $this->gettext('cannotbeempty');
890                     }
891                     else if (!check_email($notifyaddrs[$idx])) {
892                         $this->errors['actions'][$i]['address'] = $this->gettext('noemailwarning');
893                     }
894                     if (!empty($notifyfrom[$idx]) && !check_email($notifyfrom[$idx])) {
895                         $this->errors['actions'][$i]['from'] = $this->gettext('noemailwarning');
896                     }
897                     $this->form['actions'][$i]['address'] = $notifyaddrs[$idx];
898                     $this->form['actions'][$i]['body'] = $notifybodies[$idx];
899                     $this->form['actions'][$i]['message'] = $notifymessages[$idx];
900                     $this->form['actions'][$i]['from'] = $notifyfrom[$idx];
3c9959 901                     $this->form['actions'][$i]['importance'] = $notifyimp[$idx];
48e9c1 902                     break;
T 903                 }
904
905                 $this->form['actions'][$i]['type'] = $type;
906                 $i++;
907             }
908
909             if (!$this->errors && !$error) {
910                 // zapis skryptu
911                 if (!isset($this->script[$fid])) {
912                     $fid = $this->sieve->script->add_rule($this->form);
913                     $new = true;
914                 } else
915                     $fid = $this->sieve->script->update_rule($fid, $this->form);
916
917                 if ($fid !== false)
918                     $save = $this->save_script();
919
920                 if ($save && $fid !== false) {
921                     $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
922                     if ($this->rc->task != 'mail') {
923                         $this->rc->output->command('parent.managesieve_updatelist',
924                             isset($new) ? 'add' : 'update',
925                             array(
926                                 'name' => Q($this->form['name']),
927                                 'id' => $fid,
928                                 'disabled' => $this->form['disabled']
929                         ));
930                     }
931                     else {
932                         $this->rc->output->command('managesieve_dialog_close');
933                         $this->rc->output->send('iframe');
934                     }
935                 }
936                 else {
937                     $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
938 //                  $this->rc->output->send();
939                 }
940             }
941         }
942
943         $this->managesieve_send();
944     }
945
946     private function managesieve_send()
947     {
948         // Handle form action
949         if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
950             if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
951                 $this->rc->output->send('managesieve.setedit');
952             }
953             else {
954                 $this->rc->output->send('managesieve.filteredit');
955             }
956         } else {
957             $this->rc->output->set_pagetitle($this->gettext('filters'));
958             $this->rc->output->send('managesieve.managesieve');
959         }
960     }
961
962     // return the filters list as HTML table
963     function filters_list($attrib)
964     {
965         // add id to message list table if not specified
966         if (!strlen($attrib['id']))
967             $attrib['id'] = 'rcmfilterslist';
968
969         // define list of cols to be displayed
970         $a_show_cols = array('name');
971
972         $result = $this->list_rules();
973
974         // create XHTML table
975         $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
976
977         // set client env
978         $this->rc->output->add_gui_object('filterslist', $attrib['id']);
979         $this->rc->output->include_script('list.js');
980
981         // add some labels to client
982         $this->rc->output->add_label('managesieve.filterdeleteconfirm');
983
984         return $out;
985     }
986
987     // return the filters list as <SELECT>
988     function filtersets_list($attrib, $no_env = false)
989     {
990         // add id to message list table if not specified
991         if (!strlen($attrib['id']))
992             $attrib['id'] = 'rcmfiltersetslist';
993
994         $list = $this->list_scripts();
995
996         if ($list) {
997             asort($list, SORT_LOCALE_STRING);
998         }
999
1000         if (!empty($attrib['type']) && $attrib['type'] == 'list') {
1001             // define list of cols to be displayed
1002             $a_show_cols = array('name');
1003
1004             if ($list) {
1005                 foreach ($list as $idx => $set) {
1006                     $scripts['S'.$idx] = $set;
1007                     $result[] = array(
1008                         'name' => Q($set),
1009                         'id' => 'S'.$idx,
1010                         'class' => !in_array($set, $this->active) ? 'disabled' : '',
1011                     );
1012                 }
1013             }
1014
1015             // create XHTML table
1016             $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
1017
1018             $this->rc->output->set_env('filtersets', $scripts);
1019             $this->rc->output->include_script('list.js');
1020         }
1021         else {
1022             $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
1023                 'onchange' => $this->rc->task != 'mail' ? 'rcmail.managesieve_set()' : ''));
1024
1025             if ($list) {
1026                 foreach ($list as $set)
1027                     $select->add($set, $set);
1028             }
1029
1030             $out = $select->show($this->sieve->current);
1031         }
1032
1033         // set client env
1034         if (!$no_env) {
1035             $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
1036             $this->rc->output->add_label('managesieve.setdeleteconfirm');
1037         }
1038
1039         return $out;
1040     }
1041
1042     function filter_frame($attrib)
1043     {
1044         if (!$attrib['id'])
1045             $attrib['id'] = 'rcmfilterframe';
1046
1047         $attrib['name'] = $attrib['id'];
1048
1049         $this->rc->output->set_env('contentframe', $attrib['name']);
1050         $this->rc->output->set_env('blankpage', $attrib['src'] ?
cfc27c 1051         $this->rc->output->abs_url($attrib['src']) : 'program/resources/blank.gif');
48e9c1 1052
T 1053         return html::tag('iframe', $attrib);
1054     }
1055
1056     function filterset_form($attrib)
1057     {
1058         if (!$attrib['id'])
1059             $attrib['id'] = 'rcmfiltersetform';
1060
1061         $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
1062
1063         $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1064         $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1065         $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1066         $hiddenfields->add(array('name' => '_newset', 'value' => 1));
1067
1068         $out .= $hiddenfields->show();
1069
1070         $name     = get_input_value('_name', RCUBE_INPUT_POST);
1071         $copy     = get_input_value('_copy', RCUBE_INPUT_POST);
1072         $selected = get_input_value('_from', RCUBE_INPUT_POST);
1073
1074         // filter set name input
1075         $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
1076             'class' => ($this->errors['name'] ? 'error' : '')));
1077
1078         $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
1079             '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
1080
1081         $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
1082         $out .= '<input type="radio" id="from_none" name="_from" value="none"'
1083             .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
1084         $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
1085
1086         // filters set list
1087         $list   = $this->list_scripts();
1088         $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
1089
1090         if (is_array($list)) {
1091             asort($list, SORT_LOCALE_STRING);
1092
1093             if (!$copy)
1094                 $copy = $_SESSION['managesieve_current'];
1095
1096             foreach ($list as $set) {
1097                 $select->add($set, $set);
1098             }
1099
1100             $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
1101                 .($selected=='set' ? ' checked="checked"' : '').'></input>';
1102             $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
1103             $out .= $select->show($copy);
1104         }
1105
1106         // script upload box
1107         $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
1108             'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : '')));
1109
1110         $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
1111             .($selected=='file' ? ' checked="checked"' : '').'></input>';
1112         $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
1113         $out .= $upload->show();
1114         $out .= '</fieldset>';
1115
1116         $this->rc->output->add_gui_object('sieveform', 'filtersetform');
1117
1118         if ($this->errors['name'])
1119             $this->add_tip('_name', $this->errors['name'], true);
1120         if ($this->errors['file'])
1121             $this->add_tip('_file', $this->errors['file'], true);
1122
1123         $this->print_tips();
1124
1125         return $out;
1126     }
1127
1128
1129     function filter_form($attrib)
1130     {
1131         if (!$attrib['id'])
1132             $attrib['id'] = 'rcmfilterform';
1133
1134         $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
1135         $scr = isset($this->form) ? $this->form : $this->script[$fid];
1136
1137         $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
1138         $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
1139         $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
1140         $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
1141
1142         $out = '<form name="filterform" action="./" method="post">'."\n";
1143         $out .= $hiddenfields->show();
1144
1145         // 'any' flag
1146         if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
1147             $any = true;
1148
1149         // filter name input
1150         $field_id = '_name';
1151         $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
1152             'class' => ($this->errors['name'] ? 'error' : '')));
1153
1154         if ($this->errors['name'])
1155             $this->add_tip($field_id, $this->errors['name'], true);
1156
1157         if (isset($scr))
1158             $input_name = $input_name->show($scr['name']);
1159         else
1160             $input_name = $input_name->show();
1161
1162         $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s\n",
1163             $field_id, Q($this->gettext('filtername')), $input_name);
1164
1165         // filter set selector
1166         if ($this->rc->task == 'mail') {
1167             $out .= sprintf("\n&nbsp;<label for=\"%s\"><b>%s:</b></label> %s\n",
1168                 $field_id, Q($this->gettext('filterset')),
1169                 $this->filtersets_list(array('id' => 'sievescriptname'), true));
1170         }
1171
1172         $out .= '<br /><br /><fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
1173
1174         // any, allof, anyof radio buttons
1175         $field_id = '_allof';
1176         $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
1177             'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
1178
1179         if (isset($scr) && !$any)
1180             $input_join = $input_join->show($scr['join'] ? 'allof' : '');
1181         else
1182             $input_join = $input_join->show();
1183
1184         $out .= sprintf("%s<label for=\"%s\">%s</label>&nbsp;\n",
1185             $input_join, $field_id, Q($this->gettext('filterallof')));
1186
1187         $field_id = '_anyof';
1188         $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
1189             'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
1190
1191         if (isset($scr) && !$any)
1192             $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
1193         else
1194             $input_join = $input_join->show('anyof'); // default
1195
1196         $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1197             $input_join, $field_id, Q($this->gettext('filteranyof')));
1198
1199         $field_id = '_any';
1200         $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
1201             'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
1202
1203         $input_join = $input_join->show($any ? 'any' : '');
1204
1205         $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
1206             $input_join, $field_id, Q($this->gettext('filterany')));
1207
1208         $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
1209
1210         $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
1211         for ($x=0; $x<$rows_num; $x++)
1212             $out .= $this->rule_div($fid, $x);
1213         $out .= "</div>\n";
1214
1215         $out .= "</fieldset>\n";
1216
1217         // actions
1218         $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
1219
1220         $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
1221
1222         $out .= '<div id="actions">';
1223         for ($x=0; $x<$rows_num; $x++)
1224             $out .= $this->action_div($fid, $x);
1225         $out .= "</div>\n";
1226
1227         $out .= "</fieldset>\n";
1228
1229         $this->print_tips();
1230
1231         if ($scr['disabled']) {
1232             $this->rc->output->set_env('rule_disabled', true);
1233         }
1234         $this->rc->output->add_label(
1235             'managesieve.ruledeleteconfirm',
1236             'managesieve.actiondeleteconfirm'
1237         );
1238         $this->rc->output->add_gui_object('sieveform', 'filterform');
1239
1240         return $out;
1241     }
1242
1243     function rule_div($fid, $id, $div=true)
1244     {
1245         $rule     = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
1246         $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
1247
1248         // headers select
1249         $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
1250             'onchange' => 'rule_header_select(' .$id .')'));
1251         foreach($this->headers as $name => $val)
1252             $select_header->add(Q($this->gettext($name)), Q($val));
1253         if (in_array('body', $this->exts))
1254             $select_header->add(Q($this->gettext('body')), 'body');
1255         $select_header->add(Q($this->gettext('size')), 'size');
1256         $select_header->add(Q($this->gettext('...')), '...');
1257
1258         // TODO: list arguments
1259         $aout = '';
1260
1261         if ((isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope')))
1262             && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers)
1263         ) {
1264             $aout .= $select_header->show($rule['arg1']);
1265         }
1266         else if ((isset($rule['test']) && $rule['test'] == 'exists')
1267             && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers)
1268         ) {
1269             $aout .= $select_header->show($rule['arg']);
1270         }
1271         else if (isset($rule['test']) && $rule['test'] == 'size')
1272             $aout .= $select_header->show('size');
1273         else if (isset($rule['test']) && $rule['test'] == 'body')
1274             $aout .= $select_header->show('body');
1275         else if (isset($rule['test']) && $rule['test'] != 'true')
1276             $aout .= $select_header->show('...');
1277         else
1278             $aout .= $select_header->show();
1279
1280         if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) {
1281             if (is_array($rule['arg1']))
1282                 $custom = implode(', ', $rule['arg1']);
1283             else if (!in_array($rule['arg1'], $this->headers))
1284                 $custom = $rule['arg1'];
1285         }
1286         else if (isset($rule['test']) && $rule['test'] == 'exists') {
1287             if (is_array($rule['arg']))
1288                 $custom = implode(', ', $rule['arg']);
1289             else if (!in_array($rule['arg'], $this->headers))
1290                 $custom = $rule['arg'];
1291         }
1292
1293         $tout = '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
1294             <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
1295             . $this->error_class($id, 'test', 'header', 'custom_header_i')
1296             .' value="' .Q($custom). '" size="15" />&nbsp;</div>' . "\n";
1297
1298         // matching type select (operator)
1299         $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
1300             'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
1301             'class' => 'operator_selector',
1302             'onchange' => 'rule_op_select('.$id.')'));
1303         $select_op->add(Q($this->gettext('filtercontains')), 'contains');
1304         $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
1305         $select_op->add(Q($this->gettext('filteris')), 'is');
1306         $select_op->add(Q($this->gettext('filterisnot')), 'notis');
1307         $select_op->add(Q($this->gettext('filterexists')), 'exists');
1308         $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
1309         $select_op->add(Q($this->gettext('filtermatches')), 'matches');
1310         $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
1311         if (in_array('regex', $this->exts)) {
1312             $select_op->add(Q($this->gettext('filterregex')), 'regex');
1313             $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
1314         }
1315         if (in_array('relational', $this->exts)) {
1316             $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
1317             $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
1318             $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
1319             $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
1320             $select_op->add(Q($this->gettext('countequals')), 'count-eq');
1321             $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
1322             $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
1323             $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
1324             $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
1325             $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
1326             $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
1327             $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
1328         }
1329
1330         // target input (TODO: lists)
1331
1332         if (in_array($rule['test'], array('header', 'address', 'envelope'))) {
1333             $test   = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
1334             $target = $rule['arg2'];
1335         }
1336         else if ($rule['test'] == 'body') {
1337             $test   = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
1338             $target = $rule['arg'];
1339         }
1340         else if ($rule['test'] == 'size') {
1341             $test   = '';
1342             $target = '';
1343             if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) {
1344                 $sizetarget = $matches[1];
1345                 $sizeitem = $matches[2];
1346             }
1347             else {
1348                 $sizetarget = $rule['arg'];
1349                 $sizeitem = $rule['item'];
1350             }
1351         }
1352         else {
1353             $test   = ($rule['not'] ? 'not' : '').$rule['test'];
1354             $target =  '';
1355         }
1356
1357         $tout .= $select_op->show($test);
1358         $tout .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
1359             value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
1360             . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
1361
1362         $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
1363         $select_size_op->add(Q($this->gettext('filterover')), 'over');
1364         $select_size_op->add(Q($this->gettext('filterunder')), 'under');
1365
1366         $tout .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
1367         $tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
1368         $tout .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" ' 
1369             . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
1370             <input type="radio" name="_rule_size_item['.$id.']" value=""'
1371                 . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
1372             <input type="radio" name="_rule_size_item['.$id.']" value="K"'
1373                 . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
1374             <input type="radio" name="_rule_size_item['.$id.']" value="M"'
1375                 . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
1376             <input type="radio" name="_rule_size_item['.$id.']" value="G"'
1377                 . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
1378         $tout .= '</div>';
1379
1380         // Advanced modifiers (address, envelope)
1381         $select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id,
1382             'onchange' => 'rule_mod_select(' .$id .')'));
1383         $select_mod->add(Q($this->gettext('none')), '');
1384         $select_mod->add(Q($this->gettext('address')), 'address');
1385         if (in_array('envelope', $this->exts))
1386             $select_mod->add(Q($this->gettext('envelope')), 'envelope');
1387
1388         $select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id));
1389         $select_type->add(Q($this->gettext('allparts')), 'all');
1390         $select_type->add(Q($this->gettext('domain')), 'domain');
1391         $select_type->add(Q($this->gettext('localpart')), 'localpart');
1392         if (in_array('subaddress', $this->exts)) {
1393             $select_type->add(Q($this->gettext('user')), 'user');
1394             $select_type->add(Q($this->gettext('detail')), 'detail');
1395         }
1396
1397         $need_mod = $rule['test'] != 'size' && $rule['test'] != 'body';
1398         $mout = '<div id="rule_mod' .$id. '" class="adv" style="display:' . ($need_mod ? 'block' : 'none') .'">';
1399         $mout .= ' <span>';
1400         $mout .= Q($this->gettext('modifier')) . ' ';
1401         $mout .= $select_mod->show($rule['test']);
1402         $mout .= '</span>';
1403         $mout .= ' <span id="rule_mod_type' . $id . '"';
1404         $mout .= ' style="display:' . (in_array($rule['test'], array('address', 'envelope')) ? 'inline' : 'none') .'">';
1405         $mout .= Q($this->gettext('modtype')) . ' ';
1406         $mout .= $select_type->show($rule['part']);
1407         $mout .= '</span>';
1408         $mout .= '</div>';
1409
1410         // Advanced modifiers (body transformations)
1411         $select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id,
1412             'onchange' => 'rule_trans_select(' .$id .')'));
1413         $select_mod->add(Q($this->gettext('text')), 'text');
1414         $select_mod->add(Q($this->gettext('undecoded')), 'raw');
1415         $select_mod->add(Q($this->gettext('contenttype')), 'content');
1416
1417         $mout .= '<div id="rule_trans' .$id. '" class="adv" style="display:' . ($rule['test'] == 'body' ? 'block' : 'none') .'">';
1418         $mout .= ' <span>';
1419         $mout .= Q($this->gettext('modifier')) . ' ';
1420         $mout .= $select_mod->show($rule['part']);
1421         $mout .= '<input type="text" name="_rule_trans_type[]" id="rule_trans_type'.$id
1422             . '" value="'.(is_array($rule['content']) ? implode(',', $rule['content']) : $rule['content'])
1423             .'" size="20" style="display:' . ($rule['part'] == 'content' ? 'inline' : 'none') .'"'
1424             . $this->error_class($id, 'test', 'part', 'rule_trans_type') .' />';
1425         $mout .= '</span>';
1426         $mout .= '</div>';
1427
1428         // Advanced modifiers (body transformations)
1429         $select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id));
1430         $select_comp->add(Q($this->gettext('default')), '');
1431         $select_comp->add(Q($this->gettext('octet')), 'i;octet');
1432         $select_comp->add(Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
1433         if (in_array('comparator-i;ascii-numeric', $this->exts)) {
1434             $select_comp->add(Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
1435         }
1436
1437         $mout .= '<div id="rule_comp' .$id. '" class="adv" style="display:' . ($rule['test'] != 'size' ? 'block' : 'none') .'">';
1438         $mout .= ' <span>';
1439         $mout .= Q($this->gettext('comparator')) . ' ';
1440         $mout .= $select_comp->show($rule['comparator']);
1441         $mout .= '</span>';
1442         $mout .= '</div>';
1443
1444         // Build output table
1445         $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
1446         $out .= '<table><tr>';
1447         $out .= '<td class="advbutton">';
1448         $out .= '<a href="#" id="ruleadv' . $id .'" title="'. Q($this->gettext('advancedopts')). '"
1449             onclick="rule_adv_switch(' . $id .', this)" class="show">&nbsp;&nbsp;</a>';
1450         $out .= '</td>';
1451         $out .= '<td class="rowactions">' . $aout . '</td>';
1452         $out .= '<td class="rowtargets">' . $tout . "\n";
1453         $out .= '<div id="rule_advanced' .$id. '" style="display:none">' . $mout . '</div>';
1454         $out .= '</td>';
1455
1456         // add/del buttons
1457         $out .= '<td class="rowbuttons">';
1458         $out .= '<a href="#" id="ruleadd' . $id .'" title="'. Q($this->gettext('add')). '"
1459             onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
1460         $out .= '<a href="#" id="ruledel' . $id .'" title="'. Q($this->gettext('del')). '"
1461             onclick="rcmail.managesieve_ruledel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1462         $out .= '</td>';
1463         $out .= '</tr></table>';
1464
1465         $out .= $div ? "</div>\n" : '';
1466
1467         return $out;
1468     }
1469
1470     function action_div($fid, $id, $div=true)
1471     {
1472         $action   = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
1473         $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
1474
1475         $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
1476
1477         $out .= '<table><tr><td class="rowactions">';
1478
1479         // action select
1480         $select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id,
1481             'onchange' => 'action_type_select(' .$id .')'));
1482         if (in_array('fileinto', $this->exts))
1483             $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
1484         if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
1485             $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
1486         $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
1487         if (in_array('copy', $this->exts))
1488             $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
1489         if (in_array('reject', $this->exts))
1490             $select_action->add(Q($this->gettext('messagediscard')), 'reject');
1491         else if (in_array('ereject', $this->exts))
1492             $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
1493         if (in_array('vacation', $this->exts))
1494             $select_action->add(Q($this->gettext('messagereply')), 'vacation');
1495         $select_action->add(Q($this->gettext('messagedelete')), 'discard');
1496         if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
1497             $select_action->add(Q($this->gettext('setflags')), 'setflag');
1498             $select_action->add(Q($this->gettext('addflags')), 'addflag');
1499             $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
1500         }
ebb204 1501         if (in_array('variables', $this->exts)) {
AM 1502             $select_action->add(Q($this->gettext('setvariable')), 'set');
1503         }
270da4 1504         if (in_array('enotify', $this->exts) || in_array('notify', $this->exts)) {
2e7bd6 1505             $select_action->add(Q($this->gettext('notify')), 'notify');
PS 1506         }
48e9c1 1507         $select_action->add(Q($this->gettext('rulestop')), 'stop');
T 1508
1509         $select_type = $action['type'];
1510         if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
1511             $select_type .= '_copy';
1512         }
1513
1514         $out .= $select_action->show($select_type);
1515         $out .= '</td>';
1516
1517         // actions target inputs
1518         $out .= '<td class="rowtargets">';
1519         // shared targets
1520         $out .= '<input type="text" name="_action_target['.$id.']" id="action_target' .$id. '" '
1521             .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="35" '
1522             .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1523             . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1524         $out .= '<textarea name="_action_target_area['.$id.']" id="action_target_area' .$id. '" '
1525             .'rows="3" cols="35" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1526             .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1527             . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1528             . "</textarea>\n";
1529
1530         // vacation
1531         $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1532         $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1533             .'<textarea name="_action_reason['.$id.']" id="action_reason' .$id. '" '
1534             .'rows="3" cols="35" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1535             . Q($action['reason'], 'strict', false) . "</textarea>\n";
1536         $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
1537             .'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
1538             .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
1539             . $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
1540         $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1541             .'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
1542             .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
1543             . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1544         $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1545             .'<input type="text" name="_action_days['.$id.']" id="action_days'.$id.'" '
1546             .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1547             . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1548         $out .= '</div>';
1549
1550         // flags
1551         $flags = array(
1552             'read'      => '\\Seen',
1553             'answered'  => '\\Answered',
1554             'flagged'   => '\\Flagged',
1555             'deleted'   => '\\Deleted',
1556             'draft'     => '\\Draft',
1557         );
1558         $flags_target = (array)$action['target'];
1559
1560         $out .= '<div id="action_flags' .$id.'" style="display:' 
1561             . (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
1562             . $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
1563         foreach ($flags as $fidx => $flag) {
1564             $out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
1565                 . (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
1566                 . Q($this->gettext('flag'.$fidx)) .'<br>';
1567         }
1568         $out .= '</div>';
1569
ebb204 1570         // set variable
AM 1571         $set_modifiers = array(
1572             'lower',
1573             'upper',
1574             'lowerfirst',
1575             'upperfirst',
1576             'quotewildcard',
1577             'length'
1578         );
1579
1580         $out .= '<div id="action_set' .$id.'" style="display:' .($action['type']=='set' ? 'inline' : 'none') .'">';
1581         $out .= '<span class="label">' .Q($this->gettext('setvarname')) . '</span><br />'
1582             .'<input type="text" name="_action_varname['.$id.']" id="action_varname'.$id.'" '
1583             .'value="' . Q($action['name']) . '" size="35" '
1584             . $this->error_class($id, 'action', 'name', 'action_varname') .' />';
1585         $out .= '<br /><span class="label">' .Q($this->gettext('setvarvalue')) . '</span><br />'
1586             .'<input type="text" name="_action_varvalue['.$id.']" id="action_varvalue'.$id.'" '
1587             .'value="' . Q($action['value']) . '" size="35" '
1588             . $this->error_class($id, 'action', 'value', 'action_varvalue') .' />';
1589         $out .= '<br /><span class="label">' .Q($this->gettext('setvarmodifiers')) . '</span><br />';
1590         foreach ($set_modifiers as $j => $s_m) {
1591             $s_m_id = 'action_varmods' . $id . $s_m;
1592             $out .= sprintf('<input type="checkbox" name="_action_varmods[%s][]" value="%s" id="%s"%s />%s<br>',
7eba08 1593                 $id, $s_m, $s_m_id,
AM 1594                 (array_key_exists($s_m, (array)$action) && $action[$s_m] ? ' checked="checked"' : ''),
1595                 Q($this->gettext('var' . $s_m)));
ebb204 1596         }
AM 1597         $out .= '</div>';
1598
2e7bd6 1599         // notify
PS 1600         // skip :options tag - not used by the mailto method
1601         $out .= '<div id="action_notify' .$id.'" style="display:' .($action['type']=='notify' ? 'inline' : 'none') .'">';
1602         $out .= '<span class="label">' .Q($this->gettext('notifyaddress')) . '</span><br />'
1603             .'<input type="text" name="_action_notifyaddress['.$id.']" id="action_notifyaddress'.$id.'" '
1604             .'value="' . Q($action['address']) . '" size="35" '
1605             . $this->error_class($id, 'action', 'address', 'action_notifyaddress') .' />';
1606         $out .= '<br /><span class="label">'. Q($this->gettext('notifybody')) .'</span><br />'
1607             .'<textarea name="_action_notifybody['.$id.']" id="action_notifybody' .$id. '" '
1608             .'rows="3" cols="35" '. $this->error_class($id, 'action', 'method', 'action_notifybody') . '>'
1609             . Q($action['body'], 'strict', false) . "</textarea>\n";
1610         $out .= '<br /><span class="label">' .Q($this->gettext('notifysubject')) . '</span><br />'
1611             .'<input type="text" name="_action_notifymessage['.$id.']" id="action_notifymessage'.$id.'" '
1612             .'value="' . Q($action['message']) . '" size="35" '
1613             . $this->error_class($id, 'action', 'message', 'action_notifymessage') .' />';
1614         $out .= '<br /><span class="label">' .Q($this->gettext('notifyfrom')) . '</span><br />'
1615             .'<input type="text" name="_action_notifyfrom['.$id.']" id="action_notifyfrom'.$id.'" '
1616             .'value="' . Q($action['from']) . '" size="35" '
1617             . $this->error_class($id, 'action', 'from', 'action_notifyfrom') .' />';
3c9959 1618         $importance_options = array(
PS 1619             3 => 'notifyimportancelow',
1620             2 => 'notifyimportancenormal',
1621             1 => 'notifyimportancehigh'
1622         );
1623         $select_importance = new html_select(array(
1624             'name' => '_action_notifyimportance[' . $id . ']',
1625             'id' => '_action_notifyimportance' . $id,
1626             'class' => $this->error_class($id, 'action', 'importance', 'action_notifyimportance')));
1627         foreach ($importance_options as $io_v => $io_n) {
1628             $select_importance->add(Q($this->gettext($io_n)), $io_v);
1629         }
1630         $out .= '<br /><span class="label">' . Q($this->gettext('notifyimportance')) . '</span><br />';
1631         $out .= $select_importance->show(array(intval($action['importance'])));
2e7bd6 1632         $out .= '</div>';
PS 1633
48e9c1 1634         // mailbox select
T 1635         if ($action['type'] == 'fileinto')
1636             $mailbox = $this->mod_mailbox($action['target'], 'out');
1637         else
1638             $mailbox = '';
1639
1640         $select = rcmail_mailbox_select(array(
1641             'realnames' => false,
1642             'maxlength' => 100,
1643             'id' => 'action_mailbox' . $id,
1644             'name' => "_action_mailbox[$id]",
1645             'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
1646         ));
1647         $out .= $select->show($mailbox);
1648         $out .= '</td>';
1649
1650         // add/del buttons
1651         $out .= '<td class="rowbuttons">';
1652         $out .= '<a href="#" id="actionadd' . $id .'" title="'. Q($this->gettext('add')). '"
1653             onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
1654         $out .= '<a href="#" id="actiondel' . $id .'" title="'. Q($this->gettext('del')). '"
1655             onclick="rcmail.managesieve_actiondel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
1656         $out .= '</td>';
1657
1658         $out .= '</tr></table>';
1659
1660         $out .= $div ? "</div>\n" : '';
1661
1662         return $out;
1663     }
1664
1665     private function genid()
1666     {
1667         $result = preg_replace('/[^0-9]/', '', microtime(true));
1668         return $result;
1669     }
1670
1671     private function strip_value($str, $allow_html=false)
1672     {
1673         if (!$allow_html)
1674             $str = strip_tags($str);
1675
1676         return trim($str);
1677     }
1678
1679     private function error_class($id, $type, $target, $elem_prefix='')
1680     {
1681         // TODO: tooltips
1682         if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1683             ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1684         ) {
1685             $this->add_tip($elem_prefix.$id, $str, true);
1686             return ' class="error"';
1687         }
1688
1689         return '';
1690     }
1691
1692     private function add_tip($id, $str, $error=false)
1693     {
1694         if ($error)
1695             $str = html::span('sieve error', $str);
1696
1697         $this->tips[] = array($id, $str);
1698     }
1699
1700     private function print_tips()
1701     {
1702         if (empty($this->tips))
1703             return;
1704
1705         $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1706         $this->rc->output->add_script($script, 'foot');
1707     }
1708
1709     /**
1710      * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
1711      * with delimiter replacement.
1712      *
1713      * @param string $mailbox Mailbox name
1714      * @param string $mode    Conversion direction ('in'|'out')
1715      *
1716      * @return string Mailbox name
1717      */
1718     private function mod_mailbox($mailbox, $mode = 'out')
1719     {
1720         $delimiter         = $_SESSION['imap_delimiter'];
1721         $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
1722         $mbox_encoding     = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1723
1724         if ($mode == 'out') {
1725             $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
1726             if ($replace_delimiter && $replace_delimiter != $delimiter)
1727                 $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
1728         }
1729         else {
1730             $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
1731             if ($replace_delimiter && $replace_delimiter != $delimiter)
1732                 $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);
1733         }
1734
1735         return $mailbox;
1736     }
1737
1738     /**
1739      * List sieve scripts
1740      *
1741      * @return array Scripts list
1742      */
1743     public function list_scripts()
1744     {
1745         if ($this->list !== null) {
1746             return $this->list;
1747         }
1748
1749         $this->list = $this->sieve->get_scripts();
1750
1751         // Handle active script(s) and list of scripts according to Kolab's KEP:14
1752         if ($this->rc->config->get('managesieve_kolab_master')) {
1753
1754             // Skip protected names
1755             foreach ((array)$this->list as $idx => $name) {
1756                 $_name = strtoupper($name);
1757                 if ($_name == 'MASTER')
1758                     $master_script = $name;
1759                 else if ($_name == 'MANAGEMENT')
1760                     $management_script = $name;
1761                 else if($_name == 'USER')
1762                     $user_script = $name;
1763                 else
1764                     continue;
1765
1766                 unset($this->list[$idx]);
1767             }
1768
1769             // get active script(s), read USER script
1770             if ($user_script) {
1771                 $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1772                 $filename_regex = '/'.preg_quote($extension, '/').'$/';
1773                 $_SESSION['managesieve_user_script'] = $user_script;
1774
1775                 $this->sieve->load($user_script);
1776
1777                 foreach ($this->sieve->script->as_array() as $rules) {
1778                     foreach ($rules['actions'] as $action) {
1779                         if ($action['type'] == 'include' && empty($action['global'])) {
1780                             $name = preg_replace($filename_regex, '', $action['target']);
1781                             $this->active[] = $name;
1782                         }
1783                     }
1784                 }
1785             }
1786             // create USER script if it doesn't exist
1787             else {
1788                 $content = "# USER Management Script\n"
1789                     ."#\n"
1790                     ."# This script includes the various active sieve scripts\n"
1791                     ."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n"
1792                     ."#\n"
1793                     ."# For more information, see http://wiki.kolab.org/KEP:14#USER\n"
1794                     ."#\n";
1795                 if ($this->sieve->save_script('USER', $content)) {
1796                     $_SESSION['managesieve_user_script'] = 'USER';
1797                     if (empty($this->master_file))
1798                         $this->sieve->activate('USER');
1799                 }
1800             }
1801         }
1802         else if (!empty($this->list)) {
1803             // Get active script name
1804             if ($active = $this->sieve->get_active()) {
1805                 $this->active = array($active);
1806             }
1807         }
1808
1809         return $this->list;
1810     }
1811
1812     /**
1813      * Removes sieve script
1814      *
1815      * @param string $name Script name
1816      *
1817      * @return bool True on success, False on failure
1818      */
1819     public function remove_script($name)
1820     {
1821         $result = $this->sieve->remove($name);
1822
1823         // Kolab's KEP:14
1824         if ($result && $this->rc->config->get('managesieve_kolab_master')) {
1825             $this->deactivate_script($name);
1826         }
1827
1828         return $result;
1829     }
1830
1831     /**
1832      * Activates sieve script
1833      *
1834      * @param string $name Script name
1835      *
1836      * @return bool True on success, False on failure
1837      */
1838     public function activate_script($name)
1839     {
1840         // Kolab's KEP:14
1841         if ($this->rc->config->get('managesieve_kolab_master')) {
1842             $extension   = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1843             $user_script = $_SESSION['managesieve_user_script'];
1844
1845             // if the script is not active...
1846             if ($user_script && ($key = array_search($name, $this->active)) === false) {
1847                 // ...rewrite USER file adding appropriate include command
1848                 if ($this->sieve->load($user_script)) {
1849                     $script = $this->sieve->script->as_array();
1850                     $list   = array();
1851                     $regexp = '/' . preg_quote($extension, '/') . '$/';
1852
1853                     // Create new include entry
1854                     $rule = array(
1855                         'actions' => array(
1856                             0 => array(
1857                                 'target'   => $name.$extension,
1858                                 'type'     => 'include',
1859                                 'personal' => true,
1860                     )));
1861
1862                     // get all active scripts for sorting
1863                     foreach ($script as $rid => $rules) {
1864                         foreach ($rules['actions'] as $aid => $action) {
1865                             if ($action['type'] == 'include' && empty($action['global'])) {
1866                                 $target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target'];
1867                                 $list[] = $target;
1868                             }
1869                         }
1870                     }
1871                     $list[] = $name;
1872
1873                     // Sort and find current script position
1874                     asort($list, SORT_LOCALE_STRING);
1875                     $list = array_values($list);
1876                     $index = array_search($name, $list);
1877
1878                     // add rule at the end of the script
1879                     if ($index === false || $index == count($list)-1) {
1880                         $this->sieve->script->add_rule($rule);
1881                     }
1882                     // add rule at index position
1883                     else {
1884                         $script2 = array();
1885                         foreach ($script as $rid => $rules) {
1886                             if ($rid == $index) {
1887                                 $script2[] = $rule;
1888                             }
1889                             $script2[] = $rules;
1890                         }
1891                         $this->sieve->script->content = $script2;
1892                     }
1893
1894                     $result = $this->sieve->save();
1895                     if ($result) {
1896                         $this->active[] = $name;
1897                     }
1898                 }
1899             }
1900         }
1901         else {
1902             $result = $this->sieve->activate($name);
1903             if ($result)
1904                 $this->active = array($name);
1905         }
1906
1907         return $result;
1908     }
1909
1910     /**
1911      * Deactivates sieve script
1912      *
1913      * @param string $name Script name
1914      *
1915      * @return bool True on success, False on failure
1916      */
1917     public function deactivate_script($name)
1918     {
1919         // Kolab's KEP:14
1920         if ($this->rc->config->get('managesieve_kolab_master')) {
1921             $extension   = $this->rc->config->get('managesieve_filename_extension', '.sieve');
1922             $user_script = $_SESSION['managesieve_user_script'];
1923
1924             // if the script is active...
1925             if ($user_script && ($key = array_search($name, $this->active)) !== false) {
1926                 // ...rewrite USER file removing appropriate include command
1927                 if ($this->sieve->load($user_script)) {
1928                     $script = $this->sieve->script->as_array();
1929                     $name   = $name.$extension;
1930
1931                     foreach ($script as $rid => $rules) {
1932                         foreach ($rules['actions'] as $aid => $action) {
1933                             if ($action['type'] == 'include' && empty($action['global'])
1934                                 && $action['target'] == $name
1935                             ) {
1936                                 break 2;
1937                             }
1938                         }
1939                     }
1940
1941                     // Entry found
1942                     if ($rid < count($script)) {
1943                         $this->sieve->script->delete_rule($rid);
1944                         $result = $this->sieve->save();
1945                         if ($result) {
1946                             unset($this->active[$key]);
1947                         }
1948                     }
1949                 }
1950             }
1951         }
1952         else {
1953             $result = $this->sieve->deactivate();
1954             if ($result)
1955                 $this->active = array();
1956         }
1957
1958         return $result;
1959     }
1960
1961     /**
1962      * Saves current script (adding some variables)
1963      */
1964     public function save_script($name = null)
1965     {
1966         // Kolab's KEP:14
1967         if ($this->rc->config->get('managesieve_kolab_master')) {
1968             $this->sieve->script->set_var('EDITOR', self::PROGNAME);
1969             $this->sieve->script->set_var('EDITOR_VERSION', self::VERSION);
1970         }
1971
1972         return $this->sieve->save($name);
1973     }
1974
1975     /**
1976      * Returns list of rules from the current script
1977      *
1978      * @return array List of rules
1979      */
1980     public function list_rules()
1981     {
1982         $result = array();
1983         $i      = 1;
1984
1985         foreach ($this->script as $idx => $filter) {
1986             if ($filter['type'] != 'if') {
1987                 continue;
1988             }
1989             $fname = $filter['name'] ? $filter['name'] : "#$i";
1990             $result[] = array(
1991                 'id'    => $idx,
1992                 'name'  => Q($fname),
1993                 'class' => $filter['disabled'] ? 'disabled' : '',
1994             );
1995             $i++;
1996         }
1997
1998         return $result;
1999     }
2000 }