PageRenderTime 35ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/managesieve/managesieve.php

https://github.com/netconstructor/roundcubemail
PHP | 2041 lines | 1563 code | 283 blank | 195 comment | 441 complexity | 6051ba91a7f4dbb90a2b58cbc8eea8ff MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Managesieve (Sieve Filters)
  4. *
  5. * Plugin that adds a possibility to manage Sieve filters in Thunderbird's style.
  6. * It's clickable interface which operates on text scripts and communicates
  7. * with server using managesieve protocol. Adds Filters tab in Settings.
  8. *
  9. * @version @package_version@
  10. * @author Aleksander Machniak <alec@alec.pl>
  11. *
  12. * Configuration (see config.inc.php.dist)
  13. *
  14. * Copyright (C) 2008-2012, The Roundcube Dev Team
  15. * Copyright (C) 2011-2012, Kolab Systems AG
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License version 2
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License along
  27. * with this program; if not, write to the Free Software Foundation, Inc.,
  28. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  29. */
  30. class managesieve extends rcube_plugin
  31. {
  32. public $task = 'mail|settings';
  33. private $rc;
  34. private $sieve;
  35. private $errors;
  36. private $form;
  37. private $tips = array();
  38. private $script = array();
  39. private $exts = array();
  40. private $list;
  41. private $active = array();
  42. private $headers = array(
  43. 'subject' => 'Subject',
  44. 'from' => 'From',
  45. 'to' => 'To',
  46. );
  47. private $addr_headers = array(
  48. // Required
  49. "from", "to", "cc", "bcc", "sender", "resent-from", "resent-to",
  50. // Additional (RFC 822 / RFC 2822)
  51. "reply-to", "resent-reply-to", "resent-sender", "resent-cc", "resent-bcc",
  52. // Non-standard (RFC 2076, draft-palme-mailext-headers-08.txt)
  53. "for-approval", "for-handling", "for-comment", "apparently-to", "errors-to",
  54. "delivered-to", "return-receipt-to", "x-admin", "read-receipt-to",
  55. "x-confirm-reading-to", "return-receipt-requested",
  56. "registered-mail-reply-requested-by", "mail-followup-to", "mail-reply-to",
  57. "abuse-reports-to", "x-complaints-to", "x-report-abuse-to",
  58. // Undocumented
  59. "x-beenthere",
  60. );
  61. const VERSION = '6.0';
  62. const PROGNAME = 'Roundcube (Managesieve)';
  63. const PORT = 4190;
  64. function init()
  65. {
  66. $this->rc = rcmail::get_instance();
  67. // register actions
  68. $this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
  69. $this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
  70. if ($this->rc->task == 'settings') {
  71. $this->init_ui();
  72. }
  73. else if ($this->rc->task == 'mail') {
  74. // register message hook
  75. $this->add_hook('message_headers_output', array($this, 'mail_headers'));
  76. // inject Create Filter popup stuff
  77. if (empty($this->rc->action) || $this->rc->action == 'show') {
  78. $this->mail_task_handler();
  79. }
  80. }
  81. }
  82. /**
  83. * Initializes plugin's UI (localization, js script)
  84. */
  85. private function init_ui()
  86. {
  87. if ($this->ui_initialized)
  88. return;
  89. // load localization
  90. $this->add_texts('localization/', array('filters','managefilters'));
  91. $this->include_script('managesieve.js');
  92. $this->ui_initialized = true;
  93. }
  94. /**
  95. * Add UI elements to the 'mailbox view' and 'show message' UI.
  96. */
  97. function mail_task_handler()
  98. {
  99. // use jQuery for popup window
  100. $this->require_plugin('jqueryui');
  101. // include js script and localization
  102. $this->init_ui();
  103. // include styles
  104. $skin_path = $this->local_skin_path();
  105. if (is_file($this->home . "/$skin_path/managesieve_mail.css")) {
  106. $this->include_stylesheet("$skin_path/managesieve_mail.css");
  107. }
  108. // add 'Create filter' item to message menu
  109. $this->api->add_content(html::tag('li', null,
  110. $this->api->output->button(array(
  111. 'command' => 'managesieve-create',
  112. 'label' => 'managesieve.filtercreate',
  113. 'type' => 'link',
  114. 'classact' => 'icon filterlink active',
  115. 'class' => 'icon filterlink',
  116. 'innerclass' => 'icon filterlink',
  117. ))), 'messagemenu');
  118. // register some labels/messages
  119. $this->rc->output->add_label('managesieve.newfilter', 'managesieve.usedata',
  120. 'managesieve.nodata', 'managesieve.nextstep', 'save');
  121. $this->rc->session->remove('managesieve_current');
  122. }
  123. /**
  124. * Get message headers for popup window
  125. */
  126. function mail_headers($args)
  127. {
  128. // this hook can be executed many times
  129. if ($this->mail_headers_done) {
  130. return $args;
  131. }
  132. $this->mail_headers_done = true;
  133. $headers = $args['headers'];
  134. $ret = array();
  135. if ($headers->subject)
  136. $ret[] = array('Subject', rcube_mime::decode_header($headers->subject));
  137. // @TODO: List-Id, others?
  138. foreach (array('From', 'To') as $h) {
  139. $hl = strtolower($h);
  140. if ($headers->$hl) {
  141. $list = rcube_mime::decode_address_list($headers->$hl);
  142. foreach ($list as $item) {
  143. if ($item['mailto']) {
  144. $ret[] = array($h, $item['mailto']);
  145. }
  146. }
  147. }
  148. }
  149. if ($this->rc->action == 'preview')
  150. $this->rc->output->command('parent.set_env', array('sieve_headers' => $ret));
  151. else
  152. $this->rc->output->set_env('sieve_headers', $ret);
  153. return $args;
  154. }
  155. /**
  156. * Loads configuration, initializes plugin (including sieve connection)
  157. */
  158. function managesieve_start()
  159. {
  160. $this->load_config();
  161. // register UI objects
  162. $this->rc->output->add_handlers(array(
  163. 'filterslist' => array($this, 'filters_list'),
  164. 'filtersetslist' => array($this, 'filtersets_list'),
  165. 'filterframe' => array($this, 'filter_frame'),
  166. 'filterform' => array($this, 'filter_form'),
  167. 'filtersetform' => array($this, 'filterset_form'),
  168. ));
  169. // Add include path for internal classes
  170. $include_path = $this->home . '/lib' . PATH_SEPARATOR;
  171. $include_path .= ini_get('include_path');
  172. set_include_path($include_path);
  173. $host = rcube_parse_host($this->rc->config->get('managesieve_host', 'localhost'));
  174. $host = rcube_idn_to_ascii($host);
  175. $port = $this->rc->config->get('managesieve_port');
  176. if (empty($port)) {
  177. $port = getservbyname('sieve', 'tcp');
  178. if (empty($port)) {
  179. $port = self::PORT;
  180. }
  181. }
  182. $plugin = $this->rc->plugins->exec_hook('managesieve_connect', array(
  183. 'user' => $_SESSION['username'],
  184. 'password' => $this->rc->decrypt($_SESSION['password']),
  185. 'host' => $host,
  186. 'port' => $port,
  187. 'auth_type' => $this->rc->config->get('managesieve_auth_type'),
  188. 'usetls' => $this->rc->config->get('managesieve_usetls', false),
  189. 'disabled' => $this->rc->config->get('managesieve_disabled_extensions'),
  190. 'debug' => $this->rc->config->get('managesieve_debug', false),
  191. 'auth_cid' => $this->rc->config->get('managesieve_auth_cid'),
  192. 'auth_pw' => $this->rc->config->get('managesieve_auth_pw'),
  193. ));
  194. // try to connect to managesieve server and to fetch the script
  195. $this->sieve = new rcube_sieve(
  196. $plugin['user'],
  197. $plugin['password'],
  198. $plugin['host'],
  199. $plugin['port'],
  200. $plugin['auth_type'],
  201. $plugin['usetls'],
  202. $plugin['disabled'],
  203. $plugin['debug'],
  204. $plugin['auth_cid'],
  205. $plugin['auth_pw']
  206. );
  207. if (!($error = $this->sieve->error())) {
  208. // Get list of scripts
  209. $list = $this->list_scripts();
  210. if (!empty($_GET['_set']) || !empty($_POST['_set'])) {
  211. $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
  212. }
  213. else if (!empty($_SESSION['managesieve_current'])) {
  214. $script_name = $_SESSION['managesieve_current'];
  215. }
  216. else {
  217. // get (first) active script
  218. if (!empty($this->active[0])) {
  219. $script_name = $this->active[0];
  220. }
  221. else if ($list) {
  222. $script_name = $list[0];
  223. }
  224. // create a new (initial) script
  225. else {
  226. // if script not exists build default script contents
  227. $script_file = $this->rc->config->get('managesieve_default');
  228. $script_name = $this->rc->config->get('managesieve_script_name');
  229. if (empty($script_name))
  230. $script_name = 'roundcube';
  231. if ($script_file && is_readable($script_file))
  232. $content = file_get_contents($script_file);
  233. // add script and set it active
  234. if ($this->sieve->save_script($script_name, $content)) {
  235. $this->activate_script($script_name);
  236. $this->list[] = $script_name;
  237. }
  238. }
  239. }
  240. if ($script_name) {
  241. $this->sieve->load($script_name);
  242. }
  243. $error = $this->sieve->error();
  244. }
  245. // finally set script objects
  246. if ($error) {
  247. switch ($error) {
  248. case SIEVE_ERROR_CONNECTION:
  249. case SIEVE_ERROR_LOGIN:
  250. $this->rc->output->show_message('managesieve.filterconnerror', 'error');
  251. break;
  252. default:
  253. $this->rc->output->show_message('managesieve.filterunknownerror', 'error');
  254. break;
  255. }
  256. raise_error(array('code' => 403, 'type' => 'php',
  257. 'file' => __FILE__, 'line' => __LINE__,
  258. 'message' => "Unable to connect to managesieve on $host:$port"), true, false);
  259. // to disable 'Add filter' button set env variable
  260. $this->rc->output->set_env('filterconnerror', true);
  261. $this->script = array();
  262. }
  263. else {
  264. $this->exts = $this->sieve->get_extensions();
  265. $this->script = $this->sieve->script->as_array();
  266. $this->rc->output->set_env('currentset', $this->sieve->current);
  267. $_SESSION['managesieve_current'] = $this->sieve->current;
  268. }
  269. return $error;
  270. }
  271. function managesieve_actions()
  272. {
  273. $this->init_ui();
  274. $error = $this->managesieve_start();
  275. // Handle user requests
  276. if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
  277. $fid = (int) get_input_value('_fid', RCUBE_INPUT_POST);
  278. if ($action == 'delete' && !$error) {
  279. if (isset($this->script[$fid])) {
  280. if ($this->sieve->script->delete_rule($fid))
  281. $result = $this->save_script();
  282. if ($result === true) {
  283. $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
  284. $this->rc->output->command('managesieve_updatelist', 'del', array('id' => $fid));
  285. } else {
  286. $this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
  287. }
  288. }
  289. }
  290. else if ($action == 'move' && !$error) {
  291. if (isset($this->script[$fid])) {
  292. $to = (int) get_input_value('_to', RCUBE_INPUT_POST);
  293. $rule = $this->script[$fid];
  294. // remove rule
  295. unset($this->script[$fid]);
  296. $this->script = array_values($this->script);
  297. // add at target position
  298. if ($to >= count($this->script)) {
  299. $this->script[] = $rule;
  300. }
  301. else {
  302. $script = array();
  303. foreach ($this->script as $idx => $r) {
  304. if ($idx == $to)
  305. $script[] = $rule;
  306. $script[] = $r;
  307. }
  308. $this->script = $script;
  309. }
  310. $this->sieve->script->content = $this->script;
  311. $result = $this->save_script();
  312. if ($result === true) {
  313. $result = $this->list_rules();
  314. $this->rc->output->show_message('managesieve.moved', 'confirmation');
  315. $this->rc->output->command('managesieve_updatelist', 'list',
  316. array('list' => $result, 'clear' => true, 'set' => $to));
  317. } else {
  318. $this->rc->output->show_message('managesieve.moveerror', 'error');
  319. }
  320. }
  321. }
  322. else if ($action == 'act' && !$error) {
  323. if (isset($this->script[$fid])) {
  324. $rule = $this->script[$fid];
  325. $disabled = $rule['disabled'] ? true : false;
  326. $rule['disabled'] = !$disabled;
  327. $result = $this->sieve->script->update_rule($fid, $rule);
  328. if ($result !== false)
  329. $result = $this->save_script();
  330. if ($result === true) {
  331. if ($rule['disabled'])
  332. $this->rc->output->show_message('managesieve.deactivated', 'confirmation');
  333. else
  334. $this->rc->output->show_message('managesieve.activated', 'confirmation');
  335. $this->rc->output->command('managesieve_updatelist', 'update',
  336. array('id' => $fid, 'disabled' => $rule['disabled']));
  337. } else {
  338. if ($rule['disabled'])
  339. $this->rc->output->show_message('managesieve.deactivateerror', 'error');
  340. else
  341. $this->rc->output->show_message('managesieve.activateerror', 'error');
  342. }
  343. }
  344. }
  345. else if ($action == 'setact' && !$error) {
  346. $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
  347. $result = $this->activate_script($script_name);
  348. $kep14 = $this->rc->config->get('managesieve_kolab_master');
  349. if ($result === true) {
  350. $this->rc->output->set_env('active_sets', $this->active);
  351. $this->rc->output->show_message('managesieve.setactivated', 'confirmation');
  352. $this->rc->output->command('managesieve_updatelist', 'setact',
  353. array('name' => $script_name, 'active' => true, 'all' => !$kep14));
  354. } else {
  355. $this->rc->output->show_message('managesieve.setactivateerror', 'error');
  356. }
  357. }
  358. else if ($action == 'deact' && !$error) {
  359. $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
  360. $result = $this->deactivate_script($script_name);
  361. if ($result === true) {
  362. $this->rc->output->set_env('active_sets', $this->active);
  363. $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
  364. $this->rc->output->command('managesieve_updatelist', 'setact',
  365. array('name' => $script_name, 'active' => false));
  366. } else {
  367. $this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
  368. }
  369. }
  370. else if ($action == 'setdel' && !$error) {
  371. $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
  372. $result = $this->remove_script($script_name);
  373. if ($result === true) {
  374. $this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
  375. $this->rc->output->command('managesieve_updatelist', 'setdel',
  376. array('name' => $script_name));
  377. $this->rc->session->remove('managesieve_current');
  378. } else {
  379. $this->rc->output->show_message('managesieve.setdeleteerror', 'error');
  380. }
  381. }
  382. else if ($action == 'setget') {
  383. $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
  384. $script = $this->sieve->get_script($script_name);
  385. if (PEAR::isError($script))
  386. exit;
  387. $browser = new rcube_browser;
  388. // send download headers
  389. header("Content-Type: application/octet-stream");
  390. header("Content-Length: ".strlen($script));
  391. if ($browser->ie)
  392. header("Content-Type: application/force-download");
  393. if ($browser->ie && $browser->ver < 7)
  394. $filename = rawurlencode(abbreviate_string($script_name, 55));
  395. else if ($browser->ie)
  396. $filename = rawurlencode($script_name);
  397. else
  398. $filename = addcslashes($script_name, '\\"');
  399. header("Content-Disposition: attachment; filename=\"$filename.txt\"");
  400. echo $script;
  401. exit;
  402. }
  403. else if ($action == 'list') {
  404. $result = $this->list_rules();
  405. $this->rc->output->command('managesieve_updatelist', 'list', array('list' => $result));
  406. }
  407. else if ($action == 'ruleadd') {
  408. $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
  409. $id = $this->genid();
  410. $content = $this->rule_div($fid, $id, false);
  411. $this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
  412. }
  413. else if ($action == 'actionadd') {
  414. $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
  415. $id = $this->genid();
  416. $content = $this->action_div($fid, $id, false);
  417. $this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
  418. }
  419. $this->rc->output->send();
  420. }
  421. else if ($this->rc->task == 'mail') {
  422. // Initialize the form
  423. $rules = get_input_value('r', RCUBE_INPUT_GET);
  424. if (!empty($rules)) {
  425. $i = 0;
  426. foreach ($rules as $rule) {
  427. list($header, $value) = explode(':', $rule, 2);
  428. $tests[$i] = array(
  429. 'type' => 'contains',
  430. 'test' => 'header',
  431. 'arg1' => $header,
  432. 'arg2' => $value,
  433. );
  434. $i++;
  435. }
  436. $this->form = array(
  437. 'join' => count($tests) > 1 ? 'allof' : 'anyof',
  438. 'name' => '',
  439. 'tests' => $tests,
  440. 'actions' => array(
  441. 0 => array('type' => 'fileinto'),
  442. 1 => array('type' => 'stop'),
  443. ),
  444. );
  445. }
  446. }
  447. $this->managesieve_send();
  448. }
  449. function managesieve_save()
  450. {
  451. // load localization
  452. $this->add_texts('localization/', array('filters','managefilters'));
  453. // include main js script
  454. if ($this->api->output->type == 'html') {
  455. $this->include_script('managesieve.js');
  456. }
  457. // Init plugin and handle managesieve connection
  458. $error = $this->managesieve_start();
  459. // get request size limits (#1488648)
  460. $max_post = max(array(
  461. ini_get('max_input_vars'),
  462. ini_get('suhosin.request.max_vars'),
  463. ini_get('suhosin.post.max_vars'),
  464. ));
  465. $max_depth = max(array(
  466. ini_get('suhosin.request.max_array_depth'),
  467. ini_get('suhosin.post.max_array_depth'),
  468. ));
  469. // check request size limit
  470. if ($max_post && count($_POST, COUNT_RECURSIVE) >= $max_post) {
  471. rcube::raise_error(array(
  472. 'code' => 500, 'type' => 'php',
  473. 'file' => __FILE__, 'line' => __LINE__,
  474. 'message' => "Request size limit exceeded (one of max_input_vars/suhosin.request.max_vars/suhosin.post.max_vars)"
  475. ), true, false);
  476. $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
  477. }
  478. // check request depth limits
  479. else if ($max_depth && count($_POST['_header']) > $max_depth) {
  480. rcube::raise_error(array(
  481. 'code' => 500, 'type' => 'php',
  482. 'file' => __FILE__, 'line' => __LINE__,
  483. 'message' => "Request size limit exceeded (one of suhosin.request.max_array_depth/suhosin.post.max_array_depth)"
  484. ), true, false);
  485. $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
  486. }
  487. // filters set add action
  488. else if (!empty($_POST['_newset'])) {
  489. $name = get_input_value('_name', RCUBE_INPUT_POST, true);
  490. $copy = get_input_value('_copy', RCUBE_INPUT_POST, true);
  491. $from = get_input_value('_from', RCUBE_INPUT_POST);
  492. $exceptions = $this->rc->config->get('managesieve_filename_exceptions');
  493. $kolab = $this->rc->config->get('managesieve_kolab_master');
  494. $name_uc = mb_strtolower($name);
  495. $list = $this->list_scripts();
  496. if (!$name) {
  497. $this->errors['name'] = $this->gettext('cannotbeempty');
  498. }
  499. else if (mb_strlen($name) > 128) {
  500. $this->errors['name'] = $this->gettext('nametoolong');
  501. }
  502. else if (!empty($exceptions) && in_array($name, (array)$exceptions)) {
  503. $this->errors['name'] = $this->gettext('namereserved');
  504. }
  505. else if (!empty($kolab) && in_array($name_uc, array('MASTER', 'USER', 'MANAGEMENT'))) {
  506. $this->errors['name'] = $this->gettext('namereserved');
  507. }
  508. else if (in_array($name, $list)) {
  509. $this->errors['name'] = $this->gettext('setexist');
  510. }
  511. else if ($from == 'file') {
  512. // from file
  513. if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
  514. $file = file_get_contents($_FILES['_file']['tmp_name']);
  515. $file = preg_replace('/\r/', '', $file);
  516. // for security don't save script directly
  517. // check syntax before, like this...
  518. $this->sieve->load_script($file);
  519. if (!$this->save_script($name)) {
  520. $this->errors['file'] = $this->gettext('setcreateerror');
  521. }
  522. }
  523. else { // upload failed
  524. $err = $_FILES['_file']['error'];
  525. if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
  526. $msg = rcube_label(array('name' => 'filesizeerror',
  527. 'vars' => array('size' =>
  528. show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
  529. }
  530. else {
  531. $this->errors['file'] = $this->gettext('fileuploaderror');
  532. }
  533. }
  534. }
  535. else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
  536. $error = 'managesieve.setcreateerror';
  537. }
  538. if (!$error && empty($this->errors)) {
  539. // Find position of the new script on the list
  540. $list[] = $name;
  541. asort($list, SORT_LOCALE_STRING);
  542. $list = array_values($list);
  543. $index = array_search($name, $list);
  544. $this->rc->output->show_message('managesieve.setcreated', 'confirmation');
  545. $this->rc->output->command('parent.managesieve_updatelist', 'setadd',
  546. array('name' => $name, 'index' => $index));
  547. } else if ($msg) {
  548. $this->rc->output->command('display_message', $msg, 'error');
  549. } else if ($error) {
  550. $this->rc->output->show_message($error, 'error');
  551. }
  552. }
  553. // filter add/edit action
  554. else if (isset($_POST['_name'])) {
  555. $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
  556. $fid = trim(get_input_value('_fid', RCUBE_INPUT_POST));
  557. $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
  558. // and arrays
  559. $headers = get_input_value('_header', RCUBE_INPUT_POST);
  560. $cust_headers = get_input_value('_custom_header', RCUBE_INPUT_POST);
  561. $ops = get_input_value('_rule_op', RCUBE_INPUT_POST);
  562. $sizeops = get_input_value('_rule_size_op', RCUBE_INPUT_POST);
  563. $sizeitems = get_input_value('_rule_size_item', RCUBE_INPUT_POST);
  564. $sizetargets = get_input_value('_rule_size_target', RCUBE_INPUT_POST);
  565. $targets = get_input_value('_rule_target', RCUBE_INPUT_POST, true);
  566. $mods = get_input_value('_rule_mod', RCUBE_INPUT_POST);
  567. $mod_types = get_input_value('_rule_mod_type', RCUBE_INPUT_POST);
  568. $body_trans = get_input_value('_rule_trans', RCUBE_INPUT_POST);
  569. $body_types = get_input_value('_rule_trans_type', RCUBE_INPUT_POST, true);
  570. $comparators = get_input_value('_rule_comp', RCUBE_INPUT_POST);
  571. $act_types = get_input_value('_action_type', RCUBE_INPUT_POST, true);
  572. $mailboxes = get_input_value('_action_mailbox', RCUBE_INPUT_POST, true);
  573. $act_targets = get_input_value('_action_target', RCUBE_INPUT_POST, true);
  574. $area_targets = get_input_value('_action_target_area', RCUBE_INPUT_POST, true);
  575. $reasons = get_input_value('_action_reason', RCUBE_INPUT_POST, true);
  576. $addresses = get_input_value('_action_addresses', RCUBE_INPUT_POST, true);
  577. $days = get_input_value('_action_days', RCUBE_INPUT_POST);
  578. $subject = get_input_value('_action_subject', RCUBE_INPUT_POST, true);
  579. $flags = get_input_value('_action_flags', RCUBE_INPUT_POST);
  580. $varnames = get_input_value('_action_varname', RCUBE_INPUT_POST);
  581. $varvalues = get_input_value('_action_varvalue', RCUBE_INPUT_POST);
  582. $varmods = get_input_value('_action_varmods', RCUBE_INPUT_POST);
  583. $notifyaddrs = get_input_value('_action_notifyaddress', RCUBE_INPUT_POST);
  584. $notifybodies = get_input_value('_action_notifybody', RCUBE_INPUT_POST);
  585. $notifymessages = get_input_value('_action_notifymessage', RCUBE_INPUT_POST);
  586. $notifyfrom = get_input_value('_action_notifyfrom', RCUBE_INPUT_POST);
  587. $notifyimp = get_input_value('_action_notifyimportance', RCUBE_INPUT_POST);
  588. // we need a "hack" for radiobuttons
  589. foreach ($sizeitems as $item)
  590. $items[] = $item;
  591. $this->form['disabled'] = $_POST['_disabled'] ? true : false;
  592. $this->form['join'] = $join=='allof' ? true : false;
  593. $this->form['name'] = $name;
  594. $this->form['tests'] = array();
  595. $this->form['actions'] = array();
  596. if ($name == '')
  597. $this->errors['name'] = $this->gettext('cannotbeempty');
  598. else {
  599. foreach($this->script as $idx => $rule)
  600. if($rule['name'] == $name && $idx != $fid) {
  601. $this->errors['name'] = $this->gettext('ruleexist');
  602. break;
  603. }
  604. }
  605. $i = 0;
  606. // rules
  607. if ($join == 'any') {
  608. $this->form['tests'][0]['test'] = 'true';
  609. }
  610. else {
  611. foreach ($headers as $idx => $header) {
  612. $header = $this->strip_value($header);
  613. $target = $this->strip_value($targets[$idx], true);
  614. $operator = $this->strip_value($ops[$idx]);
  615. $comparator = $this->strip_value($comparators[$idx]);
  616. if ($header == 'size') {
  617. $sizeop = $this->strip_value($sizeops[$idx]);
  618. $sizeitem = $this->strip_value($items[$idx]);
  619. $sizetarget = $this->strip_value($sizetargets[$idx]);
  620. $this->form['tests'][$i]['test'] = 'size';
  621. $this->form['tests'][$i]['type'] = $sizeop;
  622. $this->form['tests'][$i]['arg'] = $sizetarget;
  623. if ($sizetarget == '')
  624. $this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
  625. else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) {
  626. $this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
  627. $this->form['tests'][$i]['item'] = $sizeitem;
  628. }
  629. else
  630. $this->form['tests'][$i]['arg'] .= $m[1];
  631. }
  632. else if ($header == 'body') {
  633. $trans = $this->strip_value($body_trans[$idx]);
  634. $trans_type = $this->strip_value($body_types[$idx], true);
  635. if (preg_match('/^not/', $operator))
  636. $this->form['tests'][$i]['not'] = true;
  637. $type = preg_replace('/^not/', '', $operator);
  638. if ($type == 'exists') {
  639. $this->errors['tests'][$i]['op'] = true;
  640. }
  641. $this->form['tests'][$i]['test'] = 'body';
  642. $this->form['tests'][$i]['type'] = $type;
  643. $this->form['tests'][$i]['arg'] = $target;
  644. if ($target == '' && $type != 'exists')
  645. $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
  646. else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
  647. $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
  648. $this->form['tests'][$i]['part'] = $trans;
  649. if ($trans == 'content') {
  650. $this->form['tests'][$i]['content'] = $trans_type;
  651. }
  652. }
  653. else {
  654. $cust_header = $headers = $this->strip_value($cust_headers[$idx]);
  655. $mod = $this->strip_value($mods[$idx]);
  656. $mod_type = $this->strip_value($mod_types[$idx]);
  657. if (preg_match('/^not/', $operator))
  658. $this->form['tests'][$i]['not'] = true;
  659. $type = preg_replace('/^not/', '', $operator);
  660. if ($header == '...') {
  661. $headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
  662. if (!count($headers))
  663. $this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
  664. else {
  665. foreach ($headers as $hr) {
  666. // RFC2822: printable ASCII except colon
  667. if (!preg_match('/^[\x21-\x39\x41-\x7E]+$/i', $hr)) {
  668. $this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
  669. }
  670. }
  671. }
  672. if (empty($this->errors['tests'][$i]['header']))
  673. $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
  674. }
  675. if ($type == 'exists') {
  676. $this->form['tests'][$i]['test'] = 'exists';
  677. $this->form['tests'][$i]['arg'] = $header == '...' ? $cust_header : $header;
  678. }
  679. else {
  680. $test = 'header';
  681. $header = $header == '...' ? $cust_header : $header;
  682. if ($mod == 'address' || $mod == 'envelope') {
  683. $found = false;
  684. if (empty($this->errors['tests'][$i]['header'])) {
  685. foreach ((array)$header as $hdr) {
  686. if (!in_array(strtolower(trim($hdr)), $this->addr_headers))
  687. $found = true;
  688. }
  689. }
  690. if (!$found)
  691. $test = $mod;
  692. }
  693. $this->form['tests'][$i]['type'] = $type;
  694. $this->form['tests'][$i]['test'] = $test;
  695. $this->form['tests'][$i]['arg1'] = $header;
  696. $this->form['tests'][$i]['arg2'] = $target;
  697. if ($target == '')
  698. $this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
  699. else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
  700. $this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
  701. if ($mod) {
  702. $this->form['tests'][$i]['part'] = $mod_type;
  703. }
  704. }
  705. }
  706. if ($header != 'size' && $comparator) {
  707. if (preg_match('/^(value|count)/', $this->form['tests'][$i]['type']))
  708. $comparator = 'i;ascii-numeric';
  709. $this->form['tests'][$i]['comparator'] = $comparator;
  710. }
  711. $i++;
  712. }
  713. }
  714. $i = 0;
  715. // actions
  716. foreach($act_types as $idx => $type) {
  717. $type = $this->strip_value($type);
  718. $target = $this->strip_value($act_targets[$idx]);
  719. switch ($type) {
  720. case 'fileinto':
  721. case 'fileinto_copy':
  722. $mailbox = $this->strip_value($mailboxes[$idx]);
  723. $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
  724. if ($type == 'fileinto_copy') {
  725. $type = 'fileinto';
  726. $this->form['actions'][$i]['copy'] = true;
  727. }
  728. break;
  729. case 'reject':
  730. case 'ereject':
  731. $target = $this->strip_value($area_targets[$idx]);
  732. $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
  733. // if ($target == '')
  734. // $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
  735. break;
  736. case 'redirect':
  737. case 'redirect_copy':
  738. $this->form['actions'][$i]['target'] = $target;
  739. if ($this->form['actions'][$i]['target'] == '')
  740. $this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
  741. else if (!check_email($this->form['actions'][$i]['target']))
  742. $this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
  743. if ($type == 'redirect_copy') {
  744. $type = 'redirect';
  745. $this->form['actions'][$i]['copy'] = true;
  746. }
  747. break;
  748. case 'addflag':
  749. case 'setflag':
  750. case 'removeflag':
  751. $_target = array();
  752. if (empty($flags[$idx])) {
  753. $this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
  754. }
  755. else {
  756. foreach ($flags[$idx] as $flag) {
  757. $_target[] = $this->strip_value($flag);
  758. }
  759. }
  760. $this->form['actions'][$i]['target'] = $_target;
  761. break;
  762. case 'vacation':
  763. $reason = $this->strip_value($reasons[$idx]);
  764. $this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason);
  765. $this->form['actions'][$i]['days'] = $days[$idx];
  766. $this->form['actions'][$i]['subject'] = $subject[$idx];
  767. $this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
  768. // @TODO: vacation :mime, :from, :handle
  769. if ($this->form['actions'][$i]['addresses']) {
  770. foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
  771. $address = trim($address);
  772. if (!$address)
  773. unset($this->form['actions'][$i]['addresses'][$aidx]);
  774. else if(!check_email($address)) {
  775. $this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
  776. break;
  777. } else
  778. $this->form['actions'][$i]['addresses'][$aidx] = $address;
  779. }
  780. }
  781. if ($this->form['actions'][$i]['reason'] == '')
  782. $this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
  783. if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
  784. $this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
  785. break;
  786. case 'set':
  787. $this->form['actions'][$i]['name'] = $varnames[$idx];
  788. $this->form['actions'][$i]['value'] = $varvalues[$idx];
  789. foreach ((array)$varmods[$idx] as $v_m) {
  790. $this->form['actions'][$i][$v_m] = true;
  791. }
  792. if (empty($varnames[$idx])) {
  793. $this->errors['actions'][$i]['name'] = $this->gettext('cannotbeempty');
  794. }
  795. else if (!preg_match('/^[0-9a-z_]+$/i', $varnames[$idx])) {
  796. $this->errors['actions'][$i]['name'] = $this->gettext('forbiddenchars');
  797. }
  798. if (!isset($varvalues[$idx]) || $varvalues[$idx] === '') {
  799. $this->errors['actions'][$i]['value'] = $this->gettext('cannotbeempty');
  800. }
  801. break;
  802. case 'notify':
  803. if (empty($notifyaddrs[$idx])) {
  804. $this->errors['actions'][$i]['address'] = $this->gettext('cannotbeempty');
  805. }
  806. else if (!check_email($notifyaddrs[$idx])) {
  807. $this->errors['actions'][$i]['address'] = $this->gettext('noemailwarning');
  808. }
  809. if (!empty($notifyfrom[$idx]) && !check_email($notifyfrom[$idx])) {
  810. $this->errors['actions'][$i]['from'] = $this->gettext('noemailwarning');
  811. }
  812. $this->form['actions'][$i]['address'] = $notifyaddrs[$idx];
  813. $this->form['actions'][$i]['body'] = $notifybodies[$idx];
  814. $this->form['actions'][$i]['message'] = $notifymessages[$idx];
  815. $this->form['actions'][$i]['from'] = $notifyfrom[$idx];
  816. $this->form['actions'][$i]['importance'] = $notifyimp[$idx];
  817. break;
  818. }
  819. $this->form['actions'][$i]['type'] = $type;
  820. $i++;
  821. }
  822. if (!$this->errors && !$error) {
  823. // zapis skryptu
  824. if (!isset($this->script[$fid])) {
  825. $fid = $this->sieve->script->add_rule($this->form);
  826. $new = true;
  827. } else
  828. $fid = $this->sieve->script->update_rule($fid, $this->form);
  829. if ($fid !== false)
  830. $save = $this->save_script();
  831. if ($save && $fid !== false) {
  832. $this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
  833. if ($this->rc->task != 'mail') {
  834. $this->rc->output->command('parent.managesieve_updatelist',
  835. isset($new) ? 'add' : 'update',
  836. array(
  837. 'name' => Q($this->form['name']),
  838. 'id' => $fid,
  839. 'disabled' => $this->form['disabled']
  840. ));
  841. }
  842. else {
  843. $this->rc->output->command('managesieve_dialog_close');
  844. $this->rc->output->send('iframe');
  845. }
  846. }
  847. else {
  848. $this->rc->output->show_message('managesieve.filtersaveerror', 'error');
  849. // $this->rc->output->send();
  850. }
  851. }
  852. }
  853. $this->managesieve_send();
  854. }
  855. private function managesieve_send()
  856. {
  857. // Handle form action
  858. if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
  859. if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
  860. $this->rc->output->send('managesieve.setedit');
  861. }
  862. else {
  863. $this->rc->output->send('managesieve.filteredit');
  864. }
  865. } else {
  866. $this->rc->output->set_pagetitle($this->gettext('filters'));
  867. $this->rc->output->send('managesieve.managesieve');
  868. }
  869. }
  870. // return the filters list as HTML table
  871. function filters_list($attrib)
  872. {
  873. // add id to message list table if not specified
  874. if (!strlen($attrib['id']))
  875. $attrib['id'] = 'rcmfilterslist';
  876. // define list of cols to be displayed
  877. $a_show_cols = array('name');
  878. $result = $this->list_rules();
  879. // create XHTML table
  880. $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
  881. // set client env
  882. $this->rc->output->add_gui_object('filterslist', $attrib['id']);
  883. $this->rc->output->include_script('list.js');
  884. // add some labels to client
  885. $this->rc->output->add_label('managesieve.filterdeleteconfirm');
  886. return $out;
  887. }
  888. // return the filters list as <SELECT>
  889. function filtersets_list($attrib, $no_env = false)
  890. {
  891. // add id to message list table if not specified
  892. if (!strlen($attrib['id']))
  893. $attrib['id'] = 'rcmfiltersetslist';
  894. $list = $this->list_scripts();
  895. if ($list) {
  896. asort($list, SORT_LOCALE_STRING);
  897. }
  898. if (!empty($attrib['type']) && $attrib['type'] == 'list') {
  899. // define list of cols to be displayed
  900. $a_show_cols = array('name');
  901. if ($list) {
  902. foreach ($list as $idx => $set) {
  903. $scripts['S'.$idx] = $set;
  904. $result[] = array(
  905. 'name' => Q($set),
  906. 'id' => 'S'.$idx,
  907. 'class' => !in_array($set, $this->active) ? 'disabled' : '',
  908. );
  909. }
  910. }
  911. // create XHTML table
  912. $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
  913. $this->rc->output->set_env('filtersets', $scripts);
  914. $this->rc->output->include_script('list.js');
  915. }
  916. else {
  917. $select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
  918. 'onchange' => $this->rc->task != 'mail' ? 'rcmail.managesieve_set()' : ''));
  919. if ($list) {
  920. foreach ($list as $set)
  921. $select->add($set, $set);
  922. }
  923. $out = $select->show($this->sieve->current);
  924. }
  925. // set client env
  926. if (!$no_env) {
  927. $this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
  928. $this->rc->output->add_label('managesieve.setdeleteconfirm');
  929. }
  930. return $out;
  931. }
  932. function filter_frame($attrib)
  933. {
  934. if (!$attrib['id'])
  935. $attrib['id'] = 'rcmfilterframe';
  936. $attrib['name'] = $attrib['id'];
  937. $this->rc->output->set_env('contentframe', $attrib['name']);
  938. $this->rc->output->set_env('blankpage', $attrib['src'] ?
  939. $this->rc->output->abs_url($attrib['src']) : 'program/resources/blank.gif');
  940. return $this->rc->output->frame($attrib);
  941. }
  942. function filterset_form($attrib)
  943. {
  944. if (!$attrib['id'])
  945. $attrib['id'] = 'rcmfiltersetform';
  946. $out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
  947. $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
  948. $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
  949. $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
  950. $hiddenfields->add(array('name' => '_newset', 'value' => 1));
  951. $out .= $hiddenfields->show();
  952. $name = get_input_value('_name', RCUBE_INPUT_POST);
  953. $copy = get_input_value('_copy', RCUBE_INPUT_POST);
  954. $selected = get_input_value('_from', RCUBE_INPUT_POST);
  955. // filter set name input
  956. $input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
  957. 'class' => ($this->errors['name'] ? 'error' : '')));
  958. $out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
  959. '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
  960. $out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
  961. $out .= '<input type="radio" id="from_none" name="_from" value="none"'
  962. .(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
  963. $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
  964. // filters set list
  965. $list = $this->list_scripts();
  966. $select = new html_select(array('name' => '_copy', 'id' => '_copy'));
  967. if (is_array($list)) {
  968. asort($list, SORT_LOCALE_STRING);
  969. if (!$copy)
  970. $copy = $_SESSION['managesieve_current'];
  971. foreach ($list as $set) {
  972. $select->add($set, $set);
  973. }
  974. $out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
  975. .($selected=='set' ? ' checked="checked"' : '').'></input>';
  976. $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
  977. $out .= $select->show($copy);
  978. }
  979. // script upload box
  980. $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
  981. 'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : '')));
  982. $out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
  983. .($selected=='file' ? ' checked="checked"' : '').'></input>';
  984. $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
  985. $out .= $upload->show();
  986. $out .= '</fieldset>';
  987. $this->rc->output->add_gui_object('sieveform', 'filtersetform');
  988. if ($this->errors['name'])
  989. $this->add_tip('_name', $this->errors['name'], true);
  990. if ($this->errors['file'])
  991. $this->add_tip('_file', $this->errors['file'], true);
  992. $this->print_tips();
  993. return $out;
  994. }
  995. function filter_form($attrib)
  996. {
  997. if (!$attrib['id'])
  998. $attrib['id'] = 'rcmfilterform';
  999. $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
  1000. $scr = isset($this->form) ? $this->form : $this->script[$fid];
  1001. $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
  1002. $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
  1003. $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
  1004. $hiddenfields->add(array('name' => '_fid', 'value' => $fid));
  1005. $out = '<form name="filterform" action="./" method="post">'."\n";
  1006. $out .= $hiddenfields->show();
  1007. // 'any' flag
  1008. if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
  1009. $any = true;
  1010. // filter name input
  1011. $field_id = '_name';
  1012. $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
  1013. 'class' => ($this->errors['name'] ? 'error' : '')));
  1014. if ($this->errors['name'])
  1015. $this->add_tip($field_id, $this->errors['name'], true);
  1016. if (isset($scr))
  1017. $input_name = $input_name->show($scr['name']);
  1018. else
  1019. $input_name = $input_name->show();
  1020. $out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s\n",
  1021. $field_id, Q($this->gettext('filtername')), $input_name);
  1022. // filter set selector
  1023. if ($this->rc->task == 'mail') {
  1024. $out .= sprintf("\n&nbsp;<label for=\"%s\"><b>%s:</b></label> %s\n",
  1025. $field_id, Q($this->gettext('filterset')),
  1026. $this->filtersets_list(array('id' => 'sievescriptname'), true));
  1027. }
  1028. $out .= '<br /><br /><fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
  1029. // any, allof, anyof radio buttons
  1030. $field_id = '_allof';
  1031. $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
  1032. 'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
  1033. if (isset($scr) && !$any)
  1034. $input_join = $input_join->show($scr['join'] ? 'allof' : '');
  1035. else
  1036. $input_join = $input_join->show();
  1037. $out .= sprintf("%s<label for=\"%s\">%s</label>&nbsp;\n",
  1038. $input_join, $field_id, Q($this->gettext('filterallof')));
  1039. $field_id = '_anyof';
  1040. $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
  1041. 'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
  1042. if (isset($scr) && !$any)
  1043. $input_join = $input_join->show($scr['join'] ? '' : 'anyof');
  1044. else
  1045. $input_join = $input_join->show('anyof'); // default
  1046. $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
  1047. $input_join, $field_id, Q($this->gettext('filteranyof')));
  1048. $field_id = '_any';
  1049. $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
  1050. 'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
  1051. $input_join = $input_join->show($any ? 'any' : '');
  1052. $out .= sprintf("%s<label for=\"%s\">%s</label>\n",
  1053. $input_join, $field_id, Q($this->gettext('filterany')));
  1054. $rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
  1055. $out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
  1056. for ($x=0; $x<$rows_num; $x++)
  1057. $out .= $this->rule_div($fid, $x);
  1058. $out .= "</div>\n";
  1059. $out .= "</fieldset>\n";
  1060. // actions
  1061. $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
  1062. $rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
  1063. $out .= '<div id="actions">';
  1064. for ($x=0; $x<$rows_num; $x++)
  1065. $out .= $this->action_div($fid, $x);
  1066. $out .= "</div>\n";
  1067. $out .= "</fieldset>\n";
  1068. $this->print_tips();
  1069. if ($scr['disabled']) {
  1070. $this->rc->output->set_env('rule_disabled', true);
  1071. }
  1072. $this->rc->output->add_label(
  1073. 'managesieve.ruledeleteconfirm',
  1074. 'managesieve.actiondeleteconfirm'
  1075. );
  1076. $this->rc->output->add_gui_object('sieveform', 'filterform');
  1077. return $out;
  1078. }
  1079. function rule_div($fid, $id, $div=true)
  1080. {
  1081. $rule = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
  1082. $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
  1083. // headers select
  1084. $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
  1085. 'onchange' => 'rule_header_select(' .$id .')'));
  1086. foreach($this->headers as $name => $val)
  1087. $select_header->add(Q($this->gettext($name)), Q($val));
  1088. if (in_array('body', $this->exts))
  1089. $select_header->add(Q($this->gettext('body')), 'body');
  1090. $select_header->add(Q($this->gettext('size')), 'size');
  1091. $select_header->add(Q($this->gettext('...')), '...');
  1092. // TODO: list arguments
  1093. $aout = '';
  1094. if ((isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope')))
  1095. && !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers)
  1096. ) {
  1097. $aout .= $select_header->show($rule['arg1']);
  1098. }
  1099. else if ((isset($rule['test']) && $rule['test'] == 'exists')
  1100. && !is_array($rule['arg']) && in_array($rule['arg'], $this->headers)
  1101. ) {
  1102. $aout .= $select_header->show($rule['arg']);
  1103. }
  1104. else if (isset($rule['test']) && $rule['test'] == 'size')
  1105. $aout .= $select_header->show('size');
  1106. else if (isset($rule['test']) && $rule['test'] == 'body')
  1107. $aout .= $select_header->show('body');
  1108. else if (isset($rule['test']) && $rule['test'] != 'true')
  1109. $aout .= $select_header->show('...');
  1110. else
  1111. $aout .= $select_header->show();
  1112. if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) {
  1113. if (is_array($rule['arg1']))
  1114. $custom = implode(', ', $rule['arg1']);
  1115. else if (!in_array($rule['arg1'], $this->headers))
  1116. $custom = $rule['arg1'];
  1117. }
  1118. else if (isset($rule['test']) && $rule['test'] == 'exists') {
  1119. if (is_array($rule['arg']))
  1120. $custom = implode(', ', $rule['arg']);
  1121. else if (!in_array($rule['arg'], $this->headers))
  1122. $custom = $rule['arg'];
  1123. }
  1124. $tout = '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
  1125. <input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
  1126. . $this->error_class($id, 'test', 'header', 'custom_header_i')
  1127. .' value="' .Q($custom). '" size="15" />&nbsp;</div>' . "\n";
  1128. // matching type select (operator)
  1129. $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
  1130. 'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
  1131. 'class' => 'operator_selector',
  1132. 'onchange' => 'rule_op_select('.$id.')'));
  1133. $select_op->add(Q($this->gettext('filtercontains')), 'contains');
  1134. $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
  1135. $select_op->add(Q($this->gettext('filteris')), 'is');
  1136. $select_op->add(Q($this->gettext('filterisnot')), 'notis');
  1137. $select_op->add(Q($this->gettext('filterexists')), 'exists');
  1138. $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
  1139. $select_op->add(Q($this->gettext('filtermatches')), 'matches');
  1140. $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
  1141. if (in_array('regex', $this->exts)) {
  1142. $select_op->add(Q($this->gettext('filterregex')), 'regex');
  1143. $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
  1144. }
  1145. if (in_array('relational', $this->exts)) {
  1146. $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
  1147. $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
  1148. $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
  1149. $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
  1150. $select_op->add(Q($this->gettext('countequals')), 'count-eq');
  1151. $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
  1152. $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
  1153. $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
  1154. $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
  1155. $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
  1156. $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
  1157. $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
  1158. }
  1159. // target input (TODO: lists)
  1160. if (in_array($rule['test'], array('header', 'address', 'envelope'))) {
  1161. $test = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
  1162. $target = $rule['arg2'];
  1163. }
  1164. else if ($rule['test'] == 'body') {
  1165. $test = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
  1166. $target = $rule['arg'];
  1167. }
  1168. else if ($rule['test'] == 'size') {
  1169. $test = '';
  1170. $target = '';
  1171. if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) {
  1172. $sizetarget = $matches[1];
  1173. $sizeitem = $matches[2];
  1174. }
  1175. else {
  1176. $sizetarget = $rule['arg'];
  1177. $sizeitem = $rule['item'];
  1178. }
  1179. }
  1180. else {
  1181. $test = ($rule['not'] ? 'not' : '').$rule['test'];
  1182. $target = '';
  1183. }
  1184. $tout .= $select_op->show($test);
  1185. $tout .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
  1186. value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
  1187. . ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
  1188. $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
  1189. $select_size_op->add(Q($this->gettext('filterover')), 'over');
  1190. $select_size_op->add(Q($this->gettext('filterunder')), 'under');
  1191. $tout .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
  1192. $tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
  1193. $tout .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" '
  1194. . $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
  1195. <input type="radio" name="_rule_size_item['.$id.']" value=""'
  1196. . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
  1197. <input type="radio" name="_rule_size_item['.$id.']" value="K"'
  1198. . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
  1199. <input type="radio" name="_rule_size_item['.$id.']" value="M"'
  1200. . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
  1201. <input type="radio" name="_rule_size_item['.$id.']" value="G"'
  1202. . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
  1203. $tout .= '</div>';
  1204. // Advanced modifiers (address, envelope)
  1205. $select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id,
  1206. 'onchange' => 'rule_mod_select(' .$id .')'));
  1207. $select_mod->add(Q($this->gettext('none')), '');
  1208. $select_mod->add(Q($this->gettext('address')), 'address');
  1209. if (in_array('envelope', $this->exts))
  1210. $select_mod->add(Q($this->gettext('envelope')), 'envelope');
  1211. $select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id));
  1212. $select_type->add(Q($this->gettext('allparts')), 'all');
  1213. $select_type->add(Q($this->gettext('domain')), 'domain');
  1214. $select_type->add(Q($this->gettext('localpart')), 'localpart');
  1215. if (in_array('subaddress', $this->exts)) {
  1216. $select_type->add(Q($this->gettext('user')), 'user');
  1217. $select_type->add(Q($this->gettext('detail')), 'detail');
  1218. }
  1219. $need_mod = $rule['test'] != 'size' && $rule['test'] != 'body';
  1220. $mout = '<div id="rule_mod' .$id. '" class="adv" style="display:' . ($need_mod ? 'block' : 'none') .'">';
  1221. $mout .= ' <span>';
  1222. $mout .= Q($this->gettext('modifier')) . ' ';
  1223. $mout .= $select_mod->show($rule['test']);
  1224. $mout .= '</span>';
  1225. $mout .= ' <span id="rule_mod_type' . $id . '"';
  1226. $mout .= ' style="display:' . (in_array($rule['test'], array('address', 'envelope')) ? 'inline' : 'none') .'">';
  1227. $mout .= Q($this->gettext('modtype')) . ' ';
  1228. $mout .= $select_type->show($rule['part']);
  1229. $mout .= '</span>';
  1230. $mout .= '</div>';
  1231. // Advanced modifiers (body transformations)
  1232. $select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id,
  1233. 'onchange' => 'rule_trans_select(' .$id .')'));
  1234. $select_mod->add(Q($this->gettext('text')), 'text');
  1235. $select_mod->add(Q($this->gettext('undecoded')), 'raw');
  1236. $select_mod->add(Q($this->gettext('contenttype')), 'content');
  1237. $mout .= '<div id="rule_trans' .$id. '" class="adv" style="display:' . ($rule['test'] == 'body' ? 'block' : 'none') .'">';
  1238. $mout .= ' <span>';
  1239. $mout .= Q($this->gettext('modifier')) . ' ';
  1240. $mout .= $select_mod->show($rule['part']);
  1241. $mout .= '<input type="text" name="_rule_trans_type[]" id="rule_trans_type'.$id
  1242. . '" value="'.(is_array($rule['content']) ? implode(',', $rule['content']) : $rule['content'])
  1243. .'" size="20" style="display:' . ($rule['part'] == 'content' ? 'inline' : 'none') .'"'
  1244. . $this->error_class($id, 'test', 'part', 'rule_trans_type') .' />';
  1245. $mout .= '</span>';
  1246. $mout .= '</div>';
  1247. // Advanced modifiers (body transformations)
  1248. $select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id));
  1249. $select_comp->add(Q($this->gettext('default')), '');
  1250. $select_comp->add(Q($this->gettext('octet')), 'i;octet');
  1251. $select_comp->add(Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
  1252. if (in_array('comparator-i;ascii-numeric', $this->exts)) {
  1253. $select_comp->add(Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
  1254. }
  1255. $mout .= '<div id="rule_comp' .$id. '" class="adv" style="display:' . ($rule['test'] != 'size' ? 'block' : 'none') .'">';
  1256. $mout .= ' <span>';
  1257. $mout .= Q($this->gettext('comparator')) . ' ';
  1258. $mout .= $select_comp->show($rule['comparator']);
  1259. $mout .= '</span>';
  1260. $mout .= '</div>';
  1261. // Build output table
  1262. $out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
  1263. $out .= '<table><tr>';
  1264. $out .= '<td class="advbutton">';
  1265. $out .= '<a href="#" id="ruleadv' . $id .'" title="'. Q($this->gettext('advancedopts')). '"
  1266. onclick="rule_adv_switch(' . $id .', this)" class="show">&nbsp;&nbsp;</a>';
  1267. $out .= '</td>';
  1268. $out .= '<td class="rowactions">' . $aout . '</td>';
  1269. $out .= '<td class="rowtargets">' . $tout . "\n";
  1270. $out .= '<div id="rule_advanced' .$id. '" style="display:none">' . $mout . '</div>';
  1271. $out .= '</td>';
  1272. // add/del buttons
  1273. $out .= '<td class="rowbuttons">';
  1274. $out .= '<a href="#" id="ruleadd' . $id .'" title="'. Q($this->gettext('add')). '"
  1275. onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
  1276. $out .= '<a href="#" id="ruledel' . $id .'" title="'. Q($this->gettext('del')). '"
  1277. onclick="rcmail.managesieve_ruledel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
  1278. $out .= '</td>';
  1279. $out .= '</tr></table>';
  1280. $out .= $div ? "</div>\n" : '';
  1281. return $out;
  1282. }
  1283. function action_div($fid, $id, $div=true)
  1284. {
  1285. $action = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
  1286. $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
  1287. $out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
  1288. $out .= '<table><tr><td class="rowactions">';
  1289. // action select
  1290. $select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id,
  1291. 'onchange' => 'action_type_select(' .$id .')'));
  1292. if (in_array('fileinto', $this->exts))
  1293. $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
  1294. if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
  1295. $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
  1296. $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
  1297. if (in_array('copy', $this->exts))
  1298. $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
  1299. if (in_array('reject', $this->exts))
  1300. $select_action->add(Q($this->gettext('messagediscard')), 'reject');
  1301. else if (in_array('ereject', $this->exts))
  1302. $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
  1303. if (in_array('vacation', $this->exts))
  1304. $select_action->add(Q($this->gettext('messagereply')), 'vacation');
  1305. $select_action->add(Q($this->gettext('messagedelete')), 'discard');
  1306. if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
  1307. $select_action->add(Q($this->gettext('setflags')), 'setflag');
  1308. $select_action->add(Q($this->gettext('addflags')), 'addflag');
  1309. $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
  1310. }
  1311. if (in_array('variables', $this->exts)) {
  1312. $select_action->add(Q($this->gettext('setvariable')), 'set');
  1313. }
  1314. if (in_array('enotify', $this->exts) || in_array('notify', $this->exts)) {
  1315. $select_action->add(Q($this->gettext('notify')), 'notify');
  1316. }
  1317. $select_action->add(Q($this->gettext('rulestop')), 'stop');
  1318. $select_type = $action['type'];
  1319. if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
  1320. $select_type .= '_copy';
  1321. }
  1322. $out .= $select_action->show($select_type);
  1323. $out .= '</td>';
  1324. // actions target inputs
  1325. $out .= '<td class="rowtargets">';
  1326. // shared targets
  1327. $out .= '<input type="text" name="_action_target['.$id.']" id="action_target' .$id. '" '
  1328. .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="35" '
  1329. .'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
  1330. . $this->error_class($id, 'action', 'target', 'action_target') .' />';
  1331. $out .= '<textarea name="_action_target_area['.$id.']" id="action_target_area' .$id. '" '
  1332. .'rows="3" cols="35" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
  1333. .'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
  1334. . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
  1335. . "</textarea>\n";
  1336. // vacation
  1337. $out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
  1338. $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
  1339. .'<textarea name="_action_reason['.$id.']" id="action_reason' .$id. '" '
  1340. .'rows="3" cols="35" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
  1341. . Q($action['reason'], 'strict', false) . "</textarea>\n";
  1342. $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
  1343. .'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
  1344. .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
  1345. . $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
  1346. $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
  1347. .'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
  1348. .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
  1349. . $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
  1350. $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
  1351. .'<input type="text" name="_action_days['.$id.']" id="action_days'.$id.'" '
  1352. .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
  1353. . $this->error_class($id, 'action', 'days', 'action_days') .' />';
  1354. $out .= '</div>';
  1355. // flags
  1356. $flags = array(
  1357. 'read' => '\\Seen',
  1358. 'answered' => '\\Answered',
  1359. 'flagged' => '\\Flagged',
  1360. 'deleted' => '\\Deleted',
  1361. 'draft' => '\\Draft',
  1362. );
  1363. $flags_target = (array)$action['target'];
  1364. $out .= '<div id="action_flags' .$id.'" style="display:'
  1365. . (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
  1366. . $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
  1367. foreach ($flags as $fidx => $flag) {
  1368. $out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
  1369. . (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
  1370. . Q($this->gettext('flag'.$fidx)) .'<br>';
  1371. }
  1372. $out .= '</div>';
  1373. // set variable
  1374. $set_modifiers = array(
  1375. 'lower',
  1376. 'upper',
  1377. 'lowerfirst',
  1378. 'upperfirst',
  1379. 'quotewildcard',
  1380. 'length'
  1381. );
  1382. $out .= '<div id="action_set' .$id.'" style="display:' .($action['type']=='set' ? 'inline' : 'none') .'">';
  1383. $out .= '<span class="label">' .Q($this->gettext('setvarname')) . '</span><br />'
  1384. .'<input type="text" name="_action_varname['.$id.']" id="action_varname'.$id.'" '
  1385. .'value="' . Q($action['name']) . '" size="35" '
  1386. . $this->error_class($id, 'action', 'name', 'action_varname') .' />';
  1387. $out .= '<br /><span class="label">' .Q($this->gettext('setvarvalue')) . '</span><br />'
  1388. .'<input type="text" name="_action_varvalue['.$id.']" id="action_varvalue'.$id.'" '
  1389. .'value="' . Q($action['value']) . '" size="35" '
  1390. . $this->error_class($id, 'action', 'value', 'action_varvalue') .' />';
  1391. $out .= '<br /><span class="label">' .Q($this->gettext('setvarmodifiers')) . '</span><br />';
  1392. foreach ($set_modifiers as $j => $s_m) {
  1393. $s_m_id = 'action_varmods' . $id . $s_m;
  1394. $out .= sprintf('<input type="checkbox" name="_action_varmods[%s][]" value="%s" id="%s"%s />%s<br>',
  1395. $id, $s_m, $s_m_id,
  1396. (array_key_exists($s_m, (array)$action) && $action[$s_m] ? ' checked="checked"' : ''),
  1397. Q($this->gettext('var' . $s_m)));
  1398. }
  1399. $out .= '</div>';
  1400. // notify
  1401. // skip :options tag - not used by the mailto method
  1402. $out .= '<div id="action_notify' .$id.'" style="display:' .($action['type']=='notify' ? 'inline' : 'none') .'">';
  1403. $out .= '<span class="label">' .Q($this->gettext('notifyaddress')) . '</span><br />'
  1404. .'<input type="text" name="_action_notifyaddress['.$id.']" id="action_notifyaddress'.$id.'" '
  1405. .'value="' . Q($action['address']) . '" size="35" '
  1406. . $this->error_class($id, 'action', 'address', 'action_notifyaddress') .' />';
  1407. $out .= '<br /><span class="label">'. Q($this->gettext('notifybody')) .'</span><br />'
  1408. .'<textarea name="_action_notifybody['.$id.']" id="action_notifybody' .$id. '" '
  1409. .'rows="3" cols="35" '. $this->error_class($id, 'action', 'method', 'action_notifybody') . '>'
  1410. . Q($action['body'], 'strict', false) . "</textarea>\n";
  1411. $out .= '<br /><span class="label">' .Q($this->gettext('notifysubject')) . '</span><br />'
  1412. .'<input type="text" name="_action_notifymessage['.$id.']" id="action_notifymessage'.$id.'" '
  1413. .'value="' . Q($action['message']) . '" size="35" '
  1414. . $this->error_class($id, 'action', 'message', 'action_notifymessage') .' />';
  1415. $out .= '<br /><span class="label">' .Q($this->gettext('notifyfrom')) . '</span><br />'
  1416. .'<input type="text" name="_action_notifyfrom['.$id.']" id="action_notifyfrom'.$id.'" '
  1417. .'value="' . Q($action['from']) . '" size="35" '
  1418. . $this->error_class($id, 'action', 'from', 'action_notifyfrom') .' />';
  1419. $importance_options = array(
  1420. 3 => 'notifyimportancelow',
  1421. 2 => 'notifyimportancenormal',
  1422. 1 => 'notifyimportancehigh'
  1423. );
  1424. $select_importance = new html_select(array(
  1425. 'name' => '_action_notifyimportance[' . $id . ']',
  1426. 'id' => '_action_notifyimportance' . $id,
  1427. 'class' => $this->error_class($id, 'action', 'importance', 'action_notifyimportance')));
  1428. foreach ($importance_options as $io_v => $io_n) {
  1429. $select_importance->add(Q($this->gettext($io_n)), $io_v);
  1430. }
  1431. $out .= '<br /><span class="label">' . Q($this->gettext('notifyimportance')) . '</span><br />';
  1432. $out .= $select_importance->show($action['importance'] ? $action['importance'] : 2);
  1433. $out .= '</div>';
  1434. // mailbox select
  1435. if ($action['type'] == 'fileinto')
  1436. $mailbox = $this->mod_mailbox($action['target'], 'out');
  1437. else
  1438. $mailbox = '';
  1439. $select = rcmail_mailbox_select(array(
  1440. 'realnames' => false,
  1441. 'maxlength' => 100,
  1442. 'id' => 'action_mailbox' . $id,
  1443. 'name' => "_action_mailbox[$id]",
  1444. 'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
  1445. ));
  1446. $out .= $select->show($mailbox);
  1447. $out .= '</td>';
  1448. // add/del buttons
  1449. $out .= '<td class="rowbuttons">';
  1450. $out .= '<a href="#" id="actionadd' . $id .'" title="'. Q($this->gettext('add')). '"
  1451. onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
  1452. $out .= '<a href="#" id="actiondel' . $id .'" title="'. Q($this->gettext('del')). '"
  1453. onclick="rcmail.managesieve_actiondel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
  1454. $out .= '</td>';
  1455. $out .= '</tr></table>';
  1456. $out .= $div ? "</div>\n" : '';
  1457. return $out;
  1458. }
  1459. private function genid()
  1460. {
  1461. $result = preg_replace('/[^0-9]/', '', microtime(true));
  1462. return $result;
  1463. }
  1464. private function strip_value($str, $allow_html=false)
  1465. {
  1466. if (!$allow_html)
  1467. $str = strip_tags($str);
  1468. return trim($str);
  1469. }
  1470. private function error_class($id, $type, $target, $elem_prefix='')
  1471. {
  1472. // TODO: tooltips
  1473. if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
  1474. ($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
  1475. ) {
  1476. $this->add_tip($elem_prefix.$id, $str, true);
  1477. return ' class="error"';
  1478. }
  1479. return '';
  1480. }
  1481. private function add_tip($id, $str, $error=false)
  1482. {
  1483. if ($error)
  1484. $str = html::span('sieve error', $str);
  1485. $this->tips[] = array($id, $str);
  1486. }
  1487. private function print_tips()
  1488. {
  1489. if (empty($this->tips))
  1490. return;
  1491. $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
  1492. $this->rc->output->add_script($script, 'foot');
  1493. }
  1494. /**
  1495. * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
  1496. * with delimiter replacement.
  1497. *
  1498. * @param string $mailbox Mailbox name
  1499. * @param string $mode Conversion direction ('in'|'out')
  1500. *
  1501. * @return string Mailbox name
  1502. */
  1503. private function mod_mailbox($mailbox, $mode = 'out')
  1504. {
  1505. $delimiter = $_SESSION['imap_delimiter'];
  1506. $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
  1507. $mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
  1508. if ($mode == 'out') {
  1509. $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
  1510. if ($replace_delimiter && $replace_delimiter != $delimiter)
  1511. $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
  1512. }
  1513. else {
  1514. $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
  1515. if ($replace_delimiter && $replace_delimiter != $delimiter)
  1516. $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);
  1517. }
  1518. return $mailbox;
  1519. }
  1520. /**
  1521. * List sieve scripts
  1522. *
  1523. * @return array Scripts list
  1524. */
  1525. public function list_scripts()
  1526. {
  1527. if ($this->list !== null) {
  1528. return $this->list;
  1529. }
  1530. $this->list = $this->sieve->get_scripts();
  1531. // Handle active script(s) and list of scripts according to Kolab's KEP:14
  1532. if ($this->rc->config->get('managesieve_kolab_master')) {
  1533. // Skip protected names
  1534. foreach ((array)$this->list as $idx => $name) {
  1535. $_name = strtoupper($name);
  1536. if ($_name == 'MASTER')
  1537. $master_script = $name;
  1538. else if ($_name == 'MANAGEMENT')
  1539. $management_script = $name;
  1540. else if($_name == 'USER')
  1541. $user_script = $name;
  1542. else
  1543. continue;
  1544. unset($this->list[$idx]);
  1545. }
  1546. // get active script(s), read USER script
  1547. if ($user_script) {
  1548. $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
  1549. $filename_regex = '/'.preg_quote($extension, '/').'$/';
  1550. $_SESSION['managesieve_user_script'] = $user_script;
  1551. $this->sieve->load($user_script);
  1552. foreach ($this->sieve->script->as_array() as $rules) {
  1553. foreach ($rules['actions'] as $action) {
  1554. if ($action['type'] == 'include' && empty($action['global'])) {
  1555. $name = preg_replace($filename_regex, '', $action['target']);
  1556. $this->active[] = $name;
  1557. }
  1558. }
  1559. }
  1560. }
  1561. // create USER script if it doesn't exist
  1562. else {
  1563. $content = "# USER Management Script\n"
  1564. ."#\n"
  1565. ."# This script includes the various active sieve scripts\n"
  1566. ."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n"
  1567. ."#\n"
  1568. ."# For more information, see http://wiki.kolab.org/KEP:14#USER\n"
  1569. ."#\n";
  1570. if ($this->sieve->save_script('USER', $content)) {
  1571. $_SESSION['managesieve_user_script'] = 'USER';
  1572. if (empty($this->master_file))
  1573. $this->sieve->activate('USER');
  1574. }
  1575. }
  1576. }
  1577. else if (!empty($this->list)) {
  1578. // Get active script name
  1579. if ($active = $this->sieve->get_active()) {
  1580. $this->active = array($active);
  1581. }
  1582. // Hide scripts from config
  1583. $exceptions = $this->rc->config->get('managesieve_filename_exceptions');
  1584. if (!empty($exceptions)) {
  1585. $this->list = array_diff($this->list, (array)$exceptions);
  1586. }
  1587. }
  1588. return $this->list;
  1589. }
  1590. /**
  1591. * Removes sieve script
  1592. *
  1593. * @param string $name Script name
  1594. *
  1595. * @return bool True on success, False on failure
  1596. */
  1597. public function remove_script($name)
  1598. {
  1599. $result = $this->sieve->remove($name);
  1600. // Kolab's KEP:14
  1601. if ($result && $this->rc->config->get('managesieve_kolab_master')) {
  1602. $this->deactivate_script($name);
  1603. }
  1604. return $result;
  1605. }
  1606. /**
  1607. * Activates sieve script
  1608. *
  1609. * @param string $name Script name
  1610. *
  1611. * @return bool True on success, False on failure
  1612. */
  1613. public function activate_script($name)
  1614. {
  1615. // Kolab's KEP:14
  1616. if ($this->rc->config->get('managesieve_kolab_master')) {
  1617. $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
  1618. $user_script = $_SESSION['managesieve_user_script'];
  1619. // if the script is not active...
  1620. if ($user_script && ($key = array_search($name, $this->active)) === false) {
  1621. // ...rewrite USER file adding appropriate include command
  1622. if ($this->sieve->load($user_script)) {
  1623. $script = $this->sieve->script->as_array();
  1624. $list = array();
  1625. $regexp = '/' . preg_quote($extension, '/') . '$/';
  1626. // Create new include entry
  1627. $rule = array(
  1628. 'actions' => array(
  1629. 0 => array(
  1630. 'target' => $name.$extension,
  1631. 'type' => 'include',
  1632. 'personal' => true,
  1633. )));
  1634. // get all active scripts for sorting
  1635. foreach ($script as $rid => $rules) {
  1636. foreach ($rules['actions'] as $aid => $action) {
  1637. if ($action['type'] == 'include' && empty($action['global'])) {
  1638. $target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target'];
  1639. $list[] = $target;
  1640. }
  1641. }
  1642. }
  1643. $list[] = $name;
  1644. // Sort and find current script position
  1645. asort($list, SORT_LOCALE_STRING);
  1646. $list = array_values($list);
  1647. $index = array_search($name, $list);
  1648. // add rule at the end of the script
  1649. if ($index === false || $index == count($list)-1) {
  1650. $this->sieve->script->add_rule($rule);
  1651. }
  1652. // add rule at index position
  1653. else {
  1654. $script2 = array();
  1655. foreach ($script as $rid => $rules) {
  1656. if ($rid == $index) {
  1657. $script2[] = $rule;
  1658. }
  1659. $script2[] = $rules;
  1660. }
  1661. $this->sieve->script->content = $script2;
  1662. }
  1663. $result = $this->sieve->save();
  1664. if ($result) {
  1665. $this->active[] = $name;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. else {
  1671. $result = $this->sieve->activate($name);
  1672. if ($result)
  1673. $this->active = array($name);
  1674. }
  1675. return $result;
  1676. }
  1677. /**
  1678. * Deactivates sieve script
  1679. *
  1680. * @param string $name Script name
  1681. *
  1682. * @return bool True on success, False on failure
  1683. */
  1684. public function deactivate_script($name)
  1685. {
  1686. // Kolab's KEP:14
  1687. if ($this->rc->config->get('managesieve_kolab_master')) {
  1688. $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
  1689. $user_script = $_SESSION['managesieve_user_script'];
  1690. // if the script is active...
  1691. if ($user_script && ($key = array_search($name, $this->active)) !== false) {
  1692. // ...rewrite USER file removing appropriate include command
  1693. if ($this->sieve->load($user_script)) {
  1694. $script = $this->sieve->script->as_array();
  1695. $name = $name.$extension;
  1696. foreach ($script as $rid => $rules) {
  1697. foreach ($rules['actions'] as $aid => $action) {
  1698. if ($action['type'] == 'include' && empty($action['global'])
  1699. && $action['target'] == $name
  1700. ) {
  1701. break 2;
  1702. }
  1703. }
  1704. }
  1705. // Entry found
  1706. if ($rid < count($script)) {
  1707. $this->sieve->script->delete_rule($rid);
  1708. $result = $this->sieve->save();
  1709. if ($result) {
  1710. unset($this->active[$key]);
  1711. }
  1712. }
  1713. }
  1714. }
  1715. }
  1716. else {
  1717. $result = $this->sieve->deactivate();
  1718. if ($result)
  1719. $this->active = array();
  1720. }
  1721. return $result;
  1722. }
  1723. /**
  1724. * Saves current script (adding some variables)
  1725. */
  1726. public function save_script($name = null)
  1727. {
  1728. // Kolab's KEP:14
  1729. if ($this->rc->config->get('managesieve_kolab_master')) {
  1730. $this->sieve->script->set_var('EDITOR', self::PROGNAME);
  1731. $this->sieve->script->set_var('EDITOR_VERSION', self::VERSION);
  1732. }
  1733. return $this->sieve->save($name);
  1734. }
  1735. /**
  1736. * Returns list of rules from the current script
  1737. *
  1738. * @return array List of rules
  1739. */
  1740. public function list_rules()
  1741. {
  1742. $result = array();
  1743. $i = 1;
  1744. foreach ($this->script as $idx => $filter) {
  1745. if ($filter['type'] != 'if') {
  1746. continue;
  1747. }
  1748. $fname = $filter['name'] ? $filter['name'] : "#$i";
  1749. $result[] = array(
  1750. 'id' => $idx,
  1751. 'name' => Q($fname),
  1752. 'class' => $filter['disabled'] ? 'disabled' : '',
  1753. );
  1754. $i++;
  1755. }
  1756. return $result;
  1757. }
  1758. }