Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

rcube_sieve_vacation.php 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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 = (array) $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. $from_addr = $this->rc->config->get('managesieve_vacation_from_init');
  301. $auto_addr = $this->rc->config->get('managesieve_vacation_addresses_init');
  302. if (count($this->vacation) < 2) {
  303. if ($auto_addr) {
  304. $this->vacation['addresses'] = $this->user_emails();
  305. }
  306. if ($from_addr) {
  307. $default_identity = $this->rc->user->list_emails(true);
  308. $this->vacation['from'] = $default_identity['email'];
  309. }
  310. }
  311. // form elements
  312. $from = new html_inputfield(array('name' => 'vacation_from', 'id' => 'vacation_from', 'size' => 50));
  313. $subject = new html_inputfield(array('name' => 'vacation_subject', 'id' => 'vacation_subject', 'size' => 50));
  314. $reason = new html_textarea(array('name' => 'vacation_reason', 'id' => 'vacation_reason', 'cols' => 60, 'rows' => 8));
  315. $interval = new html_inputfield(array('name' => 'vacation_interval', 'id' => 'vacation_interval', 'size' => 5));
  316. $addresses = '<textarea name="vacation_addresses" id="vacation_addresses" data-type="list" data-size="30" style="display: none">'
  317. . rcube::Q(implode("\n", (array) $this->vacation['addresses']), 'strict', false) . '</textarea>';
  318. $status = new html_select(array('name' => 'vacation_status', 'id' => 'vacation_status'));
  319. $action = new html_select(array('name' => 'vacation_action', 'id' => 'vacation_action', 'onchange' => 'vacation_action_select()'));
  320. $addresses_link = new html_inputfield(array(
  321. 'type' => 'button',
  322. 'href' => '#',
  323. 'class' => 'button',
  324. 'onclick' => rcmail_output::JS_OBJECT_NAME . '.managesieve_vacation_addresses()'
  325. ));
  326. $status->add($this->plugin->gettext('vacation.on'), 'on');
  327. $status->add($this->plugin->gettext('vacation.off'), 'off');
  328. $action->add($this->plugin->gettext('vacation.keep'), 'keep');
  329. $action->add($this->plugin->gettext('vacation.discard'), 'discard');
  330. $action->add($this->plugin->gettext('vacation.redirect'), 'redirect');
  331. if (in_array('copy', $this->exts)) {
  332. $action->add($this->plugin->gettext('vacation.copy'), 'copy');
  333. }
  334. if ($this->rc->config->get('managesieve_vacation') != 2 && !empty($this->vacation['list'])) {
  335. $after = new html_select(array('name' => 'vacation_after', 'id' => 'vacation_after'));
  336. $after->add('', '');
  337. foreach ($this->vacation['list'] as $idx => $rule) {
  338. $after->add($rule, $idx);
  339. }
  340. }
  341. $interval_txt = $interval->show(self::vacation_interval($this->vacation));
  342. if ($seconds_extension) {
  343. $interval_select = new html_select(array('name' => 'vacation_interval_type'));
  344. $interval_select->add($this->plugin->gettext('days'), 'days');
  345. $interval_select->add($this->plugin->gettext('seconds'), 'seconds');
  346. $interval_txt .= '&nbsp;' . $interval_select->show(isset($this->vacation['seconds']) ? 'seconds' : 'days');
  347. }
  348. else {
  349. $interval_txt .= '&nbsp;' . $this->plugin->gettext('days');
  350. }
  351. if ($date_extension || $regex_extension) {
  352. $date_from = new html_inputfield(array('name' => 'vacation_datefrom', 'id' => 'vacation_datefrom', 'class' => 'datepicker', 'size' => 12));
  353. $date_to = new html_inputfield(array('name' => 'vacation_dateto', 'id' => 'vacation_dateto', 'class' => 'datepicker', 'size' => 12));
  354. $date_format = $this->rc->config->get('date_format', 'Y-m-d');
  355. }
  356. if ($date_extension) {
  357. $time_from = new html_inputfield(array('name' => 'vacation_timefrom', 'id' => 'vacation_timefrom', 'size' => 7));
  358. $time_to = new html_inputfield(array('name' => 'vacation_timeto', 'id' => 'vacation_timeto', 'size' => 7));
  359. $time_format = $this->rc->config->get('time_format', 'H:i');
  360. $date_value = array();
  361. foreach ((array) $this->vacation['tests'] as $test) {
  362. if ($test['test'] == 'currentdate') {
  363. $idx = $test['type'] == 'value-ge' ? 'from' : 'to';
  364. if ($test['part'] == 'date') {
  365. $date_value[$idx]['date'] = $test['arg'];
  366. }
  367. else if ($test['part'] == 'iso8601') {
  368. $date_value[$idx]['datetime'] = $test['arg'];
  369. }
  370. }
  371. }
  372. foreach ($date_value as $idx => $value) {
  373. $date = $value['datetime'] ?: $value['date'];
  374. $date_value[$idx] = $this->rc->format_date($date, $date_format, false);
  375. if (!empty($value['datetime'])) {
  376. $date_value['time_' . $idx] = $this->rc->format_date($date, $time_format, true);
  377. }
  378. }
  379. }
  380. else if ($regex_extension) {
  381. // Sieve 'date' extension not available, read start/end from RegEx based rules instead
  382. if ($date_tests = self::parse_regexp_tests($this->vacation['tests'])) {
  383. $date_value['from'] = $this->rc->format_date($date_tests['from'], $date_format, false);
  384. $date_value['to'] = $this->rc->format_date($date_tests['to'], $date_format, false);
  385. }
  386. }
  387. // force domain selection in redirect email input
  388. $domains = (array) $this->rc->config->get('managesieve_domains');
  389. $redirect = $this->vacation['action'] == 'redirect' || $this->vacation['action'] == 'copy';
  390. if (!empty($domains)) {
  391. sort($domains);
  392. $domain_select = new html_select(array('name' => 'action_domain', 'id' => 'action_domain'));
  393. $domain_select->add(array_combine($domains, $domains));
  394. if ($redirect && $this->vacation['target']) {
  395. $parts = explode('@', $this->vacation['target']);
  396. if (!empty($parts)) {
  397. $this->vacation['domain'] = array_pop($parts);
  398. $this->vacation['target'] = implode('@', $parts);
  399. }
  400. }
  401. }
  402. // redirect target
  403. $action_target = ' <span id="action_target_span" style="display:' . ($redirect ? 'inline' : 'none') . '">'
  404. . '<input type="text" name="action_target" id="action_target"'
  405. . ' value="' .($redirect ? rcube::Q($this->vacation['target'], 'strict', false) : '') . '"'
  406. . (!empty($domains) ? ' size="20"' : ' size="35"') . '/>'
  407. . (!empty($domains) ? ' @ ' . $domain_select->show($this->vacation['domain']) : '')
  408. . '</span>';
  409. // Message tab
  410. $table = new html_table(array('cols' => 2));
  411. $table->add('title', html::label('vacation_subject', $this->plugin->gettext('vacation.subject')));
  412. $table->add(null, $subject->show($this->vacation['subject']));
  413. $table->add('title', html::label('vacation_reason', $this->plugin->gettext('vacation.body')));
  414. $table->add(null, $reason->show($this->vacation['reason']));
  415. if ($date_extension || $regex_extension) {
  416. $table->add('title', html::label('vacation_datefrom', $this->plugin->gettext('vacation.start')));
  417. $table->add(null, $date_from->show($date_value['from']) . ($time_from ? ' ' . $time_from->show($date_value['time_from']) : ''));
  418. $table->add('title', html::label('vacation_dateto', $this->plugin->gettext('vacation.end')));
  419. $table->add(null, $date_to->show($date_value['to']) . ($time_to ? ' ' . $time_to->show($date_value['time_to']) : ''));
  420. }
  421. $table->add('title', html::label('vacation_status', $this->plugin->gettext('vacation.status')));
  422. $table->add(null, $status->show(!isset($this->vacation['disabled']) || $this->vacation['disabled'] ? 'off' : 'on'));
  423. $out .= html::tag('fieldset', $class, html::tag('legend', null, $this->plugin->gettext('vacation.reply')) . $table->show($attrib));
  424. // Advanced tab
  425. $table = new html_table(array('cols' => 2));
  426. $table->add('title', html::label('vacation_from', $this->plugin->gettext('vacation.from')));
  427. $table->add(null, $from->show($this->vacation['from']));
  428. $table->add('title', html::label('vacation_addresses', $this->plugin->gettext('vacation.addresses')));
  429. $table->add(null, $addresses . $addresses_link->show($this->plugin->gettext('filladdresses')));
  430. $table->add('title', html::label('vacation_interval', $this->plugin->gettext('vacation.interval')));
  431. $table->add(null, $interval_txt);
  432. if ($after) {
  433. $table->add('title', html::label('vacation_after', $this->plugin->gettext('vacation.after')));
  434. $table->add(null, $after->show($this->vacation['idx'] - 1));
  435. }
  436. $table->add('title', html::label('vacation_action', $this->plugin->gettext('vacation.action')));
  437. $table->add('vacation', $action->show($this->vacation['action']) . $action_target);
  438. $out .= html::tag('fieldset', $class, html::tag('legend', null, $this->plugin->gettext('vacation.advanced')) . $table->show($attrib));
  439. $out .= '</form>';
  440. $this->rc->output->add_gui_object('sieveform', $form_id);
  441. if ($time_format) {
  442. $this->rc->output->set_env('time_format', $time_format);
  443. }
  444. return $out;
  445. }
  446. public static function build_regexp_tests($date_from, $date_to, &$error)
  447. {
  448. $tests = array();
  449. $dt_from = rcube_utils::anytodatetime($date_from);
  450. $dt_to = rcube_utils::anytodatetime($date_to);
  451. $interval = $dt_from->diff($dt_to);
  452. if ($interval->invert || $interval->days > 365) {
  453. $error = 'managesieve.invaliddateformat';
  454. return;
  455. }
  456. $dt_i = $dt_from;
  457. $interval = new DateInterval('P1D');
  458. $matchexp = '';
  459. while (!$dt_i->diff($dt_to)->invert) {
  460. $days = (int) $dt_i->format('d');
  461. $matchexp .= $days < 10 ? "[ 0]$days" : $days;
  462. if ($days == $dt_i->format('t') || $dt_i->diff($dt_to)->days == 0) {
  463. $test = array(
  464. 'test' => 'header',
  465. 'type' => 'regex',
  466. 'arg1' => 'received',
  467. 'arg2' => '('.$matchexp.') '.$dt_i->format('M Y')
  468. );
  469. $tests[] = $test;
  470. $matchexp = '';
  471. }
  472. else {
  473. $matchexp .= '|';
  474. }
  475. $dt_i->add($interval);
  476. }
  477. return $tests;
  478. }
  479. public static function parse_regexp_tests($tests)
  480. {
  481. $rx_from = '/^\(([0-9]{2}).*\)\s([A-Za-z]+)\s([0-9]{4})/';
  482. $rx_to = '/^\(.*([0-9]{2})\)\s([A-Za-z]+)\s([0-9]{4})/';
  483. $result = array();
  484. foreach ((array) $tests as $test) {
  485. if ($test['test'] == 'header' && $test['type'] == 'regex' && $test['arg1'] == 'received') {
  486. $textexp = preg_replace('/\[ ([^\]]*)\]/', '0', $test['arg2']);
  487. if (!$result['from'] && preg_match($rx_from, $textexp, $matches)) {
  488. $result['from'] = $matches[1]." ".$matches[2]." ".$matches[3];
  489. }
  490. if (preg_match($rx_to, $textexp, $matches)) {
  491. $result['to'] = $matches[1]." ".$matches[2]." ".$matches[3];
  492. }
  493. }
  494. }
  495. return $result;
  496. }
  497. /**
  498. * Get current vacation interval
  499. */
  500. public static function vacation_interval(&$vacation)
  501. {
  502. $rcube = rcube::get_instance();
  503. if (isset($vacation['seconds'])) {
  504. $interval = $vacation['seconds'];
  505. }
  506. else if (isset($vacation['days'])) {
  507. $interval = $vacation['days'];
  508. }
  509. else if ($interval_cfg = $rcube->config->get('managesieve_vacation_interval')) {
  510. if (preg_match('/^([0-9]+)s$/', $interval_cfg, $m)) {
  511. if ($seconds_extension) {
  512. $vacation['seconds'] = ($interval = intval($m[1])) ? $interval : null;
  513. }
  514. else {
  515. $vacation['days'] = $interval = ceil(intval($m[1])/86400);
  516. }
  517. }
  518. else {
  519. $vacation['days'] = $interval = intval($interval_cfg);
  520. }
  521. }
  522. return $interval ?: '';
  523. }
  524. /**
  525. * Saves vacation script (adding some variables)
  526. */
  527. protected function save_vacation_script($rule)
  528. {
  529. // if script does not exist create a new one
  530. if ($this->script_name === null || $this->script_name === false) {
  531. $this->script_name = $this->rc->config->get('managesieve_script_name');
  532. if (empty($this->script_name)) {
  533. $this->script_name = 'roundcube';
  534. }
  535. // use default script contents
  536. if (!$this->rc->config->get('managesieve_kolab_master')) {
  537. $script_file = $this->rc->config->get('managesieve_default');
  538. if ($script_file && is_readable($script_file)) {
  539. $content = file_get_contents($script_file);
  540. }
  541. }
  542. // create and load script
  543. if ($this->sieve->save_script($this->script_name, $content)) {
  544. $this->sieve->load($this->script_name);
  545. }
  546. }
  547. $script_active = in_array($this->script_name, $this->active);
  548. // re-order rules if needed
  549. if (isset($rule['after']) && $rule['after'] !== '') {
  550. // reset original vacation rule
  551. if (isset($this->vacation['idx'])) {
  552. $this->script[$this->vacation['idx']] = null;
  553. }
  554. // add at target position
  555. if ($rule['after'] >= count($this->script) - 1) {
  556. $this->script[] = $rule;
  557. }
  558. else {
  559. $script = array();
  560. foreach ($this->script as $idx => $r) {
  561. if ($r) {
  562. $script[] = $r;
  563. }
  564. if ($idx == $rule['after']) {
  565. $script[] = $rule;
  566. }
  567. }
  568. $this->script = $script;
  569. }
  570. $this->script = array_values(array_filter($this->script));
  571. }
  572. // update original vacation rule if it exists
  573. else if (isset($this->vacation['idx'])) {
  574. $this->script[$this->vacation['idx']] = $rule;
  575. }
  576. // otherwise put vacation rule on top
  577. else {
  578. array_unshift($this->script, $rule);
  579. }
  580. // if the script was not active, we need to de-activate
  581. // all rules except the vacation rule, but only if it is not disabled
  582. if (!$script_active && !$rule['disabled']) {
  583. foreach ($this->script as $idx => $r) {
  584. if (empty($r['actions']) || $r['actions'][0]['type'] != 'vacation') {
  585. $this->script[$idx]['disabled'] = true;
  586. }
  587. }
  588. }
  589. if (!$this->sieve->script) {
  590. return false;
  591. }
  592. $this->sieve->script->content = $this->script;
  593. // save the script
  594. $saved = $this->save_script($this->script_name);
  595. // activate the script
  596. if ($saved && !$script_active && !$rule['disabled']) {
  597. $this->activate_script($this->script_name);
  598. }
  599. return $saved;
  600. }
  601. /**
  602. * API: get vacation rule
  603. *
  604. * @return array Vacation rule information
  605. */
  606. public function get_vacation()
  607. {
  608. $this->exts = $this->sieve->get_extensions();
  609. $this->init_script();
  610. $this->vacation_rule();
  611. // check supported extensions
  612. $date_extension = in_array('date', $this->exts);
  613. $regex_extension = in_array('regex', $this->exts);
  614. $seconds_extension = in_array('vacation-seconds', $this->exts);
  615. // set user's timezone
  616. try {
  617. $timezone = new DateTimeZone($this->rc->config->get('timezone', 'GMT'));
  618. }
  619. catch (Exception $e) {
  620. $timezone = new DateTimeZone('GMT');
  621. }
  622. if ($date_extension) {
  623. $date_value = array();
  624. foreach ((array) $this->vacation['tests'] as $test) {
  625. if ($test['test'] == 'currentdate') {
  626. $idx = $test['type'] == 'value-ge' ? 'start' : 'end';
  627. if ($test['part'] == 'date') {
  628. $date_value[$idx]['date'] = $test['arg'];
  629. }
  630. else if ($test['part'] == 'iso8601') {
  631. $date_value[$idx]['datetime'] = $test['arg'];
  632. }
  633. }
  634. }
  635. foreach ($date_value as $idx => $value) {
  636. $$idx = new DateTime($value['datetime'] ?: $value['date'], $timezone);
  637. }
  638. }
  639. else if ($regex_extension) {
  640. // Sieve 'date' extension not available, read start/end from RegEx based rules instead
  641. if ($date_tests = self::parse_regexp_tests($this->vacation['tests'])) {
  642. $from = new DateTime($date_tests['from'] . ' ' . '00:00:00', $timezone);
  643. $to = new DateTime($date_tests['to'] . ' ' . '23:59:59', $timezone);
  644. }
  645. }
  646. if (isset($this->vacation['seconds'])) {
  647. $interval = $this->vacation['seconds'] . 's';
  648. }
  649. else if (isset($this->vacation['days'])) {
  650. $interval = $this->vacation['days'] . 'd';
  651. }
  652. $vacation = array(
  653. 'supported' => $this->exts,
  654. 'interval' => $interval,
  655. 'start' => $start,
  656. 'end' => $end,
  657. 'enabled' => $this->vacation['reason'] && empty($this->vacation['disabled']),
  658. 'message' => $this->vacation['reason'],
  659. 'subject' => $this->vacation['subject'],
  660. 'action' => $this->vacation['action'],
  661. 'target' => $this->vacation['target'],
  662. 'addresses' => $this->vacation['addresses'],
  663. 'from' => $this->vacation['from'],
  664. );
  665. return $vacation;
  666. }
  667. /**
  668. * API: set vacation rule
  669. *
  670. * @param array $vacation Vacation rule information (see self::get_vacation())
  671. *
  672. * @return bool True on success, False on failure
  673. */
  674. public function set_vacation($data)
  675. {
  676. $this->exts = $this->sieve->get_extensions();
  677. $this->error = false;
  678. $this->init_script();
  679. $this->vacation_rule();
  680. // check supported extensions
  681. $date_extension = in_array('date', $this->exts);
  682. $regex_extension = in_array('regex', $this->exts);
  683. $seconds_extension = in_array('vacation-seconds', $this->exts);
  684. $vacation['type'] = 'vacation';
  685. $vacation['reason'] = $this->strip_value(str_replace("\r\n", "\n", $data['message']));
  686. $vacation['addresses'] = $data['addresses'];
  687. $vacation['subject'] = trim($data['subject']);
  688. $vacation['from'] = trim($data['from']);
  689. $vacation_tests = (array) $this->vacation['tests'];
  690. foreach ((array) $vacation['addresses'] as $aidx => $address) {
  691. $vacation['addresses'][$aidx] = $address = trim($address);
  692. if (empty($address)) {
  693. unset($vacation['addresses'][$aidx]);
  694. }
  695. else if (!rcube_utils::check_email($address)) {
  696. $this->error = "Invalid address in vacation addresses: $address";
  697. return false;
  698. }
  699. }
  700. if (!empty($vacation['from']) && !rcube_utils::check_email($vacation['from'])) {
  701. $this->error = "Invalid address in 'from': " . $vacation['from'];
  702. return false;
  703. }
  704. if ($vacation['reason'] == '') {
  705. $this->error = "No vacation message specified";
  706. return false;
  707. }
  708. if ($data['interval']) {
  709. if (!preg_match('/^([0-9]+)\s*([sd])$/', $data['interval'], $m)) {
  710. $this->error = "Invalid vacation interval value: " . $data['interval'];
  711. return false;
  712. }
  713. else if ($m[1]) {
  714. $vacation[strtolower($m[2]) == 's' ? 'seconds' : 'days'] = $m[1];
  715. }
  716. }
  717. // find and remove existing date/regex/true rules
  718. foreach ((array) $vacation_tests as $idx => $t) {
  719. if ($t['test'] == 'currentdate' || $t['test'] == 'true'
  720. || ($t['test'] == 'header' && $t['type'] == 'regex' && $t['arg1'] == 'received')
  721. ) {
  722. unset($vacation_tests[$idx]);
  723. }
  724. }
  725. if ($date_extension) {
  726. foreach (array('start', 'end') as $var) {
  727. if ($dt = $data[$var]) {
  728. $vacation_tests[] = array(
  729. 'test' => 'currentdate',
  730. 'part' => 'iso8601',
  731. 'type' => 'value-' . ($var == 'start' ? 'ge' : 'le'),
  732. 'zone' => $dt->format('O'),
  733. 'arg' => str_replace('+00:00', 'Z', strtoupper($dt->format('c'))),
  734. );
  735. }
  736. }
  737. }
  738. else if ($regex_extension) {
  739. // Add date range rules if range specified
  740. if ($data['start'] && $data['end']) {
  741. if ($tests = self::build_regexp_tests($data['start'], $data['end'], $error)) {
  742. $vacation_tests = array_merge($vacation_tests, $tests);
  743. }
  744. if ($error) {
  745. $this->error = "Invalid dates specified or unsupported period length";
  746. return false;
  747. }
  748. }
  749. }
  750. if ($data['action'] == 'redirect' || $data['action'] == 'copy') {
  751. if (empty($data['target']) || !rcube_utils::check_email($data['target'])) {
  752. $this->error = "Invalid address in action taget: " . $data['target'];
  753. return false;
  754. }
  755. }
  756. else if ($data['action'] && $data['action'] != 'keep' && $data['action'] != 'discard') {
  757. $this->error = "Unsupported vacation action: " . $data['action'];
  758. return false;
  759. }
  760. if (empty($vacation_tests)) {
  761. $vacation_tests = (array) $this->rc->config->get('managesieve_vacation_test', array(array('test' => 'true')));
  762. }
  763. $rule = $this->vacation;
  764. $rule['type'] = 'if';
  765. $rule['name'] = $rule['name'] ?: 'Out-of-Office';
  766. $rule['disabled'] = isset($data['enabled']) && !$data['enabled'];
  767. $rule['tests'] = $vacation_tests;
  768. $rule['join'] = $date_extension ? count($vacation_tests) > 1 : false;
  769. $rule['actions'] = array($vacation);
  770. if ($data['action'] && $data['action'] != 'keep') {
  771. $rule['actions'][] = array(
  772. 'type' => $data['action'] == 'discard' ? 'discard' : 'redirect',
  773. 'copy' => $data['action'] == 'copy',
  774. 'target' => $data['action'] != 'discard' ? $data['target'] : '',
  775. );
  776. }
  777. return $this->save_vacation_script($rule);
  778. }
  779. /**
  780. * API: connect to managesieve server
  781. */
  782. public function connect($username, $password)
  783. {
  784. $error = parent::connect($username, $password);
  785. if ($error) {
  786. return $error;
  787. }
  788. return $this->load_script();
  789. }
  790. /**
  791. * API: Returns last error
  792. *
  793. * @return string Error message
  794. */
  795. public function get_error()
  796. {
  797. return $this->error;
  798. }
  799. }