<?php
/*
Plugin Name: MoeSec Security
Plugin URI: https://MoeSec.com/wordpress-security-plugin/
Description: A comprehensive Malware Scanner, Security Hardening, Login Protection, Firewall, 2FA, Brute Force Protection, Backups and much more!
Version: 2.2
Author: MoeSec
Author URI: https://MoeSec.com
Text Domain: moesec
Requires at least: 5.0
License: GPLv3
License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Include necessary files
require_once(plugin_dir_path(__FILE__) . 'admin/admin-page.php');
require_once(plugin_dir_path(__FILE__) . 'includes/external-scan.php');
require_once(plugin_dir_path(__FILE__) . 'includes/file-db-scanner.php');
require_once(plugin_dir_path(__FILE__) . 'includes/integrity-check.php');
require_once(plugin_dir_path(__FILE__) . 'includes/scheduled-scans.php');
require_once(plugin_dir_path(__FILE__) . 'includes/email-notifications.php');
require_once(plugin_dir_path(__FILE__) . 'includes/wp-hardening.php');
require_once(plugin_dir_path(__FILE__) . 'includes/login-protection.php');
require_once(plugin_dir_path(__FILE__) . 'includes/two-factor-auth.php');
require_once(plugin_dir_path(__FILE__) . 'includes/brute-force-protection.php');
require_once(plugin_dir_path(__FILE__) . 'includes/bad-bot-blocking.php');
require_once(plugin_dir_path(__FILE__) . 'includes/firewall.php');
require_once(plugin_dir_path(__FILE__) . 'includes/logging.php');
require_once(plugin_dir_path(__FILE__) . 'includes/signature-update.php');
require_once(plugin_dir_path(__FILE__) . 'includes/faqs.php');
require_once(plugin_dir_path(__FILE__) . 'includes/backups.php');


// Add admin menu
function moesec_add_admin_menu() {
    add_menu_page(
        'MoeSec Security',
        'MoeSec',
        'manage_options',
        'moesec',
        'moesec_admin_page',
        plugin_dir_url(__FILE__) . 'assets/moesec-icon.png',
        100
    );
}
add_action('admin_menu', 'moesec_add_admin_menu');

// Enqueue scripts and styles
function moesec_enqueue_scripts($hook) {
    if ($hook != 'toplevel_page_moesec') {
        return;
    }

    wp_enqueue_style('moesec-style', plugin_dir_url(__FILE__) . 'assets/css/moesec-style.css', array(), '1.8');
    wp_enqueue_script('moesec-script', plugin_dir_url(__FILE__) . 'assets/js/moesec-script.js', array('jquery'), '1.8', true);
    wp_enqueue_script('moesec-scan', plugin_dir_url(__FILE__) . 'assets/js/moesec-scan.js', array('jquery'), '1.8', true);

    wp_localize_script('moesec-script', 'moesec_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('moesec_ajax_nonce'),
        'scanning_text' => esc_html__('Scanning...', 'moesec'),
        'completed_text' => esc_html__('Scan completed', 'moesec'),
        'debug_mode' => defined('WP_DEBUG') && WP_DEBUG,
        'site_url' => site_url(),
        'plugin_version' => '1.8'
    ));
    
    // Also localize the scan script
    wp_localize_script('moesec-scan', 'moesec_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('moesec_ajax_nonce'),
        'scanning_text' => esc_html__('Scanning...', 'moesec'),
        'completed_text' => esc_html__('Scan completed', 'moesec'),
        'debug_mode' => defined('WP_DEBUG') && WP_DEBUG,
        'site_url' => site_url(),
        'plugin_version' => '1.8'
    ));
}
add_action('admin_enqueue_scripts', 'moesec_enqueue_scripts');

// Add CORS headers to all AJAX responses
function moesec_add_cors_headers_to_ajax() {
    if (defined('DOING_AJAX') && DOING_AJAX) {
        // Get the origin
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        
        // Check if the origin is empty (same origin) or if it's from the same site
        if (empty($origin)) {
            // Same origin, use wildcard
            header('Access-Control-Allow-Origin: *');
        } else {
            // Different origin, use the specific origin
            header('Access-Control-Allow-Origin: ' . $origin);
        }
        
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
        
        // Handle preflight requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            status_header(200);
            exit();
        }
    }
}
add_action('init', 'moesec_add_cors_headers_to_ajax', 1);

// Activation hook
register_activation_hook(__FILE__, 'moesec_activate');

function moesec_activate() {
    
	// Set up logging table
    moesec_create_log_table();

	// Set up scheduled scans
    moesec_setup_scheduled_scans();
        
    // Schedule signature updates
    moesec_schedule_signature_update();
    
    // Create backup directory
    moesec_create_backup_directory();
    
    // Schedule automatic backups if enabled
    moesec_schedule_automatic_backups();
    
    // Schedule integrity check if enabled
    moesec_schedule_integrity_check();
    
    moesec_log('MoeSec Security plugin activated - all scheduled tasks initialized');
}

// Deactivation hook
register_deactivation_hook(__FILE__, 'moesec_deactivate');

function moesec_deactivate() {
    wp_clear_scheduled_hook('moesec_daily_scan');
    wp_clear_scheduled_hook('moesec_weekly_scan');
    wp_clear_scheduled_hook('moesec_monthly_scan');
    wp_clear_scheduled_hook('moesec_daily_signature_update');
    wp_clear_scheduled_hook('moesec_auto_backup');
    wp_clear_scheduled_hook('moesec_daily_integrity_check');
    wp_clear_scheduled_hook('moesec_weekly_integrity_check');
    wp_clear_scheduled_hook('moesec_monthly_integrity_check');
    
    moesec_log('MoeSec Security plugin deactivated - all scheduled tasks cleared');
}

// AJAX handler for starting the scan
add_action('wp_ajax_moesec_start_scan', 'moesec_ajax_start_scan');
function moesec_ajax_start_scan() {
    check_ajax_referer('moesec_ajax_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => esc_html__('You do not have permission to perform this action.', 'moesec')));
    }

    // Start the scan process
    update_option('moesec_scan_in_progress', true);
    wp_schedule_single_event(time(), 'moesec_perform_scan');
    wp_send_json_success(array('message' => esc_html__('Scan started', 'moesec')));
}

// AJAX handler for scan progress
add_action('wp_ajax_moesec_scan_progress', 'moesec_ajax_scan_progress');
function moesec_ajax_scan_progress() {
    check_ajax_referer('moesec_ajax_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => esc_html__('You do not have permission to perform this action.', 'moesec')));
    }

    $file_progress = get_transient('moesec_file_scan_progress');
    $db_progress = get_transient('moesec_db_scan_progress');
    
    if ($file_progress === false && $db_progress === false) {
        $progress = 0;
        $message = esc_html__('Preparing to scan...', 'moesec');
    } elseif ($db_progress === false) {
        $progress = $file_progress;
        $message = esc_html__('Scanning files...', 'moesec');
    } elseif ($file_progress === false) {
        $progress = $db_progress;
        $message = esc_html__('Scanning database...', 'moesec');
    } else {
        $progress = ($file_progress + $db_progress) / 2;
        $message = esc_html__('Scanning files and database...', 'moesec');
    }
    
    if ($progress >= 100) {
        delete_option('moesec_scan_in_progress');
        $message = esc_html__('Scan completed', 'moesec');
    }
    
    wp_send_json_success(array('progress' => $progress, 'message' => $message));
}

// Scheduled action to perform the scan
add_action('moesec_perform_scan', 'moesec_perform_scan');
function moesec_perform_scan() {
    $suspicious_files = moesec_scan_files();
    $suspicious_db_entries = moesec_scan_database();

    update_option('moesec_suspicious_files', $suspicious_files);
    update_option('moesec_suspicious_db_entries', $suspicious_db_entries);

    // Update last scan time
    update_option('moesec_last_scan_time', current_time('mysql'));

    // Log the scan completion
    moesec_log(sprintf(
        /* translators: %1$d: number of suspicious files, %2$d: number of suspicious database entries */
        esc_html__('Scan completed. Found %1$d suspicious files and %2$d suspicious database entries.', 'moesec'),
        count($suspicious_files),
        count($suspicious_db_entries)
    ));
}

// Add a filter to set HTML mail content type
add_filter('wp_mail_content_type', 'moesec_set_html_mail_content_type');
function moesec_set_html_mail_content_type() {
    return 'text/html';
}

// Remove filter after email is sent
add_action('wp_mail_failed', 'moesec_set_default_content_type');
function moesec_set_default_content_type() {
    remove_filter('wp_mail_content_type', 'moesec_set_html_mail_content_type');
}

function moesec_add_cron_interval($schedules) {
    $schedules['monthly'] = array(
        'interval' => 2592000,
        'display' => esc_html__('Once Monthly', 'moesec')
    );
    return $schedules;
}
add_filter('cron_schedules', 'moesec_add_cron_interval');
?>
