<?php

/**
 * Modoboa Password Driver
 *
 * Payload is json string containing username, oldPassword and newPassword
 * Return value is a json string saying result: true if success.
 *
 * @version 2.0
 *
 * @author stephane @actionweb.fr
 *
 * Copyright (C) The Roundcube Dev Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see https://www.gnu.org/licenses/.
 *
 * The driver need modoboa core 1.10.6 or later
 *
 * You need to define theses variables in plugin/password/config.inc.php
 *
 * $config['password_driver'] = 'modoboa'; // use modoboa as driver
 * $config['password_modoboa_api_token'] = ''; // put token number from Modoboa server
 * $config['password_minimum_length'] = 8; // select same number as in Modoboa server
 */

class rcube_modoboa_password
{
    public function save($curpass, $passwd, $username)
    {
        // Init config access
        $rcmail = rcmail::get_instance();
        $token = $rcmail->config->get('password_modoboa_api_token');
        $host = $rcmail->config->get('password_modoboa_api_host');

        // We don't allow replacement variables when the host name(s) come from the user
        if (!empty($rcmail->config->get('imap_host'))) {
            $host = rcube_utils::parse_host($host);
        }

        $client = password::get_http_client();
        $url = "https://{$host}/api/v1/accounts/?search=" . urlencode($username);

        $options = [
            'http_errors' => true,
            'headers' => [
                'Authorization' => "Token {$token}",
                'Cache-Control' => 'no-cache',
                'Content-Type' => 'application/json',
            ],
        ];

        // Call GET to fetch values from modoboa server
        try {
            $response = $client->get($url, $options);
            $response = $response->getBody()->getContents();
        } catch (\Exception $e) {
            rcube::raise_error("Password plugin: Error fetching {$url} : {$e->getMessage()}", true);
            return PASSWORD_CONNECT_ERROR;
        }

        // Decode json string
        $decoded = json_decode($response);

        if (!is_array($decoded)) {
            return PASSWORD_CONNECT_ERROR;
        }

        // Get user ID (pk)
        $userid = null;
        $user = null;
        foreach ($decoded as $account) {
            if (isset($account->username) && $account->username === $username) {
                $userid = $account->pk;
                $user = [
                    'username' => $account->username,
                    'mailbox' => $account->mailbox,
                    'role' => $account->role,
                ];
                break;
            }
        }

        if ($user === null) {
            return PASSWORD_CONNECT_ERROR;
        }

        // Encode json with new password
        $user['password'] = $passwd;
        $options['body'] = json_encode($user);

        $url = "https://{$host}/api/v1/accounts/{$userid}/";

        // Call HTTP API Modoboa
        try {
            $response = $client->put($url, $options);
            $response = $response->getBody()->getContents();
        } catch (\Exception $e) {
            rcube::raise_error("Password plugin: Error on {$url} : {$e->getMessage()}", true);
            return PASSWORD_CONNECT_ERROR;
        }

        return PASSWORD_SUCCESS;
    }
}
