<?php

class ITSEC_Malware_Admin {
	private $settings;
	private $core;

	function run( $core ) {
		global $pagenow;
		
		$this->core        = $core;
		$this->settings    = get_site_option( 'itsec_malware' );
		
		add_action( 'itsec_add_admin_meta_boxes', array( $this, 'add_admin_meta_boxes' ) );
		add_action( 'wp_ajax_itsec_malware_scan', array( $this, 'get_ajax_scan_response' ) );
		
		add_filter( 'itsec_logger_displays', array( $this, 'itsec_logger_displays' ) );
		add_filter( 'itsec_logger_modules', array( $this, 'itsec_logger_modules' ) );
		add_filter( 'itsec_logger_filter_malware_data_column_details', array( $this, 'filter_logger_data_column_details' ), 10, 2 );
		
		if (
			! empty( $pagenow ) &&
			'admin.php' === $pagenow &&
			! empty( $_GET['page'] ) &&
			in_array( $_GET['page'], array( 'toplevel_page_itsec_settings', 'toplevel_page_itsec_logs' ) )
		) {
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
		}
	}
	
	public function filter_logger_data_column_details( $details, $data ) {
		if ( is_wp_error( $data ) || ( ! empty( $data ) && ! empty( $data['SCAN']['SITE'] ) ) ) {
			// Results for Sucuri scans.
			
			require_once( dirname( __FILE__ ) . '/class-itsec-malware-scan-results-template.php' );
			
			$details = "<div class='itsec-malware-scan-results-wrapper'>\n";
			$details .= ITSEC_Malware_Scan_Results_Template::get_html( $data, true );
			$details .= "</div>\n";
		}
		
		return $details;
	}
	
	/**
	 * Register malware for logger
	 *
	 * @since 4.4
	 *
	 * @param  array $logger_modules array of logger modules
	 *
	 * @return array                   array of logger modules
	 */
	public function itsec_logger_modules( $logger_modules ) {
		$logger_modules['malware'] = array(
			'type'     => 'malware',
			'function' => __( 'Malware Scan', 'better-wp-security' ),
		);
		
		return $logger_modules;
	}
	
	public function enqueue_admin_scripts() {
		global $itsec_globals;
		
		$script_id = 'itsec-malware-scan-script';
		$script_url = plugins_url( 'js/malware.js', __FILE__ );
		$js_var = 'itsecMalwareScanData';
		
		$data = array(
			'nonce'             => wp_create_nonce( 'itsec-malware-get-ajax-scan-response' ),
			'clickedButtonText' => __( 'Scanning. Please Wait.', 'better-wp-security' ),
			'hideDetailsText'   => __( 'Hide Details', 'better-wp-security' ),
			'errorMessages'     => array(
				'ajaxUnknown'  => esc_html__( 'An error prevented the scan from completing as expected. The browser was unable to successfully request scan results from the site. This could be due to a plugin conflict or a server configuration issue. The following error message was received: %1$s', 'better-wp-security' ),
				'ajaxTimeout'  => esc_html__( 'An error prevented the scan from completing as expected. The site took too long to respond. This could be due to a plugin conflict or a server configuration issue. The following error message was received: %1$s', 'better-wp-security' ),
				'nonceFailure' => esc_html__( 'An error prevented the scan from completing as expected. The nonce check, which is used to protect your site, failed. Please refresh the page and try the scan again.', 'better-wp-security' ),
				'invalidUser'  => esc_html__( 'An error prevented the scan from completing as expected. The currently logged in user does not have sufficient permissions to run this scan. You may need to log out of the site and log back in.', 'better-wp-security' ),
				'parseError'   => esc_html__( 'An error prevented the scan from completing as expected. The site returned data in an unexpected format. This could be due to a plugin conflict or a server configuration issue. The received data was in the following format: %1$s', 'better-wp-security' ),
			),
		);
		
		wp_enqueue_script( $script_id, $script_url, array( 'jquery' ), $itsec_globals['plugin_build'] );
		wp_localize_script( $script_id, $js_var, $data );
		
		
		$style_id = 'itsec-malware-scan-style';
		$style_url = plugins_url( 'css/malware.css', __FILE__ );
		
		wp_enqueue_style( $style_id, $style_url, array(), 2 );
	}
	
	protected function get_scan_details() {
		require_once( dirname( __FILE__ ) . '/class-itsec-malware-scanner.php' );
		require_once( dirname( __FILE__ ) . '/class-itsec-malware-scan-results-template.php' );
		
		$results = ITSEC_Malware_Scanner::scan();
		$html = ITSEC_Malware_Scan_Results_Template::get_html( $results, true );
		
		return $html;
	}
	
	public function get_ajax_scan_response() {
		global $itsec_globals;
		
		check_ajax_referer( 'itsec-malware-get-ajax-scan-response' );
		
		if ( ! current_user_can( $itsec_globals['plugin_access_lvl'] ) ) {
			die( '-2' );
		}
		
		echo $this->get_scan_details();
		
		wp_die();
	}

	/**
	 * Add meta boxes to primary options pages
	 *
	 * @return void
	 */
	public function add_admin_meta_boxes() {

		$id    = 'malware_options';
		$title = __( 'Malware Scanning', 'better-wp-security' );

		add_meta_box(
			$id,
			$title,
			array( $this, 'metabox_malware_settings' ),
			'security_page_toplevel_page_itsec_settings',
			'advanced',
			'core'
		);

		$this->core->add_toc_item(
			array(
				'id'    => $id,
				'title' => $title,
			)
		);

	}

	/**
	 * Array of metaboxes for the logs screen
	 *
	 * @since 4.4
	 *
	 * @param array $displays metabox array
	 *
	 * @return array metabox array
	 */
	public function itsec_logger_displays( $displays ) {
		$displays[] = array(
			'module'   => 'malware',
			'title'    => __( 'Malware Scan', 'better-wp-security' ),
			'callback' => array( $this, 'logs_metabox_content' )
		);

		return $displays;
	}

	/**
	 * Render the settings metabox
	 *
	 * @return void
	 */
	public function logs_metabox_content() {

		$this->malware_scan_form( 'logs' );

		if ( ! class_exists( 'ITSEC_Malware_Log' ) ) {
			require( dirname( __FILE__ ) . '/class-itsec-malware-log.php' );
		}

		$log_display = new ITSEC_Malware_Log();

		$log_display->prepare_items();
		$log_display->display();

	}

	/**
	 * Echos the one-time malware scan form
	 *
	 * @since 4.0
	 *
	 * @param string $origin the origin screen where the button was pressed
	 *
	 * @return void
	 */
	public function malware_scan_form( $origin ) {
		$this->show_malware_scan_button( false );
	}

	/**
	 * Render the settings metabox
	 *
	 * @since 4.0
	 *
	 * @return void
	 */
	public function metabox_malware_settings() {
		$this->show_malware_scan_button();
	}
	
	protected function show_malware_scan_button( $show_log_link = true ) {
		echo '<p>' . __( 'This malware scan is powered by <a href="https://ithemes.com/sitecheck">Sucuri SiteCheck</a>. It checks for known malware, blacklisting status, website errors, and out-of-date software. Although the Sucuri team does its best to provide the best results, 100% accuracy is not realistic and is not guaranteed.', 'better-wp-security' ) . "</p>\n";
		
		if ( $show_log_link ) {
			echo '<p>' . sprintf( __( 'Results of previous malware scans can be found on the <a href="%s">logs page</a>.', 'better-wp-security' ), admin_url( 'admin.php?page=toplevel_page_itsec_logs&itsec_log_filter=malware#itsec_log_all' ) ) . "</p>\n";
		}
		
		echo "<div class='itsec-malware-scan-results-wrapper'></div>\n";
		echo '<input class="button-primary hide-if-no-js" type="submit" id="itsec-malware-scan" name="do-malware-scan" value="' . esc_attr__( 'Scan Homepage for Malware', 'better-wp-security' ) . "\" />\n";
		echo '<div class="error inline hide-if-js"><p>' . __( 'The malware scanner requires Javascript in order to function. If Javascript is disabled in your browser, please enable it. If Javascript is not disabled, a script from another plugin, the theme, or a broken WordPress file is preventing the malware scanner\'s script from executing properly. Please try disabling other plugins to see if that resolves the issue.', 'better-wp-security' ) . "</p></div>\n";
	}
}
