<?php
/**
 * Plugin Name: WP Meta SEO Pro
 * Plugin URI: https://www.joomunited.com/wordpress-products/wp-meta-seo
 * Description: WP Meta SEO Pro brings your website ranking to the next level with advanced tools like SEO Email reports, automatic 404 URL fix and more
 * Version: 1.5.4
 * Text Domain: wpmsPro
 * Domain Path: /languages
 * Author: JoomUnited
 * Author URI: http://www.joomunited.com
 * License: GPL2
 */

// Make sure we don't expose any info if called directly
if (!function_exists('add_action')) {
    echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
    exit;
}

//Check PHP requirements
if (version_compare(PHP_VERSION, '7.4', '<')) {
    if (!function_exists('wpms_addon_disable_plugin')) {
        /**
         * Deactivate plugin
         *
         * @return void
         */
        function wpms_addon_disable_plugin()
        {
            if (current_user_can('activate_plugins') && is_plugin_active(plugin_basename(__FILE__))) {
                deactivate_plugins(__FILE__);
                //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no action
                unset($_GET['activate']);
            }
        }
    }

    if (!function_exists('wpms_addon_show_error')) {
        /**
         * Show notice
         *
         * @return void
         */
        function wpms_addon_show_error()
        {
            echo '<div class="error"><p><strong>WP Meta SEO Addon</strong>
 need at least PHP 5.6 version, please update php before installing the plugin.</p></div>';
        }
    }

    //Add actions
    add_action('admin_init', 'wpms_addon_disable_plugin');
    add_action('admin_notices', 'wpms_addon_show_error');

    //Do not load anything more
    return;
}

// Check if the WP Meta SEO plugin active then ask to deactivate it
add_action('init', function () {

    if (is_plugin_active('wp-meta-seo/wp-meta-seo.php')) {
        add_action('admin_notices', function () {
            echo '<div class="error"><p>Do not activate the free WP Meta SEO plugin while you are running the <strong>WP Meta SEO Pro</strong></p></div>';
        });
        deactivate_plugins('wp-meta-seo/wp-meta-seo.php');
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action, nonce is not required
        unset($_GET['activate']);
    }
});

//Include the jutranslation helpers
include_once('jutranslation' . DIRECTORY_SEPARATOR . 'jutranslation.php');
call_user_func(
    '\Joomunited\WPMSPro\Jutranslation\Jutranslation::init',
    __FILE__,
    'wp-meta-seo-addon',
    'WP Meta SEO Pro',
    'wpmsPro',
    'languages' . DIRECTORY_SEPARATOR . 'wp-meta-seo-addon-en_US.mo'
);

// JU Check Requirements
add_action('init', function () {

    if (!class_exists('\Joomunited\WPMSADDON\JUCheckRequirements')) {
        require_once(trailingslashit(dirname(__FILE__)) . 'requirements.php');
    }

    if (class_exists('\Joomunited\WPMSADDON\JUCheckRequirements')) {
        // Plugins name for translate
        $args = array(
            'plugin_name' => esc_html__('WP Meta SEO Pro', 'wpmsPro'),
            'plugin_path' => 'wp-meta-seo-addon/wp-meta-seo-addon.php',
            'plugin_textdomain' => 'wpmsPro',
            'requirements' => array(
                'php_version' => '7.4',
                'php_modules' => array(
                    'curl' => 'warning'
                )
            )
        );
        $wpmsCheck = call_user_func('\Joomunited\WPMSADDON\JUCheckRequirements::init', $args);

        if (!$wpmsCheck['success']) {
            //phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Do not load anything more
            unset($_GET['activate']);
            return;
        }
    }
});

if (!defined('WPMETASEO_ADDON_PLUGIN_URL')) {
    /**
     * URL to WP Meta SEO Pro plugin
     */
    define('WPMETASEO_ADDON_PLUGIN_URL', plugin_dir_url(__FILE__));
}

if (!defined('WPMETASEO_ADDON_PLUGIN_DIR')) {
    /**
     * Path to WP Meta SEO Pro plugin
     */
    define('WPMETASEO_ADDON_PLUGIN_DIR', plugin_dir_path(__FILE__));
}

if (!defined('WPMSEO_ADDON_FILE')) {
    /**
     * Path to this file
     */
    define('WPMSEO_ADDON_FILE', __FILE__);
}

require_once plugin_dir_path(__FILE__) . 'inc/defines.php';

register_activation_hook(__FILE__, array('MetaSeoAddonAdmin', 'pluginAddonActivation'));
register_activation_hook(__FILE__, array('MetaSeoAddonAdmin', 'pluginAddonDeactivation'));

// updaterV2
if (is_admin()) {
    add_action('wp_ajax_wpmsju_update_license', 'wpmsProUpdateToken');
    add_action('init', 'wpmsProWizardSetupLoaded');
    add_action('admin_init', 'wpmsProAdminRedirects', 0);

    /**
     * Includes WP Media Folder setup
     *
     * @return void
     */
    function wpmsProWizardSetupLoaded()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
        if (!empty($_GET['page'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
            switch ($_GET['page']) {
                case 'wpms-setup':
                    require_once WPMETASEO_ADDON_PLUGIN_DIR . '/inc/install-wizard/install-wizard.php';
                    break;
            }
        }
    }

    /**
     * Admin redirect
     *
     * @return void
     */
    function wpmsProAdminRedirects()
    {

        //Redirect with first install
        if (!empty(get_option('wpmsPro_first_installed', null))) {
            update_option('wpmsPro_first_installed', '0');
            wp_safe_redirect(admin_url('index.php?page=wpms-setup'));
            exit;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
        if (empty($_GET['page']) || (strpos($_GET['page'], 'wpms')  === false) && (strpos($_GET['page'], 'metaseo')  === false)) {
            return;
        }

        // validate and convert old token to new license token
        if (empty(get_site_option('wpmsPro_license_token')) && !empty(get_option('ju_user_token'))) {
            $extName = 'wp-meta-seo-addon';
            $ju_update_link = JU_BASE . 'index.php?option=com_juupdater&task=licenses.convert&token=' . get_option('ju_user_token').'&extName='.$extName.'&site=' . site_url() ;
            $res = wp_remote_get($ju_update_link);
            $new_license = wp_remote_retrieve_body($res);
            if (!empty($new_license)) {
                $new_license = json_decode($new_license);
                if (is_multisite() && current_user_can('manage_network')) {
                    update_site_option('wpmsPro_license_token', $new_license->token);
                } else {
                    update_option('wpmsPro_license_token', $new_license->token);
                }
                delete_option('wpmsPro_activation_redirect');
            }
        }

        // Setup wizard redirect
        if (!empty(get_option('wpmsPro_activation_redirect', null)) || empty(get_site_option('wpmsPro_license_token'))) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- View request, no action
            if ((!empty($_GET['page']) && in_array($_GET['page'], array('wpms-setup')))) {
                return;
            }
            if (defined('DOING_AJAX') && DOING_AJAX) {
                return;
            }
            wp_safe_redirect(admin_url('index.php?page=wpms-setup'));
            exit;
        }
    }

    /**
     * Update license token
     *
     * @return void
     */
    function wpmsProUpdateToken()
    {

        if (empty($_POST['ju_updater_nonce'])
            || !wp_verify_nonce($_POST['ju_updater_nonce'], 'ju_updater_nonce')) {
            die();
        }

        if (isset($_POST['token'])) {
            //check if it's a multisite and have network admin access
            if (is_multisite() && current_user_can('manage_network')) {
                update_site_option('wpmsPro_license_token', sanitize_text_field($_POST['token']));
            } else {
                update_option('wpmsPro_license_token', sanitize_text_field($_POST['token']));
                update_option('wpmsPro_db_install', '1');
            }
            delete_option('wpmsPro_activation_redirect');
            wp_send_json_success();
        }
    }
}


//config section
if (!defined('JU_BASE')) {
    /**
     * Joomunited url
     */
    define('JU_BASE', 'https://www.joomunited.com/');
}

$remote_updateinfo = JU_BASE . 'juupdater_files/wp-meta-seo-addon.json';
//end config

require 'juupdater/juupdater.php';
$UpdateChecker = Jufactory::buildUpdateChecker(
    $remote_updateinfo,
    __FILE__
);


if (!function_exists('wpmsProPluginCheckForUpdates')) {
    /**
     * Plugin check for updates
     *
     * @param object $update      Update
     * @param array  $plugin_data Plugin data
     * @param string $plugin_file Plugin file
     *
     * @return array|boolean|object
     */
    function wpmsProPluginCheckForUpdates($update, $plugin_data, $plugin_file)
    {
        if ($plugin_file !== 'wp-meta-seo-addon/wp-meta-seo-addon.php') {
            return $update;
        }

        if (empty($plugin_data['UpdateURI']) || !empty($update)) {
            return $update;
        }

        $response = wp_remote_get($plugin_data['UpdateURI']);

        if (is_wp_error($response) || empty($response['body'])) {
            return $update;
        }

        $custom_plugins_data = json_decode($response['body'], true);

        $package = null;
        $token = get_site_option('wpmsPro_license_token');
        if (!empty($token)) {
            $package = $custom_plugins_data['download_url'] . '&token=' . $token . '&siteurl=' . get_option('siteurl');
        }

        return array(
            'version' => $custom_plugins_data['version'],
            'package' => $package
        );
    }
    add_filter('update_plugins_www.joomunited.com', 'wpmsProPluginCheckForUpdates', 10, 3);
}

/**
 * The core plugin class that is used to define internationalization,
 * admin-specific hooks, and public-facing site hooks.
 */
require plugin_dir_path(__FILE__) . 'inc/class.wpmspro.php';
/**
 * Begins execution of the plugin.
 *
 * Since everything within the plugin is registered via hooks,
 * then kicking off the plugin from this point in the file does
 * not affect the page life cycle.
 *
 * @return void
 */
function run_wpmspro()
{

    $plugin = new WpmsPro();
    $plugin->run();
}
run_wpmspro();
