From ef2e7b3f9d264ec146d4dae257b1e295ab3b462a Mon Sep 17 00:00:00 2001 From: Hugues Hiegel Date: Tue, 21 Apr 2015 12:45:58 +0200 Subject: updates - plugins as a separate git folder --- plugins/managesieve/lib/Roundcube/rcube_sieve.php | 389 ---- .../lib/Roundcube/rcube_sieve_engine.php | 2381 -------------------- .../lib/Roundcube/rcube_sieve_script.php | 1217 ---------- .../lib/Roundcube/rcube_sieve_vacation.php | 862 ------- 4 files changed, 4849 deletions(-) delete mode 100644 plugins/managesieve/lib/Roundcube/rcube_sieve.php delete mode 100644 plugins/managesieve/lib/Roundcube/rcube_sieve_engine.php delete mode 100644 plugins/managesieve/lib/Roundcube/rcube_sieve_script.php delete mode 100644 plugins/managesieve/lib/Roundcube/rcube_sieve_vacation.php (limited to 'plugins/managesieve/lib/Roundcube') diff --git a/plugins/managesieve/lib/Roundcube/rcube_sieve.php b/plugins/managesieve/lib/Roundcube/rcube_sieve.php deleted file mode 100644 index 389c85012..000000000 --- a/plugins/managesieve/lib/Roundcube/rcube_sieve.php +++ /dev/null @@ -1,389 +0,0 @@ -sieve = new Net_Sieve(); - - if ($debug) { - $this->sieve->setDebug(true, array($this, 'debug_handler')); - } - - if (PEAR::isError($this->sieve->connect($host, $port, $options, $usetls))) { - return $this->_set_error(self::ERROR_CONNECTION); - } - - if (!empty($auth_cid)) { - $authz = $username; - $username = $auth_cid; - $password = $auth_pw; - } - - if (PEAR::isError($this->sieve->login($username, $password, - $auth_type ? strtoupper($auth_type) : null, $authz)) - ) { - return $this->_set_error(self::ERROR_LOGIN); - } - - $this->exts = $this->get_extensions(); - - // disable features by config - if (!empty($disabled)) { - // we're working on lower-cased names - $disabled = array_map('strtolower', (array) $disabled); - foreach ($disabled as $ext) { - if (($idx = array_search($ext, $this->exts)) !== false) { - unset($this->exts[$idx]); - } - } - } - } - - public function __destruct() { - $this->sieve->disconnect(); - } - - /** - * Getter for error code - */ - public function error() - { - return $this->error ? $this->error : false; - } - - /** - * Saves current script into server - */ - public function save($name = null) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if (!$this->script) - return $this->_set_error(self::ERROR_INTERNAL); - - if (!$name) - $name = $this->current; - - $script = $this->script->as_text(); - - if (!$script) - $script = '/* empty script */'; - - if (PEAR::isError($this->sieve->installScript($name, $script))) - return $this->_set_error(self::ERROR_INSTALL); - - return true; - } - - /** - * Saves text script into server - */ - public function save_script($name, $content = null) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if (!$content) - $content = '/* empty script */'; - - if (PEAR::isError($this->sieve->installScript($name, $content))) - return $this->_set_error(self::ERROR_INSTALL); - - return true; - } - - /** - * Activates specified script - */ - public function activate($name = null) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if (!$name) - $name = $this->current; - - if (PEAR::isError($this->sieve->setActive($name))) - return $this->_set_error(self::ERROR_ACTIVATE); - - return true; - } - - /** - * De-activates specified script - */ - public function deactivate() - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if (PEAR::isError($this->sieve->setActive(''))) - return $this->_set_error(self::ERROR_DEACTIVATE); - - return true; - } - - /** - * Removes specified script - */ - public function remove($name = null) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if (!$name) - $name = $this->current; - - // script must be deactivated first - if ($name == $this->sieve->getActive()) - if (PEAR::isError($this->sieve->setActive(''))) - return $this->_set_error(self::ERROR_DELETE); - - if (PEAR::isError($this->sieve->removeScript($name))) - return $this->_set_error(self::ERROR_DELETE); - - if ($name == $this->current) - $this->current = null; - - return true; - } - - /** - * Gets list of supported by server Sieve extensions - */ - public function get_extensions() - { - if ($this->exts) - return $this->exts; - - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - $ext = $this->sieve->getExtensions(); - - if (PEAR::isError($ext)) { - return array(); - } - - // we're working on lower-cased names - $ext = array_map('strtolower', (array) $ext); - - if ($this->script) { - $supported = $this->script->get_extensions(); - foreach ($ext as $idx => $ext_name) - if (!in_array($ext_name, $supported)) - unset($ext[$idx]); - } - - return array_values($ext); - } - - /** - * Gets list of scripts from server - */ - public function get_scripts() - { - if (!$this->list) { - - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - $list = $this->sieve->listScripts(); - - if (PEAR::isError($list)) - return $this->_set_error(self::ERROR_OTHER); - - $this->list = $list; - } - - return $this->list; - } - - /** - * Returns active script name - */ - public function get_active() - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - return $this->sieve->getActive(); - } - - /** - * Loads script by name - */ - public function load($name) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if ($this->current == $name) - return true; - - $script = $this->sieve->getScript($name); - - if (PEAR::isError($script)) - return $this->_set_error(self::ERROR_OTHER); - - // try to parse from Roundcube format - $this->script = $this->_parse($script); - - $this->current = $name; - - return true; - } - - /** - * Loads script from text content - */ - public function load_script($script) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - // try to parse from Roundcube format - $this->script = $this->_parse($script); - } - - /** - * Creates rcube_sieve_script object from text script - */ - private function _parse($txt) - { - // parse - $script = new rcube_sieve_script($txt, $this->exts); - - // fix/convert to Roundcube format - if (!empty($script->content)) { - // replace all elsif with if+stop, we support only ifs - foreach ($script->content as $idx => $rule) { - if (empty($rule['type']) || !preg_match('/^(if|elsif|else)$/', $rule['type'])) { - continue; - } - - $script->content[$idx]['type'] = 'if'; - - // 'stop' not found? - foreach ($rule['actions'] as $action) { - if (preg_match('/^(stop|vacation)$/', $action['type'])) { - continue 2; - } - } - if (!empty($script->content[$idx+1]) && $script->content[$idx+1]['type'] != 'if') { - $script->content[$idx]['actions'][] = array('type' => 'stop'); - } - } - } - - return $script; - } - - /** - * Gets specified script as text - */ - public function get_script($name) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - $content = $this->sieve->getScript($name); - - if (PEAR::isError($content)) - return $this->_set_error(self::ERROR_OTHER); - - return $content; - } - - /** - * Creates empty script or copy of other script - */ - public function copy($name, $copy) - { - if (!$this->sieve) - return $this->_set_error(self::ERROR_INTERNAL); - - if ($copy) { - $content = $this->sieve->getScript($copy); - - if (PEAR::isError($content)) - return $this->_set_error(self::ERROR_OTHER); - } - - return $this->save_script($name, $content); - } - - private function _set_error($error) - { - $this->error = $error; - return false; - } - - /** - * This is our own debug handler for connection - */ - public function debug_handler(&$sieve, $message) - { - rcube::write_log('sieve', preg_replace('/\r\n$/', '', $message)); - } -} diff --git a/plugins/managesieve/lib/Roundcube/rcube_sieve_engine.php b/plugins/managesieve/lib/Roundcube/rcube_sieve_engine.php deleted file mode 100644 index 69ae4b8a6..000000000 --- a/plugins/managesieve/lib/Roundcube/rcube_sieve_engine.php +++ /dev/null @@ -1,2381 +0,0 @@ - 'Subject', - 'from' => 'From', - 'to' => 'To', - ); - protected $addr_headers = array( - // Required - "from", "to", "cc", "bcc", "sender", "resent-from", "resent-to", - // Additional (RFC 822 / RFC 2822) - "reply-to", "resent-reply-to", "resent-sender", "resent-cc", "resent-bcc", - // Non-standard (RFC 2076, draft-palme-mailext-headers-08.txt) - "for-approval", "for-handling", "for-comment", "apparently-to", "errors-to", - "delivered-to", "return-receipt-to", "x-admin", "read-receipt-to", - "x-confirm-reading-to", "return-receipt-requested", - "registered-mail-reply-requested-by", "mail-followup-to", "mail-reply-to", - "abuse-reports-to", "x-complaints-to", "x-report-abuse-to", - // Undocumented - "x-beenthere", - ); - protected $notify_methods = array( - 'mailto', - // 'sms', - // 'tel', - ); - protected $notify_importance_options = array( - 3 => 'notifyimportancelow', - 2 => 'notifyimportancenormal', - 1 => 'notifyimportancehigh' - ); - - const VERSION = '8.2'; - const PROGNAME = 'Roundcube (Managesieve)'; - const PORT = 4190; - - - /** - * Class constructor - */ - function __construct($plugin) - { - $this->rc = rcube::get_instance(); - $this->plugin = $plugin; - } - - /** - * Loads configuration, initializes plugin (including sieve connection) - */ - function start($mode = null) - { - // register UI objects - $this->rc->output->add_handlers(array( - 'filterslist' => array($this, 'filters_list'), - 'filtersetslist' => array($this, 'filtersets_list'), - 'filterframe' => array($this, 'filter_frame'), - 'filterform' => array($this, 'filter_form'), - 'filtersetform' => array($this, 'filterset_form'), - )); - - // connect to managesieve server - $error = $this->connect($_SESSION['username'], $this->rc->decrypt($_SESSION['password'])); - - // load current/active script - if (!$error) { - // Get list of scripts - $list = $this->list_scripts(); - - // reset current script when entering filters UI (#1489412) - if ($this->rc->action == 'plugin.managesieve') { - $this->rc->session->remove('managesieve_current'); - } - - if ($mode != 'vacation') { - if (!empty($_GET['_set']) || !empty($_POST['_set'])) { - $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true); - } - else if (!empty($_SESSION['managesieve_current'])) { - $script_name = $_SESSION['managesieve_current']; - } - } - - $error = $this->load_script($script_name); - } - - // finally set script objects - if ($error) { - switch ($error) { - case rcube_sieve::ERROR_CONNECTION: - case rcube_sieve::ERROR_LOGIN: - $this->rc->output->show_message('managesieve.filterconnerror', 'error'); - rcube::raise_error(array('code' => 403, 'type' => 'php', - 'file' => __FILE__, 'line' => __LINE__, - 'message' => "Unable to connect to managesieve on $host:$port"), true, false); - break; - - default: - $this->rc->output->show_message('managesieve.filterunknownerror', 'error'); - break; - } - - // reload interface in case of possible error when specified script wasn't found (#1489412) - if ($script_name !== null && !empty($list) && !in_array($script_name, $list)) { - $this->rc->output->command('reload', 500); - } - - // to disable 'Add filter' button set env variable - $this->rc->output->set_env('filterconnerror', true); - $this->script = array(); - } - else { - $this->exts = $this->sieve->get_extensions(); - $this->init_script(); - $this->rc->output->set_env('currentset', $this->sieve->current); - $_SESSION['managesieve_current'] = $this->sieve->current; - } - - return $error; - } - - /** - * Connect to configured managesieve server - * - * @param string $username User login - * @param string $password User password - * - * @return int Connection status: 0 on success, >0 on failure - */ - public function connect($username, $password) - { - // Get connection parameters - $host = $this->rc->config->get('managesieve_host', 'localhost'); - $port = $this->rc->config->get('managesieve_port'); - $tls = $this->rc->config->get('managesieve_usetls', false); - - $host = rcube_utils::parse_host($host); - $host = rcube_utils::idn_to_ascii($host); - - // remove tls:// prefix, set TLS flag - if (($host = preg_replace('|^tls://|i', '', $host, 1, $cnt)) && $cnt) { - $tls = true; - } - - if (empty($port)) { - $port = getservbyname('sieve', 'tcp'); - if (empty($port)) { - $port = self::PORT; - } - } - - $plugin = $this->rc->plugins->exec_hook('managesieve_connect', array( - 'user' => $username, - 'password' => $password, - 'host' => $host, - 'port' => $port, - 'usetls' => $tls, - 'auth_type' => $this->rc->config->get('managesieve_auth_type'), - 'disabled' => $this->rc->config->get('managesieve_disabled_extensions'), - 'debug' => $this->rc->config->get('managesieve_debug', false), - 'auth_cid' => $this->rc->config->get('managesieve_auth_cid'), - 'auth_pw' => $this->rc->config->get('managesieve_auth_pw'), - 'socket_options' => $this->rc->config->get('managesieve_conn_options'), - )); - - // try to connect to managesieve server and to fetch the script - $this->sieve = new rcube_sieve( - $plugin['user'], - $plugin['password'], - $plugin['host'], - $plugin['port'], - $plugin['auth_type'], - $plugin['usetls'], - $plugin['disabled'], - $plugin['debug'], - $plugin['auth_cid'], - $plugin['auth_pw'], - $plugin['socket_options'] - ); - - return $this->sieve->error(); - } - - /** - * Load specified (or active) script - * - * @param string $script_name Optional script name - * - * @return int Connection status: 0 on success, >0 on failure - */ - protected function load_script($script_name = null) - { - // Get list of scripts - $list = $this->list_scripts(); - - if ($script_name === null || $script_name === '') { - // get (first) active script - if (!empty($this->active)) { - $script_name = $this->active[0]; - } - else if ($list) { - $script_name = $list[0]; - } - // create a new (initial) script - else { - // if script not exists build default script contents - $script_file = $this->rc->config->get('managesieve_default'); - $script_name = $this->rc->config->get('managesieve_script_name'); - - if (empty($script_name)) { - $script_name = 'roundcube'; - } - - if ($script_file && is_readable($script_file)) { - $content = file_get_contents($script_file); - } - - // add script and set it active - if ($this->sieve->save_script($script_name, $content)) { - $this->activate_script($script_name); - $this->list[] = $script_name; - } - } - } - - if ($script_name) { - $this->sieve->load($script_name); - } - - return $this->sieve->error(); - } - - /** - * User interface actions handler - */ - function actions() - { - $error = $this->start(); - - // Handle user requests - if ($action = rcube_utils::get_input_value('_act', rcube_utils::INPUT_GPC)) { - $fid = (int) rcube_utils::get_input_value('_fid', rcube_utils::INPUT_POST); - - if ($action == 'delete' && !$error) { - if (isset($this->script[$fid])) { - if ($this->sieve->script->delete_rule($fid)) - $result = $this->save_script(); - - if ($result === true) { - $this->rc->output->show_message('managesieve.filterdeleted', 'confirmation'); - $this->rc->output->command('managesieve_updatelist', 'del', array('id' => $fid)); - } else { - $this->rc->output->show_message('managesieve.filterdeleteerror', 'error'); - } - } - } - else if ($action == 'move' && !$error) { - if (isset($this->script[$fid])) { - $to = (int) rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST); - $rule = $this->script[$fid]; - - // remove rule - unset($this->script[$fid]); - $this->script = array_values($this->script); - - // add at target position - if ($to >= count($this->script)) { - $this->script[] = $rule; - } - else { - $script = array(); - foreach ($this->script as $idx => $r) { - if ($idx == $to) - $script[] = $rule; - $script[] = $r; - } - $this->script = $script; - } - - $this->sieve->script->content = $this->script; - $result = $this->save_script(); - - if ($result === true) { - $result = $this->list_rules(); - - $this->rc->output->show_message('managesieve.moved', 'confirmation'); - $this->rc->output->command('managesieve_updatelist', 'list', - array('list' => $result, 'clear' => true, 'set' => $to)); - } else { - $this->rc->output->show_message('managesieve.moveerror', 'error'); - } - } - } - else if ($action == 'act' && !$error) { - if (isset($this->script[$fid])) { - $rule = $this->script[$fid]; - $disabled = $rule['disabled'] ? true : false; - $rule['disabled'] = !$disabled; - $result = $this->sieve->script->update_rule($fid, $rule); - - if ($result !== false) - $result = $this->save_script(); - - if ($result === true) { - if ($rule['disabled']) - $this->rc->output->show_message('managesieve.deactivated', 'confirmation'); - else - $this->rc->output->show_message('managesieve.activated', 'confirmation'); - $this->rc->output->command('managesieve_updatelist', 'update', - array('id' => $fid, 'disabled' => $rule['disabled'])); - } else { - if ($rule['disabled']) - $this->rc->output->show_message('managesieve.deactivateerror', 'error'); - else - $this->rc->output->show_message('managesieve.activateerror', 'error'); - } - } - } - else if ($action == 'setact' && !$error) { - $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_POST, true); - $result = $this->activate_script($script_name); - $kep14 = $this->rc->config->get('managesieve_kolab_master'); - - if ($result === true) { - $this->rc->output->set_env('active_sets', $this->active); - $this->rc->output->show_message('managesieve.setactivated', 'confirmation'); - $this->rc->output->command('managesieve_updatelist', 'setact', - array('name' => $script_name, 'active' => true, 'all' => !$kep14)); - } else { - $this->rc->output->show_message('managesieve.setactivateerror', 'error'); - } - } - else if ($action == 'deact' && !$error) { - $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_POST, true); - $result = $this->deactivate_script($script_name); - - if ($result === true) { - $this->rc->output->set_env('active_sets', $this->active); - $this->rc->output->show_message('managesieve.setdeactivated', 'confirmation'); - $this->rc->output->command('managesieve_updatelist', 'setact', - array('name' => $script_name, 'active' => false)); - } else { - $this->rc->output->show_message('managesieve.setdeactivateerror', 'error'); - } - } - else if ($action == 'setdel' && !$error) { - $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_POST, true); - $result = $this->remove_script($script_name); - - if ($result === true) { - $this->rc->output->show_message('managesieve.setdeleted', 'confirmation'); - $this->rc->output->command('managesieve_updatelist', 'setdel', - array('name' => $script_name)); - $this->rc->session->remove('managesieve_current'); - } else { - $this->rc->output->show_message('managesieve.setdeleteerror', 'error'); - } - } - else if ($action == 'setget') { - $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true); - $script = $this->sieve->get_script($script_name); - - if (PEAR::isError($script)) - exit; - - $browser = new rcube_browser; - - // send download headers - header("Content-Type: application/octet-stream"); - header("Content-Length: ".strlen($script)); - - if ($browser->ie) { - header("Content-Type: application/force-download"); - $filename = rawurlencode($script_name); - } - else { - $filename = addcslashes($script_name, '\\"'); - } - - header("Content-Disposition: attachment; filename=\"$filename.txt\""); - echo $script; - exit; - } - else if ($action == 'list') { - $result = $this->list_rules(); - - $this->rc->output->command('managesieve_updatelist', 'list', array('list' => $result)); - } - else if ($action == 'ruleadd') { - $rid = rcube_utils::get_input_value('_rid', rcube_utils::INPUT_POST); - $id = $this->genid(); - $content = $this->rule_div($fid, $id, false); - - $this->rc->output->command('managesieve_rulefill', $content, $id, $rid); - } - else if ($action == 'actionadd') { - $aid = rcube_utils::get_input_value('_aid', rcube_utils::INPUT_POST); - $id = $this->genid(); - $content = $this->action_div($fid, $id, false); - - $this->rc->output->command('managesieve_actionfill', $content, $id, $aid); - } - - $this->rc->output->send(); - } - else if ($this->rc->task == 'mail') { - // Initialize the form - $rules = rcube_utils::get_input_value('r', rcube_utils::INPUT_GET); - if (!empty($rules)) { - $i = 0; - foreach ($rules as $rule) { - list($header, $value) = explode(':', $rule, 2); - $tests[$i] = array( - 'type' => 'contains', - 'test' => 'header', - 'arg1' => $header, - 'arg2' => $value, - ); - $i++; - } - - $this->form = array( - 'join' => count($tests) > 1 ? 'allof' : 'anyof', - 'name' => '', - 'tests' => $tests, - 'actions' => array( - 0 => array('type' => 'fileinto'), - 1 => array('type' => 'stop'), - ), - ); - } - } - - $this->send(); - } - - function save() - { - // Init plugin and handle managesieve connection - $error = $this->start(); - - // get request size limits (#1488648) - $max_post = max(array( - ini_get('max_input_vars'), - ini_get('suhosin.request.max_vars'), - ini_get('suhosin.post.max_vars'), - )); - $max_depth = max(array( - ini_get('suhosin.request.max_array_depth'), - ini_get('suhosin.post.max_array_depth'), - )); - - // check request size limit - if ($max_post && count($_POST, COUNT_RECURSIVE) >= $max_post) { - rcube::raise_error(array( - 'code' => 500, 'type' => 'php', - 'file' => __FILE__, 'line' => __LINE__, - 'message' => "Request size limit exceeded (one of max_input_vars/suhosin.request.max_vars/suhosin.post.max_vars)" - ), true, false); - $this->rc->output->show_message('managesieve.filtersaveerror', 'error'); - } - // check request depth limits - else if ($max_depth && count($_POST['_header']) > $max_depth) { - rcube::raise_error(array( - 'code' => 500, 'type' => 'php', - 'file' => __FILE__, 'line' => __LINE__, - 'message' => "Request size limit exceeded (one of suhosin.request.max_array_depth/suhosin.post.max_array_depth)" - ), true, false); - $this->rc->output->show_message('managesieve.filtersaveerror', 'error'); - } - // filters set add action - else if (!empty($_POST['_newset'])) { - $name = rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST, true); - $copy = rcube_utils::get_input_value('_copy', rcube_utils::INPUT_POST, true); - $from = rcube_utils::get_input_value('_from', rcube_utils::INPUT_POST); - $exceptions = $this->rc->config->get('managesieve_filename_exceptions'); - $kolab = $this->rc->config->get('managesieve_kolab_master'); - $name_uc = mb_strtolower($name); - $list = $this->list_scripts(); - - if (!$name) { - $this->errors['name'] = $this->plugin->gettext('cannotbeempty'); - } - else if (mb_strlen($name) > 128) { - $this->errors['name'] = $this->plugin->gettext('nametoolong'); - } - else if (!empty($exceptions) && in_array($name, (array)$exceptions)) { - $this->errors['name'] = $this->plugin->gettext('namereserved'); - } - else if (!empty($kolab) && in_array($name_uc, array('MASTER', 'USER', 'MANAGEMENT'))) { - $this->errors['name'] = $this->plugin->gettext('namereserved'); - } - else if (in_array($name, $list)) { - $this->errors['name'] = $this->plugin->gettext('setexist'); - } - else if ($from == 'file') { - // from file - if (is_uploaded_file($_FILES['_file']['tmp_name'])) { - $file = file_get_contents($_FILES['_file']['tmp_name']); - $file = preg_replace('/\r/', '', $file); - // for security don't save script directly - // check syntax before, like this... - $this->sieve->load_script($file); - if (!$this->save_script($name)) { - $this->errors['file'] = $this->plugin->gettext('setcreateerror'); - } - } - else { // upload failed - $err = $_FILES['_file']['error']; - - if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { - $msg = $this->rc->gettext(array('name' => 'filesizeerror', - 'vars' => array('size' => - $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize')))))); - } - else { - $this->errors['file'] = $this->plugin->gettext('fileuploaderror'); - } - } - } - else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) { - $error = 'managesieve.setcreateerror'; - } - - if (!$error && empty($this->errors)) { - // Find position of the new script on the list - $list[] = $name; - asort($list, SORT_LOCALE_STRING); - $list = array_values($list); - $index = array_search($name, $list); - - $this->rc->output->show_message('managesieve.setcreated', 'confirmation'); - $this->rc->output->command('parent.managesieve_updatelist', 'setadd', - array('name' => $name, 'index' => $index)); - } else if ($msg) { - $this->rc->output->command('display_message', $msg, 'error'); - } else if ($error) { - $this->rc->output->show_message($error, 'error'); - } - } - // filter add/edit action - else if (isset($_POST['_name'])) { - $name = trim(rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST, true)); - $fid = trim(rcube_utils::get_input_value('_fid', rcube_utils::INPUT_POST)); - $join = trim(rcube_utils::get_input_value('_join', rcube_utils::INPUT_POST)); - - // and arrays - $headers = rcube_utils::get_input_value('_header', rcube_utils::INPUT_POST); - $cust_headers = rcube_utils::get_input_value('_custom_header', rcube_utils::INPUT_POST); - $ops = rcube_utils::get_input_value('_rule_op', rcube_utils::INPUT_POST); - $sizeops = rcube_utils::get_input_value('_rule_size_op', rcube_utils::INPUT_POST); - $sizeitems = rcube_utils::get_input_value('_rule_size_item', rcube_utils::INPUT_POST); - $sizetargets = rcube_utils::get_input_value('_rule_size_target', rcube_utils::INPUT_POST); - $targets = rcube_utils::get_input_value('_rule_target', rcube_utils::INPUT_POST, true); - $mods = rcube_utils::get_input_value('_rule_mod', rcube_utils::INPUT_POST); - $mod_types = rcube_utils::get_input_value('_rule_mod_type', rcube_utils::INPUT_POST); - $body_trans = rcube_utils::get_input_value('_rule_trans', rcube_utils::INPUT_POST); - $body_types = rcube_utils::get_input_value('_rule_trans_type', rcube_utils::INPUT_POST, true); - $comparators = rcube_utils::get_input_value('_rule_comp', rcube_utils::INPUT_POST); - $indexes = rcube_utils::get_input_value('_rule_index', rcube_utils::INPUT_POST); - $lastindexes = rcube_utils::get_input_value('_rule_index_last', rcube_utils::INPUT_POST); - $dateheaders = rcube_utils::get_input_value('_rule_date_header', rcube_utils::INPUT_POST); - $dateparts = rcube_utils::get_input_value('_rule_date_part', rcube_utils::INPUT_POST); - $act_types = rcube_utils::get_input_value('_action_type', rcube_utils::INPUT_POST, true); - $mailboxes = rcube_utils::get_input_value('_action_mailbox', rcube_utils::INPUT_POST, true); - $act_targets = rcube_utils::get_input_value('_action_target', rcube_utils::INPUT_POST, true); - $domain_targets = rcube_utils::get_input_value('_action_target_domain', rcube_utils::INPUT_POST); - $area_targets = rcube_utils::get_input_value('_action_target_area', rcube_utils::INPUT_POST, true); - $reasons = rcube_utils::get_input_value('_action_reason', rcube_utils::INPUT_POST, true); - $addresses = rcube_utils::get_input_value('_action_addresses', rcube_utils::INPUT_POST, true); - $intervals = rcube_utils::get_input_value('_action_interval', rcube_utils::INPUT_POST); - $interval_types = rcube_utils::get_input_value('_action_interval_type', rcube_utils::INPUT_POST); - $subject = rcube_utils::get_input_value('_action_subject', rcube_utils::INPUT_POST, true); - $flags = rcube_utils::get_input_value('_action_flags', rcube_utils::INPUT_POST); - $varnames = rcube_utils::get_input_value('_action_varname', rcube_utils::INPUT_POST); - $varvalues = rcube_utils::get_input_value('_action_varvalue', rcube_utils::INPUT_POST); - $varmods = rcube_utils::get_input_value('_action_varmods', rcube_utils::INPUT_POST); - $notifymethods = rcube_utils::get_input_value('_action_notifymethod', rcube_utils::INPUT_POST); - $notifytargets = rcube_utils::get_input_value('_action_notifytarget', rcube_utils::INPUT_POST, true); - $notifyoptions = rcube_utils::get_input_value('_action_notifyoption', rcube_utils::INPUT_POST, true); - $notifymessages = rcube_utils::get_input_value('_action_notifymessage', rcube_utils::INPUT_POST, true); - $notifyfrom = rcube_utils::get_input_value('_action_notifyfrom', rcube_utils::INPUT_POST); - $notifyimp = rcube_utils::get_input_value('_action_notifyimportance', rcube_utils::INPUT_POST); - - // we need a "hack" for radiobuttons - foreach ($sizeitems as $item) - $items[] = $item; - - $this->form['disabled'] = $_POST['_disabled'] ? true : false; - $this->form['join'] = $join=='allof' ? true : false; - $this->form['name'] = $name; - $this->form['tests'] = array(); - $this->form['actions'] = array(); - - if ($name == '') - $this->errors['name'] = $this->plugin->gettext('cannotbeempty'); - else { - foreach($this->script as $idx => $rule) - if($rule['name'] == $name && $idx != $fid) { - $this->errors['name'] = $this->plugin->gettext('ruleexist'); - break; - } - } - - $i = 0; - // rules - if ($join == 'any') { - $this->form['tests'][0]['test'] = 'true'; - } - else { - foreach ($headers as $idx => $header) { - // targets are indexed differently (assume form order) - $target = $this->strip_value(array_shift($targets), true); - $header = $this->strip_value($header); - $operator = $this->strip_value($ops[$idx]); - $comparator = $this->strip_value($comparators[$idx]); - - if ($header == 'size') { - $sizeop = $this->strip_value($sizeops[$idx]); - $sizeitem = $this->strip_value($items[$idx]); - $sizetarget = $this->strip_value($sizetargets[$idx]); - - $this->form['tests'][$i]['test'] = 'size'; - $this->form['tests'][$i]['type'] = $sizeop; - $this->form['tests'][$i]['arg'] = $sizetarget; - - if ($sizetarget == '') - $this->errors['tests'][$i]['sizetarget'] = $this->plugin->gettext('cannotbeempty'); - else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) { - $this->errors['tests'][$i]['sizetarget'] = $this->plugin->gettext('forbiddenchars'); - $this->form['tests'][$i]['item'] = $sizeitem; - } - else - $this->form['tests'][$i]['arg'] .= $m[1]; - } - else if ($header == 'currentdate') { - $datepart = $this->strip_value($dateparts[$idx]); - - if (preg_match('/^not/', $operator)) - $this->form['tests'][$i]['not'] = true; - $type = preg_replace('/^not/', '', $operator); - - if ($type == 'exists') { - $this->errors['tests'][$i]['op'] = true; - } - - $this->form['tests'][$i]['test'] = 'currentdate'; - $this->form['tests'][$i]['type'] = $type; - $this->form['tests'][$i]['part'] = $datepart; - $this->form['tests'][$i]['arg'] = $target; - - if ($type != 'exists') { - if (!count($target)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('cannotbeempty'); - } - else if (strpos($type, 'count-') === 0) { - foreach ($target as $arg) { - if (preg_match('/[^0-9]/', $arg)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('forbiddenchars'); - } - } - } - else if (strpos($type, 'value-') === 0) { - // Some date/time formats do not support i;ascii-numeric comparator - if ($comparator == 'i;ascii-numeric' && in_array($datepart, array('date', 'time', 'iso8601', 'std11'))) { - $comparator = ''; - } - } - - if (!preg_match('/^(regex|matches|count-)/', $type) && count($target)) { - foreach ($target as $arg) { - if (!$this->validate_date_part($datepart, $arg)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('invaliddateformat'); - break; - } - } - } - } - } - else if ($header == 'date') { - $datepart = $this->strip_value($dateparts[$idx]); - $dateheader = $this->strip_value($dateheaders[$idx]); - $index = $this->strip_value($indexes[$idx]); - $indexlast = $this->strip_value($lastindexes[$idx]); - - if (preg_match('/^not/', $operator)) - $this->form['tests'][$i]['not'] = true; - $type = preg_replace('/^not/', '', $operator); - - if ($type == 'exists') { - $this->errors['tests'][$i]['op'] = true; - } - - if (!empty($index) && $mod != 'envelope') { - $this->form['tests'][$i]['index'] = intval($index); - $this->form['tests'][$i]['last'] = !empty($indexlast); - } - - if (empty($dateheader)) { - $dateheader = 'Date'; - } - else if (!preg_match('/^[\x21-\x39\x41-\x7E]+$/i', $dateheader)) { - $this->errors['tests'][$i]['dateheader'] = $this->plugin->gettext('forbiddenchars'); - } - - $this->form['tests'][$i]['test'] = 'date'; - $this->form['tests'][$i]['type'] = $type; - $this->form['tests'][$i]['part'] = $datepart; - $this->form['tests'][$i]['arg'] = $target; - $this->form['tests'][$i]['header'] = $dateheader; - - if ($type != 'exists') { - if (!count($target)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('cannotbeempty'); - } - else if (strpos($type, 'count-') === 0) { - foreach ($target as $arg) { - if (preg_match('/[^0-9]/', $arg)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('forbiddenchars'); - } - } - } - else if (strpos($type, 'value-') === 0) { - // Some date/time formats do not support i;ascii-numeric comparator - if ($comparator == 'i;ascii-numeric' && in_array($datepart, array('date', 'time', 'iso8601', 'std11'))) { - $comparator = ''; - } - } - - if (count($target) && !preg_match('/^(regex|matches|count-)/', $type)) { - foreach ($target as $arg) { - if (!$this->validate_date_part($datepart, $arg)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('invaliddateformat'); - break; - } - } - } - } - } - else if ($header == 'body') { - $trans = $this->strip_value($body_trans[$idx]); - $trans_type = $this->strip_value($body_types[$idx], true); - - if (preg_match('/^not/', $operator)) - $this->form['tests'][$i]['not'] = true; - $type = preg_replace('/^not/', '', $operator); - - if ($type == 'exists') { - $this->errors['tests'][$i]['op'] = true; - } - - $this->form['tests'][$i]['test'] = 'body'; - $this->form['tests'][$i]['type'] = $type; - $this->form['tests'][$i]['arg'] = $target; - - if (empty($target) && $type != 'exists') { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('cannotbeempty'); - } - else if (preg_match('/^(value|count)-/', $type)) { - foreach ($target as $target_value) { - if (preg_match('/[^0-9]/', $target_value)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('forbiddenchars'); - } - } - } - - $this->form['tests'][$i]['part'] = $trans; - if ($trans == 'content') { - $this->form['tests'][$i]['content'] = $trans_type; - } - } - else { - $cust_header = $headers = $this->strip_value(array_shift($cust_headers)); - $mod = $this->strip_value($mods[$idx]); - $mod_type = $this->strip_value($mod_types[$idx]); - $index = $this->strip_value($indexes[$idx]); - $indexlast = $this->strip_value($lastindexes[$idx]); - - if (preg_match('/^not/', $operator)) - $this->form['tests'][$i]['not'] = true; - $type = preg_replace('/^not/', '', $operator); - - if (!empty($index) && $mod != 'envelope') { - $this->form['tests'][$i]['index'] = intval($index); - $this->form['tests'][$i]['last'] = !empty($indexlast); - } - - if ($header == '...') { - if (!count($headers)) - $this->errors['tests'][$i]['header'] = $this->plugin->gettext('cannotbeempty'); - else { - foreach ($headers as $hr) { - // RFC2822: printable ASCII except colon - if (!preg_match('/^[\x21-\x39\x41-\x7E]+$/i', $hr)) { - $this->errors['tests'][$i]['header'] = $this->plugin->gettext('forbiddenchars'); - } - } - } - - if (empty($this->errors['tests'][$i]['header'])) - $cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers; - } - - $header = $header == '...' ? $cust_header : $header; - - if (is_array($header)) { - foreach ($header as $h_index => $val) { - if (isset($this->headers[$val])) { - $header[$h_index] = $this->headers[$val]; - } - } - } - - if ($type == 'exists') { - $this->form['tests'][$i]['test'] = 'exists'; - $this->form['tests'][$i]['arg'] = $header; - } - else { - $test = 'header'; - - if ($mod == 'address' || $mod == 'envelope') { - $found = false; - if (empty($this->errors['tests'][$i]['header'])) { - foreach ((array)$header as $hdr) { - if (!in_array(strtolower(trim($hdr)), $this->addr_headers)) - $found = true; - } - } - if (!$found) - $test = $mod; - } - - $this->form['tests'][$i]['type'] = $type; - $this->form['tests'][$i]['test'] = $test; - $this->form['tests'][$i]['arg1'] = $header; - $this->form['tests'][$i]['arg2'] = $target; - - if (empty($target)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('cannotbeempty'); - } - else if (preg_match('/^(value|count)-/', $type)) { - foreach ($target as $target_value) { - if (preg_match('/[^0-9]/', $target_value)) { - $this->errors['tests'][$i]['target'] = $this->plugin->gettext('forbiddenchars'); - } - } - } - - if ($mod) { - $this->form['tests'][$i]['part'] = $mod_type; - } - } - } - - if ($header != 'size' && $comparator) { - $this->form['tests'][$i]['comparator'] = $comparator; - } - - $i++; - } - } - - $i = 0; - // actions - foreach ($act_types as $idx => $type) { - $type = $this->strip_value($type); - - switch ($type) { - case 'fileinto': - case 'fileinto_copy': - $mailbox = $this->strip_value($mailboxes[$idx], false, false); - $this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in'); - - if ($type == 'fileinto_copy') { - $type = 'fileinto'; - $this->form['actions'][$i]['copy'] = true; - } - break; - - case 'reject': - case 'ereject': - $target = $this->strip_value($area_targets[$idx]); - $this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target); - - // if ($target == '') -// $this->errors['actions'][$i]['targetarea'] = $this->plugin->gettext('cannotbeempty'); - break; - - case 'redirect': - case 'redirect_copy': - $target = $this->strip_value($act_targets[$idx]); - $domain = $this->strip_value($domain_targets[$idx]); - - // force one of the configured domains - $domains = (array) $this->rc->config->get('managesieve_domains'); - if (!empty($domains) && !empty($target)) { - if (!$domain || !in_array($domain, $domains)) { - $domain = $domains[0]; - } - - $target .= '@' . $domain; - } - - $this->form['actions'][$i]['target'] = $target; - - if ($target == '') - $this->errors['actions'][$i]['target'] = $this->plugin->gettext('cannotbeempty'); - else if (!rcube_utils::check_email($target)) - $this->errors['actions'][$i]['target'] = $this->plugin->gettext(!empty($domains) ? 'forbiddenchars' : 'noemailwarning'); - - if ($type == 'redirect_copy') { - $type = 'redirect'; - $this->form['actions'][$i]['copy'] = true; - } - - break; - - case 'addflag': - case 'setflag': - case 'removeflag': - $_target = array(); - if (empty($flags[$idx])) { - $this->errors['actions'][$i]['target'] = $this->plugin->gettext('noflagset'); - } - else { - foreach ($flags[$idx] as $flag) { - $_target[] = $this->strip_value($flag); - } - } - $this->form['actions'][$i]['target'] = $_target; - break; - - case 'vacation': - $reason = $this->strip_value($reasons[$idx]); - $interval_type = $interval_types[$idx] == 'seconds' ? 'seconds' : 'days'; - - $this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason); - $this->form['actions'][$i]['subject'] = $subject[$idx]; - $this->form['actions'][$i]['addresses'] = array_shift($addresses); - $this->form['actions'][$i][$interval_type] = $intervals[$idx]; -// @TODO: vacation :mime, :from, :handle - - foreach ((array)$this->form['actions'][$i]['addresses'] as $aidx => $address) { - $this->form['actions'][$i]['addresses'][$aidx] = $address = trim($address); - - if (empty($address)) { - unset($this->form['actions'][$i]['addresses'][$aidx]); - } - else if (!rcube_utils::check_email($address)) { - $this->errors['actions'][$i]['addresses'] = $this->plugin->gettext('noemailwarning'); - break; - } - } - - if ($this->form['actions'][$i]['reason'] == '') - $this->errors['actions'][$i]['reason'] = $this->plugin->gettext('cannotbeempty'); - if ($this->form['actions'][$i][$interval_type] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i][$interval_type])) - $this->errors['actions'][$i]['interval'] = $this->plugin->gettext('forbiddenchars'); - break; - - case 'set': - $this->form['actions'][$i]['name'] = $varnames[$idx]; - $this->form['actions'][$i]['value'] = $varvalues[$idx]; - foreach ((array)$varmods[$idx] as $v_m) { - $this->form['actions'][$i][$v_m] = true; - } - - if (empty($varnames[$idx])) { - $this->errors['actions'][$i]['name'] = $this->plugin->gettext('cannotbeempty'); - } - else if (!preg_match('/^[0-9a-z_]+$/i', $varnames[$idx])) { - $this->errors['actions'][$i]['name'] = $this->plugin->gettext('forbiddenchars'); - } - - if (!isset($varvalues[$idx]) || $varvalues[$idx] === '') { - $this->errors['actions'][$i]['value'] = $this->plugin->gettext('cannotbeempty'); - } - break; - - case 'notify': - if (empty($notifymethods[$idx])) { - $this->errors['actions'][$i]['method'] = $this->plugin->gettext('cannotbeempty'); - } - if (empty($notifytargets[$idx])) { - $this->errors['actions'][$i]['target'] = $this->plugin->gettext('cannotbeempty'); - } - if (!empty($notifyfrom[$idx]) && !rcube_utils::check_email($notifyfrom[$idx])) { - $this->errors['actions'][$i]['from'] = $this->plugin->gettext('noemailwarning'); - } - - // skip empty options - foreach ((array)$notifyoptions[$idx] as $opt_idx => $opt) { - if (!strlen(trim($opt))) { - unset($notifyoptions[$idx][$opt_idx]); - } - } - - $this->form['actions'][$i]['method'] = $notifymethods[$idx] . ':' . $notifytargets[$idx]; - $this->form['actions'][$i]['options'] = $notifyoptions[$idx]; - $this->form['actions'][$i]['message'] = $notifymessages[$idx]; - $this->form['actions'][$i]['from'] = $notifyfrom[$idx]; - $this->form['actions'][$i]['importance'] = $notifyimp[$idx]; - break; - } - - $this->form['actions'][$i]['type'] = $type; - $i++; - } - - if (!$this->errors && !$error) { - // save the script - if (!isset($this->script[$fid])) { - $fid = $this->sieve->script->add_rule($this->form); - $new = true; - } - else { - $fid = $this->sieve->script->update_rule($fid, $this->form); - } - - if ($fid !== false) - $save = $this->save_script(); - - if ($save && $fid !== false) { - $this->rc->output->show_message('managesieve.filtersaved', 'confirmation'); - if ($this->rc->task != 'mail') { - $this->rc->output->command('parent.managesieve_updatelist', - isset($new) ? 'add' : 'update', - array( - 'name' => $this->form['name'], - 'id' => $fid, - 'disabled' => $this->form['disabled'] - )); - } - else { - $this->rc->output->command('managesieve_dialog_close'); - $this->rc->output->send('iframe'); - } - } - else { - $this->rc->output->show_message('managesieve.filtersaveerror', 'error'); -// $this->rc->output->send(); - } - } - } - - $this->send(); - } - - protected function send() - { - // Handle form action - if (isset($_GET['_framed']) || isset($_POST['_framed'])) { - if (isset($_GET['_newset']) || isset($_POST['_newset'])) { - $this->rc->output->send('managesieve.setedit'); - } - else { - $this->rc->output->send('managesieve.filteredit'); - } - } - else { - $this->rc->output->set_pagetitle($this->plugin->gettext('filters')); - $this->rc->output->send('managesieve.managesieve'); - } - } - - // return the filters list as HTML table - function filters_list($attrib) - { - // add id to message list table if not specified - if (!strlen($attrib['id'])) - $attrib['id'] = 'rcmfilterslist'; - - // define list of cols to be displayed - $a_show_cols = array('name'); - - $result = $this->list_rules(); - - // create XHTML table - $out = $this->rc->table_output($attrib, $result, $a_show_cols, 'id'); - - // set client env - $this->rc->output->add_gui_object('filterslist', $attrib['id']); - $this->rc->output->include_script('list.js'); - - // add some labels to client - $this->rc->output->add_label('managesieve.filterdeleteconfirm'); - - return $out; - } - - // return the filters list as '; - $out .= sprintf(' ', 'from_none', rcube::Q($this->plugin->gettext('none'))); - - // filters set list - $list = $this->list_scripts(); - $select = new html_select(array('name' => '_copy', 'id' => '_copy')); - - if (is_array($list)) { - asort($list, SORT_LOCALE_STRING); - - if (!$copy) - $copy = $_SESSION['managesieve_current']; - - foreach ($list as $set) { - $select->add($set, $set); - } - - $out .= '
'; - $out .= sprintf(' ', 'from_set', rcube::Q($this->plugin->gettext('fromset'))); - $out .= $select->show($copy); - } - - // script upload box - $upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30, - 'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : ''))); - - $out .= '
'; - $out .= sprintf(' ', 'from_file', rcube::Q($this->plugin->gettext('fromfile'))); - $out .= $upload->show(); - $out .= ''; - - $this->rc->output->add_gui_object('sieveform', 'filtersetform'); - - if ($this->errors['name']) - $this->add_tip('_name', $this->errors['name'], true); - if ($this->errors['file']) - $this->add_tip('_file', $this->errors['file'], true); - - $this->print_tips(); - - return $out; - } - - - function filter_form($attrib) - { - if (!$attrib['id']) - $attrib['id'] = 'rcmfilterform'; - - $fid = rcube_utils::get_input_value('_fid', rcube_utils::INPUT_GPC); - $scr = isset($this->form) ? $this->form : $this->script[$fid]; - - $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task)); - $hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save')); - $hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0))); - $hiddenfields->add(array('name' => '_fid', 'value' => $fid)); - - $out = '
'."\n"; - $out .= $hiddenfields->show(); - - // 'any' flag - if ((!isset($this->form) && empty($scr['tests']) && !empty($scr)) - || (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not']) - ) { - $any = true; - } - - // filter name input - $field_id = '_name'; - $input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30, - 'class' => ($this->errors['name'] ? 'error' : ''))); - - if ($this->errors['name']) - $this->add_tip($field_id, $this->errors['name'], true); - - if (isset($scr)) - $input_name = $input_name->show($scr['name']); - else - $input_name = $input_name->show(); - - $out .= sprintf("\n %s\n", - $field_id, rcube::Q($this->plugin->gettext('filtername')), $input_name); - - // filter set selector - if ($this->rc->task == 'mail') { - $out .= sprintf("\n  %s\n", - $field_id, rcube::Q($this->plugin->gettext('filterset')), - $this->filtersets_list(array('id' => 'sievescriptname'), true)); - } - - $out .= '

' . rcube::Q($this->plugin->gettext('messagesrules')) . "\n"; - - // any, allof, anyof radio buttons - $field_id = '_allof'; - $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof', - 'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio')); - - if (isset($scr) && !$any) - $input_join = $input_join->show($scr['join'] ? 'allof' : ''); - else - $input_join = $input_join->show(); - - $out .= sprintf("%s \n", - $input_join, $field_id, rcube::Q($this->plugin->gettext('filterallof'))); - - $field_id = '_anyof'; - $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof', - 'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio')); - - if (isset($scr) && !$any) - $input_join = $input_join->show($scr['join'] ? '' : 'anyof'); - else - $input_join = $input_join->show('anyof'); // default - - $out .= sprintf("%s\n", - $input_join, $field_id, rcube::Q($this->plugin->gettext('filteranyof'))); - - $field_id = '_any'; - $input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any', - 'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio')); - - $input_join = $input_join->show($any ? 'any' : ''); - - $out .= sprintf("%s\n", - $input_join, $field_id, rcube::Q($this->plugin->gettext('filterany'))); - - $rows_num = !empty($scr['tests']) ? sizeof($scr['tests']) : 1; - - $out .= '\n"; - - $out .= "
\n"; - - // actions - $out .= '
' . rcube::Q($this->plugin->gettext('messagesactions')) . "\n"; - - $rows_num = isset($scr) ? sizeof($scr['actions']) : 1; - - $out .= '
'; - for ($x=0; $x<$rows_num; $x++) - $out .= $this->action_div($fid, $x); - $out .= "
\n"; - - $out .= "
\n"; - - $this->print_tips(); - - if ($scr['disabled']) { - $this->rc->output->set_env('rule_disabled', true); - } - $this->rc->output->add_label( - 'managesieve.ruledeleteconfirm', - 'managesieve.actiondeleteconfirm' - ); - $this->rc->output->add_gui_object('sieveform', 'filterform'); - - return $out; - } - - function rule_div($fid, $id, $div=true) - { - $rule = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id]; - $rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']); - - // headers select - $select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id, - 'onchange' => 'rule_header_select(' .$id .')')); - - foreach ($this->headers as $index => $header) { - $header = $this->rc->text_exists($index) ? $this->plugin->gettext($index) : $header; - $select_header->add($header, $index); - } - $select_header->add($this->plugin->gettext('...'), '...'); - if (in_array('body', $this->exts)) - $select_header->add($this->plugin->gettext('body'), 'body'); - $select_header->add($this->plugin->gettext('size'), 'size'); - if (in_array('date', $this->exts)) { - $select_header->add($this->plugin->gettext('datetest'), 'date'); - $select_header->add($this->plugin->gettext('currdate'), 'currentdate'); - } - - if (isset($rule['test'])) { - if (in_array($rule['test'], array('header', 'address', 'envelope')) - && !is_array($rule['arg1']) - && ($header = strtolower($rule['arg1'])) - && isset($this->headers[$header]) - ) { - $test = $header; - } - else if ($rule['test'] == 'exists' - && !is_array($rule['arg']) - && ($header = strtolower($rule['arg'])) - && isset($this->headers[$header]) - ) { - $test = $header; - } - else if (in_array($rule['test'], array('size', 'body', 'date', 'currentdate'))) { - $test = $rule['test']; - } - else if ($rule['test'] != 'true') { - $test = '...'; - } - } - - $aout = $select_header->show($test); - - // custom headers input - if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) { - $custom = (array) $rule['arg1']; - if (count($custom) == 1 && isset($this->headers[strtolower($custom[0])])) { - unset($custom); - } - } - else if (isset($rule['test']) && $rule['test'] == 'exists') { - $custom = (array) $rule['arg']; - if (count($custom) == 1 && isset($this->headers[strtolower($custom[0])])) { - unset($custom); - } - } - - $tout = $this->list_input($id, 'custom_header', $custom, isset($custom), - $this->error_class($id, 'test', 'header', 'custom_header'), 15) . "\n"; - - // matching type select (operator) - $select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id, - 'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'), - 'class' => 'operator_selector', - 'onchange' => 'rule_op_select(this, '.$id.')')); - $select_op->add(rcube::Q($this->plugin->gettext('filtercontains')), 'contains'); - $select_op->add(rcube::Q($this->plugin->gettext('filternotcontains')), 'notcontains'); - $select_op->add(rcube::Q($this->plugin->gettext('filteris')), 'is'); - $select_op->add(rcube::Q($this->plugin->gettext('filterisnot')), 'notis'); - $select_op->add(rcube::Q($this->plugin->gettext('filterexists')), 'exists'); - $select_op->add(rcube::Q($this->plugin->gettext('filternotexists')), 'notexists'); - $select_op->add(rcube::Q($this->plugin->gettext('filtermatches')), 'matches'); - $select_op->add(rcube::Q($this->plugin->gettext('filternotmatches')), 'notmatches'); - if (in_array('regex', $this->exts)) { - $select_op->add(rcube::Q($this->plugin->gettext('filterregex')), 'regex'); - $select_op->add(rcube::Q($this->plugin->gettext('filternotregex')), 'notregex'); - } - if (in_array('relational', $this->exts)) { - $select_op->add(rcube::Q($this->plugin->gettext('countisgreaterthan')), 'count-gt'); - $select_op->add(rcube::Q($this->plugin->gettext('countisgreaterthanequal')), 'count-ge'); - $select_op->add(rcube::Q($this->plugin->gettext('countislessthan')), 'count-lt'); - $select_op->add(rcube::Q($this->plugin->gettext('countislessthanequal')), 'count-le'); - $select_op->add(rcube::Q($this->plugin->gettext('countequals')), 'count-eq'); - $select_op->add(rcube::Q($this->plugin->gettext('countnotequals')), 'count-ne'); - $select_op->add(rcube::Q($this->plugin->gettext('valueisgreaterthan')), 'value-gt'); - $select_op->add(rcube::Q($this->plugin->gettext('valueisgreaterthanequal')), 'value-ge'); - $select_op->add(rcube::Q($this->plugin->gettext('valueislessthan')), 'value-lt'); - $select_op->add(rcube::Q($this->plugin->gettext('valueislessthanequal')), 'value-le'); - $select_op->add(rcube::Q($this->plugin->gettext('valueequals')), 'value-eq'); - $select_op->add(rcube::Q($this->plugin->gettext('valuenotequals')), 'value-ne'); - } - - $test = self::rule_test($rule); - $target = ''; - - // target(s) input - if (in_array($rule['test'], array('header', 'address', 'envelope'))) { - $target = $rule['arg2']; - } - else if (in_array($rule['test'], array('body', 'date', 'currentdate'))) { - $target = $rule['arg']; - } - else if ($rule['test'] == 'size') { - if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) { - $sizetarget = $matches[1]; - $sizeitem = $matches[2]; - } - else { - $sizetarget = $rule['arg']; - $sizeitem = $rule['item']; - } - } - - // (current)date part select - if (in_array('date', $this->exts) || in_array('currentdate', $this->exts)) { - $date_parts = array('date', 'iso8601', 'std11', 'julian', 'time', - 'year', 'month', 'day', 'hour', 'minute', 'second', 'weekday', 'zone'); - $select_dp = new html_select(array('name' => "_rule_date_part[]", 'id' => 'rule_date_part'.$id, - 'style' => in_array($rule['test'], array('currentdate', 'date')) && !preg_match('/^(notcount|count)-/', $test) ? '' : 'display:none', - 'class' => 'datepart_selector', - )); - - foreach ($date_parts as $part) { - $select_dp->add(rcube::Q($this->plugin->gettext($part)), $part); - } - - $tout .= $select_dp->show($rule['test'] == 'currentdate' || $rule['test'] == 'date' ? $rule['part'] : ''); - } - - $tout .= $select_op->show($test); - $tout .= $this->list_input($id, 'rule_target', $target, - $rule['test'] != 'size' && $rule['test'] != 'exists', - $this->error_class($id, 'test', 'target', 'rule_target')) . "\n"; - - $select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id)); - $select_size_op->add(rcube::Q($this->plugin->gettext('filterover')), 'over'); - $select_size_op->add(rcube::Q($this->plugin->gettext('filterunder')), 'under'); - - $tout .= '
'; - $tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : ''); - $tout .= 'error_class($id, 'test', 'sizetarget', 'rule_size_i') .' /> - - - - '; - $tout .= '
'; - - // Advanced modifiers (address, envelope) - $select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id, - 'onchange' => 'rule_mod_select(' .$id .')')); - $select_mod->add(rcube::Q($this->plugin->gettext('none')), ''); - $select_mod->add(rcube::Q($this->plugin->gettext('address')), 'address'); - if (in_array('envelope', $this->exts)) - $select_mod->add(rcube::Q($this->plugin->gettext('envelope')), 'envelope'); - - $select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id)); - $select_type->add(rcube::Q($this->plugin->gettext('allparts')), 'all'); - $select_type->add(rcube::Q($this->plugin->gettext('domain')), 'domain'); - $select_type->add(rcube::Q($this->plugin->gettext('localpart')), 'localpart'); - if (in_array('subaddress', $this->exts)) { - $select_type->add(rcube::Q($this->plugin->gettext('user')), 'user'); - $select_type->add(rcube::Q($this->plugin->gettext('detail')), 'detail'); - } - - $need_mod = !in_array($rule['test'], array('size', 'body', 'date', 'currentdate')); - $mout = ''; - - // Advanced modifiers (body transformations) - $select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id, - 'onchange' => 'rule_trans_select(' .$id .')')); - $select_mod->add(rcube::Q($this->plugin->gettext('text')), 'text'); - $select_mod->add(rcube::Q($this->plugin->gettext('undecoded')), 'raw'); - $select_mod->add(rcube::Q($this->plugin->gettext('contenttype')), 'content'); - - $mout .= ''; - - // Advanced modifiers (body transformations) - $select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id)); - $select_comp->add(rcube::Q($this->plugin->gettext('default')), ''); - $select_comp->add(rcube::Q($this->plugin->gettext('octet')), 'i;octet'); - $select_comp->add(rcube::Q($this->plugin->gettext('asciicasemap')), 'i;ascii-casemap'); - if (in_array('comparator-i;ascii-numeric', $this->exts)) { - $select_comp->add(rcube::Q($this->plugin->gettext('asciinumeric')), 'i;ascii-numeric'); - } - - // Comparators - $mout .= ''; - - // Date header - if (in_array('date', $this->exts)) { - $mout .= ''; - } - - // Index - if (in_array('index', $this->exts)) { - $need_index = in_array($rule['test'], array('header', ', address', 'date')); - $mout .= ''; - } - - // Build output table - $out = $div ? '
'."\n" : ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - - // add/del buttons - $out .= ''; - $out .= '
'; - $out .= '  '; - $out .= '' . $aout . '' . $tout . "\n"; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= '
'; - - $out .= $div ? "
\n" : ''; - - return $out; - } - - private static function rule_test(&$rule) - { - // first modify value/count tests with 'not' keyword - // we'll revert the meaning of operators - if ($rule['not'] && preg_match('/^(count|value)-([gteqnl]{2})/', $rule['type'], $m)) { - $rule['not'] = false; - - switch ($m[2]) { - case 'gt': $rule['type'] = $m[1] . '-le'; break; - case 'ge': $rule['type'] = $m[1] . '-lt'; break; - case 'lt': $rule['type'] = $m[1] . '-ge'; break; - case 'le': $rule['type'] = $m[1] . '-gt'; break; - case 'eq': $rule['type'] = $m[1] . '-ne'; break; - case 'ne': $rule['type'] = $m[1] . '-eq'; break; - } - } - else if ($rule['not'] && $rule['test'] == 'size') { - $rule['not'] = false; - $rule['type'] = $rule['type'] == 'over' ? 'under' : 'over'; - } - - $set = array('header', 'address', 'envelope', 'body', 'date', 'currentdate'); - - // build test string supported by select element - if ($rule['size']) { - $test = $rule['type']; - } - else if (in_array($rule['test'], $set)) { - $test = ($rule['not'] ? 'not' : '') . ($rule['type'] ? $rule['type'] : 'is'); - } - else { - $test = ($rule['not'] ? 'not' : '') . $rule['test']; - } - - return $test; - } - - function action_div($fid, $id, $div=true) - { - $action = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id]; - $rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']); - - $out = $div ? '
'."\n" : ''; - - $out .= ''; - - // actions target inputs - $out .= ''; - - // add/del buttons - $out .= ''; - - $out .= '
'; - - // action select - $select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id, - 'onchange' => 'action_type_select(' .$id .')')); - if (in_array('fileinto', $this->exts)) - $select_action->add(rcube::Q($this->plugin->gettext('messagemoveto')), 'fileinto'); - if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts)) - $select_action->add(rcube::Q($this->plugin->gettext('messagecopyto')), 'fileinto_copy'); - $select_action->add(rcube::Q($this->plugin->gettext('messageredirect')), 'redirect'); - if (in_array('copy', $this->exts)) - $select_action->add(rcube::Q($this->plugin->gettext('messagesendcopy')), 'redirect_copy'); - if (in_array('reject', $this->exts)) - $select_action->add(rcube::Q($this->plugin->gettext('messagediscard')), 'reject'); - else if (in_array('ereject', $this->exts)) - $select_action->add(rcube::Q($this->plugin->gettext('messagediscard')), 'ereject'); - if (in_array('vacation', $this->exts)) - $select_action->add(rcube::Q($this->plugin->gettext('messagereply')), 'vacation'); - $select_action->add(rcube::Q($this->plugin->gettext('messagedelete')), 'discard'); - if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) { - $select_action->add(rcube::Q($this->plugin->gettext('setflags')), 'setflag'); - $select_action->add(rcube::Q($this->plugin->gettext('addflags')), 'addflag'); - $select_action->add(rcube::Q($this->plugin->gettext('removeflags')), 'removeflag'); - } - if (in_array('variables', $this->exts)) { - $select_action->add(rcube::Q($this->plugin->gettext('setvariable')), 'set'); - } - if (in_array('enotify', $this->exts) || in_array('notify', $this->exts)) { - $select_action->add(rcube::Q($this->plugin->gettext('notify')), 'notify'); - } - $select_action->add(rcube::Q($this->plugin->gettext('messagekeep')), 'keep'); - $select_action->add(rcube::Q($this->plugin->gettext('rulestop')), 'stop'); - - $select_type = $action['type']; - if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) { - $select_type .= '_copy'; - } - - $out .= $select_action->show($select_type); - $out .= ''; - - // force domain selection in redirect email input - $domains = (array) $this->rc->config->get('managesieve_domains'); - if (!empty($domains)) { - sort($domains); - - $domain_select = new html_select(array('name' => "_action_target_domain[$id]", 'id' => 'action_target_domain'.$id)); - $domain_select->add(array_combine($domains, $domains)); - - if ($action['type'] == 'redirect') { - $parts = explode('@', $action['target']); - if (!empty($parts)) { - $action['domain'] = array_pop($parts); - $action['target'] = implode('@', $parts); - } - } - } - - // redirect target - $out .= '' - . 'error_class($id, 'action', 'target', 'action_target') .' />' - . (!empty($domains) ? ' @ ' . $domain_select->show($action['domain']) : '') - . ''; - - // (e)reject target - $out .= '\n"; - - // vacation - $vsec = in_array('vacation-seconds', $this->exts); - $out .= '
'; - $out .= ''. rcube::Q($this->plugin->gettext('vacationreason')) .'
' - .'\n"; - $out .= '
' .rcube::Q($this->plugin->gettext('vacationsubject')) . '
' - .'error_class($id, 'action', 'subject', 'action_subject') .' />'; - $out .= '
' .rcube::Q($this->plugin->gettext('vacationaddr')) . '
' - . $this->list_input($id, 'action_addresses', $action['addresses'], true, - $this->error_class($id, 'action', 'addresses', 'action_addresses'), 30); - $out .= '
' . rcube::Q($this->plugin->gettext($vsec ? 'vacationinterval' : 'vacationdays')) . '
' - .'error_class($id, 'action', 'interval', 'action_interval') .' />'; - if ($vsec) { - $out .= ' ' - . ' '; - } - $out .= '
'; - - // flags - $flags = array( - 'read' => '\\Seen', - 'answered' => '\\Answered', - 'flagged' => '\\Flagged', - 'deleted' => '\\Deleted', - 'draft' => '\\Draft', - ); - $flags_target = (array)$action['target']; - - $out .= '
error_class($id, 'action', 'flags', 'action_flags') . '>'; - foreach ($flags as $fidx => $flag) { - $out .= '' - . rcube::Q($this->plugin->gettext('flag'.$fidx)) .'
'; - } - $out .= '
'; - - // set variable - $set_modifiers = array( - 'lower', - 'upper', - 'lowerfirst', - 'upperfirst', - 'quotewildcard', - 'length' - ); - - $out .= '
'; - $out .= '' .rcube::Q($this->plugin->gettext('setvarname')) . '
' - .'error_class($id, 'action', 'name', 'action_varname') .' />'; - $out .= '
' .rcube::Q($this->plugin->gettext('setvarvalue')) . '
' - .'error_class($id, 'action', 'value', 'action_varvalue') .' />'; - $out .= '
' .rcube::Q($this->plugin->gettext('setvarmodifiers')) . '
'; - foreach ($set_modifiers as $s_m) { - $s_m_id = 'action_varmods' . $id . $s_m; - $out .= sprintf('%s
', - $id, $s_m, $s_m_id, - (array_key_exists($s_m, (array)$action) && $action[$s_m] ? ' checked="checked"' : ''), - rcube::Q($this->plugin->gettext('var' . $s_m))); - } - $out .= '
'; - - // notify - $notify_methods = (array) $this->rc->config->get('managesieve_notify_methods'); - $importance_options = $this->notify_importance_options; - - if (empty($notify_methods)) { - $notify_methods = $this->notify_methods; - } - - list($method, $target) = explode(':', $action['method'], 2); - $method = strtolower($method); - - if ($method && !in_array($method, $notify_methods)) { - $notify_methods[] = $method; - } - - $select_method = new html_select(array( - 'name' => "_action_notifymethod[$id]", - 'id' => "_action_notifymethod$id", - 'class' => $this->error_class($id, 'action', 'method', 'action_notifymethod'), - )); - foreach ($notify_methods as $m_n) { - $select_method->add(rcube::Q($this->rc->text_exists('managesieve.notifymethod'.$m_n) ? $this->plugin->gettext('managesieve.notifymethod'.$m_n) : $m_n), $m_n); - } - - $select_importance = new html_select(array( - 'name' => "_action_notifyimportance[$id]", - 'id' => "_action_notifyimportance$id", - 'class' => $this->error_class($id, 'action', 'importance', 'action_notifyimportance') - )); - foreach ($importance_options as $io_v => $io_n) { - $select_importance->add(rcube::Q($this->plugin->gettext($io_n)), $io_v); - } - - // @TODO: nice UI for mailto: (other methods too) URI parameters - $out .= '
'; - $out .= '' .rcube::Q($this->plugin->gettext('notifytarget')) . '
' - . $select_method->show($method) - .'error_class($id, 'action', 'target', 'action_notifytarget') .' />'; - $out .= '
'. rcube::Q($this->plugin->gettext('notifymessage')) .'
' - .'\n"; - if (in_array('enotify', $this->exts)) { - $out .= '
' .rcube::Q($this->plugin->gettext('notifyfrom')) . '
' - .'error_class($id, 'action', 'from', 'action_notifyfrom') .' />'; - } - $out .= '
' . rcube::Q($this->plugin->gettext('notifyimportance')) . '
'; - $out .= $select_importance->show($action['importance'] ? (int) $action['importance'] : 2); - $out .= '
' - .'' . rcube::Q($this->plugin->gettext('notifyoptions')) . '
' - .$this->list_input($id, 'action_notifyoption', (array)$action['options'], true, - $this->error_class($id, 'action', 'options', 'action_notifyoption'), 30) . '
'; - $out .= '
'; - - // mailbox select - if ($action['type'] == 'fileinto') { - $mailbox = $this->mod_mailbox($action['target'], 'out'); - // make sure non-existing (or unsubscribed) mailbox is listed (#1489956) - $additional = array($mailbox); - } - else { - $mailbox = ''; - } - - $select = $this->rc->folder_selector(array( - 'realnames' => false, - 'maxlength' => 100, - 'id' => 'action_mailbox' . $id, - 'name' => "_action_mailbox[$id]", - 'style' => 'display:'.(empty($action['type']) || $action['type'] == 'fileinto' ? 'inline' : 'none'), - 'additional' => $additional, - )); - $out .= $select->show($mailbox); - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= '
'; - - $out .= $div ? "
\n" : ''; - - return $out; - } - - protected function genid() - { - return preg_replace('/[^0-9]/', '', microtime(true)); - } - - protected function strip_value($str, $allow_html = false, $trim = true) - { - if (is_array($str)) { - foreach ($str as $idx => $val) { - $val = $this->strip_value($val, $allow_html, $trim); - - if ($val === '') { - unset($str[$idx]); - } - } - - return $str; - } - - if (!$allow_html) { - $str = strip_tags($str); - } - - return $trim ? trim($str) : $str; - } - - protected function error_class($id, $type, $target, $elem_prefix='') - { - // TODO: tooltips - if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) || - ($type == 'action' && ($str = $this->errors['actions'][$id][$target])) - ) { - $this->add_tip($elem_prefix.$id, $str, true); - return ' class="error"'; - } - - return ''; - } - - protected function add_tip($id, $str, $error=false) - { - if ($error) - $str = html::span('sieve error', $str); - - $this->tips[] = array($id, $str); - } - - protected function print_tips() - { - if (empty($this->tips)) - return; - - $script = rcmail_output::JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');'; - $this->rc->output->add_script($script, 'foot'); - } - - protected function list_input($id, $name, $value, $enabled, $class, $size=null) - { - $value = (array) $value; - $value = array_map(array('rcube', 'Q'), $value); - $value = implode("\n", $value); - - return ''; - } - - /** - * Validate input for date part elements - */ - protected function validate_date_part($type, $value) - { - // we do simple validation of date/part format - switch ($type) { - case 'date': // yyyy-mm-dd - return preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $value); - case 'iso8601': - return preg_match('/^[0-9: .,ZWT+-]+$/', $value); - case 'std11': - return preg_match('/^((Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s+)?[0-9]{1,2}\s+' - . '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]{2,4}\s+' - . '[0-9]{2}:[0-9]{2}(:[0-9]{2})?\s+([+-]*[0-9]{4}|[A-Z]{1,3})$', $value); - case 'julian': - return preg_match('/^[0-9]+$/', $value); - case 'time': // hh:mm:ss - return preg_match('/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $value); - case 'year': - return preg_match('/^[0-9]{4}$/', $value); - case 'month': - return preg_match('/^[0-9]{2}$/', $value) && $value > 0 && $value < 13; - case 'day': - return preg_match('/^[0-9]{2}$/', $value) && $value > 0 && $value < 32; - case 'hour': - return preg_match('/^[0-9]{2}$/', $value) && $value < 24; - case 'minute': - return preg_match('/^[0-9]{2}$/', $value) && $value < 60; - case 'second': - // According to RFC5260, seconds can be from 00 to 60 - return preg_match('/^[0-9]{2}$/', $value) && $value < 61; - case 'weekday': - return preg_match('/^[0-9]$/', $value) && $value < 7; - case 'zone': - return preg_match('/^[+-][0-9]{4}$/', $value); - } - } - - /** - * Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding - * with delimiter replacement. - * - * @param string $mailbox Mailbox name - * @param string $mode Conversion direction ('in'|'out') - * - * @return string Mailbox name - */ - protected function mod_mailbox($mailbox, $mode = 'out') - { - $delimiter = $_SESSION['imap_delimiter']; - $replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter'); - $mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP'); - - if ($mode == 'out') { - $mailbox = rcube_charset::convert($mailbox, $mbox_encoding, 'UTF7-IMAP'); - if ($replace_delimiter && $replace_delimiter != $delimiter) - $mailbox = str_replace($replace_delimiter, $delimiter, $mailbox); - } - else { - $mailbox = rcube_charset::convert($mailbox, 'UTF7-IMAP', $mbox_encoding); - if ($replace_delimiter && $replace_delimiter != $delimiter) - $mailbox = str_replace($delimiter, $replace_delimiter, $mailbox); - } - - return $mailbox; - } - - /** - * List sieve scripts - * - * @return array Scripts list - */ - public function list_scripts() - { - if ($this->list !== null) { - return $this->list; - } - - $this->list = $this->sieve->get_scripts(); - - // Handle active script(s) and list of scripts according to Kolab's KEP:14 - if ($this->rc->config->get('managesieve_kolab_master')) { - // Skip protected names - foreach ((array)$this->list as $idx => $name) { - $_name = strtoupper($name); - if ($_name == 'MASTER') - $master_script = $name; - else if ($_name == 'MANAGEMENT') - $management_script = $name; - else if($_name == 'USER') - $user_script = $name; - else - continue; - - unset($this->list[$idx]); - } - - // get active script(s), read USER script - if ($user_script) { - $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve'); - $filename_regex = '/'.preg_quote($extension, '/').'$/'; - $_SESSION['managesieve_user_script'] = $user_script; - - $this->sieve->load($user_script); - - foreach ($this->sieve->script->as_array() as $rules) { - foreach ($rules['actions'] as $action) { - if ($action['type'] == 'include' && empty($action['global'])) { - $name = preg_replace($filename_regex, '', $action['target']); - // make sure the script exist - if (in_array($name, $this->list)) { - $this->active[] = $name; - } - } - } - } - } - // create USER script if it doesn't exist - else { - $content = "# USER Management Script\n" - ."#\n" - ."# This script includes the various active sieve scripts\n" - ."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n" - ."#\n" - ."# For more information, see http://wiki.kolab.org/KEP:14#USER\n" - ."#\n"; - if ($this->sieve->save_script('USER', $content)) { - $_SESSION['managesieve_user_script'] = 'USER'; - if (empty($this->master_file)) - $this->sieve->activate('USER'); - } - } - } - else if (!empty($this->list)) { - // Get active script name - if ($active = $this->sieve->get_active()) { - $this->active = array($active); - } - - // Hide scripts from config - $exceptions = $this->rc->config->get('managesieve_filename_exceptions'); - if (!empty($exceptions)) { - $this->list = array_diff($this->list, (array)$exceptions); - } - } - - // reindex - if (!empty($this->list)) { - $this->list = array_values($this->list); - } - - return $this->list; - } - - /** - * Removes sieve script - * - * @param string $name Script name - * - * @return bool True on success, False on failure - */ - public function remove_script($name) - { - $result = $this->sieve->remove($name); - - // Kolab's KEP:14 - if ($result && $this->rc->config->get('managesieve_kolab_master')) { - $this->deactivate_script($name); - } - - return $result; - } - - /** - * Activates sieve script - * - * @param string $name Script name - * - * @return bool True on success, False on failure - */ - public function activate_script($name) - { - // Kolab's KEP:14 - if ($this->rc->config->get('managesieve_kolab_master')) { - $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve'); - $user_script = $_SESSION['managesieve_user_script']; - - // if the script is not active... - if ($user_script && array_search($name, $this->active) === false) { - // ...rewrite USER file adding appropriate include command - if ($this->sieve->load($user_script)) { - $script = $this->sieve->script->as_array(); - $list = array(); - $regexp = '/' . preg_quote($extension, '/') . '$/'; - - // Create new include entry - $rule = array( - 'actions' => array( - 0 => array( - 'target' => $name.$extension, - 'type' => 'include', - 'personal' => true, - ))); - - // get all active scripts for sorting - foreach ($script as $rid => $rules) { - foreach ($rules['actions'] as $action) { - if ($action['type'] == 'include' && empty($action['global'])) { - $target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target']; - $list[] = $target; - } - } - } - $list[] = $name; - - // Sort and find current script position - asort($list, SORT_LOCALE_STRING); - $list = array_values($list); - $index = array_search($name, $list); - - // add rule at the end of the script - if ($index === false || $index == count($list)-1) { - $this->sieve->script->add_rule($rule); - } - // add rule at index position - else { - $script2 = array(); - foreach ($script as $rid => $rules) { - if ($rid == $index) { - $script2[] = $rule; - } - $script2[] = $rules; - } - $this->sieve->script->content = $script2; - } - - $result = $this->sieve->save(); - if ($result) { - $this->active[] = $name; - } - } - } - } - else { - $result = $this->sieve->activate($name); - if ($result) - $this->active = array($name); - } - - return $result; - } - - /** - * Deactivates sieve script - * - * @param string $name Script name - * - * @return bool True on success, False on failure - */ - public function deactivate_script($name) - { - // Kolab's KEP:14 - if ($this->rc->config->get('managesieve_kolab_master')) { - $extension = $this->rc->config->get('managesieve_filename_extension', '.sieve'); - $user_script = $_SESSION['managesieve_user_script']; - - // if the script is active... - if ($user_script && ($key = array_search($name, $this->active)) !== false) { - // ...rewrite USER file removing appropriate include command - if ($this->sieve->load($user_script)) { - $script = $this->sieve->script->as_array(); - $name = $name.$extension; - - foreach ($script as $rid => $rules) { - foreach ($rules['actions'] as $action) { - if ($action['type'] == 'include' && empty($action['global']) - && $action['target'] == $name - ) { - break 2; - } - } - } - - // Entry found - if ($rid < count($script)) { - $this->sieve->script->delete_rule($rid); - $result = $this->sieve->save(); - if ($result) { - unset($this->active[$key]); - } - } - } - } - } - else { - $result = $this->sieve->deactivate(); - if ($result) - $this->active = array(); - } - - return $result; - } - - /** - * Saves current script (adding some variables) - */ - public function save_script($name = null) - { - // Kolab's KEP:14 - if ($this->rc->config->get('managesieve_kolab_master')) { - $this->sieve->script->set_var('EDITOR', self::PROGNAME); - $this->sieve->script->set_var('EDITOR_VERSION', self::VERSION); - } - - return $this->sieve->save($name); - } - - /** - * Returns list of rules from the current script - * - * @return array List of rules - */ - public function list_rules() - { - $result = array(); - $i = 1; - - foreach ($this->script as $idx => $filter) { - if (empty($filter['actions'])) { - continue; - } - $fname = $filter['name'] ? $filter['name'] : "#$i"; - $result[] = array( - 'id' => $idx, - 'name' => $fname, - 'class' => $filter['disabled'] ? 'disabled' : '', - ); - $i++; - } - - return $result; - } - - /** - * Initializes internal script data - */ - protected function init_script() - { - if (!$this->sieve->script) { - return; - } - - $this->script = $this->sieve->script->as_array(); - - $headers = array(); - $exceptions = array('date', 'currentdate', 'size', 'body'); - - // find common headers used in script, will be added to the list - // of available (predefined) headers (#1489271) - foreach ($this->script as $rule) { - foreach ((array) $rule['tests'] as $test) { - if ($test['test'] == 'header') { - foreach ((array) $test['arg1'] as $header) { - $lc_header = strtolower($header); - - // skip special names to not confuse UI - if (in_array($lc_header, $exceptions)) { - continue; - } - - if (!isset($this->headers[$lc_header]) && !isset($headers[$lc_header])) { - $headers[$lc_header] = $header; - } - } - } - } - } - - ksort($headers); - - $this->headers += $headers; - } -} diff --git a/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php b/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php deleted file mode 100644 index 518d79d35..000000000 --- a/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php +++ /dev/null @@ -1,1217 +0,0 @@ -supported as $idx => $ext) { - if (!in_array($ext, $capabilities)) { - unset($this->supported[$idx]); - } - } - } - - // Parse text content of the script - $this->_parse_text($script); - } - - /** - * Adds rule to the script (at the end) - * - * @param string Rule name - * @param array Rule content (as array) - * - * @return int The index of the new rule - */ - public function add_rule($content) - { - // TODO: check this->supported - array_push($this->content, $content); - return sizeof($this->content)-1; - } - - public function delete_rule($index) - { - if(isset($this->content[$index])) { - unset($this->content[$index]); - return true; - } - return false; - } - - public function size() - { - return sizeof($this->content); - } - - public function update_rule($index, $content) - { - // TODO: check this->supported - if ($this->content[$index]) { - $this->content[$index] = $content; - return $index; - } - return false; - } - - /** - * Sets "global" variable - * - * @param string $name Variable name - * @param string $value Variable value - * @param array $mods Variable modifiers - */ - public function set_var($name, $value, $mods = array()) - { - // Check if variable exists - for ($i=0, $len=count($this->vars); $i<$len; $i++) { - if ($this->vars[$i]['name'] == $name) { - break; - } - } - - $var = array_merge($mods, array('name' => $name, 'value' => $value)); - $this->vars[$i] = $var; - } - - /** - * Unsets "global" variable - * - * @param string $name Variable name - */ - public function unset_var($name) - { - // Check if variable exists - foreach ($this->vars as $idx => $var) { - if ($var['name'] == $name) { - unset($this->vars[$idx]); - break; - } - } - } - - /** - * Gets the value of "global" variable - * - * @param string $name Variable name - * - * @return string Variable value - */ - public function get_var($name) - { - // Check if variable exists - for ($i=0, $len=count($this->vars); $i<$len; $i++) { - if ($this->vars[$i]['name'] == $name) { - return $this->vars[$i]['name']; - } - } - } - - /** - * Sets script header content - * - * @param string $text Header content - */ - public function set_prefix($text) - { - $this->prefix = $text; - } - - /** - * Returns script as text - */ - public function as_text() - { - $output = ''; - $exts = array(); - $idx = 0; - - if (!empty($this->vars)) { - if (in_array('variables', (array)$this->supported)) { - $has_vars = true; - array_push($exts, 'variables'); - } - foreach ($this->vars as $var) { - if (empty($has_vars)) { - // 'variables' extension not supported, put vars in comments - $output .= sprintf("# %s %s\n", $var['name'], $var['value']); - } - else { - $output .= 'set '; - foreach (array_diff(array_keys($var), array('name', 'value')) as $opt) { - $output .= ":$opt "; - } - $output .= self::escape_string($var['name']) . ' ' . self::escape_string($var['value']) . ";\n"; - } - } - } - - $imapflags = in_array('imap4flags', $this->supported) ? 'imap4flags' : 'imapflags'; - $notify = in_array('enotify', $this->supported) ? 'enotify' : 'notify'; - - // rules - foreach ($this->content as $rule) { - $script = ''; - $tests = array(); - $i = 0; - - // header - if (!empty($rule['name']) && strlen($rule['name'])) { - $script .= '# rule:[' . $rule['name'] . "]\n"; - } - - // constraints expressions - if (!empty($rule['tests'])) { - foreach ($rule['tests'] as $test) { - $tests[$i] = ''; - switch ($test['test']) { - case 'size': - $tests[$i] .= ($test['not'] ? 'not ' : ''); - $tests[$i] .= 'size :' . ($test['type']=='under' ? 'under ' : 'over ') . $test['arg']; - break; - - case 'true': - $tests[$i] .= ($test['not'] ? 'false' : 'true'); - break; - - case 'exists': - $tests[$i] .= ($test['not'] ? 'not ' : ''); - $tests[$i] .= 'exists ' . self::escape_string($test['arg']); - break; - - case 'header': - $tests[$i] .= ($test['not'] ? 'not ' : ''); - $tests[$i] .= 'header'; - - $this->add_index($test, $tests[$i], $exts); - $this->add_operator($test, $tests[$i], $exts); - - $tests[$i] .= ' ' . self::escape_string($test['arg1']); - $tests[$i] .= ' ' . self::escape_string($test['arg2']); - break; - - case 'address': - case 'envelope': - if ($test['test'] == 'envelope') { - array_push($exts, 'envelope'); - } - - $tests[$i] .= ($test['not'] ? 'not ' : ''); - $tests[$i] .= $test['test']; - - if ($test['test'] != 'envelope') { - $this->add_index($test, $tests[$i], $exts); - } - - // :all address-part is optional, skip it - if (!empty($test['part']) && $test['part'] != 'all') { - $tests[$i] .= ' :' . $test['part']; - if ($test['part'] == 'user' || $test['part'] == 'detail') { - array_push($exts, 'subaddress'); - } - } - - $this->add_operator($test, $tests[$i], $exts); - - $tests[$i] .= ' ' . self::escape_string($test['arg1']); - $tests[$i] .= ' ' . self::escape_string($test['arg2']); - break; - - case 'body': - array_push($exts, 'body'); - - $tests[$i] .= ($test['not'] ? 'not ' : '') . 'body'; - - if (!empty($test['part'])) { - $tests[$i] .= ' :' . $test['part']; - - if (!empty($test['content']) && $test['part'] == 'content') { - $tests[$i] .= ' ' . self::escape_string($test['content']); - } - } - - $this->add_operator($test, $tests[$i], $exts); - - $tests[$i] .= ' ' . self::escape_string($test['arg']); - break; - - case 'date': - case 'currentdate': - array_push($exts, 'date'); - - $tests[$i] .= ($test['not'] ? 'not ' : '') . $test['test']; - - $this->add_index($test, $tests[$i], $exts); - - if (!empty($test['originalzone']) && $test['test'] == 'date') { - $tests[$i] .= ' :originalzone'; - } - else if (!empty($test['zone'])) { - $tests[$i] .= ' :zone ' . self::escape_string($test['zone']); - } - - $this->add_operator($test, $tests[$i], $exts); - - if ($test['test'] == 'date') { - $tests[$i] .= ' ' . self::escape_string($test['header']); - } - - $tests[$i] .= ' ' . self::escape_string($test['part']); - $tests[$i] .= ' ' . self::escape_string($test['arg']); - - break; - } - $i++; - } - } - - // disabled rule: if false #.... - if (!empty($tests)) { - $script .= 'if ' . ($rule['disabled'] ? 'false # ' : ''); - - if (count($tests) > 1) { - $tests_str = implode(', ', $tests); - } - else { - $tests_str = $tests[0]; - } - - if ($rule['join'] || count($tests) > 1) { - $script .= sprintf('%s (%s)', $rule['join'] ? 'allof' : 'anyof', $tests_str); - } - else { - $script .= $tests_str; - } - $script .= "\n{\n"; - } - - // action(s) - if (!empty($rule['actions'])) { - foreach ($rule['actions'] as $action) { - $action_script = ''; - - switch ($action['type']) { - - case 'fileinto': - array_push($exts, 'fileinto'); - $action_script .= 'fileinto '; - if ($action['copy']) { - $action_script .= ':copy '; - array_push($exts, 'copy'); - } - $action_script .= self::escape_string($action['target']); - break; - - case 'redirect': - $action_script .= 'redirect '; - if ($action['copy']) { - $action_script .= ':copy '; - array_push($exts, 'copy'); - } - $action_script .= self::escape_string($action['target']); - break; - - case 'reject': - case 'ereject': - array_push($exts, $action['type']); - $action_script .= $action['type'].' ' - . self::escape_string($action['target']); - break; - - case 'addflag': - case 'setflag': - case 'removeflag': - array_push($exts, $imapflags); - $action_script .= $action['type'].' ' - . self::escape_string($action['target']); - break; - - case 'keep': - case 'discard': - case 'stop': - $action_script .= $action['type']; - break; - - case 'include': - array_push($exts, 'include'); - $action_script .= 'include '; - foreach (array_diff(array_keys($action), array('target', 'type')) as $opt) { - $action_script .= ":$opt "; - } - $action_script .= self::escape_string($action['target']); - break; - - case 'set': - array_push($exts, 'variables'); - $action_script .= 'set '; - foreach (array_diff(array_keys($action), array('name', 'value', 'type')) as $opt) { - $action_script .= ":$opt "; - } - $action_script .= self::escape_string($action['name']) . ' ' . self::escape_string($action['value']); - break; - - case 'notify': - array_push($exts, $notify); - $action_script .= 'notify'; - - $method = $action['method']; - unset($action['method']); - $action['options'] = (array) $action['options']; - - // Here we support draft-martin-sieve-notify-01 used by Cyrus - if ($notify == 'notify') { - switch ($action['importance']) { - case 1: $action_script .= " :high"; break; - //case 2: $action_script .= " :normal"; break; - case 3: $action_script .= " :low"; break; - } - - // Old-draft way: :method "mailto" :options "email@address" - if (!empty($method)) { - $parts = explode(':', $method, 2); - $action['method'] = $parts[0]; - array_unshift($action['options'], $parts[1]); - } - - unset($action['importance']); - unset($action['from']); - unset($method); - } - - foreach (array('id', 'importance', 'method', 'options', 'from', 'message') as $n_tag) { - if (!empty($action[$n_tag])) { - $action_script .= " :$n_tag " . self::escape_string($action[$n_tag]); - } - } - - if (!empty($method)) { - $action_script .= ' ' . self::escape_string($method); - } - - break; - - case 'vacation': - array_push($exts, 'vacation'); - $action_script .= 'vacation'; - if (isset($action['seconds'])) { - array_push($exts, 'vacation-seconds'); - $action_script .= " :seconds " . intval($action['seconds']); - } - else if (!empty($action['days'])) { - $action_script .= " :days " . intval($action['days']); - } - if (!empty($action['addresses'])) - $action_script .= " :addresses " . self::escape_string($action['addresses']); - if (!empty($action['subject'])) - $action_script .= " :subject " . self::escape_string($action['subject']); - if (!empty($action['handle'])) - $action_script .= " :handle " . self::escape_string($action['handle']); - if (!empty($action['from'])) - $action_script .= " :from " . self::escape_string($action['from']); - if (!empty($action['mime'])) - $action_script .= " :mime"; - $action_script .= " " . self::escape_string($action['reason']); - break; - } - - if ($action_script) { - $script .= !empty($tests) ? "\t" : ''; - $script .= $action_script . ";\n"; - } - } - } - - if ($script) { - $output .= $script . (!empty($tests) ? "}\n" : ''); - $idx++; - } - } - - // requires - if (!empty($exts)) { - $exts = array_unique($exts); - - if (in_array('vacation-seconds', $exts) && ($key = array_search('vacation', $exts)) !== false) { - unset($exts[$key]); - } - - sort($exts); // for convenience use always the same order - - $output = 'require ["' . implode('","', $exts) . "\"];\n" . $output; - } - - if (!empty($this->prefix)) { - $output = $this->prefix . "\n\n" . $output; - } - - return $output; - } - - /** - * Returns script object - * - */ - public function as_array() - { - return $this->content; - } - - /** - * Returns array of supported extensions - * - */ - public function get_extensions() - { - return array_values($this->supported); - } - - /** - * Converts text script to rules array - * - * @param string Text script - */ - private function _parse_text($script) - { - $prefix = ''; - $options = array(); - - while ($script) { - $script = trim($script); - $rule = array(); - - // Comments - while (!empty($script) && $script[0] == '#') { - $endl = strpos($script, "\n"); - $line = $endl ? substr($script, 0, $endl) : $script; - - // Roundcube format - if (preg_match('/^# rule:\[(.*)\]/', $line, $matches)) { - $rulename = $matches[1]; - } - // KEP:14 variables - else if (preg_match('/^# (EDITOR|EDITOR_VERSION) (.+)$/', $line, $matches)) { - $this->set_var($matches[1], $matches[2]); - } - // Horde-Ingo format - else if (!empty($options['format']) && $options['format'] == 'INGO' - && preg_match('/^# (.*)/', $line, $matches) - ) { - $rulename = $matches[1]; - } - else if (empty($options['prefix'])) { - $prefix .= $line . "\n"; - } - - $script = ltrim(substr($script, strlen($line) + 1)); - } - - // handle script header - if (empty($options['prefix'])) { - $options['prefix'] = true; - if ($prefix && strpos($prefix, 'horde.org/ingo')) { - $options['format'] = 'INGO'; - } - } - - // Control structures/blocks - if (preg_match('/^(if|else|elsif)/i', $script)) { - $rule = $this->_tokenize_rule($script); - if (strlen($rulename) && !empty($rule)) { - $rule['name'] = $rulename; - } - } - // Simple commands - else { - $rule = $this->_parse_actions($script, ';'); - if (!empty($rule[0]) && is_array($rule)) { - // set "global" variables - if ($rule[0]['type'] == 'set') { - unset($rule[0]['type']); - $this->vars[] = $rule[0]; - unset($rule); - } - else { - $rule = array('actions' => $rule); - } - } - } - - $rulename = ''; - - if (!empty($rule)) { - $this->content[] = $rule; - } - } - - if (!empty($prefix)) { - $this->prefix = trim($prefix); - } - } - - /** - * Convert text script fragment to rule object - * - * @param string Text rule - * - * @return array Rule data - */ - private function _tokenize_rule(&$content) - { - $cond = strtolower(self::tokenize($content, 1)); - - if ($cond != 'if' && $cond != 'elsif' && $cond != 'else') { - return null; - } - - $disabled = false; - $join = false; - $join_not = false; - - // disabled rule (false + comment): if false # ..... - if (preg_match('/^\s*false\s+#/i', $content)) { - $content = preg_replace('/^\s*false\s+#\s*/i', '', $content); - $disabled = true; - } - - while (strlen($content)) { - $tokens = self::tokenize($content, true); - $separator = array_pop($tokens); - - if (!empty($tokens)) { - $token = array_shift($tokens); - } - else { - $token = $separator; - } - - $token = strtolower($token); - - if ($token == 'not') { - $not = true; - $token = strtolower(array_shift($tokens)); - } - else { - $not = false; - } - - // we support "not allof" as a negation of allof sub-tests - if ($join_not) { - $not = !$not; - } - - switch ($token) { - case 'allof': - $join = true; - $join_not = $not; - break; - - case 'anyof': - break; - - case 'size': - $test = array('test' => 'size', 'not' => $not); - - $test['arg'] = array_pop($tokens); - - for ($i=0, $len=count($tokens); $i<$len; $i++) { - if (!is_array($tokens[$i]) - && preg_match('/^:(under|over)$/i', $tokens[$i]) - ) { - $test['type'] = strtolower(substr($tokens[$i], 1)); - } - } - - $tests[] = $test; - break; - - case 'header': - case 'address': - case 'envelope': - $test = array('test' => $token, 'not' => $not); - - $test['arg2'] = array_pop($tokens); - $test['arg1'] = array_pop($tokens); - - $test += $this->test_tokens($tokens); - - if ($token != 'header' && !empty($tokens)) { - for ($i=0, $len=count($tokens); $i<$len; $i++) { - if (!is_array($tokens[$i]) && preg_match('/^:(localpart|domain|all|user|detail)$/i', $tokens[$i])) { - $test['part'] = strtolower(substr($tokens[$i], 1)); - } - } - } - - $tests[] = $test; - break; - - case 'body': - $test = array('test' => 'body', 'not' => $not); - - $test['arg'] = array_pop($tokens); - - $test += $this->test_tokens($tokens); - - for ($i=0, $len=count($tokens); $i<$len; $i++) { - if (!is_array($tokens[$i]) && preg_match('/^:(raw|content|text)$/i', $tokens[$i])) { - $test['part'] = strtolower(substr($tokens[$i], 1)); - - if ($test['part'] == 'content') { - $test['content'] = $tokens[++$i]; - } - } - } - - $tests[] = $test; - break; - - case 'date': - case 'currentdate': - $test = array('test' => $token, 'not' => $not); - - $test['arg'] = array_pop($tokens); - $test['part'] = array_pop($tokens); - - if ($token == 'date') { - $test['header'] = array_pop($tokens); - } - - $test += $this->test_tokens($tokens); - - for ($i=0, $len=count($tokens); $i<$len; $i++) { - if (!is_array($tokens[$i]) && preg_match('/^:zone$/i', $tokens[$i])) { - $test['zone'] = $tokens[++$i]; - } - else if (!is_array($tokens[$i]) && preg_match('/^:originalzone$/i', $tokens[$i])) { - $test['originalzone'] = true; - } - } - - $tests[] = $test; - break; - - case 'exists': - $tests[] = array('test' => 'exists', 'not' => $not, - 'arg' => array_pop($tokens)); - break; - - case 'true': - $tests[] = array('test' => 'true', 'not' => $not); - break; - - case 'false': - $tests[] = array('test' => 'true', 'not' => !$not); - break; - } - - // goto actions... - if ($separator == '{') { - break; - } - } - - // ...and actions block - $actions = $this->_parse_actions($content); - - if ($tests && $actions) { - $result = array( - 'type' => $cond, - 'tests' => $tests, - 'actions' => $actions, - 'join' => $join, - 'disabled' => $disabled, - ); - } - - return $result; - } - - /** - * Parse body of actions section - * - * @param string $content Text body - * @param string $end End of text separator - * - * @return array Array of parsed action type/target pairs - */ - private function _parse_actions(&$content, $end = '}') - { - $result = null; - - while (strlen($content)) { - $tokens = self::tokenize($content, true); - $separator = array_pop($tokens); - $token = !empty($tokens) ? array_shift($tokens) : $separator; - - switch ($token) { - case 'discard': - case 'keep': - case 'stop': - $result[] = array('type' => $token); - break; - - case 'fileinto': - case 'redirect': - $action = array('type' => $token, 'target' => array_pop($tokens)); - $args = array('copy'); - $action += $this->action_arguments($tokens, $args); - - $result[] = $action; - break; - - case 'vacation': - $action = array('type' => 'vacation', 'reason' => array_pop($tokens)); - $args = array('mime'); - $vargs = array('seconds', 'days', 'addresses', 'subject', 'handle', 'from'); - $action += $this->action_arguments($tokens, $args, $vargs); - - $result[] = $action; - break; - - case 'reject': - case 'ereject': - case 'setflag': - case 'addflag': - case 'removeflag': - $result[] = array('type' => $token, 'target' => array_pop($tokens)); - break; - - case 'include': - $action = array('type' => 'include', 'target' => array_pop($tokens)); - $args = array('once', 'optional', 'global', 'personal'); - $action += $this->action_arguments($tokens, $args); - - $result[] = $action; - break; - - case 'set': - $action = array('type' => 'set', 'value' => array_pop($tokens), 'name' => array_pop($tokens)); - $args = array('lower', 'upper', 'lowerfirst', 'upperfirst', 'quotewildcard', 'length'); - $action += $this->action_arguments($tokens, $args); - - $result[] = $action; - break; - - case 'require': - // skip, will be build according to used commands - // $result[] = array('type' => 'require', 'target' => array_pop($tokens)); - break; - - case 'notify': - $action = array('type' => 'notify'); - $priorities = array('high' => 1, 'normal' => 2, 'low' => 3); - $vargs = array('from', 'id', 'importance', 'options', 'message', 'method'); - $args = array_keys($priorities); - $action += $this->action_arguments($tokens, $args, $vargs); - - // Here we'll convert draft-martin-sieve-notify-01 into RFC 5435 - if (!isset($action['importance'])) { - foreach ($priorities as $key => $val) { - if (isset($action[$key])) { - $action['importance'] = $val; - unset($action[$key]); - } - } - } - - $action['options'] = (array) $action['options']; - - // Old-draft way: :method "mailto" :options "email@address" - if (!empty($action['method']) && !empty($action['options'])) { - $action['method'] .= ':' . array_shift($action['options']); - } - // unnamed parameter is a :method in enotify extension - else if (!isset($action['method'])) { - $action['method'] = array_pop($tokens); - } - - $result[] = $action; - break; - } - - if ($separator == $end) - break; - } - - return $result; - } - - /** - * Add comparator to the test - */ - private function add_comparator($test, &$out, &$exts) - { - if (empty($test['comparator'])) { - return; - } - - if ($test['comparator'] == 'i;ascii-numeric') { - array_push($exts, 'relational'); - array_push($exts, 'comparator-i;ascii-numeric'); - } - else if (!in_array($test['comparator'], array('i;octet', 'i;ascii-casemap'))) { - array_push($exts, 'comparator-' . $test['comparator']); - } - - // skip default comparator - if ($test['comparator'] != 'i;ascii-casemap') { - $out .= ' :comparator ' . self::escape_string($test['comparator']); - } - } - - /** - * Add index argument to the test - */ - private function add_index($test, &$out, &$exts) - { - if (!empty($test['index'])) { - array_push($exts, 'index'); - $out .= ' :index ' . intval($test['index']) . ($test['last'] ? ' :last' : ''); - } - } - - /** - * Add operators to the test - */ - private function add_operator($test, &$out, &$exts) - { - if (empty($test['type'])) { - return; - } - - // relational operator - if (preg_match('/^(value|count)-([gteqnl]{2})/', $test['type'], $m)) { - array_push($exts, 'relational'); - - $out .= ' :' . $m[1] . ' "' . $m[2] . '"'; - } - else { - if ($test['type'] == 'regex') { - array_push($exts, 'regex'); - } - - $out .= ' :' . $test['type']; - } - - $this->add_comparator($test, $out, $exts); - } - - /** - * Extract test tokens - */ - private function test_tokens(&$tokens) - { - $test = array(); - $result = array(); - - for ($i=0, $len=count($tokens); $i<$len; $i++) { - if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) { - $test['comparator'] = $tokens[++$i]; - } - else if (!is_array($tokens[$i]) && preg_match('/^:(count|value)$/i', $tokens[$i])) { - $test['type'] = strtolower(substr($tokens[$i], 1)) . '-' . $tokens[++$i]; - } - else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) { - $test['type'] = strtolower(substr($tokens[$i], 1)); - } - else if (!is_array($tokens[$i]) && preg_match('/^:index$/i', $tokens[$i])) { - $test['index'] = intval($tokens[++$i]); - if ($tokens[$i+1] && preg_match('/^:last$/i', $tokens[$i+1])) { - $test['last'] = true; - $i++; - } - } - else { - $result[] = $tokens[$i]; - } - } - - $tokens = $result; - - return $test; - } - - /** - * Extract action arguments - */ - private function action_arguments(&$tokens, $bool_args, $val_args = array()) - { - $action = array(); - $result = array(); - - for ($i=0, $len=count($tokens); $i<$len; $i++) { - $tok = $tokens[$i]; - if (!is_array($tok) && $tok[0] == ':') { - $tok = strtolower(substr($tok, 1)); - if (in_array($tok, $bool_args)) { - $action[$tok] = true; - } - else if (in_array($tok, $val_args)) { - $action[$tok] = $tokens[++$i]; - } - else { - $result[] = $tok; - } - } - else { - $result[] = $tok; - } - } - - $tokens = $result; - - return $action; - } - - /** - * Escape special chars into quoted string value or multi-line string - * or list of strings - * - * @param string $str Text or array (list) of strings - * - * @return string Result text - */ - static function escape_string($str) - { - if (is_array($str) && count($str) > 1) { - foreach($str as $idx => $val) - $str[$idx] = self::escape_string($val); - - return '[' . implode(',', $str) . ']'; - } - else if (is_array($str)) { - $str = array_pop($str); - } - - // multi-line string - if (preg_match('/[\r\n\0]/', $str) || strlen($str) > 1024) { - return sprintf("text:\n%s\n.\n", self::escape_multiline_string($str)); - } - // quoted-string - else { - return '"' . addcslashes($str, '\\"') . '"'; - } - } - - /** - * Escape special chars in multi-line string value - * - * @param string $str Text - * - * @return string Text - */ - static function escape_multiline_string($str) - { - $str = preg_split('/(\r?\n)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE); - - foreach ($str as $idx => $line) { - // dot-stuffing - if (isset($line[0]) && $line[0] == '.') { - $str[$idx] = '.' . $line; - } - } - - return implode($str); - } - - /** - * Splits script into string tokens - * - * @param string &$str The script - * @param mixed $num Number of tokens to return, 0 for all - * or True for all tokens until separator is found. - * Separator will be returned as last token. - * - * @return mixed Tokens array or string if $num=1 - */ - static function tokenize(&$str, $num=0) - { - $result = array(); - - // remove spaces from the beginning of the string - while (($str = ltrim($str)) !== '' - && (!$num || $num === true || count($result) < $num) - ) { - switch ($str[0]) { - - // Quoted string - case '"': - $len = strlen($str); - - for ($pos=1; $pos<$len; $pos++) { - if ($str[$pos] == '"') { - break; - } - if ($str[$pos] == "\\") { - if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") { - $pos++; - } - } - } - if ($str[$pos] != '"') { - // error - } - // we need to strip slashes for a quoted string - $result[] = stripslashes(substr($str, 1, $pos - 1)); - $str = substr($str, $pos + 1); - break; - - // Parenthesized list - case '[': - $str = substr($str, 1); - $result[] = self::tokenize($str, 0); - break; - case ']': - $str = substr($str, 1); - return $result; - break; - - // list/test separator - case ',': - // command separator - case ';': - // block/tests-list - case '(': - case ')': - case '{': - case '}': - $sep = $str[0]; - $str = substr($str, 1); - if ($num === true) { - $result[] = $sep; - break 2; - } - break; - - // bracket-comment - case '/': - if ($str[1] == '*') { - if ($end_pos = strpos($str, '*/')) { - $str = substr($str, $end_pos + 2); - } - else { - // error - $str = ''; - } - } - break; - - // hash-comment - case '#': - if ($lf_pos = strpos($str, "\n")) { - $str = substr($str, $lf_pos); - break; - } - else { - $str = ''; - } - - // String atom - default: - // empty or one character - if ($str === '' || $str === null) { - break 2; - } - if (strlen($str) < 2) { - $result[] = $str; - $str = ''; - break; - } - - // tag/identifier/number - if (preg_match('/^([a-z0-9:_]+)/i', $str, $m)) { - $str = substr($str, strlen($m[1])); - - if ($m[1] != 'text:') { - $result[] = $m[1]; - } - // multiline string - else { - // possible hash-comment after "text:" - if (preg_match('/^( |\t)*(#[^\n]+)?\n/', $str, $m)) { - $str = substr($str, strlen($m[0])); - } - // get text until alone dot in a line - if (preg_match('/^(.*)\r?\n\.\r?\n/sU', $str, $m)) { - $text = $m[1]; - // remove dot-stuffing - $text = str_replace("\n..", "\n.", $text); - $str = substr($str, strlen($m[0])); - } - else { - $text = ''; - } - - $result[] = $text; - } - } - // fallback, skip one character as infinite loop prevention - else { - $str = substr($str, 1); - } - - break; - } - } - - return $num === 1 ? (isset($result[0]) ? $result[0] : null) : $result; - } - -} diff --git a/plugins/managesieve/lib/Roundcube/rcube_sieve_vacation.php b/plugins/managesieve/lib/Roundcube/rcube_sieve_vacation.php deleted file mode 100644 index 8d865008f..000000000 --- a/plugins/managesieve/lib/Roundcube/rcube_sieve_vacation.php +++ /dev/null @@ -1,862 +0,0 @@ -start('vacation'); - - // find current vacation rule - if (!$error) { - $this->vacation_rule(); - $this->vacation_post(); - } - - $this->plugin->add_label('vacation.saving'); - $this->rc->output->add_handlers(array( - 'vacationform' => array($this, 'vacation_form'), - )); - - $this->rc->output->set_pagetitle($this->plugin->gettext('vacation')); - $this->rc->output->send('managesieve.vacation'); - } - - /** - * Find and load sieve script with/for vacation rule - * - * @return int Connection status: 0 on success, >0 on failure - */ - protected function load_script() - { - if ($this->script_name !== null) { - return 0; - } - - $list = $this->list_scripts(); - $master = $this->rc->config->get('managesieve_kolab_master'); - $included = array(); - - $this->script_name = false; - - // first try the active script(s)... - if (!empty($this->active)) { - // Note: there can be more than one active script on KEP:14-enabled server - foreach ($this->active as $script) { - if ($this->sieve->load($script)) { - foreach ($this->sieve->script->as_array() as $rule) { - if (!empty($rule['actions'])) { - if ($rule['actions'][0]['type'] == 'vacation') { - $this->script_name = $script; - return 0; - } - else if (empty($master) && $rule['actions'][0]['type'] == 'include') { - $included[] = $rule['actions'][0]['target']; - } - } - } - } - } - - // ...else try scripts included in active script (not for KEP:14) - foreach ($included as $script) { - if ($this->sieve->load($script)) { - foreach ($this->sieve->script->as_array() as $rule) { - if (!empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') { - $this->script_name = $script; - return 0; - } - } - } - } - } - - // try all other scripts - if (!empty($list)) { - // else try included scripts - foreach (array_diff($list, $included, $this->active) as $script) { - if ($this->sieve->load($script)) { - foreach ($this->sieve->script->as_array() as $rule) { - if (!empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') { - $this->script_name = $script; - return 0; - } - } - } - } - - // none of the scripts contains existing vacation rule - // use any (first) active or just existing script (in that order) - if (!empty($this->active)) { - $this->sieve->load($this->script_name = $this->active[0]); - } - else { - $this->sieve->load($this->script_name = $list[0]); - } - } - - return $this->sieve->error(); - } - - private function vacation_rule() - { - if ($this->script_name === false || $this->script_name === null || !$this->sieve->load($this->script_name)) { - return; - } - - $list = array(); - $active = in_array($this->script_name, $this->active); - - // find (first) vacation rule - foreach ($this->script as $idx => $rule) { - if (empty($this->vacation) && !empty($rule['actions']) && $rule['actions'][0]['type'] == 'vacation') { - foreach ($rule['actions'] as $act) { - if ($act['type'] == 'discard' || $act['type'] == 'keep') { - $action = $act['type']; - } - else if ($act['type'] == 'redirect') { - $action = $act['copy'] ? 'copy' : 'redirect'; - $target = $act['target']; - } - } - - $this->vacation = array_merge($rule['actions'][0], array( - 'idx' => $idx, - 'disabled' => $rule['disabled'] || !$active, - 'name' => $rule['name'], - 'tests' => $rule['tests'], - 'action' => $action ?: 'keep', - 'target' => $target, - )); - } - else if ($active) { - $list[$idx] = $rule['name']; - } - } - - $this->vacation['list'] = $list; - } - - private function vacation_post() - { - if (empty($_POST)) { - return; - } - - $date_extension = in_array('date', $this->exts); - $regex_extension = in_array('regex', $this->exts); - - // set user's timezone - try { - $timezone = new DateTimeZone($this->rc->config->get('timezone', 'GMT')); - } - catch (Exception $e) { - $timezone = new DateTimeZone('GMT'); - } - - $status = rcube_utils::get_input_value('vacation_status', rcube_utils::INPUT_POST); - $subject = rcube_utils::get_input_value('vacation_subject', rcube_utils::INPUT_POST, true); - $reason = rcube_utils::get_input_value('vacation_reason', rcube_utils::INPUT_POST, true); - $addresses = rcube_utils::get_input_value('vacation_addresses', rcube_utils::INPUT_POST, true); - $interval = rcube_utils::get_input_value('vacation_interval', rcube_utils::INPUT_POST); - $interval_type = rcube_utils::get_input_value('vacation_interval_type', rcube_utils::INPUT_POST); - $date_from = rcube_utils::get_input_value('vacation_datefrom', rcube_utils::INPUT_POST); - $date_to = rcube_utils::get_input_value('vacation_dateto', rcube_utils::INPUT_POST); - $time_from = rcube_utils::get_input_value('vacation_timefrom', rcube_utils::INPUT_POST); - $time_to = rcube_utils::get_input_value('vacation_timeto', rcube_utils::INPUT_POST); - $after = rcube_utils::get_input_value('vacation_after', rcube_utils::INPUT_POST); - $action = rcube_utils::get_input_value('vacation_action', rcube_utils::INPUT_POST); - $target = rcube_utils::get_input_value('action_target', rcube_utils::INPUT_POST, true); - $target_domain = rcube_utils::get_input_value('action_domain', rcube_utils::INPUT_POST); - - $interval_type = $interval_type == 'seconds' ? 'seconds' : 'days'; - $vacation_action['type'] = 'vacation'; - $vacation_action['reason'] = $this->strip_value(str_replace("\r\n", "\n", $reason)); - $vacation_action['subject'] = $subject; - $vacation_action['addresses'] = $addresses; - $vacation_action[$interval_type] = $interval; - $vacation_tests = (array) $this->vacation['tests']; - - foreach ((array) $vacation_action['addresses'] as $aidx => $address) { - $vacation_action['addresses'][$aidx] = $address = trim($address); - - if (empty($address)) { - unset($vacation_action['addresses'][$aidx]); - } - else if (!rcube_utils::check_email($address)) { - $error = 'noemailwarning'; - break; - } - } - - if ($vacation_action['reason'] == '') { - $error = 'managesieve.emptyvacationbody'; - } - - if ($vacation_action[$interval_type] && !preg_match('/^[0-9]+$/', $vacation_action[$interval_type])) { - $error = 'managesieve.forbiddenchars'; - } - - // find and remove existing date/regex/true rules - foreach ((array) $vacation_tests as $idx => $t) { - if ($t['test'] == 'currentdate' || $t['test'] == 'true' - || ($t['test'] == 'header' && $t['type'] == 'regex' && $t['arg1'] == 'received') - ) { - unset($vacation_tests[$idx]); - } - } - - if ($date_extension) { - foreach (array('date_from', 'date_to') as $var) { - $time = ${str_replace('date', 'time', $var)}; - $date = trim($$var . ' ' . $time); - - if ($date && ($dt = rcube_utils::anytodatetime($date, $timezone))) { - if ($time) { - $vacation_tests[] = array( - 'test' => 'currentdate', - 'part' => 'iso8601', - 'type' => 'value-' . ($var == 'date_from' ? 'ge' : 'le'), - 'zone' => $dt->format('O'), - 'arg' => str_replace('+00:00', 'Z', strtoupper($dt->format('c'))), - ); - } - else { - $vacation_tests[] = array( - 'test' => 'currentdate', - 'part' => 'date', - 'type' => 'value-' . ($var == 'date_from' ? 'ge' : 'le'), - 'zone' => $dt->format('O'), - 'arg' => $dt->format('Y-m-d'), - ); - } - } - } - } - else if ($regex_extension) { - // Add date range rules if range specified - if ($date_from && $date_to) { - if ($tests = self::build_regexp_tests($date_from, $date_to, $error)) { - $vacation_tests = array_merge($vacation_tests, $tests); - } - } - } - - if ($action == 'redirect' || $action == 'copy') { - if ($target_domain) { - $target .= '@' . $target_domain; - } - - if (empty($target) || !rcube_utils::check_email($target)) { - $error = 'noemailwarning'; - } - } - - if (empty($vacation_tests)) { - $vacation_tests = $this->rc->config->get('managesieve_vacation_test', array(array('test' => 'true'))); - } - - if (!$error) { - $rule = $this->vacation; - $rule['type'] = 'if'; - $rule['name'] = $rule['name'] ?: $this->plugin->gettext('vacation'); - $rule['disabled'] = $status == 'off'; - $rule['tests'] = $vacation_tests; - $rule['join'] = $date_extension ? count($vacation_tests) > 1 : false; - $rule['actions'] = array($vacation_action); - $rule['after'] = $after; - - if ($action && $action != 'keep') { - $rule['actions'][] = array( - 'type' => $action == 'discard' ? 'discard' : 'redirect', - 'copy' => $action == 'copy', - 'target' => $action != 'discard' ? $target : '', - ); - } - - if ($this->save_vacation_script($rule)) { - $this->rc->output->show_message('managesieve.vacationsaved', 'confirmation'); - $this->rc->output->send(); - } - } - - $this->rc->output->show_message($error ? $error : 'managesieve.saveerror', 'error'); - $this->rc->output->send(); - } - - /** - * Independent vacation form - */ - public function vacation_form($attrib) - { - // check supported extensions - $date_extension = in_array('date', $this->exts); - $regex_extension = in_array('regex', $this->exts); - $seconds_extension = in_array('vacation-seconds', $this->exts); - - // build FORM tag - $form_id = !empty($attrib['id']) ? $attrib['id'] : 'form'; - $out = $this->rc->output->request_form(array( - 'id' => $form_id, - 'name' => $form_id, - 'method' => 'post', - 'task' => 'settings', - 'action' => 'plugin.managesieve-vacation', - 'noclose' => true - ) + $attrib); - - // form elements - $subject = new html_inputfield(array('name' => 'vacation_subject', 'id' => 'vacation_subject', 'size' => 50)); - $reason = new html_textarea(array('name' => 'vacation_reason', 'id' => 'vacation_reason', 'cols' => 60, 'rows' => 8)); - $interval = new html_inputfield(array('name' => 'vacation_interval', 'id' => 'vacation_interval', 'size' => 5)); - $addresses = ''; - $status = new html_select(array('name' => 'vacation_status', 'id' => 'vacation_status')); - $action = new html_select(array('name' => 'vacation_action', 'id' => 'vacation_action', 'onchange' => 'vacation_action_select()')); - - $status->add($this->plugin->gettext('vacation.on'), 'on'); - $status->add($this->plugin->gettext('vacation.off'), 'off'); - - $action->add($this->plugin->gettext('vacation.keep'), 'keep'); - $action->add($this->plugin->gettext('vacation.discard'), 'discard'); - $action->add($this->plugin->gettext('vacation.redirect'), 'redirect'); - if (in_array('copy', $this->exts)) { - $action->add($this->plugin->gettext('vacation.copy'), 'copy'); - } - - if ($this->rc->config->get('managesieve_vacation') != 2 && count($this->vacation['list'])) { - $after = new html_select(array('name' => 'vacation_after', 'id' => 'vacation_after')); - - $after->add('', ''); - foreach ($this->vacation['list'] as $idx => $rule) { - $after->add($rule, $idx); - } - } - - $interval_txt = $interval->show(isset($this->vacation['seconds']) ? $this->vacation['seconds'] : $this->vacation['days']); - if ($seconds_extension) { - $interval_select = new html_select(array('name' => 'vacation_interval_type')); - $interval_select->add($this->plugin->gettext('days'), 'days'); - $interval_select->add($this->plugin->gettext('seconds'), 'seconds'); - $interval_txt .= ' ' . $interval_select->show(isset($this->vacation['seconds']) ? 'seconds' : 'days'); - } - else { - $interval_txt .= ' ' . $this->plugin->gettext('days'); - } - - if ($date_extension || $regex_extension) { - $date_from = new html_inputfield(array('name' => 'vacation_datefrom', 'id' => 'vacation_datefrom', 'class' => 'datepicker', 'size' => 12)); - $date_to = new html_inputfield(array('name' => 'vacation_dateto', 'id' => 'vacation_dateto', 'class' => 'datepicker', 'size' => 12)); - $date_format = $this->rc->config->get('date_format', 'Y-m-d'); - } - - if ($date_extension) { - $time_from = new html_inputfield(array('name' => 'vacation_timefrom', 'id' => 'vacation_timefrom', 'size' => 6)); - $time_to = new html_inputfield(array('name' => 'vacation_timeto', 'id' => 'vacation_timeto', 'size' => 6)); - $time_format = $this->rc->config->get('time_format', 'H:i'); - $date_value = array(); - - foreach ((array) $this->vacation['tests'] as $test) { - if ($test['test'] == 'currentdate') { - $idx = $test['type'] == 'value-ge' ? 'from' : 'to'; - - if ($test['part'] == 'date') { - $date_value[$idx]['date'] = $test['arg']; - } - else if ($test['part'] == 'iso8601') { - $date_value[$idx]['datetime'] = $test['arg']; - } - } - } - - foreach ($date_value as $idx => $value) { - $date = $value['datetime'] ?: $value['date']; - $date_value[$idx] = $this->rc->format_date($date, $date_format, false); - - if (!empty($value['datetime'])) { - $date_value['time_' . $idx] = $this->rc->format_date($date, $time_format, true); - } - } - } - else if ($regex_extension) { - // Sieve 'date' extension not available, read start/end from RegEx based rules instead - if ($date_tests = self::parse_regexp_tests($this->vacation['tests'])) { - $date_value['from'] = $this->rc->format_date($date_tests['from'], $date_format, false); - $date_value['to'] = $this->rc->format_date($date_tests['to'], $date_format, false); - } - } - - // force domain selection in redirect email input - $domains = (array) $this->rc->config->get('managesieve_domains'); - $redirect = $this->vacation['action'] == 'redirect' || $this->vacation['action'] == 'copy'; - - if (!empty($domains)) { - sort($domains); - - $domain_select = new html_select(array('name' => 'action_domain', 'id' => 'action_domain')); - $domain_select->add(array_combine($domains, $domains)); - - if ($redirect && $this->vacation['target']) { - $parts = explode('@', $this->vacation['target']); - if (!empty($parts)) { - $this->vacation['domain'] = array_pop($parts); - $this->vacation['target'] = implode('@', $parts); - } - } - } - - // redirect target - $action_target = ' ' - . '' - . (!empty($domains) ? ' @ ' . $domain_select->show($this->vacation['domain']) : '') - . ''; - - // Message tab - $table = new html_table(array('cols' => 2)); - - $table->add('title', html::label('vacation_subject', $this->plugin->gettext('vacation.subject'))); - $table->add(null, $subject->show($this->vacation['subject'])); - $table->add('title', html::label('vacation_reason', $this->plugin->gettext('vacation.body'))); - $table->add(null, $reason->show($this->vacation['reason'])); - - if ($date_extension || $regex_extension) { - $table->add('title', html::label('vacation_datefrom', $this->plugin->gettext('vacation.start'))); - $table->add(null, $date_from->show($date_value['from']) . ($time_from ? ' ' . $time_from->show($date_value['time_from']) : '')); - $table->add('title', html::label('vacation_dateto', $this->plugin->gettext('vacation.end'))); - $table->add(null, $date_to->show($date_value['to']) . ($time_to ? ' ' . $time_to->show($date_value['time_to']) : '')); - } - - $table->add('title', html::label('vacation_status', $this->plugin->gettext('vacation.status'))); - $table->add(null, $status->show(!isset($this->vacation['disabled']) || $this->vacation['disabled'] ? 'off' : 'on')); - - $out .= html::tag('fieldset', $class, html::tag('legend', null, $this->plugin->gettext('vacation.reply')) . $table->show($attrib)); - - // Advanced tab - $table = new html_table(array('cols' => 2)); - - $table->add('title', html::label('vacation_addresses', $this->plugin->gettext('vacation.addresses'))); - $table->add(null, $addresses); - $table->add('title', html::label('vacation_interval', $this->plugin->gettext('vacation.interval'))); - $table->add(null, $interval_txt); - - if ($after) { - $table->add('title', html::label('vacation_after', $this->plugin->gettext('vacation.after'))); - $table->add(null, $after->show($this->vacation['idx'] - 1)); - } - - $table->add('title', html::label('vacation_action', $this->plugin->gettext('vacation.action'))); - $table->add('vacation', $action->show($this->vacation['action']) . $action_target); - - $out .= html::tag('fieldset', $class, html::tag('legend', null, $this->plugin->gettext('vacation.advanced')) . $table->show($attrib)); - - $out .= '
'; - - $this->rc->output->add_gui_object('sieveform', $form_id); - - if ($time_format) { - $this->rc->output->set_env('time_format', $time_format); - } - - return $out; - } - - public static function build_regexp_tests($date_from, $date_to, &$error) - { - $tests = array(); - $dt_from = rcube_utils::anytodatetime($date_from); - $dt_to = rcube_utils::anytodatetime($date_to); - $interval = $dt_from->diff($dt_to); - - if ($interval->invert || $interval->days > 365) { - $error = 'managesieve.invaliddateformat'; - return; - } - - $dt_i = $dt_from; - $interval = new DateInterval('P1D'); - $matchexp = ''; - - while (!$dt_i->diff($dt_to)->invert) { - $days = (int) $dt_i->format('d'); - $matchexp .= $days < 10 ? "[ 0]$days" : $days; - - if ($days == $dt_i->format('t') || $dt_i->diff($dt_to)->days == 0) { - $test = array( - 'test' => 'header', - 'type' => 'regex', - 'arg1' => 'received', - 'arg2' => '('.$matchexp.') '.$dt_i->format('M Y') - ); - - $tests[] = $test; - $matchexp = ''; - } - else { - $matchexp .= '|'; - } - - $dt_i->add($interval); - } - - return $tests; - } - - public static function parse_regexp_tests($tests) - { - $rx_from = '/^\(([0-9]{2}).*\)\s([A-Za-z]+)\s([0-9]{4})/'; - $rx_to = '/^\(.*([0-9]{2})\)\s([A-Za-z]+)\s([0-9]{4})/'; - $result = array(); - - foreach ((array) $tests as $test) { - if ($test['test'] == 'header' && $test['type'] == 'regex' && $test['arg1'] == 'received') { - $textexp = preg_replace('/\[ ([^\]]*)\]/', '0', $test['arg2']); - - if (!$result['from'] && preg_match($rx_from, $textexp, $matches)) { - $result['from'] = $matches[1]." ".$matches[2]." ".$matches[3]; - } - - if (preg_match($rx_to, $textexp, $matches)) { - $result['to'] = $matches[1]." ".$matches[2]." ".$matches[3]; - } - } - } - - return $result; - } - - /** - * Saves vacation script (adding some variables) - */ - protected function save_vacation_script($rule) - { - // if script does not exist create a new one - if ($this->script_name === null || $this->script_name === false) { - $this->script_name = $this->rc->config->get('managesieve_script_name'); - if (empty($this->script_name)) { - $this->script_name = 'roundcube'; - } - - // use default script contents - if (!$this->rc->config->get('managesieve_kolab_master')) { - $script_file = $this->rc->config->get('managesieve_default'); - if ($script_file && is_readable($script_file)) { - $content = file_get_contents($script_file); - } - } - - // create and load script - if ($this->sieve->save_script($this->script_name, $content)) { - $this->sieve->load($this->script_name); - } - } - - $script_active = in_array($this->script_name, $this->active); - - // re-order rules if needed - if (isset($rule['after']) && $rule['after'] !== '') { - // reset original vacation rule - if (isset($this->vacation['idx'])) { - $this->script[$this->vacation['idx']] = null; - } - - // add at target position - if ($rule['after'] >= count($this->script) - 1) { - $this->script[] = $rule; - } - else { - $script = array(); - - foreach ($this->script as $idx => $r) { - if ($r) { - $script[] = $r; - } - - if ($idx == $rule['after']) { - $script[] = $rule; - } - } - - $this->script = $script; - } - - $this->script = array_values(array_filter($this->script)); - } - // update original vacation rule if it exists - else if (isset($this->vacation['idx'])) { - $this->script[$this->vacation['idx']] = $rule; - } - // otherwise put vacation rule on top - else { - array_unshift($this->script, $rule); - } - - // if the script was not active, we need to de-activate - // all rules except the vacation rule, but only if it is not disabled - if (!$script_active && !$rule['disabled']) { - foreach ($this->script as $idx => $r) { - if (empty($r['actions']) || $r['actions'][0]['type'] != 'vacation') { - $this->script[$idx]['disabled'] = true; - } - } - } - - if (!$this->sieve->script) { - return false; - } - - $this->sieve->script->content = $this->script; - - // save the script - $saved = $this->save_script($this->script_name); - - // activate the script - if ($saved && !$script_active && !$rule['disabled']) { - $this->activate_script($this->script_name); - } - - return $saved; - } - - /** - * API: get vacation rule - * - * @return array Vacation rule information - */ - public function get_vacation() - { - $this->exts = $this->sieve->get_extensions(); - $this->init_script(); - $this->vacation_rule(); - - // check supported extensions - $date_extension = in_array('date', $this->exts); - $regex_extension = in_array('regex', $this->exts); - $seconds_extension = in_array('vacation-seconds', $this->exts); - - // set user's timezone - try { - $timezone = new DateTimeZone($this->rc->config->get('timezone', 'GMT')); - } - catch (Exception $e) { - $timezone = new DateTimeZone('GMT'); - } - - if ($date_extension) { - $date_value = array(); - foreach ((array) $this->vacation['tests'] as $test) { - if ($test['test'] == 'currentdate') { - $idx = $test['type'] == 'value-ge' ? 'start' : 'end'; - - if ($test['part'] == 'date') { - $date_value[$idx]['date'] = $test['arg']; - } - else if ($test['part'] == 'iso8601') { - $date_value[$idx]['datetime'] = $test['arg']; - } - } - } - - foreach ($date_value as $idx => $value) { - $$idx = new DateTime($value['datetime'] ?: $value['date'], $timezone); - } - } - else if ($regex_extension) { - // Sieve 'date' extension not available, read start/end from RegEx based rules instead - if ($date_tests = self::parse_regexp_tests($this->vacation['tests'])) { - $from = new DateTime($date_tests['from'] . ' ' . '00:00:00', $timezone); - $to = new DateTime($date_tests['to'] . ' ' . '23:59:59', $timezone); - } - } - - if (isset($this->vacation['seconds'])) { - $interval = $this->vacation['seconds'] . 's'; - } - else if (isset($this->vacation['days'])) { - $interval = $this->vacation['days'] . 'd'; - } - - $vacation = array( - 'supported' => $this->exts, - 'interval' => $interval, - 'start' => $start, - 'end' => $end, - 'enabled' => $this->vacation['reason'] && empty($this->vacation['disabled']), - 'message' => $this->vacation['reason'], - 'subject' => $this->vacation['subject'], - 'action' => $this->vacation['action'], - 'target' => $this->vacation['target'], - 'addresses' => $this->vacation['addresses'], - ); - - return $vacation; - } - - /** - * API: set vacation rule - * - * @param array $vacation Vacation rule information (see self::get_vacation()) - * - * @return bool True on success, False on failure - */ - public function set_vacation($data) - { - $this->exts = $this->sieve->get_extensions(); - $this->error = false; - - $this->init_script(); - $this->vacation_rule(); - - // check supported extensions - $date_extension = in_array('date', $this->exts); - $regex_extension = in_array('regex', $this->exts); - $seconds_extension = in_array('vacation-seconds', $this->exts); - - $vacation['type'] = 'vacation'; - $vacation['reason'] = $this->strip_value(str_replace("\r\n", "\n", $data['message'])); - $vacation['addresses'] = $data['addresses']; - $vacation['subject'] = $data['subject']; - $vacation_tests = (array) $this->vacation['tests']; - - foreach ((array) $vacation['addresses'] as $aidx => $address) { - $vacation['addresses'][$aidx] = $address = trim($address); - - if (empty($address)) { - unset($vacation['addresses'][$aidx]); - } - else if (!rcube_utils::check_email($address)) { - $this->error = "Invalid address in vacation addresses: $address"; - return false; - } - } - - if ($vacation['reason'] == '') { - $this->error = "No vacation message specified"; - return false; - } - - if ($data['interval']) { - if (!preg_match('/^([0-9]+)\s*([sd])$/', $data['interval'], $m)) { - $this->error = "Invalid vacation interval value: " . $data['interval']; - return false; - } - else if ($m[1]) { - $vacation[strtolower($m[2]) == 's' ? 'seconds' : 'days'] = $m[1]; - } - } - - // find and remove existing date/regex/true rules - foreach ((array) $vacation_tests as $idx => $t) { - if ($t['test'] == 'currentdate' || $t['test'] == 'true' - || ($t['test'] == 'header' && $t['type'] == 'regex' && $t['arg1'] == 'received') - ) { - unset($vacation_tests[$idx]); - } - } - - if ($date_extension) { - foreach (array('start', 'end') as $var) { - if ($dt = $data[$var]) { - $vacation_tests[] = array( - 'test' => 'currentdate', - 'part' => 'iso8601', - 'type' => 'value-' . ($var == 'start' ? 'ge' : 'le'), - 'zone' => $dt->format('O'), - 'arg' => str_replace('+00:00', 'Z', strtoupper($dt->format('c'))), - ); - } - } - } - else if ($regex_extension) { - // Add date range rules if range specified - if ($data['start'] && $data['end']) { - if ($tests = self::build_regexp_tests($data['start'], $data['end'], $error)) { - $vacation_tests = array_merge($vacation_tests, $tests); - } - - if ($error) { - $this->error = "Invalid dates specified or unsupported period length"; - return false; - } - } - } - - if ($data['action'] == 'redirect' || $data['action'] == 'copy') { - if (empty($data['target']) || !rcube_utils::check_email($data['target'])) { - $this->error = "Invalid address in action taget: " . $data['target']; - return false; - } - } - else if ($data['action'] && $data['action'] != 'keep' && $data['action'] != 'discard') { - $this->error = "Unsupported vacation action: " . $data['action']; - return false; - } - - if (empty($vacation_tests)) { - $vacation_tests = $this->rc->config->get('managesieve_vacation_test', array(array('test' => 'true'))); - } - - $rule = $this->vacation; - $rule['type'] = 'if'; - $rule['name'] = $rule['name'] ?: 'Out-of-Office'; - $rule['disabled'] = isset($data['enabled']) && !$data['enabled']; - $rule['tests'] = $vacation_tests; - $rule['join'] = $date_extension ? count($vacation_tests) > 1 : false; - $rule['actions'] = array($vacation); - - if ($data['action'] && $data['action'] != 'keep') { - $rule['actions'][] = array( - 'type' => $data['action'] == 'discard' ? 'discard' : 'redirect', - 'copy' => $data['action'] == 'copy', - 'target' => $data['action'] != 'discard' ? $data['target'] : '', - ); - } - - return $this->save_vacation_script($rule); - } - - /** - * API: connect to managesieve server - */ - public function connect($username, $password) - { - if (!parent::connect($username, $password)) { - return $this->load_script(); - } - } - - /** - * API: Returns last error - * - * @return string Error message - */ - public function get_error() - { - return $this->error; - } -} -- cgit v1.2.3