<?php
namespace Bdp\Modules\Security;


use ZipArchive;

class Security
{
    public const required_security_plugins = [];

    public const delete_plugins = [
        'akismet/akismet.php',
        'hello.php',
	    'limit-login-attempts-reloaded'
    ];

    public static function setup()
    {
        self::deletePlugins();
        foreach (self::required_security_plugins as $pluginSlug => $pluginData) {
            if (!is_dir(WP_PLUGIN_DIR . '/' . $pluginSlug)) {
                self::installSecurityPlugin($pluginSlug, $pluginData['downloadUrl']);
            }
        }

        enable_option_disable_xmlrpc();
	    enable_option_block_authorscan();
	    enable_option_block_execution_in_uploads();
	    enable_option_prohibit_special_files();
	    enable_option_file_editor();
	    enable_option_disable_conatenation();
	    enable_option_secure_include_dir();
	    enable_option_prohibit_bot_access();
	    enable_option_block_directory_listing();
		self::resetLimitLoginAttempts();


    }

    public static function deletePlugins() {
		$existingPlugins = [];
		foreach (self::delete_plugins as $curPlugin) {
			if (file_exists(WP_PLUGIN_DIR . '/' . $curPlugin)) {
				$existingPlugins[] = $curPlugin;
			}
		}
		deactivate_plugins($existingPlugins);
        delete_plugins($existingPlugins);
    }

	public static function ProhibitBots() {
		$botList = get_prohibitedbot_list();

		if (!is_bot_access_prohibited() || count($botList) == 0) {
			return;
		}

		foreach ($botList as $botListEntry) {
			if (stripos($_SERVER['HTTP_USER_AGENT'], $botListEntry) !== false) {
				status_header(403);
				die();
			}
		}
	}


	public static function protectAuthorScan()
	{
		global $wp;

		if (str_starts_with($wp->request, 'author/') && is_authorscan_blocked()) {
			status_header(403);
			die();
		}
	}

	public static function SetPageFilters() {
		global $wp;

		add_action('template_redirect', [Security::class, 'protectAuthorScan']);
        Security::protectLoginSecurity();
	}

	public static function protectLoginSecurity() {
		$hideLogin = is_login_rewritten();
		if (null === $hideLogin) {
			return;
		}
        update_option('whl_page', get_option(get_option('kompass_sec_rewrite_login', null)));
        delete_option('kompass_sec_rewrite_login');
        kompass_install_plugin( 'https://downloads.wordpress.org/plugin/wps-hide-login.1.9.17.1.zip', 'wps-hide-login' );


        if ( str_contains( $_SERVER['REQUEST_URI'], 'wp-login.php' ) && ! isset( $_POST['redirect_to'] ) && $_POST['redirect_to'] !== 'interner-bereich' ) {
			wp_redirect( home_url() );
			die();
		}

		if ( str_contains( $_SERVER['REQUEST_URI'], $hideLogin ) !== false ) {
			$user_login  = '';
			if (!isset($error)) {
				$error = '';
			}
			$_REQUEST['redirect_to'] = 'interner-bereich';
			require_once 'wp-login.php';
			die();
		}

		if ( str_contains( $_SERVER['REQUEST_URI'], 'interner-bereich' ) !== false ) {
			wp_redirect( '/wp-admin' );
			die();
		}
	}

    public static function installSecurityPlugin(string $pluginSlug, string $downloadUrl) : bool
    {
        $ch = curl_init();
        $source = $downloadUrl;
        curl_setopt($ch, CURLOPT_URL, $source);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec ($ch);
        curl_close ($ch);

        $destination = WP_PLUGIN_DIR . '/' . $pluginSlug . '.zip';
        $file = fopen($destination, "w+");
        fputs($file, $data);
        fclose($file);

        $zip = new ZipArchive();
        $zip->open($destination);
        $zip->extractTo(WP_PLUGIN_DIR);
        $zip->close();
        unlink($destination);

        $pluginInfos = get_plugins( '/'.$pluginSlug );
        $installfile = $pluginSlug . '/';
        if( ! empty( $pluginInfos ) ) {
            foreach ($pluginInfos as $file => $info) :
                $installfile .= $file;
            endforeach;
        }



        $result = activate_plugin($installfile);

        return $result === null;
    }

	public static function resetLimitLoginAttempts() {
		update_option('kompass_limit_login_lockout_duration', 900);
		update_option('kompass_limit_login_allowed_retries', 3);
		update_option('kompass_limit_login_allowed_lockouts', 3);
		update_option('kompass_password_minimal_strength', 3);
		update_option('kompass_limit_login_client_type', 'REMOTE_ADDR');
		update_option('kompass_limit_login_long_duration', 86400);
		update_option('kompass_limit_login_lockout_notify', ['email']);
		update_option('kompass_limit_login_notify_email_after', 3);
		update_option('kompass_limit_login_cookies',0);
	}
}