You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_sieve_vacation.php 36KB

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