Aleksander Machniak
2015-08-07 1b39d9a6c744a393e7930c2493cc2ddc9c9e95bf
commit | author | age
50a57e 1 <?php
AM 2
3 /**
4  * Managesieve Vacation Engine
5  *
6  * Engine part of Managesieve plugin implementing UI and backend access.
7  *
8  * Copyright (C) 2011-2014, Kolab Systems AG
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see http://www.gnu.org/licenses/.
22  */
23
24 class rcube_sieve_vacation extends rcube_sieve_engine
25 {
613f96 26     protected $error;
dc9cc7 27     protected $script_name;
AM 28     protected $vacation = array();
613f96 29
50a57e 30     function actions()
AM 31     {
32         $error = $this->start('vacation');
33
34         // find current vacation rule
35         if (!$error) {
36             $this->vacation_rule();
37             $this->vacation_post();
38         }
dc9cc7 39
50a57e 40         $this->plugin->add_label('vacation.saving');
AM 41         $this->rc->output->add_handlers(array(
42             'vacationform' => array($this, 'vacation_form'),
43         ));
44
45         $this->rc->output->set_pagetitle($this->plugin->gettext('vacation'));
46         $this->rc->output->send('managesieve.vacation');
47     }
48
dc9cc7 49     /**
AM 50      * Find and load sieve script with/for vacation rule
51      *
1b39d9 52      * @param string $script_name Optional script name
AM 53      *
dc9cc7 54      * @return int Connection status: 0 on success, >0 on failure
AM 55      */
1b39d9 56     protected function load_script($script_name = null)
dc9cc7 57     {
AM 58         if ($this->script_name !== null) {
59             return 0;
60         }
61
62         $list     = $this->list_scripts();
63         $master   = $this->rc->config->get('managesieve_kolab_master');
64         $included = array();
65
66         $this->script_name = false;
67
68         // first try the active script(s)...
69         if (!empty($this->active)) {
70             // Note: there can be more than one active script on KEP:14-enabled server
71             foreach ($this->active as $script) {
72                 if ($this->sieve->load($script)) {
73                     foreach ($this->sieve->script->as_array() as $rule) {
74                         if (!empty($rule['actions'])) {
75                             if ($rule['actions'][0]['type'] == 'vacation') {
76                                 $this->script_name = $script;
77                                 return 0;
78                             }
79                             else if (empty($master) && $rule['actions'][0]['type'] == 'include') {
80                                 $included[] = $rule['actions'][0]['target'];
81                             }
82                         }
83                     }
84                 }
85             }
86
87             // ...else try scripts included in active script (not for KEP:14)
88             foreach ($included as $script) {
89                 if ($this->sieve->load($script)) {
90                     foreach ($this->sieve->script->as_array() as $rule) {
91                         if (!empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') {
92                             $this->script_name = $script;
93                             return 0;
94                         }
95                     }
96                 }
97             }
98         }
99
100         // try all other scripts
101         if (!empty($list)) {
102             // else try included scripts
103             foreach (array_diff($list, $included, $this->active) as $script) {
104                 if ($this->sieve->load($script)) {
105                     foreach ($this->sieve->script->as_array() as $rule) {
106                         if (!empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') {
107                             $this->script_name = $script;
108                             return 0;
109                         }
110                     }
111                 }
112             }
113
114             // none of the scripts contains existing vacation rule
115             // use any (first) active or just existing script (in that order)
116             if (!empty($this->active)) {
117                 $this->sieve->load($this->script_name = $this->active[0]);
118             }
119             else {
120                 $this->sieve->load($this->script_name = $list[0]);
121             }
122         }
123
124         return $this->sieve->error();
125     }
126
50a57e 127     private function vacation_rule()
AM 128     {
04009e 129         if ($this->script_name === false || $this->script_name === null || !$this->sieve->load($this->script_name)) {
50a57e 130             return;
AM 131         }
132
dc9cc7 133         $list   = array();
AM 134         $active = in_array($this->script_name, $this->active);
50a57e 135
AM 136         // find (first) vacation rule
137         foreach ($this->script as $idx => $rule) {
138             if (empty($this->vacation) && !empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') {
c883f6 139                 foreach ($rule['actions'] as $act) {
AM 140                     if ($act['type'] == 'discard' || $act['type'] == 'keep') {
141                         $action = $act['type'];
142                     }
143                     else if ($act['type'] == 'redirect') {
144                         $action = $act['copy'] ? 'copy' : 'redirect';
145                         $target = $act['target'];
146                     }
147                 }
148
50a57e 149                 $this->vacation = array_merge($rule['actions'][0], array(
AM 150                         'idx'      => $idx,
dc9cc7 151                         'disabled' => $rule['disabled'] || !$active,
50a57e 152                         'name'     => $rule['name'],
AM 153                         'tests'    => $rule['tests'],
c883f6 154                         'action'   => $action ?: 'keep',
AM 155                         'target'   => $target,
50a57e 156                 ));
AM 157             }
dc9cc7 158             else if ($active) {
50a57e 159                 $list[$idx] = $rule['name'];
AM 160             }
161         }
162
163         $this->vacation['list'] = $list;
164     }
165
166     private function vacation_post()
167     {
168         if (empty($_POST)) {
169             return;
170         }
171
147530 172         $date_extension  = in_array('date', $this->exts);
JL 173         $regex_extension = in_array('regex', $this->exts);
174
581b6b 175         // set user's timezone
AM 176         try {
177             $timezone = new DateTimeZone($this->rc->config->get('timezone', 'GMT'));
178         }
179         catch (Exception $e) {
180             $timezone = new DateTimeZone('GMT');
181         }
182
50a57e 183         $status        = rcube_utils::get_input_value('vacation_status', rcube_utils::INPUT_POST);
AM 184         $subject       = rcube_utils::get_input_value('vacation_subject', rcube_utils::INPUT_POST, true);
185         $reason        = rcube_utils::get_input_value('vacation_reason', rcube_utils::INPUT_POST, true);
186         $addresses     = rcube_utils::get_input_value('vacation_addresses', rcube_utils::INPUT_POST, true);
187         $interval      = rcube_utils::get_input_value('vacation_interval', rcube_utils::INPUT_POST);
188         $interval_type = rcube_utils::get_input_value('vacation_interval_type', rcube_utils::INPUT_POST);
189         $date_from     = rcube_utils::get_input_value('vacation_datefrom', rcube_utils::INPUT_POST);
190         $date_to       = rcube_utils::get_input_value('vacation_dateto', rcube_utils::INPUT_POST);
581b6b 191         $time_from     = rcube_utils::get_input_value('vacation_timefrom', rcube_utils::INPUT_POST);
AM 192         $time_to       = rcube_utils::get_input_value('vacation_timeto', rcube_utils::INPUT_POST);
50a57e 193         $after         = rcube_utils::get_input_value('vacation_after', rcube_utils::INPUT_POST);
c883f6 194         $action        = rcube_utils::get_input_value('vacation_action', rcube_utils::INPUT_POST);
AM 195         $target        = rcube_utils::get_input_value('action_target', rcube_utils::INPUT_POST, true);
196         $target_domain = rcube_utils::get_input_value('action_domain', rcube_utils::INPUT_POST);
50a57e 197
AM 198         $interval_type                   = $interval_type == 'seconds' ? 'seconds' : 'days';
199         $vacation_action['type']         = 'vacation';
200         $vacation_action['reason']       = $this->strip_value(str_replace("\r\n", "\n", $reason));
201         $vacation_action['subject']      = $subject;
202         $vacation_action['addresses']    = $addresses;
203         $vacation_action[$interval_type] = $interval;
204         $vacation_tests                  = (array) $this->vacation['tests'];
205
206         foreach ((array) $vacation_action['addresses'] as $aidx => $address) {
207             $vacation_action['addresses'][$aidx] = $address = trim($address);
208
209             if (empty($address)) {
210                 unset($vacation_action['addresses'][$aidx]);
211             }
212             else if (!rcube_utils::check_email($address)) {
213                 $error = 'noemailwarning';
214                 break;
215             }
216         }
217
218         if ($vacation_action['reason'] == '') {
9828c1 219             $error = 'managesieve.emptyvacationbody';
50a57e 220         }
9828c1 221
50a57e 222         if ($vacation_action[$interval_type] && !preg_match('/^[0-9]+$/', $vacation_action[$interval_type])) {
AM 223             $error = 'managesieve.forbiddenchars';
224         }
225
f72815 226         // find and remove existing date/regex/true rules
AM 227         foreach ((array) $vacation_tests as $idx => $t) {
581b6b 228             if ($t['test'] == 'currentdate' || $t['test'] == 'true'
f72815 229                 || ($t['test'] == 'header' && $t['type'] == 'regex' && $t['arg1'] == 'received')
AM 230             ) {
231                 unset($vacation_tests[$idx]);
232             }
233         }
234
147530 235         if ($date_extension) {
JL 236             foreach (array('date_from', 'date_to') as $var) {
581b6b 237                 $time = ${str_replace('date', 'time', $var)};
AM 238                 $date = trim($$var . ' ' . $time);
239
240                 if ($date && ($dt = rcube_utils::anytodatetime($date, $timezone))) {
241                     if ($time) {
242                         $vacation_tests[] = array(
243                             'test' => 'currentdate',
5a6415 244                             'part' => 'iso8601',
581b6b 245                             'type' => 'value-' . ($var == 'date_from' ? 'ge' : 'le'),
AM 246                             'zone' => $dt->format('O'),
5a6415 247                             'arg'  => str_replace('+00:00', 'Z', strtoupper($dt->format('c'))),
AM 248                         );
249                     }
250                     else {
251                         $vacation_tests[] = array(
252                             'test' => 'currentdate',
253                             'part' => 'date',
254                             'type' => 'value-' . ($var == 'date_from' ? 'ge' : 'le'),
255                             'zone' => $dt->format('O'),
256                             'arg'  => $dt->format('Y-m-d'),
581b6b 257                         );
AM 258                     }
147530 259                 }
JL 260             }
261         }
319751 262         else if ($regex_extension) {
AM 263             // Add date range rules if range specified
147530 264             if ($date_from && $date_to) {
f72815 265                 if ($tests = self::build_regexp_tests($date_from, $date_to, $error)) {
AM 266                     $vacation_tests = array_merge($vacation_tests, $tests);
147530 267                 }
50a57e 268             }
AM 269         }
270
c883f6 271         if ($action == 'redirect' || $action == 'copy') {
AM 272             if ($target_domain) {
273                 $target .= '@' . $target_domain;
274             }
275
276             if (empty($target) || !rcube_utils::check_email($target)) {
277                 $error = 'noemailwarning';
278             }
279         }
280
50a57e 281         if (empty($vacation_tests)) {
AM 282             $vacation_tests = $this->rc->config->get('managesieve_vacation_test', array(array('test' => 'true')));
283         }
284
285         if (!$error) {
286             $rule               = $this->vacation;
287             $rule['type']       = 'if';
288             $rule['name']       = $rule['name'] ?: $this->plugin->gettext('vacation');
289             $rule['disabled']   = $status == 'off';
290             $rule['tests']      = $vacation_tests;
319751 291             $rule['join']       = $date_extension ? count($vacation_tests) > 1 : false;
c883f6 292             $rule['actions']    = array($vacation_action);
dc9cc7 293             $rule['after']      = $after;
c883f6 294
AM 295             if ($action && $action != 'keep') {
296                 $rule['actions'][] = array(
297                     'type'   => $action == 'discard' ? 'discard' : 'redirect',
298                     'copy'   => $action == 'copy',
299                     'target' => $action != 'discard' ? $target : '',
300                 );
301             }
50a57e 302
dc9cc7 303             if ($this->save_vacation_script($rule)) {
50a57e 304                 $this->rc->output->show_message('managesieve.vacationsaved', 'confirmation');
AM 305                 $this->rc->output->send();
306             }
307         }
308
309         $this->rc->output->show_message($error ? $error : 'managesieve.saveerror', 'error');
310         $this->rc->output->send();
311     }
312
313     /**
314      * Independent vacation form
315      */
316     public function vacation_form($attrib)
317     {
318         // check supported extensions
319         $date_extension    = in_array('date', $this->exts);
147530 320         $regex_extension   = in_array('regex', $this->exts);
50a57e 321         $seconds_extension = in_array('vacation-seconds', $this->exts);
AM 322
323         // build FORM tag
324         $form_id = !empty($attrib['id']) ? $attrib['id'] : 'form';
325         $out     = $this->rc->output->request_form(array(
326             'id'      => $form_id,
327             'name'    => $form_id,
328             'method'  => 'post',
329             'task'    => 'settings',
330             'action'  => 'plugin.managesieve-vacation',
331             'noclose' => true
332             ) + $attrib);
333
9c38c5 334         $auto_addr = $this->rc->config->get('managesieve_vacation_addresses_init');
AM 335         $addresses = !$auto_addr || count($this->vacation) > 1 ? (array) $this->vacation['addresses'] : $this->user_emails();
336
50a57e 337         // form elements
13b33d 338         $subject   = new html_inputfield(array('name' => 'vacation_subject', 'id' => 'vacation_subject', 'size' => 50));
AM 339         $reason    = new html_textarea(array('name' => 'vacation_reason', 'id' => 'vacation_reason', 'cols' => 60, 'rows' => 8));
340         $interval  = new html_inputfield(array('name' => 'vacation_interval', 'id' => 'vacation_interval', 'size' => 5));
341         $addresses = '<textarea name="vacation_addresses" id="vacation_addresses" data-type="list" data-size="30" style="display: none">'
9c38c5 342             . rcube::Q(implode("\n", $addresses), 'strict', false) . '</textarea>';
13b33d 343         $status    = new html_select(array('name' => 'vacation_status', 'id' => 'vacation_status'));
c883f6 344         $action    = new html_select(array('name' => 'vacation_action', 'id' => 'vacation_action', 'onchange' => 'vacation_action_select()'));
9c38c5 345         $addresses_link = new html_inputfield(array(
AM 346                 'type'    => 'button',
347                 'href'    => '#',
348                 'class' => 'button',
349                 'onclick' => rcmail_output::JS_OBJECT_NAME . '.managesieve_vacation_addresses()'
350             ));
50a57e 351
AM 352         $status->add($this->plugin->gettext('vacation.on'), 'on');
353         $status->add($this->plugin->gettext('vacation.off'), 'off');
c883f6 354
AM 355         $action->add($this->plugin->gettext('vacation.keep'), 'keep');
356         $action->add($this->plugin->gettext('vacation.discard'), 'discard');
357         $action->add($this->plugin->gettext('vacation.redirect'), 'redirect');
358         if (in_array('copy', $this->exts)) {
359             $action->add($this->plugin->gettext('vacation.copy'), 'copy');
360         }
50a57e 361
AM 362         if ($this->rc->config->get('managesieve_vacation') != 2 && count($this->vacation['list'])) {
13b33d 363             $after = new html_select(array('name' => 'vacation_after', 'id' => 'vacation_after'));
50a57e 364
AM 365             $after->add('', '');
366             foreach ($this->vacation['list'] as $idx => $rule) {
367                 $after->add($rule, $idx);
368             }
369         }
370
fa8577 371         $interval_txt = $interval->show(self::vacation_interval($this->vacation));
50a57e 372         if ($seconds_extension) {
AM 373             $interval_select = new html_select(array('name' => 'vacation_interval_type'));
374             $interval_select->add($this->plugin->gettext('days'), 'days');
375             $interval_select->add($this->plugin->gettext('seconds'), 'seconds');
376             $interval_txt .= '&nbsp;' . $interval_select->show(isset($this->vacation['seconds']) ? 'seconds' : 'days');
377         }
378         else {
379             $interval_txt .= '&nbsp;' . $this->plugin->gettext('days');
380         }
381
147530 382         if ($date_extension || $regex_extension) {
13b33d 383             $date_from   = new html_inputfield(array('name' => 'vacation_datefrom', 'id' => 'vacation_datefrom', 'class' => 'datepicker', 'size' => 12));
581b6b 384             $date_to     = new html_inputfield(array('name' => 'vacation_dateto', 'id' => 'vacation_dateto', 'class' => 'datepicker', 'size' => 12));
50a57e 385             $date_format = $this->rc->config->get('date_format', 'Y-m-d');
147530 386         }
50a57e 387
147530 388         if ($date_extension) {
581b6b 389             $time_from   = new html_inputfield(array('name' => 'vacation_timefrom', 'id' => 'vacation_timefrom', 'size' => 6));
AM 390             $time_to     = new html_inputfield(array('name' => 'vacation_timeto', 'id' => 'vacation_timeto', 'size' => 6));
391             $time_format = $this->rc->config->get('time_format', 'H:i');
392             $date_value  = array();
393
50a57e 394             foreach ((array) $this->vacation['tests'] as $test) {
5a6415 395                 if ($test['test'] == 'currentdate') {
581b6b 396                     $idx = $test['type'] == 'value-ge' ? 'from' : 'to';
5a6415 397
AM 398                     if ($test['part'] == 'date') {
399                         $date_value[$idx]['date'] = $test['arg'];
400                     }
401                     else if ($test['part'] == 'iso8601') {
402                         $date_value[$idx]['datetime'] = $test['arg'];
581b6b 403                     }
AM 404                 }
405             }
406
407             foreach ($date_value as $idx => $value) {
5a6415 408                 $date = $value['datetime'] ?: $value['date'];
AM 409                 $date_value[$idx] = $this->rc->format_date($date, $date_format, false);
581b6b 410
5a6415 411                 if (!empty($value['datetime'])) {
AM 412                     $date_value['time_' . $idx] = $this->rc->format_date($date, $time_format, true);
50a57e 413                 }
AM 414             }
147530 415         }
319751 416         else if ($regex_extension) {
147530 417             // Sieve 'date' extension not available, read start/end from RegEx based rules instead
f72815 418             if ($date_tests = self::parse_regexp_tests($this->vacation['tests'])) {
AM 419                 $date_value['from'] = $this->rc->format_date($date_tests['from'], $date_format, false);
420                 $date_value['to']   = $this->rc->format_date($date_tests['to'], $date_format, false);
147530 421             }
50a57e 422         }
AM 423
c883f6 424         // force domain selection in redirect email input
AM 425         $domains  = (array) $this->rc->config->get('managesieve_domains');
426         $redirect = $this->vacation['action'] == 'redirect' || $this->vacation['action'] == 'copy';
427
428         if (!empty($domains)) {
429             sort($domains);
430
431             $domain_select = new html_select(array('name' => 'action_domain', 'id' => 'action_domain'));
432             $domain_select->add(array_combine($domains, $domains));
433
434             if ($redirect && $this->vacation['target']) {
435                 $parts = explode('@', $this->vacation['target']);
436                 if (!empty($parts)) {
437                     $this->vacation['domain'] = array_pop($parts);
438                     $this->vacation['target'] = implode('@', $parts);
439                 }
440             }
441         }
442
443         // redirect target
444         $action_target = ' <span id="action_target_span" style="display:' . ($redirect ? 'inline' : 'none') . '">'
445             . '<input type="text" name="action_target" id="action_target"'
446             . ' value="' .($redirect ? rcube::Q($this->vacation['target'], 'strict', false) : '') . '"'
447             . (!empty($domains) ? ' size="20"' : ' size="35"') . '/>'
448             . (!empty($domains) ? ' @ ' . $domain_select->show($this->vacation['domain']) : '')
449             . '</span>';
450
50a57e 451         // Message tab
AM 452         $table = new html_table(array('cols' => 2));
453
454         $table->add('title', html::label('vacation_subject', $this->plugin->gettext('vacation.subject')));
455         $table->add(null, $subject->show($this->vacation['subject']));
456         $table->add('title', html::label('vacation_reason', $this->plugin->gettext('vacation.body')));
457         $table->add(null, $reason->show($this->vacation['reason']));
458
147530 459         if ($date_extension || $regex_extension) {
581b6b 460             $table->add('title', html::label('vacation_datefrom', $this->plugin->gettext('vacation.start')));
AM 461             $table->add(null, $date_from->show($date_value['from']) . ($time_from ? ' ' . $time_from->show($date_value['time_from']) : ''));
462             $table->add('title', html::label('vacation_dateto', $this->plugin->gettext('vacation.end')));
463             $table->add(null, $date_to->show($date_value['to']) . ($time_to ? ' ' . $time_to->show($date_value['time_to']) : ''));
50a57e 464         }
AM 465
466         $table->add('title', html::label('vacation_status', $this->plugin->gettext('vacation.status')));
9828c1 467         $table->add(null, $status->show(!isset($this->vacation['disabled']) || $this->vacation['disabled'] ? 'off' : 'on'));
50a57e 468
AM 469         $out .= html::tag('fieldset', $class, html::tag('legend', null, $this->plugin->gettext('vacation.reply')) . $table->show($attrib));
470
471         // Advanced tab
472         $table = new html_table(array('cols' => 2));
473
13b33d 474         $table->add('title', html::label('vacation_addresses', $this->plugin->gettext('vacation.addresses')));
9c38c5 475         $table->add(null, $addresses . $addresses_link->show($this->plugin->gettext('filladdresses')));
13b33d 476         $table->add('title', html::label('vacation_interval', $this->plugin->gettext('vacation.interval')));
50a57e 477         $table->add(null, $interval_txt);
c883f6 478
50a57e 479         if ($after) {
13b33d 480             $table->add('title', html::label('vacation_after', $this->plugin->gettext('vacation.after')));
50a57e 481             $table->add(null, $after->show($this->vacation['idx'] - 1));
AM 482         }
483
c883f6 484         $table->add('title', html::label('vacation_action', $this->plugin->gettext('vacation.action')));
AM 485         $table->add('vacation', $action->show($this->vacation['action']) . $action_target);
486
50a57e 487         $out .= html::tag('fieldset', $class, html::tag('legend', null, $this->plugin->gettext('vacation.advanced')) . $table->show($attrib));
AM 488
489         $out .= '</form>';
490
491         $this->rc->output->add_gui_object('sieveform', $form_id);
492
581b6b 493         if ($time_format) {
AM 494             $this->rc->output->set_env('time_format', $time_format);
495         }
496
50a57e 497         return $out;
AM 498     }
f72815 499
AM 500     public static function build_regexp_tests($date_from, $date_to, &$error)
501     {
502         $tests    = array();
503         $dt_from  = rcube_utils::anytodatetime($date_from);
504         $dt_to    = rcube_utils::anytodatetime($date_to);
505         $interval = $dt_from->diff($dt_to);
506
507         if ($interval->invert || $interval->days > 365) {
508             $error = 'managesieve.invaliddateformat';
509             return;
510         }
511
512         $dt_i     = $dt_from;
513         $interval = new DateInterval('P1D');
514         $matchexp = '';
515
516         while (!$dt_i->diff($dt_to)->invert) {
517             $days     = (int) $dt_i->format('d');
518             $matchexp .= $days < 10 ? "[ 0]$days" : $days;
519
520             if ($days == $dt_i->format('t') || $dt_i->diff($dt_to)->days == 0) {
521                 $test = array(
522                     'test' => 'header',
523                     'type' => 'regex',
524                     'arg1' => 'received',
525                     'arg2' => '('.$matchexp.') '.$dt_i->format('M Y')
526                 );
527
528                 $tests[]  = $test;
529                 $matchexp = '';
530             }
531             else {
532                 $matchexp .= '|';
533             }
534
535             $dt_i->add($interval);
536         }
537
538         return $tests;
539     }
540
541     public static function parse_regexp_tests($tests)
542     {
543         $rx_from = '/^\(([0-9]{2}).*\)\s([A-Za-z]+)\s([0-9]{4})/';
544         $rx_to   = '/^\(.*([0-9]{2})\)\s([A-Za-z]+)\s([0-9]{4})/';
545         $result  = array();
546
547         foreach ((array) $tests as $test) {
548             if ($test['test'] == 'header' && $test['type'] == 'regex' && $test['arg1'] == 'received') {
549                 $textexp = preg_replace('/\[ ([^\]]*)\]/', '0', $test['arg2']);
550
551                 if (!$result['from'] && preg_match($rx_from, $textexp, $matches)) {
552                     $result['from'] = $matches[1]." ".$matches[2]." ".$matches[3];
553                 }
554
555                 if (preg_match($rx_to, $textexp, $matches)) {
556                     $result['to'] = $matches[1]." ".$matches[2]." ".$matches[3];
557                 }
558             }
559         }
560
561         return $result;
562     }
613f96 563
AM 564     /**
fa8577 565      * Get current vacation interval
AM 566      */
567     public static function vacation_interval(&$vacation)
568     {
569         $rcube = rcube::get_instance();
570
571         if (isset($vacation['seconds'])) {
572             $interval = $vacation['seconds'];
573         }
574         else if (isset($vacation['days'])) {
575             $interval = $vacation['days'];
576         }
577         else if ($interval_cfg = $rcube->config->get('managesieve_vacation_interval')) {
578             if (preg_match('/^([0-9]+)s$/', $interval_cfg, $m)) {
579                 if ($seconds_extension) {
580                     $vacation['seconds'] = ($interval = intval($m[1])) ? $interval : null;
581                 }
582                 else {
583                     $vacation['days'] = $interval = ceil(intval($m[1])/86400);
584                 }
585             }
586             else {
587                 $vacation['days'] = $interval = intval($interval_cfg);
588             }
589         }
590
591         return $interval ? $interval : '';
592     }
593
594     /**
dc9cc7 595      * Saves vacation script (adding some variables)
AM 596      */
597     protected function save_vacation_script($rule)
598     {
599         // if script does not exist create a new one
04009e 600         if ($this->script_name === null || $this->script_name === false) {
dc9cc7 601             $this->script_name = $this->rc->config->get('managesieve_script_name');
AM 602             if (empty($this->script_name)) {
603                 $this->script_name = 'roundcube';
604             }
605
3e0ad2 606             // use default script contents
AM 607             if (!$this->rc->config->get('managesieve_kolab_master')) {
608                 $script_file = $this->rc->config->get('managesieve_default');
609                 if ($script_file && is_readable($script_file)) {
610                     $content = file_get_contents($script_file);
611                 }
612             }
613
614             // create and load script
615             if ($this->sieve->save_script($this->script_name, $content)) {
616                 $this->sieve->load($this->script_name);
617             }
dc9cc7 618         }
AM 619
3e0ad2 620         $script_active = in_array($this->script_name, $this->active);
dc9cc7 621
3e0ad2 622         // re-order rules if needed
AM 623         if (isset($rule['after']) && $rule['after'] !== '') {
624             // reset original vacation rule
625             if (isset($this->vacation['idx'])) {
626                 $this->script[$this->vacation['idx']] = null;
dc9cc7 627             }
3e0ad2 628
AM 629             // add at target position
630             if ($rule['after'] >= count($this->script) - 1) {
631                 $this->script[] = $rule;
dc9cc7 632             }
AM 633             else {
3e0ad2 634                 $script = array();
dc9cc7 635
AM 636                 foreach ($this->script as $idx => $r) {
3e0ad2 637                     if ($r) {
AM 638                         $script[] = $r;
639                     }
640
641                     if ($idx == $rule['after']) {
642                         $script[] = $rule;
dc9cc7 643                     }
AM 644                 }
3e0ad2 645
AM 646                 $this->script = $script;
dc9cc7 647             }
3e0ad2 648
AM 649             $this->script = array_values(array_filter($this->script));
650         }
651         // update original vacation rule if it exists
652         else if (isset($this->vacation['idx'])) {
653             $this->script[$this->vacation['idx']] = $rule;
654         }
655         // otherwise put vacation rule on top
656         else {
657             array_unshift($this->script, $rule);
658         }
659
660         // if the script was not active, we need to de-activate
661         // all rules except the vacation rule, but only if it is not disabled
662         if (!$script_active && !$rule['disabled']) {
663             foreach ($this->script as $idx => $r) {
664                 if (empty($r['actions']) || $r['actions'][0]['type'] != 'vacation') {
665                     $this->script[$idx]['disabled'] = true;
666                 }
667             }
668         }
669
670         if (!$this->sieve->script) {
671             return false;
dc9cc7 672         }
AM 673
674         $this->sieve->script->content = $this->script;
675
676         // save the script
677         $saved = $this->save_script($this->script_name);
678
679         // activate the script
680         if ($saved && !$script_active && !$rule['disabled']) {
681             $this->activate_script($this->script_name);
682         }
683
684         return $saved;
685     }
686
687     /**
613f96 688      * API: get vacation rule
AM 689      *
690      * @return array Vacation rule information
691      */
692     public function get_vacation()
693     {
694         $this->exts = $this->sieve->get_extensions();
695         $this->init_script();
696         $this->vacation_rule();
697
698         // check supported extensions
699         $date_extension    = in_array('date', $this->exts);
700         $regex_extension   = in_array('regex', $this->exts);
701         $seconds_extension = in_array('vacation-seconds', $this->exts);
702
703         // set user's timezone
704         try {
705             $timezone = new DateTimeZone($this->rc->config->get('timezone', 'GMT'));
706         }
707         catch (Exception $e) {
708             $timezone = new DateTimeZone('GMT');
709         }
710
711         if ($date_extension) {
712             $date_value = array();
713             foreach ((array) $this->vacation['tests'] as $test) {
714                 if ($test['test'] == 'currentdate') {
715                     $idx = $test['type'] == 'value-ge' ? 'start' : 'end';
716
717                     if ($test['part'] == 'date') {
718                         $date_value[$idx]['date'] = $test['arg'];
719                     }
720                     else if ($test['part'] == 'iso8601') {
721                         $date_value[$idx]['datetime'] = $test['arg'];
722                     }
723                 }
724             }
725
726             foreach ($date_value as $idx => $value) {
727                 $$idx = new DateTime($value['datetime'] ?: $value['date'], $timezone);
728             }
729         }
730         else if ($regex_extension) {
731             // Sieve 'date' extension not available, read start/end from RegEx based rules instead
732             if ($date_tests = self::parse_regexp_tests($this->vacation['tests'])) {
733                 $from = new DateTime($date_tests['from'] . ' ' . '00:00:00', $timezone);
734                 $to   = new DateTime($date_tests['to'] . ' ' . '23:59:59', $timezone);
735             }
736         }
737
738         if (isset($this->vacation['seconds'])) {
739             $interval = $this->vacation['seconds'] . 's';
740         }
741         else if (isset($this->vacation['days'])) {
742             $interval = $this->vacation['days'] . 'd';
743         }
744
745         $vacation = array(
746             'supported' => $this->exts,
747             'interval'  => $interval,
748             'start'     => $start,
749             'end'       => $end,
750             'enabled'   => $this->vacation['reason'] && empty($this->vacation['disabled']),
751             'message'   => $this->vacation['reason'],
752             'subject'   => $this->vacation['subject'],
753             'action'    => $this->vacation['action'],
754             'target'    => $this->vacation['target'],
755             'addresses' => $this->vacation['addresses'],
756         );
757
758         return $vacation;
759     }
760
761     /**
762      * API: set vacation rule
763      *
764      * @param array $vacation Vacation rule information (see self::get_vacation())
765      *
766      * @return bool True on success, False on failure
767      */
768     public function set_vacation($data)
769     {
770         $this->exts  = $this->sieve->get_extensions();
771         $this->error = false;
772
773         $this->init_script();
774         $this->vacation_rule();
775
776         // check supported extensions
777         $date_extension    = in_array('date', $this->exts);
778         $regex_extension   = in_array('regex', $this->exts);
779         $seconds_extension = in_array('vacation-seconds', $this->exts);
780
781         $vacation['type']      = 'vacation';
782         $vacation['reason']    = $this->strip_value(str_replace("\r\n", "\n", $data['message']));
783         $vacation['addresses'] = $data['addresses'];
784         $vacation['subject']   = $data['subject'];
785         $vacation_tests        = (array) $this->vacation['tests'];
786
787         foreach ((array) $vacation['addresses'] as $aidx => $address) {
788             $vacation['addresses'][$aidx] = $address = trim($address);
789
790             if (empty($address)) {
791                 unset($vacation['addresses'][$aidx]);
792             }
793             else if (!rcube_utils::check_email($address)) {
794                 $this->error = "Invalid address in vacation addresses: $address";
795                 return false;
796             }
797         }
798
799         if ($vacation['reason'] == '') {
800             $this->error = "No vacation message specified";
801             return false;
802         }
803
804         if ($data['interval']) {
805             if (!preg_match('/^([0-9]+)\s*([sd])$/', $data['interval'], $m)) {
806                 $this->error = "Invalid vacation interval value: " . $data['interval'];
807                 return false;
808             }
809             else if ($m[1]) {
810                 $vacation[strtolower($m[2]) == 's' ? 'seconds' : 'days'] = $m[1];
811             }
812         }
813
814         // find and remove existing date/regex/true rules
815         foreach ((array) $vacation_tests as $idx => $t) {
816             if ($t['test'] == 'currentdate' || $t['test'] == 'true'
817                 || ($t['test'] == 'header' && $t['type'] == 'regex' && $t['arg1'] == 'received')
818             ) {
819                 unset($vacation_tests[$idx]);
820             }
821         }
822
823         if ($date_extension) {
824             foreach (array('start', 'end') as $var) {
825                 if ($dt = $data[$var]) {
826                     $vacation_tests[] = array(
827                         'test' => 'currentdate',
828                         'part' => 'iso8601',
829                         'type' => 'value-' . ($var == 'start' ? 'ge' : 'le'),
830                         'zone' => $dt->format('O'),
831                         'arg'  => str_replace('+00:00', 'Z', strtoupper($dt->format('c'))),
832                     );
833                 }
834             }
835         }
836         else if ($regex_extension) {
837             // Add date range rules if range specified
838             if ($data['start'] && $data['end']) {
839                 if ($tests = self::build_regexp_tests($data['start'], $data['end'], $error)) {
840                     $vacation_tests = array_merge($vacation_tests, $tests);
841                 }
842
843                 if ($error) {
844                     $this->error = "Invalid dates specified or unsupported period length";
845                     return false;
846                 }
847             }
848         }
849
850         if ($data['action'] == 'redirect' || $data['action'] == 'copy') {
851             if (empty($data['target']) || !rcube_utils::check_email($data['target'])) {
852                 $this->error = "Invalid address in action taget: " . $data['target'];
853                 return false;
854             }
855         }
856         else if ($data['action'] && $data['action'] != 'keep' && $data['action'] != 'discard') {
857             $this->error = "Unsupported vacation action: " . $data['action'];
858             return false;
859         }
860
861         if (empty($vacation_tests)) {
862             $vacation_tests = $this->rc->config->get('managesieve_vacation_test', array(array('test' => 'true')));
863         }
864
865         $rule             = $this->vacation;
866         $rule['type']     = 'if';
867         $rule['name']     = $rule['name'] ?: 'Out-of-Office';
868         $rule['disabled'] = isset($data['enabled']) && !$data['enabled'];
869         $rule['tests']    = $vacation_tests;
870         $rule['join']     = $date_extension ? count($vacation_tests) > 1 : false;
871         $rule['actions']  = array($vacation);
872
873         if ($data['action'] && $data['action'] != 'keep') {
874             $rule['actions'][] = array(
875                 'type'   => $data['action'] == 'discard' ? 'discard' : 'redirect',
876                 'copy'   => $data['action'] == 'copy',
877                 'target' => $data['action'] != 'discard' ? $data['target'] : '',
878             );
879         }
880
dc9cc7 881         return $this->save_vacation_script($rule);
613f96 882     }
AM 883
884     /**
885      * API: connect to managesieve server
886      */
887     public function connect($username, $password)
888     {
889         if (!parent::connect($username, $password)) {
890             return $this->load_script();
891         }
892     }
893
894     /**
895      * API: Returns last error
896      *
897      * @return string Error message
898      */
899     public function get_error()
900     {
901         return $this->error;
902     }
50a57e 903 }