<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class DPDEV_WP_Reset {
	public function __construct(){
		add_action("admin_post_DPDEV_reset", array($this, 'DPDEV_reset_func'));
    }

    public function DPDEV_reset_func(){
        // Only allow administrators
        if (!current_user_can('administrator')) {
            wp_nonce_ays('DPDEV_reset');
            die();
        }

        // Check nonce
        check_admin_referer('DPDEV_reset');

        $reset_database = $_POST['reset_database'];
        $empty_wpcontent = $_POST['empty_wpcontent'];
        $delete_content = $_POST['delete_content'];
        $delete_plugins = $_POST['delete_plugins'];
        $delete_themes = $_POST['delete_themes'];

        if(!empty($reset_database)){
        	$this->reset_database();
        }

        if(!empty($delete_content)){
        	$this->delete_content($reset_database);
        }

        if(!empty($delete_plugins)){
        	$this->delete_plugins();
        }

        if(!empty($delete_themes)){
            $this->delete_themes();
        }

        if(!empty($empty_wpcontent)){
            $this->empty_wpcontent();
        }

        wp_redirect(wp_get_referer());
    }

    public function empty_wpcontent() {
        // Clean the uploads folder
        $upload_dir = wp_upload_dir();
        $folder = $upload_dir['basedir'];
        $this->delete_folder($folder, false);

        $folders = array_diff(scandir(WP_CONTENT_DIR), array('.', '..', 'index.php', 'mu-plugins', 'plugins', 'themes', 'upgrade', 'uploads'));
        $folders = array_values($folders);
        if(!empty($folders)){
            foreach($folders as $folder){
                $this->delete_folder(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $folder, true);
            }
        }
    }

    public function delete_folder($dir, $delete_main){
        if (is_dir($dir)) {
            $objects = scandir($dir);
            //print_r($objects); exit;
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir.DIRECTORY_SEPARATOR.$object) == "dir") 
                       $this->delete_folder($dir.DIRECTORY_SEPARATOR.$object, true); 
                    else unlink($dir.DIRECTORY_SEPARATOR.$object);
                }
            }
            reset($objects);
            if($delete_main){
                rmdir($dir);
            }
        }
    }

    public function delete_plugins(){
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
    	// first deactivate active plugins except this one
        $active_plugins = get_option('active_plugins', array());
        $key = array_search(DPDEV_BASE, $active_plugins);
        if($key !== false){
            unset($active_plugins[$key]);
        }
        if(!empty($active_plugins)){
            deactivate_plugins($active_plugins, true);
        }

        // get all plugins other than this one
        $plugins = get_plugins();
        unset($plugins[DPDEV_BASE]);
        if (!empty($plugins)) {
            delete_plugins(array_keys($plugins));
        }
    }

    public function delete_themes(){
        require_once ABSPATH . 'wp-admin/includes/theme.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';

        global $wp_version;
        $active_theme = "";
        $themes = wp_get_themes( array('errors' => false) );

        // set default theme after deletion
        if($wp_version >= '5.3' ){
            $active_theme = "twentytwenty";
        } else if($wp_version >= '5.0' ){
            $active_theme = "twentynineteen";
        } else {
            $active_theme = "twentyseventeen";
        }
        unset($themes[$active_theme]);

        foreach ($themes as $key => $val) {
            delete_theme($key);
        }

        switch_theme($active_theme);
    }

    public function delete_content($reset_database){
    	global $wpdb;
    	$tables = $this->tables_to_truncate();
    	foreach($tables['only_delete_content'] as $table){
    		$wpdb->query("TRUNCATE TABLE $table");
    	}

    	if(empty($reset_database)){
    		foreach($tables['delete_all_content'] as $table){
	    		$wpdb->query("TRUNCATE TABLE $table");
	    	}
    	}
    }

    public function tables_to_truncate(){
    	global $wpdb;
    	$tables = array(
    		'only_delete_content' => array(
    			$wpdb->prefix . 'posts',
	    		$wpdb->prefix . 'postmeta',
	    		$wpdb->prefix . 'comments',
	    		$wpdb->prefix . 'commentmeta',
    		),
    		'delete_all_content' => array(
    			$wpdb->prefix . 'termmeta',
    			$wpdb->prefix . 'terms',
    			$wpdb->prefix . 'term_relationships',
    			$wpdb->prefix . 'term_taxonomy',
    		)
    	);

    	return $tables;
    }

    public function reset_database(){
    	global $wpdb, $current_user;
    	$users_table = $wpdb->prefix . 'users';
    	$reset_options = $this->get_options_to_reset();
    	
    	$tables = $wpdb->get_col("SHOW TABLES LIKE '%'");
    	$tables = implode('`, `', $tables);
    	$tables_imploded = str_replace("'", "", $this->implode_arrays($tables));
    	$wpdb->query("DROP TABLE IF EXISTS `$tables`;");

    	// Re-install WordPress
        require_once ABSPATH . '/wp-admin/includes/upgrade.php';
        wp_check_mysql_version();
        wp_cache_flush();
        make_db_current_silent();
        populate_options();
        populate_roles();

        update_option('fresh_site', 1);
        foreach($reset_options as $option){
    		update_option($option['option_name'], $option['option_value']);
    		if($option['option_name'] == "blog_public"){
    			if(!$option['option_value']){
    				update_option('default_pingback_flag', 0);
    			}
    		}
    	}

    	$user_id = username_exists($current_user->user_login);
    	if(!$user_id){
    		$user_id = wp_create_user($current_user->user_login, 'dummyPassword', $current_user->user_email);
    	}

        $user = new WP_User($user_id);
        $user->set_role('administrator');

        wp_install_defaults($user_id);

        wp_install_maybe_enable_pretty_permalinks();
        flush_rewrite_rules();
        wp_cache_flush();

        // Restore user pass
        $user_pass = $current_user->user_pass;
        $wpdb->query("UPDATE $users_table SET user_pass = '$user_pass', user_activation_key = '' WHERE ID = $user_id");
        update_user_meta($user_id, 'show_welcome_panel', 0);

        // Activate this plugin
        activate_plugin(DPDEV_BASE);

        // Reset auth cookies
        wp_clear_auth_cookie();
        wp_set_auth_cookie($user_id);
    }

    public function get_options_to_reset(){
    	global $wpdb;
    	$return_options = array();
    	$options_table = $wpdb->prefix . 'options';
    	$options_to_reset = $this->options_to_reset();
 		$options_imploded = $this->implode_arrays($options_to_reset);
    	$options = $wpdb->get_results( "SELECT option_name, option_value FROM $options_table WHERE option_name IN('$options_imploded')", ARRAY_A );
		if(!empty($options)){
			return $options;
		}
		return $return_options;
    }

    public function options_to_reset(){
    	$options = array(
    		'blogname',
    		'blog_public',
    		'blogdescription',
    		'admin_email',
    		'wplang',
    		'siteurl',
    		'home',
    	);

    	return $options;
    }

    public function implode_arrays($array_to_implode){
    	$joined_array = join("','",$array_to_implode);
    	return $joined_array;
    }
}

new DPDEV_WP_Reset();