<?php

class HMWP_Controllers_Settings extends HMWP_Classes_FrontController {

    public $tabs;
    public $logout = false;

    public function __construct() {
        parent::__construct();
        add_filter('relative_url', array(HMWP_Classes_ObjController::getClass('HMWP_Classes_Tools'), 'getRelativePath'));

        if (HMWP_Classes_Tools::getOption('logout') && !HMWP_Classes_Tools::getOption('error')) {
            if (HMWP_Classes_Tools::getValue('action') == '' && HMWP_Classes_Tools::getValue('page') <> 'hmwp_settings') {
                add_action('admin_notices', array($this, 'show_reconnect_error'));
            }
        }

        if (HMWP_Classes_Tools::getOption('changes') && HMWP_Classes_Tools::getValue('page') <> 'hmwp_settings') {
            add_action('admin_notices', array($this, 'show_changes_require'));
        }
    }

    function init() {
        $this->tabs = array('hmwp_permalinks' => __("Permalinks", _HMWP_PLUGIN_NAME_));

        if (!function_exists('is_plugin_active_for_network')) {
            require_once(ABSPATH . '/wp-admin/includes/plugin.php');
        }


        //if the permalink is set up
        if (HMWP_Classes_Tools::isPermalinkStructure()) {
            //show vulnerabilities only for apache and litespeed servers
            if (HMWP_Classes_Tools::isApache() || HMWP_Classes_Tools::isLitespeed()) {
                $this->tabs['hmwp_injection'] = __("Vulnerabilities", _HMWP_PLUGIN_NAME_);
            }
        }

        $this->tabs['hmwp_brute'] = __("Brute Force Protection", _HMWP_PLUGIN_NAME_);
        $this->tabs['hmwp_advanced'] = __("Advanced", _HMWP_PLUGIN_NAME_);

        HMWP_Classes_Error::setError(sprintf(__("If you can't login, use this URL: <strong>%s/wp-login.php?hmwp_disable=%s</strong> and all changes are rollback to default"), site_url(), HMWP_Classes_Tools::getOption('hmwp_disable')));

        if (HMWP_Classes_Tools::getOption('logout') && !HMWP_Classes_Tools::getOption('error')) {
            $logoutForm = '
                        <form method="POST">
                            <input type="hidden" name="action" value="hmwp_logout" />
                            <input type="hidden" name="hmwp_nonce" value="' . wp_create_nonce(_HMWP_NONCE_ID_) . '" />
                            <input type="submit" class="btn btn-success save" value="Yes, I\'m ready to reconnect" />
                        </form>
                        ';
            $abortForm = '
                        <form method="POST">
                            <input type="hidden" name="action" value="hmwp_abort" />
                            <input type="hidden" name="hmwp_nonce" value="' . wp_create_nonce(_HMWP_NONCE_ID_) . '" />
                            <input type="submit" class="btn btn-warning save" value="No, abort" />
                        </form>
                        ';
            HMWP_Classes_Error::setError(sprintf(__('To activate the new Hide My Wp settings you need to confirm and redirect! %s'), '<div class="hmwp_logout">' . $logoutForm . '</div><div class="hmwp_abort" style="display: inline-block; margin-left: 5px;">' . $abortForm . '</div>'));
        } elseif (HMWP_Classes_Tools::getOption('error')) {
            $abortForm = '
                        <form method="POST">
                            <input type="hidden" name="action" value="hmwp_abort" />
                            <input type="hidden" name="hmwp_nonce" value="' . wp_create_nonce(_HMWP_NONCE_ID_) . '" />
                            <input type="submit" class="btn btn-warning save" value="Cancel the changes" />
                        </form>
                        ';
            HMWP_Classes_Error::setError(__('Action Required. Proceed with the instructions or cancel the changes ', _HMWP_PLUGIN_NAME_) . '<div class="hmwp_abort" style="display: inline-block;">' . $abortForm . '</div>');

        } elseif (get_transient('hmwp_restore') == 1) {
            $restoreForm = '
                        <form method="POST">
                            <input type="hidden" name="action" value="hmwp_abort" />
                            <input type="hidden" name="hmwp_nonce" value="' . wp_create_nonce(_HMWP_NONCE_ID_) . '" />
                            <input type="submit" class="btn btn-success save" value="' . __("Restore Settings", _HMWP_PLUGIN_NAME_) . '" />
                        </form>
                        ';
            HMWP_Classes_Error::setError(__('You want to restore the last saved settings? ', _HMWP_PLUGIN_NAME_) . '<div class="hmwp_abort" style="display: inline-block;">' . $restoreForm . '</div>');
            // Delete the redirect transient
            delete_transient('hmwp_restore');

        }


        if (HMWP_Classes_Tools::isApache() && !HMWP_Classes_Tools::isModeRewrite()) {
            HMWP_Classes_Error::setError(sprintf(__('Hide my WP does not work without mode_rewrite. Please activate the rewrite module in Apache. %sMore details%s', _HMWP_PLUGIN_NAME_), '<a href="https://tecadmin.net/enable-apache-mod-rewrite-module-in-ubuntu-linuxmint/" target="_blank">', '</a>'));
        }

        if (!HMWP_Classes_Tools::isPermalinkStructure()) {
            HMWP_Classes_Error::setError(sprintf(__('Hide my WP does not work with %s Permalinks. Change it to %s or other type in Settings > Permalinks in order to hide it', _HMWP_PLUGIN_NAME_), __('Plain'), __('Post Name')));
            define('HMWP_DISABLE', true);
        } else {
            if (HMWP_Classes_Tools::isIIS() && HMWP_Classes_Tools::isPHPPermalink()) {
                HMWP_Classes_Error::setError(sprintf(__('You need to activate the URL Rewrite for IIS to be able to change the permalink structure to friendly URL (without index.php). %sMore details%s', _HMWP_PLUGIN_NAME_), '<a href="https://www.iis.net/downloads/microsoft/url-rewrite" target="_blank">', '</a>'));
            } elseif (HMWP_Classes_Tools::isPHPPermalink()) {
                HMWP_Classes_Error::setError(__('You need to set the permalink structure to friendly URL (without index.php).', _HMWP_PLUGIN_NAME_));
            }
        }


        if (HMWP_Classes_Tools::$default['hmwp_admin_url'] == HMWP_Classes_Tools::getOption('hmwp_admin_url')) {
            if (strpos(admin_url(), HMWP_Classes_Tools::$default['hmwp_admin_url']) === false) {
                HMWP_Classes_Error::setError(sprintf(__('Your admin path is changed. To prevent errors, disable the other plugin who changes the admin path.', _HMWP_PLUGIN_NAME_)));
                define('HMWP_DISABLE', true);
            }
        } elseif (isset($_SERVER['REQUEST_URI']) && !HMWP_Classes_Tools::getOption('logout') && !HMWP_Classes_Tools::getOption('error')) {
            if (strpos($_SERVER['REQUEST_URI'], '/' . HMWP_Classes_Tools::$default['hmwp_admin_url']) !== false) {
                HMWP_Classes_Error::setError(sprintf(__('You still see %s because you are logged in. To prevent errors, log-in with the new admin url: %s', _HMWP_PLUGIN_NAME_), '<strong>' . HMWP_Classes_Tools::$default['hmwp_admin_url'] . '</strong>', '<strong>' . admin_url() . '</strong>'));
            }
        }


        HMWP_Classes_ObjController::getClass('HMWP_Classes_DisplayController')->loadMedia('settings');
        HMWP_Classes_ObjController::getClass('HMWP_Classes_DisplayController')->loadMedia('switchery.min');

        foreach ($this->tabs as $slug => $value) {
            if (HMWP_Classes_Tools::getValue('tab', 'hmwp_permalinks') == $slug) {
                echo $this->admin_tabs($slug);
                HMWP_Classes_ObjController::getClass('HMWP_Classes_Error')->hookNotices();

                echo $this->getView(ucfirst(str_replace('hmwp_', '', $slug)));
            }
        }

    }

    public function show_changes_require() {
        ?>
        <div class="hmwp_notice error notice" style="margin-left: 0;">
            <div style="display: inline-block;">
                <p>
                    <?php echo sprintf(__("New Plugin/Theme detected! You need to update the Hide My WP Setting to include this plugin too! %sClick here%s", _HMWP_PLUGIN_NAME_),'<a href="options-general.php?page=hmwp_settings" >','</a>'); ?>
                </p>
            </div>
        </div>
        <?php
    }

    function show_reconnect_error() {
        ?>
        <div class="hmwp_notice error notice" style="margin-left: 0;">
            <div style="display: inline-block;">
                <p>
                    <?php echo __("To activate the new Hide My Wp settings you need to confirm and redirect!", _HMWP_PLUGIN_NAME_); ?>
                </p>
            </div>

            <div class="hmwp_logout" style="display: inline-block; margin-left: 10px;">
                <form method="POST" action="options-general.php?page=hmwp_settings">
                    <input type="hidden" name="action" value="hmwp_logout"/>
                    <input type="hidden" name="hmwp_nonce" value="<?php echo wp_create_nonce(_HMWP_NONCE_ID_) ?>"/>
                    <input type="submit" class="hmwp_btn hmwp_btn-success" value="<?php echo __("Yes, I'm ready to reconnect", _HMWP_PLUGIN_NAME_) ?>"/>
                </form>
            </div>
            <div class="hmwp_abort" style="display: inline-block;">
                <form method="POST" action="options-general.php?page=hmwp_settings">
                    <input type="hidden" name="action" value="hmwp_abort"/>
                    <input type="hidden" name="hmwp_nonce" value="<?php echo wp_create_nonce(_HMWP_NONCE_ID_) ?>"/>
                    <input type="submit" class="hmwp_btn hmwp_btn-warning" value="<?php echo __("No, abort", _HMWP_PLUGIN_NAME_) ?>"/>
                </form>
            </div>
            <style type="text/css">
                .hmwp_notice p {
                    display: block;
                    font-size: 13px;
                    font-weight: normal;
                    letter-spacing: normal;
                    line-height: 30px;
                    margin: 0 0 10px 0;
                    font-style: normal;
                    white-space: normal;
                }

                .hmwp_btn {
                    font-size: 13px;
                    border: 1px solid transparent;
                    border-radius: 0;
                    outline: none !important;
                    display: inline-block;
                    padding: 6px 12px;
                    margin-bottom: 0;
                    font-weight: normal;
                    line-height: 1.42857143;
                    text-align: center;
                    white-space: nowrap;
                    vertical-align: middle;
                    -ms-touch-action: manipulation;
                    touch-action: manipulation;
                    cursor: pointer;
                    -webkit-user-select: none;
                    -moz-user-select: none;
                    -ms-user-select: none;
                    user-select: none;
                    background-image: none;
                }

                .hmwp_btn-success {
                    color: #fff;
                    background-color: green;
                    border-color: transparent;
                }

                .hmwp_btn-warning {
                    color: #fff;
                    background-color: #e8bf40;
                    border-color: transparent;
                }
            </style>
        </div>
        <?php
    }

    function admin_tabs($current = null) {
        $content = '';
        $content .= '<h2 class="nav-tab-wrapper">';
        foreach ($this->tabs as $location => $tabname) {
            if ($current == $location) {
                $class = ' nav-tab-active';
            } else {
                $class = '';
            }
            $content .= '<a class="nav-tab' . $class . '" href="?page=hmwp_settings&tab=' . $location . '">' . $tabname . '</a>';
        }
        $content .= '</h2>';
        return $content;
    }

    public function getHideOldPathRewrite() {
        $rules = "<IfModule mod_rewrite.c>\n";
        $rules .= "RewriteEngine On\n";
        $rules .= "RewriteCond %{HTTP:Cookie} !(wordpress_logged_in_|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_) [NC]\n";
        $rules .= "RewriteCond %{THE_REQUEST} /(wp-(content|includes)/.*) [NC]\n";
        $rules .= "RewriteRule ^(.*)$ - [L,R=404]\n";
        $rules .= "</IfModule>";

        return $rules;
    }

    public function getInjectionRewrite() {

        $site_root = parse_url(site_url());
        if (isset($site_root['path']))
            $site_root = trailingslashit($site_root['path']);

        $home_root = parse_url(home_url());
        if (isset($home_root['path']))
            $home_root = trailingslashit($home_root['path']);
        else
            $home_root = '/';

        $rules = "<IfModule mod_rewrite.c>\n";
        $rules .= "RewriteEngine On\n";
        $rules .= "RewriteBase $home_root\n";
        // Prevent -f checks on index.php.
        $rules .= "RewriteCond %{HTTP_USER_AGENT} (havij|libwww-perl|wget|python|nikto|curl|scan|java|winhttp|clshttp|loader) [NC,OR]\n";
        $rules .= "RewriteCond %{HTTP_USER_AGENT} (%0A|%0D|%3C|%3E|%00) [NC,OR]\n";
        $rules .= "RewriteCond %{HTTP_USER_AGENT} (;|<|>|'|\\\"|\\)|\\(|%0A|%0D|%22|%28|%3C|%3E|%00).*(libwww-perl|wget|python|nikto|curl|scan|java|winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC,OR]\n";
        $rules .= "RewriteCond %{THE_REQUEST} (\\?|\\*|%2a)+(%20+|\\s+|%20+\\s+|\\s+%20+|\\s+%20+\\s+)HTTP(:/|/) [NC,OR]\n";
        $rules .= "RewriteCond %{THE_REQUEST} etc/passwd [NC,OR]\n";
        $rules .= "RewriteCond %{THE_REQUEST} cgi-bin [NC,OR]\n";
        $rules .= "RewriteCond %{THE_REQUEST} (%0A|%0D|\\r|\\n) [NC,OR]\n";

        $rules .= "RewriteCond %{REQUEST_URI} owssvr\\.dll [NC,OR]\n";
        $rules .= "RewriteCond %{HTTP_REFERER} (%0A|%0D|%3C|%3E|%00) [NC,OR]\n";
        $rules .= "RewriteCond %{HTTP_REFERER} \\.opendirviewer\\. [NC,OR]\n";
        $rules .= "RewriteCond %{HTTP_REFERER} users\\.skynet\\.be.* [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http:// [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\\.\\.//?)+ [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} \\=PHP[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (\\.\\./|%2e%2e%2f|%2e%2e/|\\.\\.%2f|%2e\\.%2f|%2e\\./|\\.%2e%2f|\\.%2e/) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} ftp\\: [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} \\=\\|w\\| [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} ^(.*)/self/(.*)$ [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} ^(.*)cPath=http://(.*)$ [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (\\<|%3C).*script.*(\\>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (\\<|%3C).*embed.*(\\>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (<|%3C)([^e]*e)+mbed.*(>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (\\<|%3C).*object.*(\\>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (<|%3C)([^o]*o)+bject.*(>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (\\<|%3C).*iframe.*(\\>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (<|%3C)([^i]*i)+frame.*(>|%3E) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} base64_encode.*\\(.*\\) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} base64_(en|de)code[^(]*\\([^)]*\\) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} GLOBALS(=|\\[|\\%[0-9A-Z]{0,2}) [OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} _REQUEST(=|\\[|\\%[0-9A-Z]{0,2}) [OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} ^.*(\\(|\\)|<|>|%3c|%3e).* [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} ^.*(\\x00|\\x04|\\x08|\\x0d|\\x1b|\\x20|\\x3c|\\x3e|\\x7f).* [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (NULL|OUTFILE|LOAD_FILE) [OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (\\.{1,}/)+(motd|etc|bin) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (localhost|loopback|127\\.0\\.0\\.1) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (<|>|'|%0A|%0D|%3C|%3E|%00) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} concat[^\\(]*\\( [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} union([^s]*s)+elect [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} union([^a]*a)+ll([^s]*s)+elect [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} \\-[sdcr].*(allow_url_include|allow_url_fopen|safe_mode|disable_functions|auto_prepend_file) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (;|<|>|'|\"|\\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\\*|union|select|insert|drop|delete|update|cast|create|char|convert|alter|declare|script|set|md5|benchmark|encode) [NC,OR]\n";
        $rules .= "RewriteCond %{QUERY_STRING} (sp_executesql) [NC]\n";
        $rules .= "RewriteRule ^(.*)$ - [F]\n";
        $rules .= "</IfModule>\n\n";

        $rules .= '<FilesMatch "^(readme\\.html|license\\.txt|install\\.php|wp-signup\\.php|wp-config\\.php|php\\.ini|php5\\.ini|bb-config\\.php)">' . "\n";
        $rules .= "<IfModule mod_authz_core.c>\n";
        $rules .= "Require all denied\n";
        $rules .= "</IfModule>\n";
        $rules .= "</FilesMatch>\n";
        // Add in the rules
        return $rules;
    }

    public function writeInHtaccess($rules, $header = 'HMWP') {
        global $wp_rewrite;

        $home_path = get_home_path();
        $htaccess_file = $home_path . '.htaccess';

        if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) {
            if (got_mod_rewrite()) {
                if ($rules <> '') {
                    HMWP_Classes_Error::setError(__('Saved'), 'success');
                }
                return insert_with_markers($htaccess_file, $header, $rules);
            }
        }

        return false;
    }

    /**
     * Called when Post action is triggered
     *
     * @return void
     */
    public function action() {
        parent::action();

        if (!current_user_can('manage_options')) {
            return;
        }

        switch (HMWP_Classes_Tools::getValue('action')) {

            case 'hmwp_settings':
                if (!empty($_POST)) {
                    $this->saveValues($_POST);
                }

                if (!HMWP_Classes_Tools::getOption('error')) {
                    add_action('shutdown', array('HMWP_Classes_Tools', 'emptyCache'));
                }

                if (!HMWP_Classes_Tools::getOption('error') && !HMWP_Classes_Tools::getOption('logout')) {
                    HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->flushChanges();
                }
                break;

            case 'hmwp_advsettings':

                if (!empty($_POST)) {
                    foreach ($_POST as $key => $value) {
                        $value = preg_replace('/[^A-Za-z0-9-_.\@]/', '', $value);

                        if ($value <> '' && $key <> 'action' && $key <> 'hmwp_hide_classes' && $key <> 'hmwp_nonce') {
                            HMWP_Classes_Tools::saveOptions($key, $value);
                        } elseif ($key == 'hmwp_hide_classes') {
                            $classes = HMWP_Classes_Tools::getValue('hmwp_hide_classes', '', true);
                            $classes = explode(PHP_EOL, $classes);
                            $classes = str_replace("\r", "", $classes);

                            if (!empty($classes)) {
                                $classes = array_unique($classes);
                                HMWP_Classes_Tools::saveOptions('hmwp_hide_classes', json_encode($classes));
                            }
                        }

                        //If hmwp_hide_oldpaths do also the htaccess rewrite
                        if ($key == 'hmwp_hide_oldpaths') {
                            if ($value == 1) {
                                if (!$this->writeInHtaccess($this->getHideOldPathRewrite(), 'HMWP_OLDPATHS')) {
                                    HMWP_Classes_Error::setError(sprintf(__('Could not save the data in .htaccess file. You have to added it manually at the end of the .htaccess file: %s ', '<code># BEGIN HMWP_OLDPATHS' . $this->getHideOldPathRewrite() . '# END HMWP_OLDPATHS</code>')));
                                }
                            } else {
                                $this->writeInHtaccess('', 'HMWP_OLDPATHS');
                            }
                        }
                    }
                    if (!HMWP_Classes_Tools::getOption('error')) {
                        add_action('shutdown', array('HMWP_Classes_Tools', 'emptyCache'));
                    }
                }
                break;

            case 'hmwp_abort':
                //get the safe options from database
                HMWP_Classes_Tools::$options = HMWP_Classes_Tools::getOptions(true);
                //set th eprevious admin path
                HMWP_Classes_Tools::saveOptions('hmwp_admin_url', HMWP_Classes_Tools::getOption('hmwp_admin_url'));
                HMWP_Classes_Tools::saveOptions('error', false);
                HMWP_Classes_Tools::saveOptions('logout', false);

                add_action('shutdown', array('HMWP_Classes_Tools', 'emptyCache'));
                HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->flushChanges();

                break;
            case 'hmwp_savedefault':
                HMWP_Classes_Tools::saveOptions('logout', false);

                $options = HMWP_Classes_Tools::getOptions();
                foreach ($options as $key => $value) {
                    HMWP_Classes_Tools::saveOptions($key, $value, true);
                }
                break;
            case 'hmwp_sqlinjection':
                if (!$this->writeInHtaccess($this->getInjectionRewrite())) {
                    HMWP_Classes_Error::setError(__('Could not save the data in .htaccess file. You have to added it manually at the end of the .htaccess file'));
                }

                break;
            case 'hmwp_logout':
                //save to safe mode in case of doudb
                foreach (HMWP_Classes_Tools::$options as $key => $value) {
                    HMWP_Classes_Tools::saveOptions($key, $value, true);
                }
                HMWP_Classes_Tools::saveOptions('error', false);
                HMWP_Classes_Tools::saveOptions('logout', false);

                add_action('shutdown', array('HMWP_Classes_Tools', 'emptyCache'));

                HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->flushChanges();
                HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->wp_logout();
                die();
                break;

            case 'hmwp_manualrewrite':
                HMWP_Classes_Tools::saveOptions('error', false);

                foreach (HMWP_Classes_Tools::$options as $key => $value) {
                    HMWP_Classes_Tools::saveOptions($key, $value, true);
                }

                add_action('shutdown', array('HMWP_Classes_Tools', 'emptyCache'));

                break;

            case 'hmwp_backup':
                if (!current_user_can('manage_options')) {
                    return;
                }
                HMWP_Classes_Tools::getOptions();
                HMWP_Classes_Tools::setHeader('text');
                header("Content-Disposition: attachment; filename=hidemywp_backup.txt");

                if (function_exists('base64_encode')) {
                    echo base64_encode(json_encode(HMWP_Classes_Tools::$options));
                } else {
                    echo json_encode(HMWP_Classes_Tools::$options);
                }
                exit();
                break;
            case 'hmwp_restore':
                if (!current_user_can('manage_options')) {
                    return;
                }

                if (!empty($_FILES['hmwp_options']) && $_FILES['hmwp_options']['tmp_name'] <> '') {
                    $options = file_get_contents($_FILES['hmwp_options']['tmp_name']);
                    try {
                        if (function_exists('base64_encode') && base64_decode($options) <> '') {
                            $options = base64_decode($options);
                        }
                        $options = json_decode($options, true);
                        if (is_array($options) && isset($options['hmwp_ver'])) {
                            HMWP_Classes_Tools::$options = $options;
                            HMWP_Classes_Tools::saveOptions();
                            HMWP_Classes_Error::setError(__('Great! The backup is restored.', _HMWP_PLUGIN_NAME_) . " <br /> ", 'success');

                            if (!HMWP_Classes_Tools::getOption('error')) {
                                add_action('shutdown', array('HMWP_Classes_Tools', 'emptyCache'));
                            }

                            if (!HMWP_Classes_Tools::getOption('error') && !HMWP_Classes_Tools::getOption('logout')) {
                                HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->flushChanges();
                            }

                        } else {
                            HMWP_Classes_Error::setError(__('Error! The backup is not valid.', _HMWP_PLUGIN_NAME_) . " <br /> ");
                        }
                    } catch (Exception $e) {
                        HMWP_Classes_Error::setError(__('Error! The backup is not valid.', _HMWP_PLUGIN_NAME_) . " <br /> ");
                    }
                } else {
                    HMWP_Classes_Error::setError(__('Error! You have to enter a previous saved backup file.', _HMWP_PLUGIN_NAME_) . " <br /> ");
                }
                break;
        }
    }

    public function saveValues($params) {
        if (!empty($params)) {
            HMWP_Classes_Tools::saveOptions('error', false);
            HMWP_Classes_Tools::saveOptions('changes', false);

            if ($params['hmwp_admin_url'] == $params['hmwp_login_url']) {
                HMWP_Classes_Tools::saveOptions('error', true);
                HMWP_Classes_Error::setError(__("You can't set both ADMIN and LOGIN with the same name. Please use different names", _HMWP_PLUGIN_NAME_));

                return;
            }

            //send email when the admin is changed
            if (isset($params['hmwp_send_email'])) {
                HMWP_Classes_Tools::$default['hmwp_send_email'] = $params['hmwp_send_email'];
            }

            if ($params['hmwp_mode'] == 'default') {
                $params = HMWP_Classes_Tools::$default;
                //remove the custom rules
                HMWP_Classes_ObjController::getClass('HMWP_Controllers_Settings')->writeInHtaccess('');
                HMWP_Classes_ObjController::getClass('HMWP_Controllers_Settings')->writeInHtaccess('', 'HMWP_OLDPATHS');
            }

            if ($params['hmwp_mode'] == 'lite') {
                $params = @array_merge(HMWP_Classes_Tools::$default, HMWP_Classes_Tools::$lite);
                HMWP_Classes_ObjController::getClass('HMWP_Controllers_Settings')->writeInHtaccess('', 'HMWP_OLDPATHS');
            }

            if ($params['hmwp_mode'] == 'ninja') {
                $params = @array_merge(HMWP_Classes_Tools::$ninja, $params);
                //Save the category and tags
                $blog_prefix = '';

                global $wp_rewrite;
                if (is_multisite() && !is_subdomain_install() && is_main_site() && 0 === strpos(get_option('permalink_structure'), '/blog/')) {
                    $blog_prefix = '/blog';
                }

                if (isset($params['hmwp_category_base'])) {
                    $category_base = $params['hmwp_category_base'];
                    if (!empty($category_base))
                        $category_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $category_base));
                    $wp_rewrite->set_category_base($category_base);
                }

                if (isset($params['hmwp_tag_base'])) {
                    $tag_base = $params['hmwp_tag_base'];
                    if (!empty($tag_base))
                        $tag_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $tag_base));
                    $wp_rewrite->set_tag_base($tag_base);
                }

            }

            //If the admin is changed, require a logout
            $lastsafeoptions = HMWP_Classes_Tools::getOptions(true);

            if ($lastsafeoptions['hmwp_admin_url'] <> $params['hmwp_admin_url']) {
                HMWP_Classes_Tools::saveOptions('logout', true);
            }
            //Prevent duplicates
            foreach ($params as $key => $value) {
                if ($key == 'action' && $key == 'hmwp_nonce') {
                    continue;
                }
                if ($params['hmwp_mode'] == 'ninja') {
                    HMWP_Classes_Tools::saveOptions($key, HMWP_Classes_Tools::getValue($key, $params[$key]));
                } else {
                    //set the default params from tools
                    HMWP_Classes_Tools::saveOptions($key, $params[$key]);
                }
            }

            //generate unique names for plugins if needed
            if (HMWP_Classes_Tools::getOption('hmwp_hide_plugins')) {
                HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->hidePluginNames();
            }
            if (HMWP_Classes_Tools::getOption('hmwp_hide_themes')) {
                HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->hideThemeNames();
            }

            if (!HMWP_Classes_Tools::getOption('error')) {
                if (!HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->hmwp_remove_config_cache()) {
                    HMWP_Classes_Tools::saveOptions('error', true);
                }
            }

            //check if writable htaccess file
            if (!HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->is_writeable_Htaccess()) {
                //if not writeable, call the rules to show manually changes
                if (!HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->clearRedirect()->buildRedirect()->setRewriteRules()) {
                    HMWP_Classes_Tools::saveOptions('error', true);
                }
            }


            //Save the White Lable Wp ROcket
            $this->saveRocketOption();

        }
    }

    public function hookFooter() {
        HMWP_Classes_Tools::saveOptions();
    }

    public function saveRocketOption() {
        if (defined('WP_ROCKET_SLUG')) {
            if (is_multisite()) {
                if (function_exists('get_sites') && class_exists('WP_Site_Query')) {
                    $sites = get_sites();
                    foreach ($sites as $site) {
                        switch_to_blog($site->blog_id);
                        $options = get_option(WP_ROCKET_SLUG);
                        $options['wl_plugin_name'] = 'WP Rocket';
                        $options['wl_plugin_slug'] = 'wprocket';
                        $options['wl_plugin_URI'] = 'https://wpplugins.tips';
                        $options['wl_description'] = array('The best WordPress security plugin.');
                        $options['wl_author'] = 'WpPlugins';
                        $options['wl_author_URI'] = 'https://wpplugins.tips';

                        update_option(WP_ROCKET_SLUG, $options);

                        restore_current_blog();
                    }
                }
            } else {
                $options = get_option(WP_ROCKET_SLUG);
                $options['wl_plugin_name'] = 'WP Rocket';
                $options['wl_plugin_slug'] = 'wprocket';
                $options['wl_plugin_URI'] = 'https://wpplugins.tips';
                $options['wl_description'] = array('The best WordPress security plugin.');
                $options['wl_author'] = 'WpPlugins';
                $options['wl_author_URI'] = 'https://wpplugins.tips';

                update_option(WP_ROCKET_SLUG, $options);
            }

        }
    }
}
