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

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

        $this->load_config();

        $this->add_hook('identity_form', array($this, 'fix_form'));
        $this->add_hook('identity_create', array($this, 'validate_create'));
        $this->add_hook('identity_update', array($this, 'validate_update'));
    }

    function fix_form($params) {
        $record = $params['record'];
        $options = [];
        $permitted_addresses = $this->get_permitted_addresses();

        if (!empty($record['email']) && in_array($record['email'], $permitted_addresses))
            $options[$record['email']] = $record['email'];

        foreach ($permitted_addresses as $addr) {
            $options[$addr] = $addr;
        }

        $form = $params['form'];
        $form['addressing']['content']['email'] = array(
            'type' => 'select',
            'skip-empty' => true,
            'options' => $options
        );
        return array('form' => $form, 'record' => $params['record']);
    }

    function validate_create($params) {
        $record = $params['record'];
        return array(
            'abort' => $this->validate_modification($record),
            'record' => $record
        );
    }

    function validate_update($params) {
        $record = $params['record'];
        return array(
            'abort' => $this->validate_modification($record),
            'record' => $record
        );
    }

    function validate_modification($record) {
        return !in_array($record['email'],
                         $this->get_permitted_addresses($record));
    }

    private function get_permitted_addresses() {
        if (!($sql = $this->rcmail->config->get('identity_addresses_query'))) {
            return [];
        }

        if ($dsn = $this->rcmail->config->get('identity_addresses_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()) {
            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);

        $result = $db->query($sql);
        if ($db->is_error($result))
            return [];

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

        return $permitted_addresses;
    }

    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;
    }
}
?>
