<?php

class HMWP_Controllers_Rewrite extends HMWP_Classes_FrontController {

    public function __construct() {
        parent::__construct();
        //Change the paths only for html
        if ($this->model->doReplace($this->model->getCurrentURL())) {
            if (!HMWP_Classes_Tools::getOption('hmwp_laterload')) {
                $this->model->startBuffer();
            }

            //Init the main hooks
            $this->initHooks();

        } else {
            //If file and the rewrite is not set, show the file to avoid errors
            add_action('template_redirect', array($this->model, 'showFile'), 1);
        }

    }

    /**
     * Init the hooks for hide my wp
     */
    public function initHooks(){
        if (HMWP_Classes_Tools::isPermalinkStructure()) {
            if (HMWP_Classes_Tools::isApache() && !HMWP_Classes_Tools::isModeRewrite()) {
                return;
            }

            add_action('login_head', array($this->model, 'login_head'), 99);
            add_filter('query_vars', array($this->model, 'addParams'), 1, 1);
            add_action('login_init', array($this->model, 'login_init'), 1);
            add_filter('login_redirect', array($this->model, 'sanitize_redirect'), 1, 3);

            //change the admin url
            add_filter('login_url', array($this->model, 'login_url'), 1, 1);
            add_filter('admin_url', array($this->model, 'admin_url'), 1, 3);
            add_filter('network_admin_url', array($this->model, 'network_admin_url'), 1, 3);
            add_filter('site_url', array($this->model, 'site_url'), 1, 3);
        }

        //Load the hooks
        add_action('plugins_loaded', array($this, 'hookPreload'), 1);
        //just to make sure it called in case plugins_loaded is not triggered
        add_action('template_redirect', array($this, 'hookPreload'), 1);

    }


    public function hookPreload() {
        //if plugin_loaded then remove template_redirect
        remove_action('template_redirect', array($this, 'hookPreload'), 1);
        
        include_once(ABSPATH . 'wp-admin/includes/plugin.php');
        if (is_plugin_active('hide_my_wp/index.php')) {
            echo '<div class="error notice"><p>' . __('Please deactivate the free version of "Hide My WP" first!', _HMWP_PLUGIN_NAME_) . '</p></div>';
            return;
        }

        //Make sure is permalink set up
        if (HMWP_Classes_Tools::isPermalinkStructure()) {
            if (HMWP_Classes_Tools::isApache() && !HMWP_Classes_Tools::isModeRewrite()) {
                return;
            }

            //Don't go further if the safe parameter is set
            if (HMWP_Classes_Tools::getIsset('hmwp_disable')) {
                if (HMWP_Classes_Tools::getValue('hmwp_disable') == HMWP_Classes_Tools::getOption('hmwp_disable')) {
                    return;
                }
            }

            //Build the find_replace list
            $this->model->buildRedirect();

            //check and set the cookied for the modified urls
            $this->model->checkCookies();

            //Check compatibilities with other plugins
            HMWP_Classes_Tools::checkOtherPlugins();


            //don't let to rename and hide the current paths if logout is required
            if (HMWP_Classes_Tools::getOption('error') || HMWP_Classes_Tools::getOption('logout')) {
                return;
            }

            //If WP Super cache installed with later init
            global $wp_super_cache_late_init;
            if (isset($wp_super_cache_late_init) && $wp_super_cache_late_init == 1) {
                //add an action after Super cache is started
                add_action('init', array($this->model, 'startBuffer'), 99999);
                add_action('wp_footer', array($this->model, 'getBuffer'), 99999);
            } elseif (HMWP_Classes_Tools::getOption('hmwp_laterload')) {
                add_action('template_redirect', array($this->model, 'startBuffer'), 99999);
                add_action('shutdown', array($this->model, 'getBuffer'));
            }

            //Change the rest api if needed
            add_filter('rest_url_prefix', array($this->model, 'replace_rest_api'), 99, 1);
            add_filter('the_generator', array($this, 'getFalse'), 99, 1);

            //hide the URLs from admin and login
            add_action('init', array($this->model, 'hideUrls'), 99);

            //Patch for WP-rocket plugin
            add_filter('rocket_buffer', array($this->model, 'find_replace'), 99);
            add_filter('rocket_cache_busting_filename', array($this->model, 'find_replace_wp'), 99);
            add_filter('rocket_iframe_lazyload_placeholder', array($this->model, 'find_replace_wp'), 99);

            if (HMWP_Classes_Tools::getOption('hmwp_hide_version')) {
                remove_action('wp_head', 'wp_generator');
                remove_action('wp_head', 'wp_resource_hints', 2);
            }

            if (HMWP_Classes_Tools::getOption('hmwp_disable_emojicons')) {
                //disable the emoji icons
                $this->disable_emojicons();
            }

            if (HMWP_Classes_Tools::getOption('hmwp_disable_rest_api')) {
                //disable the rest_api
                $this->disable_rest_api();
            }

            if (HMWP_Classes_Tools::getOption('hmwp_disable_embeds')) {
                //disable the embeds
                $this->disable_embeds();
            }

            if (HMWP_Classes_Tools::getOption('hmwp_disable_manifest')) {
                //disable the embeds
                $this->disable_manifest();
            }

            if (HMWP_Classes_Tools::getOption('hmwp_in_dashboard')) {
                add_filter('show_admin_bar', array($this, 'disable_adminbar'));
            }
        }

    }

    /**
     * On admin init
     *  Load the Menu
     *  If the user changes the Permalink to default ... prevent errors
     */
    public function hookInit() {
        HMWP_Debug::dump('hookInit');

        if (HMWP_Classes_Tools::getIsset('hmwp_disable')) {
            if (HMWP_Classes_Tools::getValue('hmwp_disable') == HMWP_Classes_Tools::getOption('hmwp_disable')) {
                return;
            }
        }

        //Show the menu for admins only
        if (current_user_can('manage_options')) {
            HMWP_Classes_ObjController::getClass('HMWP_Controllers_Menu')->hookInit();
        }

        //If the user changes the Permalink to default ... prevent errors
        if (!HMWP_Classes_Tools::isPermalinkStructure()) {
            if (current_user_can('manage_options')) {
                if (HMWP_Classes_Tools::$default['hmwp_admin_url'] <> HMWP_Classes_Tools::getOption('hmwp_admin_url')) {
                    HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->flushChanges();
                }
            }
        } else {
            if (HMWP_Classes_Tools::isApache() && !HMWP_Classes_Tools::isModeRewrite()) {
                return;
            }

            //check the rewrite
            add_action('generate_rewrite_rules', array($this->model, 'setRewriteRules'), 99);
            //rename the author if set so
            add_filter('author_rewrite_rules', array($this->model, 'author_url'), 99, 1);
        }

    }

    /**
     * Disable the admin bar whe users are hidden in admin
     * @return bool
     */
    public function disable_adminbar() {
        return false;
    }

    /**
     * Disable the emoji icons
     */
    public function disable_emojicons() {

        // all actions related to emojis
        remove_action('admin_print_styles', 'print_emoji_styles');
        remove_action('wp_head', 'print_emoji_detection_script', 7);
        remove_action('admin_print_scripts', 'print_emoji_detection_script');
        remove_action('wp_print_styles', 'print_emoji_styles');
        remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
        remove_filter('the_content_feed', 'wp_staticize_emoji');
        remove_filter('comment_text_rss', 'wp_staticize_emoji');
        add_filter('emoji_svg_url', '__return_false');

        // filter to remove TinyMCE emojis
        add_filter('tiny_mce_plugins', array($this, 'disable_emojicons_tinymce'));
    }

    function disable_emojicons_tinymce($plugins) {
        if (is_array($plugins)) {
            return array_diff($plugins, array('wpemoji'));
        } else {
            return array();
        }
    }

    /**
     * Disable the Rest Api access
     */
    public function disable_rest_api() {
        remove_action('init', 'rest_api_init');
        remove_action('rest_api_init', 'rest_api_default_filters', 10);
        remove_action('wp_head', 'rest_output_link_wp_head', 10);
        remove_action('parse_request', 'rest_api_loaded');
    }

    /**
     * Disable the embeds
     */
    public function disable_embeds() {
        // Remove the REST API endpoint.
        remove_action('rest_api_init', 'wp_oembed_register_route');

        // Turn off oEmbed auto discovery.
        // Don't filter oEmbed results.
        remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);

        // Remove oEmbed discovery links.
        remove_action('wp_head', 'wp_oembed_add_discovery_links');

        // Remove oEmbed-specific JavaScript from the front-end and back-end.
        remove_action('wp_head', 'wp_oembed_add_host_js');
    }

    public function disable_manifest() {
        remove_action('wp_head', 'wlwmanifest_link');
        remove_action('wp_head', 'rsd_link');
    }

    public function getFalse() {
        return false;
    }


}
