<?php
class inbox_settings extends rcube_plugin {
    public $task = 'settings';
    private $rcmail;

    function init() {
        $this->rcmail = rcmail::get_instance();

        $this->load_config();
        $this->add_texts('localization/');

        $this->add_hook('settings_actions', [$this, 'amend_settings_list']);
        if ($this->rcmail->config->get('inbox_settings_scrub_encryption_preference', true))
            $this->add_hook(
                'preferences_sections_list',
                [$this, 'scrub_encryption_preference']);

        $this->register_action('plugin.inbox_settings', [$this, 'render_settings_ui']);
        $this->register_action('plugin.inbox_keys', [$this, 'render_keys_ui']);
    }

    function scrub_encryption_preference($params) {
        unset($params['list']['encryption']);
        return $params;
    }

    function amend_settings_list($params) {
        $params['actions'][] = [
            'action' => 'plugin.inbox_settings',
            'class' => 'inbox_settings',
            'label' => 'inbox_settings',
            'title' => 'inbox_settings',
            'domain' => 'inbox_settings'
        ];
        $params['actions'][] = [
            'action' => 'plugin.inbox_keys',
            'class' => 'enigma keys',
            'label' => 'inbox_keys',
            'title' => 'inbox_keys',
            'domain' => 'inbox_settings'
        ];
        return $params;
    }

    private function save_settings() {
        if (empty($_POST['save']))
            return;

        $encrypt_inbox = isset($_POST['encrypt_inbox']) ? '1' : '0';
        $this->run_query('update_encryption', ['%se' => $encrypt_inbox]);

        if (empty($_POST['addr']) || !is_array($_POST['addr']))
            return;

        foreach ($_POST['addr'] as $idx => $addr) {
            if (!empty($_POST['fwd_addr'][$idx])
                && !rcube_utils::check_email($_POST['fwd_addr'][$idx]))
                continue;

            $fwd_addr = $_POST['fwd_addr'][$idx];
            $fwd_addr = empty($fwd_addr) ? '' : $fwd_addr;
            $do_forward = isset($_POST['do_fwd'][$idx]) ? '1' : '0';
            
            $local_part = $addr;
            $domain_part = '';
            if ($at_separator = strrpos($addr, '@')) {
                $local_part = substr($addr, 0, $at_separator);
                $domain_part = substr($addr, $at_separator + 1);
            }

            $this->run_query('update_forwarder', [
                '%aa' => $addr,
                '%al' => $local_part,
                '%ad' => $domain_part,
                '%sf' => $do_forward,
                '%sa' => $fwd_addr
            ]);
        }
    }

    function render_keys_ui() {
        $this->register_handler('plugin.body', [$this, 'render_keys_form']);
        $this->rcmail->output->set_pagetitle($this->gettext('inbox_keys'));
        $this->rcmail->output->send('plugin');
    }

    function render_keys_form() {}

    function render_settings_ui() {
        $this->register_handler('plugin.body', [$this, 'render_settings_form']);
        $this->rcmail->output->set_pagetitle($this->gettext('inbox_settings'));
        $this->save_settings();
        $this->rcmail->output->send('plugin');
    }

    function render_settings_form() {
        $page_title = html::tag('h1', 'voice', rcube::Q($this->gettext('inbox_settings')));
        $encryption_result = $this->run_query('encryption_enabled');
        $encrypt_inbox = 0;
        if (!empty($encryption_result) && !empty($encryption_result[0]))
            $encrypt_inbox = $encryption_result[0][0] ? 1 : 0;
        $encryption_form = new html_table(['cols' => 2, 'class' => 'propform']);
        $encryption_form->add_row(['class' => 'form-group row']);
        $encryption_form->add('title col-sm-8', html::label([
                'class' => 'col-form-label',
                'for' => 'rcmfd_encrypt_inbox'
            ], rcube::Q($this->gettext('encrypt_inbox'))));
        $encryption_form->add('col-sm-2 offset-1', self::get_checkbox(
            'rcmfd_encrypt_inbox', 'encrypt_inbox', $encrypt_inbox));

        $forwarders = $this->run_query('forwarding_addresses');
        $forwarding_form = new html_table(['cols' => 3, 'class' => 'propform']);
        foreach ($forwarders as $idx => $row) {
            $forwarding_form->add_row(['class' => 'form-group row']);
            $forwarding_form->add('title col-sm-4',
                html::label(
                    ['class' => 'col-form-label', 'for' => 'fwd_addr_' . $idx],
                    rcube::Q($row[0]))
                . self::get_hiddenfield('addr[' . $idx . ']', $row[0]));
            $forwarding_form->add('col-sm-4',
                self::get_textfield(
                    'fwd_addr_' . $idx,
                    'fwd_addr[' . $idx . ']',
                    $row[1],
                    ['placeholder' => 'anyone@gmail.com']));
            $forwarding_form->add('col-sm-2 offset-1',
                self::get_checkbox(
                    'do_fwd_' . $idx,
                    'do_fwd[' . $idx . ']',
                    $row[2],
                    ['title' => $this->gettext('fwd_addr')]));
        }

        $form = html::div(['class' => 'formcontent'],
                    html::tag('fieldset', null,
                        html::tag('legend', null, rcube::Q($this->gettext('encryption')))
                        . $encryption_form->show(null)
                    )
                  . html::tag('fieldset', null,
                        html::tag('legend', null, rcube::Q($this->gettext('forwarding')))
                        . $forwarding_form->show(null)));
        $save_button = (new html_inputfield([
                'type' => 'submit',
                'name' => 'save',
                'class' => 'button mainaction submit'
            ]))->show($this->rcmail->gettext('save'));
        $form_buttons = html::div(['class' => 'formbuttons'], $save_button);
        $page_content = html::div(['class' => 'formcontainer'],
                            $page_title
                            . $this->rcmail->output->form_tag([
                                'action' => $this->rcmail->url(
                                    ['action' => 'plugin.inbox_settings']),
                                'method' => 'post'                            
                            ], $form . $form_buttons));
        return $page_content;
    }

    private static function get_checkbox($id, $name, $checked, $attrs = []) {
        return html::div(['class' => 'custom-control custom-switch'],
            (new html_checkbox([
                'id' => $id,
                'name' => $name,
                'class' => 'form-check-input custom-control-input',
                'value' => '1'
            ] + $attrs))->show($checked ? '1' : '0')
            . html::label(['class' => 'custom-control-label', 'for' => $id] + $attrs, ''));
    }

    private static function get_textfield($id, $name, $value, $attrs = []) {
        return (new html_inputfield([
            'id' => $id,
            'type' => 'text',
            'name' => $name,
            'size' => 40,
        ] + $attrs))->show($value);
    }

    private static function get_hiddenfield($name, $value) {
        return (new html_inputfield(['type' => 'hidden', 'name' => $name]))->show($value);
    }

    private function run_query($qid, $substitutions = []) {
        if (!($sql = $this->rcmail->config->get('inbox_settings_' . $qid . '_query'))) {
            $this->rcmail->output->command(
                'display_message', $this->gettext('no_query'), 'error');
            return [];
        }

        if ($dsn = $this->rcmail->config->get('inbox_settings_db_dsn')) {
            $db = rcube_db::factory(self::parse_dsn($dsn), '', false);
            $db->set_debug((bool) $this->rcmail->config->get('sql_debug'));
        } else {
            $db = $this->rcmail->get_dbh();
        }

        if ($db->is_error()) {
            $this->rcmail->output->command(
                'display_message', $this->gettext('no_db'), 'error');
            return [];
        }

        $local_part = $this->rcmail->user->get_username('local');
        $domain_part = rcube_utils::idn_to_utf8($this->rcmail->user->get_username('domain'));
        $username = rcube_utils::idn_to_utf8($_SESSION['username']);
        $host = rcube_utils::idn_to_utf8($_SESSION['imap_host']);

        $sql = str_replace('%l', $db->quote($local_part, 'text'), $sql);
        $sql = str_replace('%d', $db->quote($domain_part, 'text'), $sql);
        $sql = str_replace('%u', $db->quote($username, 'text'), $sql);
        $sql = str_replace('%h', $db->quote($host, 'text'), $sql);

        foreach ($substitutions as $key => $value) {
            $sql = str_replace($key, $db->quote($value, 'text'), $sql);
        }

        $result = $db->query($sql);
        if ($db->is_error($result)) {
            $this->rcmail->output->command(
                'display_message', $this->gettext('sql_error'), 'error');
            return [];
        }

        $ndresult = [];
        while ($row = $db->fetch_array($result))
            $ndresult[] = $row;

        return $ndresult;
    }

    private static function parse_dsn($dsn) {
        if (strpos($dsn, '%')) {
            // parse DSN and replace variables in hostname
            $parsed = rcube_db::parse_dsn($dsn);
            $host = rcube_utils::parse_host($parsed['hostspec']);

            // build back the DSN string
            if ($host != $parsed['hostspec']) {
                $dsn = str_replace('@' . $parsed['hostspec'], '@' . $host, $dsn);
            }
        }

        return $dsn;
    }
}
?>
