<?php

/*
 *  LMS version 1.11-git
 *
 *  (C) Copyright 2001-2015 LMS Developers
 *
 *  Please, see the doc/AUTHORS for more information about authors!
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License Version 2 as
 *  published by the Free Software Foundation.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
 *  USA.
 *
 *  $Id$
 */

function userpanel_style_change()
{
    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    $files = getdir(USERPANEL_DIR . DIRECTORY_SEPARATOR . 'templates_c', '^.*\.html\.php$');
    if (!empty($files)) {
        foreach ($files as $file) {
            unlink(USERPANEL_DIR . DIRECTORY_SEPARATOR . 'templates_c' . DIRECTORY_SEPARATOR . $file);
        }
    }
}

function module_setup()
{
    global $SMARTY, $DB, $USERPANEL, $USERPANEL_AUTH_TYPES, $USERPANEL_REMINDER_TYPES, $layout, $LMS, $CSTATUSES;

    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    $layout['pagetitle'] = trans('Userpanel Configuration');
    $SMARTY->assign('page_header', ConfigHelper::getConfig('userpanel.page_header', ''));
    $SMARTY->assign('company_logo', ConfigHelper::getConfig('userpanel.company_logo', ''));
    $SMARTY->assign('shortcut_icon', ConfigHelper::getConfig('userpanel.shortcut_icon', ''));
    $SMARTY->assign('stylelist', getdir(USERPANEL_DIR . DIRECTORY_SEPARATOR . 'style', '^[a-z0-9]*$'));
    $SMARTY->assign('extra_style', ConfigHelper::getConfig('userpanel.extra_style', ''));
    $SMARTY->assign('style', ConfigHelper::getConfig('userpanel.style', 'default'));
    $SMARTY->assign('startupmodule', ConfigHelper::getConfig('userpanel.startup_module', 'info'));
    $SMARTY->assign('hint', ConfigHelper::getConfig('userpanel.hint', 'modern'));
    $SMARTY->assign('hide_nodes_modules', ConfigHelper::getConfig('userpanel.hide_nodes_modules', 0));
    $SMARTY->assign('reminder_mail_sender', ConfigHelper::getConfig('userpanel.reminder_mail_sender', ''));
    $SMARTY->assign('reminder_mail_subject', ConfigHelper::getConfig('userpanel.reminder_mail_subject', trans('credential reminder')));
    $SMARTY->assign('reminder_mail_body', ConfigHelper::getConfig('userpanel.reminder_mail_body', "ID: %id\nPIN: %pin"));
    $SMARTY->assign('reminder_sms_body', ConfigHelper::getConfig('userpanel.reminder_sms_body', "ID: %id, PIN: %pin"));

    $SMARTY->assign('reminder_type', ConfigHelper::getConfig('userpanel.reminder_type', USERPANEL_REMINDER_TYPE_ID));
    $SMARTY->assign('auth_type', ConfigHelper::getConfig('userpanel.auth_type', USERPANEL_AUTH_TYPE_ID_PIN));

    $auth_options = array();
    foreach ($USERPANEL_AUTH_TYPES as $auth_type) {
        if (!empty($auth_type['options'])) {
            foreach ($auth_type['options'] as $option) {
                $auth_options[$option['name']] = ConfigHelper::getConfig('userpanel.' . $option['name'], '');
            }
        }
    }
    $SMARTY->assign('auth_options', $auth_options);

    $reminder_options = array();
    foreach ($USERPANEL_REMINDER_TYPES as $reminder_type) {
        if (!empty($reminder_type['options'])) {
            foreach ($reminder_type['options'] as $option) {
                $reminder_options[$option['name']] = ConfigHelper::getConfig('userpanel.' . $option['name'], '');
            }
        }
    }
    $SMARTY->assign('reminder_options', $reminder_options);

    $SMARTY->assign('twofactor_auth_type', ConfigHelper::getConfig('userpanel.twofactor_auth_type', '', true));

    $allowed_customer_status =
        Utils::determineAllowedCustomerStatus(ConfigHelper::getConfig('userpanel.allowed_customer_status', ''), -1);
    if ($allowed_customer_status === -1) {
        $allowed_customer_status = array_keys($CSTATUSES);
    }
    $SMARTY->assign('allowed_customer_status', $allowed_customer_status);

    $SMARTY->assign('force_ssl', ConfigHelper::getConfig('userpanel.force_ssl', ConfigHelper::getConfig('phpui.force_ssl', 1)));
    $SMARTY->assign('google_recaptcha_sitekey', ConfigHelper::getConfig('userpanel.google_recaptcha_sitekey', ''));
    $SMARTY->assign('google_recaptcha_secret', ConfigHelper::getConfig('userpanel.google_recaptcha_secret', ''));
    $SMARTY->assign('timeout', intval(ConfigHelper::getConfig('userpanel.timeout')));
    $SMARTY->assign('sms_credential_reminders', ConfigHelper::checkConfig('userpanel.sms_credential_reminders'));
    $SMARTY->assign('mail_credential_reminders', ConfigHelper::checkConfig('userpanel.mail_credential_reminders'));
    $SMARTY->assign('pin_validation', ConfigHelper::checkConfig('userpanel.pin_validation'));
    $enabled_modules = ConfigHelper::getConfig('userpanel.enabled_modules', null, true);
    if (is_null($enabled_modules)) {
        $enabled_modules = array();
        if (!empty($USERPANEL->MODULES)) {
            foreach ($USERPANEL->MODULES as $module) {
                $enabled_modules[] = $module['module'];
            }
        }
        $DB->Execute(
            "INSERT INTO uiconfig (section, var, value) VALUES (?, ?, ?)",
            array('userpanel', 'enabled_modules', implode(',', $enabled_modules))
        );
    } else {
        $enabled_modules = explode(',', $enabled_modules);
    }
    $SMARTY->assign('enabled_modules', $enabled_modules);
    $SMARTY->assign('total', count($USERPANEL->MODULES));
    $SMARTY->display('file:' . USERPANEL_DIR . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'setup.html');
}

function module_submit_setup()
{
    global $DB, $LMS, $CSTATUSES, $USERPANEL_AUTH_TYPES, $USERPANEL_REMINDER_TYPES;

    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    if (!isset($_POST['hint'])) {
        module_setup();
        return;
    }

    // write main configuration
    if ($test = $DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'hint'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'hint'", array($_POST['hint']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'hint', ?)", array($_POST['hint']));
    }

    $oldstyle = $DB->GetOne("SELECT value FROM uiconfig WHERE section = 'userpanel' AND var = 'style'");
    if (is_string($oldstyle)) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'style'", array($_POST['style']));
        if ($oldstyle != $_POST['style']) {
            userpanel_style_change();
        }
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'style', ?)", array($_POST['style']));
    }

    $old_extra_style = $DB->GetOne("SELECT value FROM uiconfig WHERE section = 'userpanel' AND var = 'extra_style'");
    if (is_string($old_extra_style)) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'extra_style'", array($_POST['extra_style']));
        if ($old_extra_style != $_POST['extra_style']) {
            userpanel_style_change();
        }
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'extra_style', ?)", array($_POST['extra_style']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'startup_module'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'startup_module'", array($_POST['startupmodule']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'startup_module', ?)", array($_POST['startupmodule']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'hide_nodes_modules'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'hide_nodes_modules'", array(isset($_POST['hide_nodes_modules']) ? 1 : 0));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'hide_nodes_modules', ?)", array(isset($_POST['hide_nodes_modules']) ? 1 : 0));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'reminder_mail_sender'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'reminder_mail_sender'", array($_POST['reminder_mail_sender']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'reminder_mail_sender', ?)", array($_POST['reminder_mail_sender']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'reminder_mail_subject'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'reminder_mail_subject'", array($_POST['reminder_mail_subject']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'reminder_mail_subject', ?)", array($_POST['reminder_mail_subject']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'reminder_mail_body'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'reminder_mail_body'", array($_POST['reminder_mail_body']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'reminder_mail_body', ?)", array($_POST['reminder_mail_body']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'page_header'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'page_header'", array($_POST['page_header']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'page_header', ?)", array($_POST['page_header']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'company_logo'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'company_logo'", array($_POST['company_logo']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'company_logo', ?)", array($_POST['company_logo']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'shortcut_icon'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'shortcut_icon'", array($_POST['shortcut_icon']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'shortcut_icon', ?)", array($_POST['shortcut_icon']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'reminder_sms_body'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'reminder_sms_body'", array($_POST['reminder_sms_body']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'reminder_sms_body', ?)", array($_POST['reminder_sms_body']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'auth_type'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'auth_type'", array($_POST['auth_type']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'auth_type', ?)", array($_POST['auth_type']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'reminder_type'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'reminder_type'", array($_POST['reminder_type']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'reminder_type', ?)", array($_POST['reminder_type']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'twofactor_auth_type'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'twofactor_auth_type'", array($_POST['twofactor_auth_type']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'twofactor_auth_type', ?)", array($_POST['twofactor_auth_type']));
    }

    foreach ($USERPANEL_AUTH_TYPES as $auth_type) {
        if (!empty($auth_type['options'])) {
            foreach ($auth_type['options'] as $option) {
                $option_name = $option['name'];
                if (isset($_POST[$option_name])) {
                    if ($DB->GetOne(
                        'SELECT 1 FROM uiconfig WHERE section = ? AND var = ?',
                        array(
                            'userpanel',
                            $option_name,
                        )
                    )) {
                        $DB->Execute(
                            'UPDATE uiconfig SET value = ? WHERE section = ? AND var = ?',
                            array(
                                $_POST[$option_name],
                                'userpanel',
                                $option_name,
                            )
                        );
                    } else {
                        $DB->Execute(
                            'INSERT INTO uiconfig (section, var, value) VALUES(?, ?, ?)',
                            array(
                                'userpanel',
                                $option_name,
                                $_POST[$option_name],
                            )
                        );
                    }
                }
            }
        }
    }

    foreach ($USERPANEL_REMINDER_TYPES as $rem_type) {
        if (!empty($rem_type['options'])) {
            foreach ($rem_type['options'] as $option) {
                $option_name = $option['name'];
                if (isset($_POST[$option_name])) {
                    if ($DB->GetOne(
                        'SELECT 1 FROM uiconfig WHERE section = ? AND var = ?',
                        array('userpanel', $option_name)
                    )) {
                        $DB->Execute(
                            'UPDATE uiconfig SET value = ? WHERE section = ? AND var = ?',
                            array($_POST[$option_name], 'userpanel', $option_name)
                        );
                    } else {
                        $DB->Execute(
                            'INSERT INTO uiconfig (section, var, value) VALUES(?, ?, ?)',
                            array('userpanel', $option_name, $_POST[$option_name])
                        );
                    }
                }
            }
        }
    }

    $allowed_customer_status = array();
    if (isset($_POST['allowed_customer_status'])) {
        foreach ($_POST['allowed_customer_status'] as $statusidx) {
            if (isset($CSTATUSES[$statusidx])) {
                $allowed_customer_status[] = $CSTATUSES[$statusidx]['alias'];
            }
        }
        if (count($allowed_customer_status) == count($CSTATUSES)) {
            $allowed_customer_status = array();
        }
    }
    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'allowed_customer_status'")) {
        $DB->Execute(
            "UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'allowed_customer_status'",
            array(implode(',', $allowed_customer_status))
        );
    } else {
        $DB->Execute(
            "INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'allowed_customer_status', ?)",
            array(implode(',', $allowed_customer_status))
        );
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'force_ssl'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'force_ssl'", array(isset($_POST['force_ssl']) ? 1 : 0));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'force_ssl', ?)", array(isset($_POST['force_ssl']) ? 1 : 0));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'google_recaptcha_sitekey'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'google_recaptcha_sitekey'", array($_POST['google_recaptcha_sitekey']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'google_recaptcha_sitekey', ?)", array($_POST['google_recaptcha_sitekey']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'google_recaptcha_secret'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'google_recaptcha_secret'", array($_POST['google_recaptcha_secret']));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'google_recaptcha_secret', ?)", array($_POST['google_recaptcha_secret']));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'timeout'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'timeout'", array(intval($_POST['timeout'])));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'timeout', ?)", array(intval($_POST['timeout'])));
    }

    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'pin_validation'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'pin_validation'", array(isset($_POST['pin_validation']) ? 'true' : 'false'));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'pin_validation', ?)", array(isset($_POST['pin_validation']) ? 'true' : 'false'));
    }

    foreach (array('sms_credential_reminders', 'mail_credential_reminders') as $var) {
        if ($DB->GetOne(
            "SELECT 1 FROM uiconfig WHERE section = ? AND var = ?",
            array('userpanel', $var)
        )) {
            $DB->Execute(
                "UPDATE uiconfig SET value = ? WHERE section = ? AND var = ?",
                array(
                    isset($_POST[$var]) ? 'true' : 'false',
                    'userpanel',
                    $var
                )
            );
        } else {
            $DB->Execute(
                "INSERT INTO uiconfig (section, var, value) VALUES(?, ?, ?)",
                array(
                    'userpanel',
                    $var,
                    isset($_POST[$var]) ? 'true' : 'false'
                )
            );
        }
    }

    if (isset($_POST['enabled_modules'])) {
        $enabled_modules = implode(',', array_keys($_POST['enabled_modules']));
    } else {
        $enabled_modules = '';
    }
    if ($DB->GetOne("SELECT 1 FROM uiconfig WHERE section = 'userpanel' AND var = 'enabled_modules'")) {
        $DB->Execute("UPDATE uiconfig SET value = ? WHERE section = 'userpanel' AND var = 'enabled_modules'", array($enabled_modules));
    } else {
        $DB->Execute("INSERT INTO uiconfig (section, var, value) VALUES('userpanel', 'enabled_modules', ?)", array($enabled_modules));
    }

    LMSConfig::getConfig(array(
        'force' => true,
        'force_ui_only' => true,
        'invalidate_cache' => true,
    ));

    module_setup();
}

function module_rights()
{
    global $SMARTY, $DB, $LMS, $layout;

    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    $layout['pagetitle'] = trans('Customers\' rights');

    $customerlist = $LMS->GetCustomerNames();
    $userpanelrights = $DB->GetAll('SELECT id, module, name, description, setdefault FROM up_rights');

    $SMARTY->assign('customerlist', $customerlist);
    $SMARTY->assign('userpanelrights', $userpanelrights);
    $SMARTY->display('file:' . USERPANEL_DIR . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'setup_rights.html');
}

function module_submit_rights()
{
    global $DB;

    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    $setrights=$_POST['setrights'];
    if (isset($setrights) && isset($setrights['mcustomerid'])) {
        $newrights=$setrights['rights'];
        foreach ($setrights['mcustomerid'] as $customer) {
            $oldrights=$DB->GetAll(
                'SELECT id, rightid FROM up_rights_assignments WHERE customerid=?',
                array($customer)
            );
            if ($oldrights != null) {
                foreach ($oldrights as $right) {
                    if (isset($newrights[$right['rightid']])) {
                        unset($newrights[$right['rightid']]);
                    } else {
                        $DB->Execute(
                            'DELETE FROM up_rights_assignments WHERE id=?',
                            array($right['id'])
                        );
                    }
                }
            }
            if ($newrights != null) {
                foreach ($newrights as $right) {
                    $DB->Execute(
                        'INSERT INTO up_rights_assignments(customerid, rightid) VALUES(?, ?)',
                        array($customer, $right)
                    );
                }
            }
        }
    }
    module_rights();
}

function module_submit_rights_default()
{
    global $DB;

    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    if (!isset($_POST['loginform'])) {
        $rights = $_POST['setdefaultrights'] ?? array();
        foreach ($DB->GetCol('SELECT id FROM up_rights') as $right) {
            $DB->Execute(
                'UPDATE up_rights SET setdefault = ? WHERE id = ?',
                array(isset($rights[$right]) ? 1 : 0, $right)
            );
        }
    }
    module_rights();
}

function module_save_module_order()
{
    if (!ConfigHelper::checkPrivilege('userpanel_management')) {
        access_denied();
    }

    $DB = LMSDB::getInstance();
    $DB->Execute(
        'UPDATE uiconfig SET value = ? WHERE section = ? AND var = ?',
        array(implode(',', $_POST['modules']), 'userpanel', 'module_order')
    );
    header('Content-Type: application/json');
    echo json_encode(array('result' => 'OK'));
    die;
}
