<?php

/**
 * Handles the parameters and url
 *
 * @author StarBox
 */
class HMWP_Classes_Tools extends HMWP_Classes_FrontController {

    /** @var array Saved options in database */
    public static $default = array();
    public static $lite = array();
    public static $ninja = array();
    public static $options = array();
    public static $debug = array();

    public static $is_multisite;

    /** @var integer Count the errors in site */
    static $errors_count = 0;

    public function __construct() {
        parent::__construct();

        self::$options = self::getOptions();
    }

    /**
     * Load the Options from user option table in DB
     *
     * @param bool|false $safe
     * @return array|mixed|object
     */
    public static function getOptions($safe = false) {
        $keymeta = HMWP_OPTION;
        $homeurl = parse_url(site_url(), PHP_URL_HOST) . parse_url(site_url(), PHP_URL_PATH);
        $pluginurl = parse_url(plugins_url(), PHP_URL_HOST) . parse_url(plugins_url(), PHP_URL_PATH);
        $contenturl = parse_url(content_url(), PHP_URL_HOST) . parse_url(content_url(), PHP_URL_PATH);

        if ($safe) {
            $keymeta = HMWP_OPTION_SAFE;
        }
        $init = array(
            'hmwp_ver' => 0,
            'hmwp_token' => 0,
            'hmwp_disable' => mt_rand(111111, 999999),
            'logout' => false,
            'error' => false,
            'changes' => false,
            'admin_notice' => array(),
            //--
            'hmwp_laterload' => 0,
            'hmwp_send_email' => 1,
            'hmwp_fix_relative' => 1,
            'hmwp_email_address' => '',
            'hmwp_url_redirect' => '404',
            'hmwp_remove_third_hooks' => 0,
            'hmwp_hide_oldpaths' => 0,
            //--
            'hmwp_bruteforce' => 0,
            'hmwp_brute_message' => __('Your IP has been flagged for potential security violations. Please try again in a little while...', _HMWP_PLUGIN_NAME_),
            'whitelist_ip' => array(),
            'hmwp_hide_classes' => json_encode(array('wp-image', 'wp-post', 'wp-caption')),
            'trusted_ip_header' => '',
            'brute_use_math' => 1,
            'brute_max_attempts' => 5,
            'brute_max_timeout' => 3600,
            //
            'hmw_new_plugins' => array(),
            'hmw_new_themes' => array(),
        );
        self::$default = array(
            'hmwp_mode' => 'default',
            'hmwp_admin_url' => 'wp-admin',
            'hmwp_login_url' => 'wp-login.php',
            'hmwp_lostpassword_url' => '',
            'hmwp_register_url' => '',
            'hmwp_plugin_url' => trim(str_replace($homeurl, '', $pluginurl), '/'),
            'hmwp_plugins' => array(),
            'hmwp_themes_url' => 'themes',
            'hmwp_themes' => array(),
            'hmwp_upload_url' => 'uploads',
            'hmwp_admin-ajax_url' => 'admin-ajax.php',
            'hmwp_tags_url' => 'tag',
            'hmwp_wp-content_url' => trim(str_replace($homeurl, '', $contenturl), '/'),
            'hmwp_wp-includes_url' => 'wp-includes',
            'hmwp_author_url' => 'author',
            'hmwp_wp-comments-post' => 'wp-comments-post.php',
            'hmwp_themes_style' => 'style.css',
            'hmwp_noncekey' => '_wpnonce',
            'hmwp_wp-json' => 'wp-json',
            'hmwp_hide_admin' => 0,
            'hmwp_hide_login' => 0,
            'hmwp_hide_nonce' => 0,
            'hmwp_hide_plugins' => 0,
            'hmwp_hide_themes' => 0,
            'hmwp_in_dashboard' => 0,
            'hmwp_disable_emojicons' => 0,
            'hmwp_disable_rest_api' => 0,
            'hmwp_disable_embeds' => 0,
            'hmwp_disable_manifest' => 0,
            'hmwp_hide_img_classes' => 0,
            'hmwp_hide_version' => 0,
            'hmwp_hide_styleids' => 0,
        );

        self::$lite = array(
            'hmwp_mode' => 'lite',
            'hmwp_admin_url' => 'admin',
            'hmwp_login_url' => 'login',
            'hmwp_hide_admin' => 1,
            'hmwp_hide_login' => 1,
            'hmwp_hide_version' => 1,
        );

        self::$ninja = array(
            'hmwp_mode' => 'lite',
            'hmwp_admin_url' => 'newadmin',
            'hmwp_login_url' => 'newlogin',
            'hmwp_lostpassword_url' => 'lostpass',
            'hmwp_register_url' => 'signup',
            'hmwp_admin-ajax_url' => 'ajax',
            'hmwp_plugin_url' => 'modules',
            'hmwp_themes_url' => 'assets',
            'hmwp_upload_url' => 'storage',
            'hmwp_wp-content_url' => 'core',
            'hmwp_wp-includes_url' => 'lib',
            'hmwp_author_url' => 'writer',
            'hmwp_wp-comments-post' => 'comments',
            'hmwp_themes_style' => 'main.css',
            'hmwp_noncekey' => self::generateRandomString(),
            'hmwp_wp-json' => 'json',
            'hmwp_hide_admin' => 1,
            'hmwp_hide_login' => 1,
            'hmwp_hide_plugins' => 1,
            'hmwp_hide_themes' => 1,
            'hmwp_hide_img_classes' => 1,
            'hmwp_hide_nonce' => 0,
            'hmwp_in_dashboard' => 0,
            'hmwp_disable_emojicons' => 1,
            'hmwp_disable_rest_api' => 1,
            'hmwp_disable_embeds' => 1,
            'hmwp_disable_manifest' => 1,
            'hmwp_hide_version' => 1,
            'hmwp_hide_styleids' => 0,
        );


        if (is_multisite()) {
            $options = json_decode(get_blog_option(BLOG_ID_CURRENT_SITE, $keymeta), true);
        } else {
            $options = json_decode(get_option($keymeta), true);
        }

        if (is_array($options)) {
            $options = @array_merge($init, self::$default, $options);
        } else {
            $options = @array_merge($init, self::$default);
        }

        $category_base = get_option('category_base');
        $tag_base = get_option('tag_base');

        if (is_multisite() && !is_subdomain_install() && is_main_site() && 0 === strpos(get_option('permalink_structure'), '/blog/')) {
            $category_base = preg_replace('|^/?blog|', '', $category_base);
            $tag_base = preg_replace('|^/?blog|', '', $tag_base);
        }

        $options['hmwp_category_base'] = $category_base;
        $options['hmwp_tag_base'] = $tag_base;

        return $options;
    }

    /**
     * Get the option from database
     * @param $key
     * @return mixed
     */
    public static function getOption($key) {
        if (!isset(self::$options[$key])) {
            self::$options = self::getOptions();

            if (!isset(self::$options[$key])) {
                self::$options[$key] = 0;
            }
        }

        return self::$options[$key];
    }

    /**
     * Save the Options in user option table in DB
     *
     * @param string $key
     * @param string $value
     * @param bool|false $safe
     *
     */
    public static function saveOptions($key = null, $value = '', $safe = false) {
        $keymeta = HMWP_OPTION;

        if ($safe) {
            $keymeta = HMWP_OPTION_SAFE;
        }

        if (isset($key)) {
            self::$options[$key] = $value;
        }

        if (is_multisite()) {
            update_blog_option(BLOG_ID_CURRENT_SITE, $keymeta, json_encode(self::$options));
        } else {
            update_option($keymeta, json_encode(self::$options));
        }
    }

    /**
     * This hook will save the current version in database
     *
     * @return void
     */
    function hookInit() {
        //TinyMCE editor required
        //set_user_setting('editor', 'tinymce');

        $this->loadMultilanguage();

        //add setting link in plugin
        add_filter('plugin_action_links', array($this, 'hookActionlink'), 5, 2);
    }

    /**
     * Add a link to settings in the plugin list
     *
     * @param array $links
     * @param string $file
     * @return array
     */
    public function hookActionlink($links, $file) {
        if ($file == _HMWP_PLUGIN_NAME_ . '/index.php') {
            if (!is_multisite()) {
                $link = '<a href="' . admin_url('admin.php?page=hmwp_settings') . '">' . __('Settings', _HMWP_PLUGIN_NAME_) . '</a>';
            } else {
                $link = '<a href="' . network_admin_url('settings.php?page=hmwp_settings') . '">' . __('Settings', _HMWP_PLUGIN_NAME_) . '</a>';

            }
            array_unshift($links, $link);
        }

        return $links;
    }

    /**
     * Load the multilanguage support from .mo
     */
    private function loadMultilanguage() {
        if (!defined('WP_PLUGIN_DIR')) {
            load_plugin_textdomain(_HMWP_PLUGIN_NAME_, _HMWP_PLUGIN_NAME_ . '/languages/');
        } else {
            load_plugin_textdomain(_HMWP_PLUGIN_NAME_, null, _HMWP_PLUGIN_NAME_ . '/languages/');
        }
    }

    /**
     * Set the header type
     * @param string $type
     */
    public static function setHeader($type) {
        switch ($type) {
            case 'json':
                header('Content-Type: application/json');
            case 'text':
                header("Content-type: text/plain");
        }
    }

    /**
     * Get a value from $_POST / $_GET
     * if unavailable, take a default value
     *
     * @param string $key Value key
     * @param boolean $keep_newlines Keep the new lines in variable
     * @param mixed $defaultValue (optional)
     * @return mixed Value
     */
    public static function getValue($key, $defaultValue = false, $keep_newlines = false) {
        if (!isset($key) || empty($key) || !is_string($key))
            return false;
        $ret = (isset($_POST[$key]) ? (is_string($_POST[$key]) ? urldecode($_POST[$key]) : $_POST[$key]) : (isset($_GET[$key]) ? (is_string($_GET[$key]) ? urldecode($_GET[$key]) : $_GET[$key]) : $defaultValue));

        if (is_string($ret) === true) {
            if ($keep_newlines === false) {
                $ret = preg_replace('/[^A-Za-z0-9-_.\#\/\*]/', '', $ret);
                $ret = sanitize_text_field($ret);
            } else {
                $ret = preg_replace('/[^A-Za-z0-9-_.\#\n\r\s\/\*]/', '', $ret);
                if (function_exists('sanitize_textarea_field')) {
                    $ret = sanitize_textarea_field($ret);
                }
            }
        }

        return !is_string($ret) ? $ret : stripslashes($ret);
    }

    public static function setValue($key, $value) {
        $_POST[$key] = $value;
        $_GET[$key] = $value;
    }

    /**
     * Check if the parameter is set
     *
     * @param string $key
     * @return boolean
     */
    public static function getIsset($key) {
        if (!isset($key) || empty($key) || !is_string($key))
            return false;
        return isset($_POST[$key]) ? true : (isset($_GET[$key]) ? true : false);
    }

    /**
     * Show the notices to WP
     *
     * @param $message
     * @param string $type
     * @return string
     */
    public static function showNotices($message, $type = '') {
        if (file_exists(_HMWP_THEME_DIR_ . 'Notices.php')) {
            ob_start();
            include(_HMWP_THEME_DIR_ . 'Notices.php');
            $message = ob_get_contents();
            ob_end_clean();
        }

        return $message;
    }

    /**
     * Connect remote with CURL if exists
     *
     * @param $url
     * @param array $param
     * @param array $options
     * @return bool|string
     */
    public static function hmwp_remote_get($url, $param = array(), $options = array()) {
        $parameters = '';

        if (isset($param)) {
            foreach ($param as $key => $value) {
                if (isset($key) && $key <> '' && $key <> 'timeout')
                    $parameters .= ($parameters == "" ? "" : "&") . $key . "=" . $value;
            }
        }

        if ($parameters <> '') {
            $url .= ((strpos($url, "?") === false) ? "?" : "&") . $parameters;
        }

        $options['timeout'] = (isset($options['timeout'])) ? $options['timeout'] : 30;
        $options['sslverify'] = false;

        if (!$response = self::hmwp_wpcall($url, $options)) {
            if (function_exists('curl_init') && !ini_get('safe_mode') && !ini_get('open_basedir')) {
                $response = self::hmwp_curl($url, $options);
            } else {
                return false;
            }
        }

        return $response;
    }

    /**
     * Call remote UR with CURL
     * @param string $url
     * @param array $options
     * @return string
     */
    private static function hmwp_curl($url, $options) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //--
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //--
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, $options['timeout']);

        if (isset($options['followlocation'])) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
        }

        if ($options['cookie_string'] <> '') {
            curl_setopt($ch, CURLOPT_COOKIE, $options['cookie_string']);
        }

        if (isset($options['User-Agent']) && $options['User-Agent'] <> '') {
            curl_setopt($ch, CURLOPT_USERAGENT, $options['User-Agent']);
        }

        $response = curl_exec($ch);
        $response = self::cleanResponce($response);

        HMWP_Debug::dump('CURL', $url, $options, $ch, $response); //output debug

        if (curl_errno($ch) == 1 || $response === false) { //if protocol not supported
            if (curl_errno($ch)) {
                HMWP_Debug::dump(curl_getinfo($ch), curl_errno($ch), curl_error($ch));
            }
            curl_close($ch);
            $response = self::hmwp_wpcall($url, $options); //use the wordpress call
        } else {
            curl_close($ch);
        }

        return $response;
    }

    /**
     * Use the WP remote call
     *
     * @param string $url
     * @param array $options
     * @return string
     */
    private static function hmwp_wpcall($url, $options) {
        $response = wp_remote_get($url, $options);
        if (is_wp_error($response)) {
            HMWP_Debug::dump($response);
            return false;
        }

        $response = self::cleanResponce(wp_remote_retrieve_body($response)); //clear and get the body
        HMWP_Debug::dump('wp_remote_get', $url, $options, $response); //output debug
        return $response;
    }

    /**
     * Connect remote with CURL if exists
     *
     * @param $url
     * @return array|bool|WP_Error
     */
    public static function hmwp_remote_head($url) {
        $response = array();

        if (function_exists('curl_exec')) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_exec($ch);

            $response['headers']['content-type'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            $response['response']['code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            return $response;
        } else {
            return wp_remote_head($url, array('timeout' => 30));
        }

    }

    /**
     * Get the Json from responce if any
     * @param string $response
     * @return string
     */
    private static function cleanResponce($response) {

        if (function_exists('substr_count'))
            if (substr_count($response, '(') > 1)
                return $response;

        if (strpos($response, '(') !== false && strpos($response, ')') !== false)
            $response = substr($response, (strpos($response, '(') + 1), (strpos($response, ')') - 1));

        return $response;
    }

    /**
     * Support for i18n with wpml, polyglot or qtrans
     *
     * @param string $in
     * @return string $in localized
     */
    public static function i18n($in) {
        if (function_exists('langswitch_filter_langs_with_message')) {
            $in = langswitch_filter_langs_with_message($in);
        }
        if (function_exists('polyglot_filter')) {
            $in = polyglot_filter($in);
        }
        if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
            $in = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($in);
        }
        $in = apply_filters('localization', $in);
        return $in;
    }

    /**
     * Convert integer on the locale format.
     *
     * @param int $number The number to convert based on locale.
     * @param int $decimals Precision of the number of decimal places.
     * @return string Converted number in string format.
     */
    public static function i18n_number_format($number, $decimals = 0) {
        global $wp_locale;
        $formatted = number_format($number, absint($decimals), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep']);
        return apply_filters('number_format_i18n', $formatted);
    }

    /**
     * Returns true if permalink structure
     *
     * @return boolean
     */
    public static function isPermalinkStructure() {

        return get_option('permalink_structure');
    }

    public static function isPHPPermalink() {
        if (get_option('permalink_structure')) {
            if (strpos(get_option('permalink_structure'), 'index.php') !== false || strpos(get_option('permalink_structure'), 'index.html') !== false || strpos(get_option('permalink_structure'), 'index.htm') !== false) {
                return true;
            }
        }
        return false;
    }


    /**
     * Check if HTML Headers
     * @return bool
     */
    public static function isHtmlHeader() {
        $headers = headers_list();

        foreach ($headers as $index => $value) {
            if (strpos($value, ':') !== false) {
                $exploded = @explode(': ', $value);
                if (count($exploded) > 1) {
                    $headers[$exploded[0]] = $exploded[1];
                }
            }
        }

        if (isset($headers['Content-Type'])) {
            if (strpos($headers['Content-Type'], 'text/html') !== false) {
                return true;
            }
        } else {
            return false;
        }

        return false;
    }


    /**
     * Returns true if server is Apache
     *
     * @return boolean
     */
    public static function isApache() {
        return (isset($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false);
    }

    /**
     * Check if mode rewrite is on
     * @return bool
     */
    public static function isModeRewrite() {
        if (function_exists('apache_get_modules')) {
            $modules = apache_get_modules();
            return in_array('mod_rewrite', $modules);
        }
        return true;
    }

    /**
     * Check whether server is LiteSpeed
     *
     * @return bool
     */
    public static function isLitespeed() {
        return (isset($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false);
    }

    /**
     * Check if multisites with path
     *
     * @return bool
     */
    public static function isMultisites() {
        if (!isset(self::$is_multisite)) {
            self::$is_multisite = (is_multisite() && ((defined('SUBDOMAIN_INSTALL') && !SUBDOMAIN_INSTALL) || (defined('VHOST') && VHOST == 'no')));
        }
        return self::$is_multisite;
    }

    /**
     * Returns true if server is nginx
     *
     * @return boolean
     */
    public static function isNginx() {
        return (isset($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false);
    }

    public static function isIIS() {
        return (isset($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'microsoft-iis') !== false);
    }

    public static function checkOtherPlugins() {
        //is CDN plugin installed
        if (defined('CDN_ENABLER_MIN_WP')) {
            self::$options['hmwp_laterload'] = 1;
            if (is_admin() || is_network_admin()) {
                if (self::getOption('hmwp_mode') == 'ninja') {
                    if ($cdn_enabler = get_option('cdn_enabler')) {
                        if (isset($cdn_enabler['dirs'])) {
                            $dirs = explode(',', $cdn_enabler['dirs']);
                            if (!empty($dirs) &&
                                !in_array(self::getOption('hmwp_wp-content_url'), $dirs) &&
                                !in_array(self::getOption('hmwp_wp-includes_url'), $dirs)
                            ) {
                                HMWP_Classes_Error::setError(__('CDN Enabled detected. Please include the new wp-content and wp-includes paths in CDN Enabler Settings', _HMWP_PLUGIN_NAME_), 'default');
                            }
                        }
                    }
                }
            }
        }

        if (defined('WPFC_MAIN_PATH')) {
            self::$options['hmwp_laterload'] = 1;
            if (is_admin() || is_network_admin()) {
                if (self::getOption('hmwp_mode') == 'ninja') {
                    if ($WpFastestCache = get_option('WpFastestCache')) {
                        $WpFastestCache = json_decode($WpFastestCache);
                        if (isset($WpFastestCache->wpFastestCacheMinifyCss) && $WpFastestCache->wpFastestCacheMinifyCss = 'on') {
                            HMWP_Classes_Error::setError(__("WP Fastest Cache Detected. Hide My WP doesn't work properly with the minify option from WPFC. Try using the Wp-Rocket plugin instead.", _HMWP_PLUGIN_NAME_), 'default');
                        }
                    }
                }
            }
        }

    }

    public static function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public static function getRelativePath($url) {
        $url = wp_make_link_relative($url);

        if ($url <> '') {
            $url = str_replace(wp_make_link_relative(get_bloginfo('url')), '', $url);

            if (HMWP_Classes_Tools::isMultisites() && defined('PATH_CURRENT_SITE')) {
                $url = str_replace(rtrim(PATH_CURRENT_SITE, '/'), '', $url);
                $url = trim($url, '/');
                $url = $url . '/';
            } else {
                $url = trim($url, '/');
            }
        }

        HMWP_Debug::dump($url);
        return $url;
    }

    public static function emptyCache() {
        if (function_exists('w3tc_pgcache_flush')) {
            w3tc_pgcache_flush();
        }

        if (function_exists('w3tc_minify_flush')) {
            w3tc_minify_flush();
        }
        if (function_exists('w3tc_dbcache_flush')) {
            w3tc_dbcache_flush();
        }
        if (function_exists('w3tc_objectcache_flush')) {
            w3tc_objectcache_flush();
        }

        if (function_exists('wp_cache_clear_cache')) {
            wp_cache_clear_cache();
        }

        if (function_exists('rocket_clean_domain')) {
            // Remove all cache files
            rocket_clean_domain();
        }

        if (function_exists('opcache_reset')) {
            // Remove all opcache if enabled
            opcache_reset();
        }

        if (function_exists('apc_clear_cache')) {
            // Remove all apc if enabled
            apc_clear_cache();
        }

        //Clear the fastest cache
        global $wp_fastest_cache;
        if (isset($wp_fastest_cache) && method_exists($wp_fastest_cache, 'deleteCache')) {
            $wp_fastest_cache->deleteCache();
        }
    }

    /**
     * Called on plugin activation
     */
    public function hmwp_activate() {
        set_transient('hmwp_activate', true);

        $lastsafeoptions = self::getOptions(true);
        if (isset($lastsafeoptions['error']) && $lastsafeoptions['error'] == false) {
            set_transient('hmwp_restore', true);
        }
    }

    /**
     * Called on plugin deactivation
     */
    public function hmwp_deactivate() {
        if (!HMWP_Classes_Tools::getValue('force', false)) {
            self::$options = self::$default;
            self::saveOptions();


            //remove the custom rules
            HMWP_Classes_ObjController::getClass('HMWP_Controllers_Settings')->writeInHtaccess('');
            HMWP_Classes_ObjController::getClass('HMWP_Controllers_Settings')->writeInHtaccess('', 'HMWP_OLDPATHS');
            //clear the locked ips
            HMWP_Classes_ObjController::getClass('HMWP_Controllers_Brute')->clearBlockedIPs();

            //Set the settings to default
            if (HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->hmwp_remove_config_cache()) {
                global $wp_rewrite;
                $wp_rewrite->flush_rules();
            } else {
                //If errors, show the message
                HMWP_Classes_ObjController::getClass('HMWP_Classes_Error')->hookNotices();
                echo sprintf(__("%sClick here%s when you're done.", _HMWP_PLUGIN_NAME_), '<a href="javascript:void;" onclick="location.href=location.href+\'&force=true\'">', '</a>');
                exit();
            }
        }
    }

    /**
     * Check for updates
     * Called on activation
     */
    public static function checkUpgrade() {
        self::$options = self::getOptions();

        //get the options from the free version
        if (get_option('hmw_options')) {

            $options = json_decode(get_option('hmw_options'), true);
            self::$options['hmwp_disable'] = $options['hmw_disable'];
            self::$options['hmwp_mode'] = 'lite';
            self::$options['hmwp_admin_url'] = $options['hmw_admin_url'];
            self::$options['hmwp_login_url'] = $options['hmw_login_url'];
            self::$options['hmwp_hide_admin'] = $options['hmw_hide_admin'];
            self::$options['hmwp_hide_login'] = $options['hmw_hide_login'];
            self::saveOptions();

            delete_option('hmw_options');
        }
        if ((int)self::$options['hmwp_ver'] == 0) {
            HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->hmwp_remove_config_cache();
            self::setCookieContants();
        }

        self::$options['hmwp_ver'] = HMWP_VERSION_ID;
        self::saveOptions();
    }

    public function checkWpUpdates() {
        HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->clearRedirect()->buildRedirect();

        $all_plugins = HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->getAllPlugins();
        $dbplugins = HMWP_Classes_Tools::getOption('hmwp_plugins');
        foreach ($all_plugins as $plugin) {
            if (is_plugin_active($plugin) && isset($dbplugins['from']) && !empty($dbplugins['from'])) {
                if (!in_array(plugin_dir_path($plugin), $dbplugins['from'])) {
                    self::saveOptions('changes', true);
                }
            }
        }

        $all_themes = HMWP_Classes_ObjController::getClass('HMWP_Models_Rewrite')->getAllThemes();
        $dbthemes = HMWP_Classes_Tools::getOption('hmwp_themes');
        foreach ($all_themes as $theme => $value) {
            if (is_dir($value['theme_root']) && isset($dbthemes['from']) && !empty($dbthemes['from'])) {
                if (!in_array($theme . '/', $dbthemes['from'])) {
                    self::saveOptions('changes', true);
                }
            }
        }
    }

    /**
     * Send the email is case there are major changes
     * @return bool
     */
    public static function sendEmail() {
        $email = self::$options['hmwp_email_address'];
        if ($email == '') {
            global $current_user;
            $email = $current_user->user_email;
        }

        $line = "\n" . "________________________________________" . "\n";
        $to = $email;
        $from = 'support@wpplugins.tips';
        $subject = __('Hide My Wordpress - New Login Data', _HMWP_PLUGIN_NAME_);
        $message = "Thank you for using Hide My Wordpress!" . "\n";
        $message .= $line;
        $message .= "Your new site URLs are:" . "\n";
        $message .= "Admin URL: " . admin_url() . "\n";
        $message .= "Login URL: " . site_url(self::$options['hmwp_login_url']) . "\n";
        $message .= $line;
        $message .= "Note: If you can't login to your site, just access this URL: \n";
        $message .= site_url() . "/wp-login.php?hmwp_disable=" . self::$options['hmwp_disable'] . "\n\n";
        $message .= $line;
        $message .= "Best regards," . "\n";
        $message .= "Wpplugins.tips Team" . "\n";
        $headers = array();
        $headers[] = 'From: Hide My Wordpress <' . $from . '>';
        $headers[] = 'Content-type: text/plain';

        if (@wp_mail($to, $subject, $message, $headers)) {
            return true;
        }

        return false;
    }

    /**
     * Set the cookie constants in case of admin change
     */
    public static function setCookieContants() {
        if (!defined('HMWP_ADMIN_COOKIE_PATH')) {
            if (is_multisite()) {
                global $blog_id;
                switch_to_blog($blog_id);
                if (!is_subdomain_install() || trim(parse_url(get_option('siteurl'), PHP_URL_PATH), '/')) {
                    define('HMWP_ADMIN_COOKIE_PATH', SITECOOKIEPATH);
                } else {
                    define('HMWP_ADMIN_COOKIE_PATH', SITECOOKIEPATH . self::getOption('hmwp_admin_url'));
                }
            } else {
                define('HMWP_ADMIN_COOKIE_PATH', SITECOOKIEPATH . self::getOption('hmwp_admin_url'));
            }
        }
        if (!defined('HMWP_PLUGINS_COOKIE_PATH')) {
            define('HMWP_PLUGINS_COOKIE_PATH', preg_replace('|https?://[^/]+|i', '', get_option('siteurl') . '/' . HMWP_Classes_Tools::$default['hmwp_wp-content_url'] . '/' . HMWP_Classes_Tools::$default['hmwp_plugin_url']));
        }


    }


}