]> git.donarmstrong.com Git - roundcube.git/blob - plugins/managesieve/managesieve.php
Imported Upstream version 0.5.2+dfsg
[roundcube.git] / plugins / managesieve / managesieve.php
1 <?php
2
3 /**
4  * Managesieve (Sieve Filters)
5  *
6  * Plugin that adds a possibility to manage Sieve filters in Thunderbird's style.
7  * It's clickable interface which operates on text scripts and communicates
8  * with server using managesieve protocol. Adds Filters tab in Settings.
9  *
10  * @version 3.0
11  * @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
12  *
13  * Configuration (see config.inc.php.dist)
14  *
15  * $Id: managesieve.php 4555 2011-02-16 10:48:11Z alec $
16  */
17
18 class managesieve extends rcube_plugin
19 {
20     public $task = 'settings';
21
22     private $rc;
23     private $sieve;
24     private $errors;
25     private $form;
26     private $tips = array();
27     private $script = array();
28     private $exts = array();
29     private $headers = array(
30         'subject'   => 'Subject',
31         'sender'    => 'From',
32         'recipient' => 'To',
33     );
34
35
36     function init()
37     {
38         // add Tab label/title
39         $this->add_texts('localization/', array('filters','managefilters'));
40
41         // register actions
42         $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
43         $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
44
45         // include main js script
46         $this->include_script('managesieve.js');
47     }
48
49     function managesieve_start()
50     {
51         $this->rc = rcmail::get_instance();
52         $this->load_config();
53
54         // register UI objects
55         $this->rc->output->add_handlers(array(
56             'filterslist'    => array($this, 'filters_list'),
57             'filtersetslist' => array($this, 'filtersets_list'),
58             'filterframe'    => array($this, 'filter_frame'),
59             'filterform'     => array($this, 'filter_form'),
60             'filtersetform'  => array($this, 'filterset_form'),
61         ));
62
63         require_once($this->home . '/lib/Net/Sieve.php');
64         require_once($this->home . '/lib/rcube_sieve.php');
65
66         $host = rcube_parse_host($this->rc->config->get('managesieve_host', 'localhost'));
67         $port = $this->rc->config->get('managesieve_port', 2000);
68
69         $host = rcube_idn_to_ascii($host);
70
71         // try to connect to managesieve server and to fetch the script
72         $this->sieve = new rcube_sieve($_SESSION['username'],
73             $this->rc->decrypt($_SESSION['password']), $host, $port,
74             $this->rc->config->get('managesieve_auth_type'),
75             $this->rc->config->get('managesieve_usetls', false),
76             $this->rc->config->get('managesieve_disabled_extensions'),
77             $this->rc->config->get('managesieve_debug', false),
78             $this->rc->config->get('managesieve_auth_cid'), 
79             $this->rc->config->get('managesieve_auth_pw')
80         );
81
82         if (!($error = $this->sieve->error())) {
83
84             $list = $this->sieve->get_scripts();
85             $active = $this->sieve->get_active();
86             $_SESSION['managesieve_active'] = $active;
87
88             if (!empty($_GET['_set'])) {
89                 $script_name = get_input_value('_set', RCUBE_INPUT_GET);
90             }
91             else if (!empty($_SESSION['managesieve_current'])) {
92                 $script_name = $_SESSION['managesieve_current'];
93             }
94             else {
95                 // get active script
96                 if ($active) {
97                     $script_name = $active;
98                 }
99                 else if ($list) {
100                     $script_name = $list[0];
101                 }
102                 // create a new (initial) script
103                 else {
104                     // if script not exists build default script contents
105                     $script_file = $this->rc->config->get('managesieve_default');
106                     $script_name = 'roundcube';
107                     if ($script_file && is_readable($script_file))
108                         $content = file_get_contents($script_file);
109
110                 // add script and set it active
111                 if ($this->sieve->save_script($script_name, $content))
112                     if ($this->sieve->activate($script_name))
113                         $_SESSION['managesieve_active'] = $script_name;
114                 }
115             }
116
117             if ($script_name)
118                 $this->sieve->load($script_name);
119
120             $error = $this->sieve->error();
121         }
122
123         // finally set script objects
124         if ($error) {
125             switch ($error) {
126                 case SIEVE_ERROR_CONNECTION:
127                 case SIEVE_ERROR_LOGIN:
128                     $this->rc->output->show_message('managesieve.filterconnerror', 'error');
129                     break;
130                 default:
131                     $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
132                     break;
133             }
134
135             raise_error(array('code' => 403, 'type' => 'php',
136                 'file' => __FILE__, 'line' => __LINE__,
137                 'message' => "Unable to connect to managesieve on $host:$port"), true, false);
138
139             // to disable 'Add filter' button set env variable
140             $this->rc->output->set_env('filterconnerror', true);
141             $this->script = array();
142         }
143         else {
144             $this->script = $this->sieve->script->as_array();
145             $this->exts = $this->sieve->get_extensions();
146             $this->rc->output->set_env('active_set', $_SESSION['managesieve_active']);
147             $_SESSION['managesieve_current'] = $this->sieve->current;
148         }
149
150         return $error;
151     }
152
153     function managesieve_actions()
154     {
155         // Init plugin and handle managesieve connection
156         $error = $this->managesieve_start();
157
158         // Handle user requests
159         if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
160             $fid = (int) get_input_value('_fid', RCUBE_INPUT_GET);
161
162             if ($action == 'up' && !$error) {
163                 if ($fid && isset($this->script[$fid]) && isset($this->script[$fid-1])) {
164                     if ($this->sieve->script->update_rule($fid, $this->script[$fid-1]) !== false
165                         && $this->sieve->script->update_rule($fid-1, $this->script[$fid]) !== false) {
166                         $result = $this->sieve->save();
167                     }
168
169                     if ($result) {
170 //                      $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
171                         $this->rc->output->command('managesieve_updatelist', 'up', '', $fid);
172                     } else
173                         $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
174                 }
175             }
176             else if ($action == 'down' && !$error) {
177                 if (isset($this->script[$fid]) && isset($this->script[$fid+1])) {
178                     if ($this->sieve->script->update_rule($fid, $this->script[$fid+1]) !== false
179                         && $this->sieve->script->update_rule($fid+1, $this->script[$fid]) !== false) {
180                         $result = $this->sieve->save();
181                     }
182
183                     if ($result === true) {
184 //                      $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
185                         $this->rc->output->command('managesieve_updatelist', 'down', '', $fid);
186                     } else {
187                         $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
188                     }
189                 }
190             }
191             else if ($action == 'delete' && !$error) {
192                 if (isset($this->script[$fid])) {
193                     if ($this->sieve->script->delete_rule($fid))
194                         $result = $this->sieve->save();
195
196                     if ($result === true) {
197                         $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
198                         $this->rc->output->command('managesieve_updatelist', 'delete', '', $fid);
199                     } else {
200                         $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
201                     }
202                 }
203             }
204             else if ($action == 'setact' && !$error) {
205                 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
206                 $result = $this->sieve->activate($script_name);
207
208                 if ($result === true) {
209                     $this->rc->output->set_env('active_set', $script_name);
210                     $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
211                     $this->rc->output->command('managesieve_reset');
212                     $_SESSION['managesieve_active'] = $script_name;
213                 } else {
214                     $this->rc->output->show_message('managesieve.setactivateerror', 'error');
215                 }
216             }
217             else if ($action == 'deact' && !$error) {
218                 $result = $this->sieve->deactivate();
219
220                 if ($result === true) {
221                     $this->rc->output->set_env('active_set', '');
222                     $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
223                     $this->rc->output->command('managesieve_reset');
224                     $_SESSION['managesieve_active'] = '';
225                 } else {
226                     $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
227                 }
228             }
229             else if ($action == 'setdel' && !$error) {
230                 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
231                 $result = $this->sieve->remove($script_name);
232
233                 if ($result === true) {
234                     $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
235                     $this->rc->output->command('managesieve_reload');
236                     $this->rc->session->remove('managesieve_current');
237                 } else {
238                     $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
239                 }
240             }
241             else if ($action == 'setget') {
242                 $script_name = get_input_value('_set', RCUBE_INPUT_GPC);
243                 $script = $this->sieve->get_script($script_name);
244
245                 if (PEAR::isError($script))
246                     exit;
247
248                 $browser = new rcube_browser;
249
250                 // send download headers
251                 header("Content-Type: application/octet-stream");
252                 header("Content-Length: ".strlen($script));
253
254                 if ($browser->ie)
255                     header("Content-Type: application/force-download");
256                 if ($browser->ie && $browser->ver < 7)
257                     $filename = rawurlencode(abbreviate_string($script_name, 55));
258                 else if ($browser->ie)
259                     $filename = rawurlencode($script_name);
260                 else
261                     $filename = addcslashes($script_name, '\\"');
262
263                 header("Content-Disposition: attachment; filename=\"$filename.txt\"");
264                 echo $script;
265                 exit;
266             }
267             elseif ($action == 'ruleadd') {
268                 $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
269                 $id = $this->genid();
270                 $content = $this->rule_div($fid, $id, false);
271
272                 $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
273             }
274             elseif ($action == 'actionadd') {
275                 $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
276                 $id = $this->genid();
277                 $content = $this->action_div($fid, $id, false);
278
279                 $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
280             }
281
282             $this->rc->output->send();
283         }
284
285         $this->managesieve_send();
286     }
287
288     function managesieve_save()
289     {
290         // Init plugin and handle managesieve connection
291         $error = $this->managesieve_start();
292
293         // filters set add action
294         if (!empty($_POST['_newset'])) {
295             $name = get_input_value('_name', RCUBE_INPUT_POST);
296             $copy = get_input_value('_copy', RCUBE_INPUT_POST);
297             $from = get_input_value('_from', RCUBE_INPUT_POST);
298
299             if (!$name)
300                 $error = 'managesieve.emptyname';
301             else if (mb_strlen($name)>128)
302                 $error = 'managesieve.nametoolong';
303             else if ($from == 'file') {
304                 // from file
305                 if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
306                     $file = file_get_contents($_FILES['_file']['tmp_name']);
307                     $file = preg_replace('/\r/', '', $file);
308                     // for security don't save script directly
309                     // check syntax before, like this...
310                     $this->sieve->load_script($file);
311                     if (!$this->sieve->save($name)) {
312                         $error = 'managesieve.setcreateerror';
313                     }
314                 }
315                 else {  // upload failed
316                     $err = $_FILES['_file']['error'];
317                     $error = true;
318
319                     if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
320                         $msg = rcube_label(array('name' => 'filesizeerror',
321                             'vars' => array('size' =>
322                                 show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
323                     }
324                     else {
325                         $error = 'fileuploaderror';
326                     }
327                 }
328             }
329             else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
330                 $error = 'managesieve.setcreateerror';
331             }
332
333             if (!$error) {
334                 $this->rc->output->show_message('managesieve.setcreated', 'confirmation');
335                 $this->rc->output->command('parent.managesieve_reload', $name);
336             } else if ($msg) {
337                 $this->rc->output->command('display_message', $msg, 'error');
338             } else {
339                 $this->rc->output->show_message($error, 'error');
340             }
341         }
342         // filter add/edit action
343         else if (isset($_POST['_name'])) {
344             $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
345             $fid  = trim(get_input_value('_fid', RCUBE_INPUT_POST));
346             $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
347
348             // and arrays
349             $headers = $_POST['_header'];
350             $cust_headers = $_POST['_custom_header'];
351             $ops = $_POST['_rule_op'];
352             $sizeops = $_POST['_rule_size_op'];
353             $sizeitems = $_POST['_rule_size_item'];
354             $sizetargets = $_POST['_rule_size_target'];
355             $targets = $_POST['_rule_target'];
356             $act_types = $_POST['_action_type'];
357             $mailboxes = $_POST['_action_mailbox'];
358             $act_targets = $_POST['_action_target'];
359             $area_targets = $_POST['_action_target_area'];
360             $reasons = $_POST['_action_reason'];
361             $addresses = $_POST['_action_addresses'];
362             $days = $_POST['_action_days'];
363
364             // we need a "hack" for radiobuttons
365             foreach ($sizeitems as $item)
366                 $items[] = $item;
367
368             $this->form['disabled'] = $_POST['_disabled'] ? true : false;
369             $this->form['join']     = $join=='allof' ? true : false;
370             $this->form['name']     = $name;
371             $this->form['tests']    = array();
372             $this->form['actions']  = array();
373
374             if ($name == '')
375                 $this->errors['name'] = $this->gettext('cannotbeempty');
376             else
377                 foreach($this->script as $idx => $rule)
378                     if($rule['name'] == $name && $idx != $fid) {
379                         $this->errors['name'] = $this->gettext('ruleexist');
380                         break;
381                     }
382
383             $i = 0;
384             // rules
385             if ($join == 'any') {
386                 $this->form['tests'][0]['test'] = 'true';
387             }
388             else {
389                 foreach ($headers as $idx => $header) {
390                     $header = $this->strip_value($header);
391                     $target = $this->strip_value($targets[$idx], true);
392                     $op     = $this->strip_value($ops[$idx]);
393
394                     // normal header
395                     if (in_array($header, $this->headers)) {
396                         if (preg_match('/^not/', $op))
397                             $this->form['tests'][$i]['not'] = true;
398                         $type = preg_replace('/^not/', '', $op);
399
400                         if ($type == 'exists') {
401                             $this->form['tests'][$i]['test'] = 'exists';
402                             $this->form['tests'][$i]['arg'] = $header;
403                         }
404                         else {
405                             $this->form['tests'][$i]['type'] = $type;
406                             $this->form['tests'][$i]['test'] = 'header';
407                             $this->form['tests'][$i]['arg1'] = $header;
408                             $this->form['tests'][$i]['arg2'] = $target;
409
410                             if ($target == '')
411                                 $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
412                             else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
413                                 $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
414                         }
415                     }
416                     else
417                         switch ($header) {
418                         case 'size':
419                             $sizeop     = $this->strip_value($sizeops[$idx]);
420                             $sizeitem   = $this->strip_value($items[$idx]);
421                             $sizetarget = $this->strip_value($sizetargets[$idx]);
422
423                             $this->form['tests'][$i]['test'] = 'size';
424                             $this->form['tests'][$i]['type'] = $sizeop;
425                             $this->form['tests'][$i]['arg']  = $sizetarget.$sizeitem;
426
427                             if ($sizetarget == '')
428                                 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
429                             else if (!preg_match('/^[0-9]+(K|M|G)*$/i', $sizetarget))
430                                 $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
431                             break;
432                         case '...':
433                             $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
434
435                             if (preg_match('/^not/', $op))
436                                 $this->form['tests'][$i]['not'] = true;
437                             $type = preg_replace('/^not/', '', $op);
438
439                             if ($cust_header == '')
440                                 $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
441                             else {
442                                 $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
443
444                                 if (!count($headers))
445                                     $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
446                                 else {
447                                     foreach ($headers as $hr)
448                                         if (!preg_match('/^[a-z0-9-]+$/i', $hr))
449                                             $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
450                                 }
451                             }
452
453                             if (empty($this->errors['tests'][$i]['header']))
454                                 $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
455
456                             if ($type == 'exists') {
457                                 $this->form['tests'][$i]['test'] = 'exists';
458                                 $this->form['tests'][$i]['arg']  = $cust_header;
459                             }
460                             else {
461                                 $this->form['tests'][$i]['test'] = 'header';
462                                 $this->form['tests'][$i]['type'] = $type;
463                                 $this->form['tests'][$i]['arg1'] = $cust_header;
464                                 $this->form['tests'][$i]['arg2'] = $target;
465
466                                 if ($target == '')
467                                     $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
468                                 else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
469                                     $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
470                             }
471                             break;
472                         }
473                     $i++;
474                 }
475             }
476
477             $i = 0;
478             // actions
479             foreach($act_types as $idx => $type) {
480                 $type   = $this->strip_value($type);
481                 $target = $this->strip_value($act_targets[$idx]);
482
483                 switch ($type) {
484                 case 'fileinto':
485                 case 'fileinto_copy':
486                     $mailbox = $this->strip_value($mailboxes[$idx]);
487                     $this->form['actions'][$i]['target'] = $mailbox;
488                     if ($type == 'fileinto_copy') {
489                         $type = 'fileinto';
490                         $this->form['actions'][$i]['copy'] = true;
491                     }
492                     break;
493                 case 'reject':
494                 case 'ereject':
495                     $target = $this->strip_value($area_targets[$idx]);
496                     $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
497
498  //                 if ($target == '')
499 //                      $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
500                     break;
501                 case 'redirect':
502                 case 'redirect_copy':
503                     $this->form['actions'][$i]['target'] = $target;
504
505                     if ($this->form['actions'][$i]['target'] == '')
506                         $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
507                     else if (!check_email($this->form['actions'][$i]['target']))
508                         $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
509
510                     if ($type == 'redirect_copy') {
511                         $type = 'redirect';
512                         $this->form['actions'][$i]['copy'] = true;
513                     }
514                     break;
515                 case 'vacation':
516                     $reason = $this->strip_value($reasons[$idx]);
517                     $this->form['actions'][$i]['reason']    = str_replace("\r\n", "\n", $reason);
518                     $this->form['actions'][$i]['days']      = $days[$idx];
519                     $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
520 // @TODO: vacation :subject, :mime, :from, :handle
521
522                     if ($this->form['actions'][$i]['addresses']) {
523                         foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
524                             $address = trim($address);
525                             if (!$address)
526                                 unset($this->form['actions'][$i]['addresses'][$aidx]);
527                             else if(!check_email($address)) {
528                                 $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
529                                 break;
530                             } else
531                                 $this->form['actions'][$i]['addresses'][$aidx] = $address;
532                         }
533                     }
534
535                     if ($this->form['actions'][$i]['reason'] == '')
536                         $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
537                     if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
538                         $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
539                     break;
540                 }
541
542                 $this->form['actions'][$i]['type'] = $type;
543                 $i++;
544             }
545
546             if (!$this->errors) {
547                 // zapis skryptu
548                 if (!isset($this->script[$fid])) {
549                     $fid = $this->sieve->script->add_rule($this->form);
550                     $new = true;
551                 } else
552                     $fid = $this->sieve->script->update_rule($fid, $this->form);
553
554                 if ($fid !== false)
555                     $save = $this->sieve->save();
556
557                 if ($save && $fid !== false) {
558                     $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
559                     $this->rc->output->add_script(
560                         sprintf("rcmail.managesieve_updatelist('%s', '%s', %d, %d);",
561                             isset($new) ? 'add' : 'update', Q($this->form['name']),
562                             $fid, $this->form['disabled']),
563                         'foot');
564                 }
565                 else {
566                     $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
567 //                  $this->rc->output->send();
568                 }
569             }
570         }
571
572         $this->managesieve_send();
573     }
574
575     private function managesieve_send()
576     {
577         // Handle form action
578         if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
579             if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
580                 $this->rc->output->send('managesieve.setedit');
581             }
582             else {
583                 $this->rc->output->send('managesieve.filteredit');
584             }
585         } else {
586             $this->rc->output->set_pagetitle($this->gettext('filters'));
587             $this->rc->output->send('managesieve.managesieve');
588         }
589     }
590
591     // return the filters list as HTML table
592     function filters_list($attrib)
593     {
594         // add id to message list table if not specified
595         if (!strlen($attrib['id']))
596             $attrib['id'] = 'rcmfilterslist';
597
598         // define list of cols to be displayed
599         $a_show_cols = array('managesieve.filtername');
600
601         foreach($this->script as $idx => $filter)
602             $result[] = array(
603                 'managesieve.filtername' => $filter['name'],
604                 'id' => $idx,
605                 'class' => $filter['disabled'] ? 'disabled' : '',
606             );
607
608         // create XHTML table
609         $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
610
611         // set client env
612         $this->rc->output->add_gui_object('filterslist', $attrib['id']);
613         $this->rc->output->include_script('list.js');
614
615         // add some labels to client
616         $this->rc->output->add_label('managesieve.filterdeleteconfirm');
617
618         return $out;
619     }
620
621     // return the filters list as <SELECT>
622     function filtersets_list($attrib)
623     {
624         // add id to message list table if not specified
625         if (!strlen($attrib['id']))
626             $attrib['id'] = 'rcmfiltersetslist';
627
628         $list = $this->sieve->get_scripts();
629         $active = $this->sieve->get_active();
630
631         $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
632             'onchange' => 'rcmail.managesieve_set()'));
633
634         if ($list) {
635             asort($list, SORT_LOCALE_STRING);
636
637             foreach ($list as $set)
638                 $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
639         }
640
641         $out = $select->show($this->sieve->current);
642
643         // set client env
644         $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
645         $this->rc->output->add_label(
646             'managesieve.setdeleteconfirm',
647             'managesieve.active',
648             'managesieve.filtersetact',
649             'managesieve.filtersetdeact'
650         );
651
652         return $out;
653     }
654
655     function filter_frame($attrib)
656     {
657         if (!$attrib['id'])
658             $attrib['id'] = 'rcmfilterframe';
659
660         $attrib['name'] = $attrib['id'];
661
662         $this->rc->output->set_env('contentframe', $attrib['name']);
663         $this->rc->output->set_env('blankpage', $attrib['src'] ?
664         $this->rc->output->abs_url($attrib['src']) : 'program/blank.gif');
665
666         return html::tag('iframe', $attrib);
667     }
668
669     function filterset_form($attrib)
670     {
671         if (!$attrib['id'])
672             $attrib['id'] = 'rcmfiltersetform';
673
674         $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
675
676         $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
677         $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
678         $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
679         $hiddenfields->add(array('name' => '_newset', 'value' => 1));
680
681         $out .= $hiddenfields->show();
682
683         $name     = get_input_value('_name', RCUBE_INPUT_POST);
684         $copy     = get_input_value('_copy', RCUBE_INPUT_POST);
685         $selected = get_input_value('_from', RCUBE_INPUT_POST);
686
687         // filter set name input
688         $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
689             'class' => ($this->errors['name'] ? 'error' : '')));
690
691         $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
692             '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
693
694         $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
695         $out .= '<input type="radio" id="from_none" name="_from" value="none"'
696             .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
697         $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
698
699         // filters set list
700         $list   = $this->sieve->get_scripts();
701         $active = $this->sieve->get_active();
702
703         $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
704
705         if (is_array($list)) {
706             asort($list, SORT_LOCALE_STRING);
707
708             foreach ($list as $set)
709                 $select->add($set . ($set == $active ? ' ('.$this->gettext('active').')' : ''), $set);
710
711             $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
712                 .($selected=='set' ? ' checked="checked"' : '').'></input>';
713             $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
714             $out .= $select->show($copy);
715         }
716
717         // script upload box
718         $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
719             'type' => 'file', 'class' => ($this->errors['name'] ? 'error' : '')));
720
721         $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
722             .($selected=='file' ? ' checked="checked"' : '').'></input>';
723         $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
724         $out .= $upload->show();
725         $out .= '</fieldset>';
726
727         $this->rc->output->add_gui_object('sieveform', 'filtersetform');
728
729         return $out;
730     }
731
732
733     function filter_form($attrib)
734     {
735         if (!$attrib['id'])
736             $attrib['id'] = 'rcmfilterform';
737
738         $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
739         $scr = isset($this->form) ? $this->form : $this->script[$fid];
740
741         $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
742         $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
743         $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
744         $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
745
746         $out = '<form name="filterform" action="./" method="post">'."\n";
747         $out .= $hiddenfields->show();
748
749         // 'any' flag
750         if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
751             $any = true;
752
753         // filter name input
754         $field_id = '_name';
755         $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
756             'class' => ($this->errors['name'] ? 'error' : '')));
757
758         if ($this->errors['name'])
759             $this->add_tip($field_id, $this->errors['name'], true);
760
761         if (isset($scr))
762             $input_name = $input_name->show($scr['name']);
763         else
764             $input_name = $input_name->show();
765
766         $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s<br /><br />\n",
767             $field_id, Q($this->gettext('filtername')), $input_name);
768
769         $out .= '<fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
770
771         // any, allof, anyof radio buttons
772         $field_id = '_allof';
773         $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
774             'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
775
776         if (isset($scr) && !$any)
777             $input_join = $input_join->show($scr['join'] ? 'allof' : '');
778         else
779             $input_join = $input_join->show();
780
781         $out .= sprintf("%s<label for=\"%s\">%s</label>&nbsp;\n",
782             $input_join, $field_id, Q($this->gettext('filterallof')));
783
784         $field_id = '_anyof';
785         $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
786             'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
787
788         if (isset($scr) && !$any)
789             $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
790         else
791             $input_join = $input_join->show('anyof'); // default
792
793         $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
794             $input_join, $field_id, Q($this->gettext('filteranyof')));
795
796         $field_id = '_any';
797         $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
798             'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
799
800         $input_join = $input_join->show($any ? 'any' : '');
801
802         $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
803             $input_join, $field_id, Q($this->gettext('filterany')));
804
805         $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
806
807         $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
808         for ($x=0; $x<$rows_num; $x++)
809             $out .= $this->rule_div($fid, $x);
810         $out .= "</div>\n";
811
812         $out .= "</fieldset>\n";
813
814         // actions
815         $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
816
817         $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
818
819         $out .= '<div id="actions">';
820         for ($x=0; $x<$rows_num; $x++)
821             $out .= $this->action_div($fid, $x);
822         $out .= "</div>\n";
823
824         $out .= "</fieldset>\n";
825
826         $this->print_tips();
827
828         if ($scr['disabled']) {
829             $this->rc->output->set_env('rule_disabled', true);
830         }
831         $this->rc->output->add_label(
832             'managesieve.ruledeleteconfirm',
833             'managesieve.actiondeleteconfirm'
834         );
835         $this->rc->output->add_gui_object('sieveform', 'filterform');
836
837         return $out;
838     }
839
840     function rule_div($fid, $id, $div=true)
841     {
842         $rule     = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
843         $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
844
845         $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
846
847         $out .= '<table><tr><td class="rowactions">';
848
849         // headers select
850         $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
851             'onchange' => 'header_select(' .$id .')'));
852         foreach($this->headers as $name => $val)
853             $select_header->add(Q($this->gettext($name)), Q($val));
854         $select_header->add(Q($this->gettext('size')), 'size');
855         $select_header->add(Q($this->gettext('...')), '...');
856
857         // TODO: list arguments
858
859         if ((isset($rule['test']) && $rule['test'] == 'header')
860             && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers))
861             $out .= $select_header->show($rule['arg1']);
862         else if ((isset($rule['test']) && $rule['test'] == 'exists')
863             && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers))
864             $out .= $select_header->show($rule['arg']);
865         else if (isset($rule['test']) && $rule['test'] == 'size')
866             $out .= $select_header->show('size');
867         else if (isset($rule['test']) && $rule['test'] != 'true')
868             $out .= $select_header->show('...');
869         else
870             $out .= $select_header->show();
871
872         $out .= '</td><td class="rowtargets">';
873
874         if ((isset($rule['test']) && $rule['test'] == 'header')
875             && (is_array($rule['arg1']) || !in_array($rule['arg1'], $this->headers)))
876             $custom = is_array($rule['arg1']) ? implode(', ', $rule['arg1']) : $rule['arg1'];
877         else if ((isset($rule['test']) && $rule['test'] == 'exists')
878             && (is_array($rule['arg']) || !in_array($rule['arg'], $this->headers)))
879             $custom = is_array($rule['arg']) ? implode(', ', $rule['arg']) : $rule['arg'];
880
881         $out .= '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
882             <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
883             . $this->error_class($id, 'test', 'header', 'custom_header_i')
884             .' value="' .Q($custom). '" size="20" />&nbsp;</div>' . "\n";
885
886         // matching type select (operator)
887         $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
888             'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
889             'onchange' => 'rule_op_select('.$id.')'));
890         $select_op->add(Q($this->gettext('filtercontains')), 'contains');
891         $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
892         $select_op->add(Q($this->gettext('filteris')), 'is');
893         $select_op->add(Q($this->gettext('filterisnot')), 'notis');
894         $select_op->add(Q($this->gettext('filterexists')), 'exists');
895         $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
896 //      $select_op->add(Q($this->gettext('filtermatches')), 'matches');
897 //      $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
898                 if (in_array('relational', $this->exts)) {
899                         $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
900                         $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
901                         $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
902                         $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
903                         $select_op->add(Q($this->gettext('countequals')), 'count-eq');
904                         $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
905                         $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
906                         $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
907                         $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
908                         $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
909                         $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
910                         $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
911                 }
912
913         // target input (TODO: lists)
914
915         if ($rule['test'] == 'header') {
916             $out .= $select_op->show(($rule['not'] ? 'not' : '').$rule['type']);
917             $target = $rule['arg2'];
918         }
919         else if ($rule['test'] == 'size') {
920             $out .= $select_op->show();
921             if (preg_match('/^([0-9]+)(K|M|G)*$/', $rule['arg'], $matches)) {
922                 $sizetarget = $matches[1];
923                 $sizeitem = $matches[2];
924             }
925         }
926         else {
927             $out .= $select_op->show(($rule['not'] ? 'not' : '').$rule['test']);
928             $target = '';
929         }
930
931         $out .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
932             value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
933             . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
934
935         $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
936         $select_size_op->add(Q($this->gettext('filterunder')), 'under');
937         $select_size_op->add(Q($this->gettext('filterover')), 'over');
938
939         $out .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
940         $out .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
941         $out .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" ' 
942             . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
943             <input type="radio" name="_rule_size_item['.$id.']" value=""'
944                 . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
945             <input type="radio" name="_rule_size_item['.$id.']" value="K"'
946                 . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
947             <input type="radio" name="_rule_size_item['.$id.']" value="M"'
948                 . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
949             <input type="radio" name="_rule_size_item['.$id.']" value="G"'
950                 . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
951         $out .= '</div>';
952         $out .= '</td>';
953
954         // add/del buttons
955         $out .= '<td class="rowbuttons">';
956         $out .= '<input type="button" id="ruleadd' . $id .'" value="'. Q($this->gettext('add')). '"
957             onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button" /> ';
958         $out .= '<input type="button" id="ruledel' . $id .'" value="'. Q($this->gettext('del')). '"
959             onclick="rcmail.managesieve_ruledel(' . $id .')" class="button' . ($rows_num<2 ? ' disabled' : '') .'"'
960             . ($rows_num<2 ? ' disabled="disabled"' : '') .' />';
961         $out .= '</td></tr></table>';
962
963         $out .= $div ? "</div>\n" : '';
964
965         return $out;
966     }
967
968     function action_div($fid, $id, $div=true)
969     {
970         $action   = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
971         $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
972
973         $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
974
975         $out .= '<table><tr><td class="rowactions">';
976
977         // action select
978         $select_action = new html_select(array('name' => "_action_type[]", 'id' => 'action_type'.$id,
979             'onchange' => 'action_type_select(' .$id .')'));
980         if (in_array('fileinto', $this->exts))
981             $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
982         if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
983             $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
984         $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
985         if (in_array('copy', $this->exts))
986             $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
987         if (in_array('reject', $this->exts))
988             $select_action->add(Q($this->gettext('messagediscard')), 'reject');
989         else if (in_array('ereject', $this->exts))
990             $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
991         if (in_array('vacation', $this->exts))
992             $select_action->add(Q($this->gettext('messagereply')), 'vacation');
993         $select_action->add(Q($this->gettext('messagedelete')), 'discard');
994         $select_action->add(Q($this->gettext('rulestop')), 'stop');
995
996         $select_type = $action['type'];
997         if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
998             $select_type .= '_copy';
999         }
1000
1001         $out .= $select_action->show($select_type);
1002         $out .= '</td>';
1003
1004         // actions target inputs
1005         $out .= '<td class="rowtargets">';
1006         // shared targets
1007         $out .= '<input type="text" name="_action_target[]" id="action_target' .$id. '" '
1008             .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="40" '
1009             .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
1010             . $this->error_class($id, 'action', 'target', 'action_target') .' />';
1011         $out .= '<textarea name="_action_target_area[]" id="action_target_area' .$id. '" '
1012             .'rows="3" cols="40" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
1013             .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
1014             . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
1015             . "</textarea>\n";
1016
1017         // vacation
1018         $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
1019         $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
1020             .'<textarea name="_action_reason[]" id="action_reason' .$id. '" '
1021             .'rows="3" cols="40" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
1022             . Q($action['reason'], 'strict', false) . "</textarea>\n";
1023         $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
1024             .'<input type="text" name="_action_addresses[]" id="action_addr'.$id.'" '
1025             .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="40" '
1026             . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
1027         $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
1028             .'<input type="text" name="_action_days[]" id="action_days'.$id.'" '
1029             .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
1030             . $this->error_class($id, 'action', 'days', 'action_days') .' />';
1031         $out .= '</div>';
1032
1033         // mailbox select
1034         $out .= '<select id="action_mailbox' .$id. '" name="_action_mailbox[]" style="display:'
1035             .(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none'). '">';
1036
1037         $this->rc->imap_connect();
1038
1039         $a_folders = $this->rc->imap->list_mailboxes();
1040         $delimiter = $this->rc->imap->get_hierarchy_delimiter();
1041
1042         // set mbox encoding
1043         $mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
1044
1045         if ($action['type'] == 'fileinto')
1046             $mailbox = $action['target'];
1047         else
1048             $mailbox = '';
1049
1050         foreach ($a_folders as $folder) {
1051             $utf7folder = $this->rc->imap->mod_mailbox($folder);
1052             $names = explode($delimiter, rcube_charset_convert($folder, 'UTF7-IMAP'));
1053             $name  = $names[sizeof($names)-1];
1054
1055             if ($replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter'))
1056                 $utf7folder = str_replace($delimiter, $replace_delimiter, $utf7folder);
1057
1058             // convert to Sieve implementation encoding
1059             $utf7folder = $this->mbox_encode($utf7folder, $mbox_encoding);
1060
1061             if ($folder_class = rcmail_folder_classname($name))
1062                 $foldername = $this->gettext($folder_class);
1063             else
1064                 $foldername = $name;
1065
1066             $out .= sprintf('<option value="%s"%s>%s%s</option>'."\n",
1067                 htmlspecialchars($utf7folder),
1068                 ($mailbox == $utf7folder ? ' selected="selected"' : ''),
1069                 str_repeat('&nbsp;', 4 * (sizeof($names)-1)),
1070                 Q(abbreviate_string($foldername, 40 - (2 * sizeof($names)-1))));
1071         }
1072         $out .= '</select>';
1073         $out .= '</td>';
1074
1075         // add/del buttons
1076         $out .= '<td class="rowbuttons">';
1077         $out .= '<input type="button" id="actionadd' . $id .'" value="'. Q($this->gettext('add')). '"
1078             onclick="rcmail.managesieve_actionadd(' . $id .')" class="button" /> ';
1079         $out .= '<input type="button" id="actiondel' . $id .'" value="'. Q($this->gettext('del')). '"
1080             onclick="rcmail.managesieve_actiondel(' . $id .')" class="button' . ($rows_num<2 ? ' disabled' : '') .'"'
1081             . ($rows_num<2 ? ' disabled="disabled"' : '') .' />';
1082         $out .= '</td>';
1083
1084         $out .= '</tr></table>';
1085
1086         $out .= $div ? "</div>\n" : '';
1087
1088         return $out;
1089     }
1090
1091     private function genid()
1092     {
1093         $result = intval(rcube_timer());
1094         return $result;
1095     }
1096
1097     private function strip_value($str, $allow_html=false)
1098     {
1099         if (!$allow_html)
1100             $str = strip_tags($str);
1101
1102         return trim($str);
1103     }
1104
1105     private function error_class($id, $type, $target, $elem_prefix='')
1106     {
1107         // TODO: tooltips
1108         if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
1109             ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
1110         ) {
1111             $this->add_tip($elem_prefix.$id, $str, true);
1112             return ' class="error"';
1113         }
1114
1115         return '';
1116     }
1117
1118     private function mbox_encode($text, $encoding)
1119     {
1120         return rcube_charset_convert($text, 'UTF7-IMAP', $encoding);
1121     }
1122
1123     private function add_tip($id, $str, $error=false)
1124     {
1125         if ($error)
1126             $str = html::span('sieve error', $str);
1127
1128         $this->tips[] = array($id, $str);
1129     }
1130
1131     private function print_tips()
1132     {
1133         if (empty($this->tips))
1134             return;
1135
1136         $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
1137         $this->rc->output->add_script($script, 'foot');
1138     }
1139
1140 }