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