<?php

/**
 * Log malware scan reports
 *
 * @package    iThemes-Security
 * @subpackage Intrusion-Detection
 * @since      4.4
 */
final class ITSEC_Malware_Log extends ITSEC_WP_List_Table {

	function __construct() {

		parent::__construct(
			array(
				'singular' => 'itsec_malware_log_item',
				'plural'   => 'itsec_malware_log_items',
				'ajax'     => true
			)
		);

	}

	/**
	 * Define first time column
	 *
	 * @param array $item array of row data
	 *
	 * @return string formatted output
	 *
	 **/
	function column_details( $item ) {

		$content = '';

		if ( ! empty( $item['results'] ) && in_array( $item['results'], array( 'clean', 'warn', 'error' ) ) ) {
			// Results for Sucuri scans.
			
			require_once( dirname( __FILE__ ) . '/class-itsec-malware-scan-results-template.php' );
			
			$content .= '<a href="itsec-log-malware-row-' . $item['count'] . '" class="dialog">' . __( 'Details', 'it-l10n-ithemes-security-pro' ) . '</a>';
			$content .= '<div id="itsec-log-malware-row-' . $item['count'] . '" style="display:none;">';
			$content .= "<div class='itsec-malware-scan-results-wrapper'>\n";
			
			$content .= ITSEC_Malware_Scan_Results_Template::get_html( $item['data'], true );
			
			$content .= "</div>\n";
			$content .= "</div>\n";
		} else if ( isset( $item['report'] ) ) {
			// Results for legacy VirusTotal scans.

			$content .= '<a href="itsec-log-malware-row-' . $item['count'] . '" class="dialog">' . __( 'Details', 'it-l10n-ithemes-security-pro' ) . '</a>';

			$content .= '<div id="itsec-log-malware-row-' . $item['count'] . '" style="display:none;">';

			if ( isset( $item['report']['resource'] ) ) {
				$content .= '<strong>' . __( 'Resource Scanned', 'it-l10n-ithemes-security-pro' ) . ':</strong> ' . $item['report']['resource'] . '<br />';
			}

			if ( isset( $item['report']['results'] ) ) {

				if ( isset( $item['report']['results']['total'] ) ) {
					$content .= '<strong>' . __( 'Total Scans', 'it-l10n-ithemes-security-pro' ) . ':</strong> ' . $item['report']['results']['total'] . '<br />';
				}

				if ( isset( $item['report']['results']['positives'] ) ) {
					$content .= '<strong>' . __( 'Problems Found', 'it-l10n-ithemes-security-pro' ) . ':</strong> ' . $item['report']['results']['positives'] . '<br />';
				}

				if ( isset( $item['report']['results']['scans'] ) ) {

					$content .= '<h3>' . __( 'Scan Details', 'it-l10n-ithemes-security-pro' ) . '</h3>';

					$content .= '<ol class="malware_detail_list">';

					foreach ( $item['report']['results']['scans'] as $service => $results ) {
						$content .= '<li class="malware_detail"><strong>' . $service . '</strong>: ' . $results['result'] . ' ' . $results['detected'] . '<br /></li>';
					}

					$content .= '</ol>';

				}

			}

			$content .= '</div>';

		}

		return $content;

	}

	/**
	 * Define results column
	 *
	 * @param array $item array of row data
	 *
	 * @return string formatted output
	 *
	 **/
	function column_results( $item ) {

		$content = '';

		if ( ! empty( $item['results'] ) && in_array( $item['results'], array( 'clean', 'warn', 'error' ) ) ) {
			// Results for Sucuri scans.
			if ( 'error' === $item['results'] ) {
				$content = '<span style="color: red">' . __( 'Error', 'it-l10n-ithemes-security-pro' ) . '</span>';
			} else if ( 'warn' === $item['results'] ) {
				$content = '<span style="color: red">' . __( 'Warning', 'it-l10n-ithemes-security-pro' ) . '</span>';
			} else {
				$content = '<span style="color: green">' . __( 'Clean', 'it-l10n-ithemes-security-pro' ) . '</span>';
			}
		} else if ( isset( $item['report']['results']['positives'] ) ) {
			// Results for legacy VirusTotal scans.

			if ( $item['report']['results']['positives'] == 0 ) {
				$content = '<span style="color: green">' . __( 'Clean', 'it-l10n-ithemes-security-pro' ) . '</span>';
			} else {
				$content = '<span style="color: red">' . __( 'Issues Detected', 'it-l10n-ithemes-security-pro' ) . '</span>';
			}

		}

		return $content;

	}

	/**
	 * Define time column
	 *
	 * @param array $item array of row data
	 *
	 * @return string formatted output
	 *
	 **/
	function column_time( $item ) {

		return $item['time'];

	}

	/**
	 * Define count column
	 *
	 * @param array $item array of row data
	 *
	 * @return string formatted output
	 *
	 **/
	function column_user( $item ) {

		$user = get_user_by( 'login', $item['user'] );

		if ( $user !== false ) {

			return '<a href="/wp-admin/user-edit.php?user_id=' . $user->ID . '">' . $item['user'] . '</a>';

		} else {

			return $item['user'];

		}

	}

	/**
	 * Define uri column
	 *
	 * @param array $item array of row data
	 *
	 * @return string formatted output
	 *
	 **/
	function column_action( $item ) {

		return $item['action'];

	}

	/**
	 * Define Columns
	 *
	 * @return array array of column titles
	 */
	public function get_columns() {

		return array(
			'time'    => __( 'Time', 'it-l10n-ithemes-security-pro' ),
			'action'  => __( 'Action', 'it-l10n-ithemes-security-pro' ),
			'results' => __( 'Results', 'it-l10n-ithemes-security-pro' ),
			'user'    => __( 'User', 'it-l10n-ithemes-security-pro' ),
			'details' => __( 'Details', 'it-l10n-ithemes-security-pro' ),
		);

	}

	/**
	 * Prepare data for table
	 *
	 * @return void
	 */
	public function prepare_items() {
		global $itsec_logger, $wpdb;

		$columns               = $this->get_columns();
		$hidden                = array();
		$this->_column_headers = array( $columns, $hidden, false );
		$per_page              = 20;
		$current_page          = $this->get_pagenum();
		$total_items           = $wpdb->get_var( "SELECT COUNT(*) FROM `" . $wpdb->base_prefix . "itsec_log` WHERE `log_type`='malware'" );

		$items = $itsec_logger->get_events( 'malware', array(), $per_page, ( ( $current_page - 1 ) * $per_page ), 'log_date' );

		$table_data = array();

		$count = 0;

		foreach ( $items as $item ) { //loop through and group 404s

			$log_data = maybe_unserialize( $item['log_data'] );

			$table_data[$count]['time'] = sanitize_text_field( $item['log_date'] );
			$table_data[$count]['host'] = sanitize_text_field( $item['log_host'] );

			if ( strlen( trim( sanitize_text_field( $item['log_username'] ) ) ) > 0 ) {

				$table_data[$count]['user'] = sanitize_text_field( $item['log_username'] );

			} elseif ( intval( $item['log_user'] ) > 0 && ITSEC_Lib::user_id_exists( $item['log_user'] ) ) {

				$user = get_user_by( 'id', $item['log_user'] );

				$table_data[$count]['user'] = $user->data->user_login;

			} else {

				$table_data[$count]['user'] = '';

			}

			$table_data[$count]['action'] = ( is_array( $log_data ) && isset( $log_data['type'] ) ) ? sanitize_text_field( $log_data['type'] ) : __( 'Malware Scan Report', 'it-l10n-ithemes-security-pro' );
			
			if ( is_wp_error( $log_data ) ) {
				$table_data[$count]['results'] = 'error';
				$table_data[$count]['data'] = $log_data;
			} else if ( isset( $log_data['SCAN']['SITE'] ) ) {
				// New log data from Sucuri scan.
				
				if (
					empty( $log_data['SYSTEM']['WARN'] ) &&
					empty( $log_data['MALWARE']['WARN'] ) &&
					empty( $log_data['BLACKLIST']['WARN'] )
				) {
					$table_data[$count]['results'] = 'clean';
				} else {
					$table_data[$count]['results'] = 'warn';
				}
				
				$table_data[$count]['data'] = $log_data;
			} else {
				// Legacy log data from VirusTotal scan.

				if ( isset( $log_data['resource'] ) ) {

					$table_data[$count]['report'] = array(
						'resource' => $log_data['resource'],
					);

				} else {

					$table_data[$count]['report'] = array();

				}

				if ( isset( $log_data['report'] ) ) {
					$table_data[$count]['report']['results'] = $log_data['report'];
				}

			}

			$table_data[$count]['count'] = $count;

			$count ++;

		}

//		usort( $table_data, array( $this, 'sortrows' ) );

		$this->items = $table_data;

		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
				'total_pages' => ceil( $total_items / $per_page )
			)
		);
	}

	/**
	 * Sorts rows by count in descending order
	 *
	 * @param array $a first array to compare
	 * @param array $b second array to compare
	 *
	 * @return int comparison result
	 */
	function sortrows( $a, $b ) {

		// If no sort, default to count
		$orderby = ( ! empty( $_GET['orderby'] ) ) ? esc_attr( $_GET['orderby'] ) : 'time';

		// If no order, default to desc
		$order = ( ! empty( $_GET['order'] ) ) ? esc_attr( $_GET['order'] ) : 'desc';

		if ( $orderby == 'count' ) {

			if ( intval( $a[$orderby] ) < intval( $b[$orderby] ) ) {
				$result = - 1;
			} elseif ( intval( $a[$orderby] ) === intval( $b[$orderby] ) ) {
				$result = 0;
			} else {
				$result = 1;
			}

		} else {

			// Determine sort order
			$result = strcmp( $a[$orderby], $b[$orderby] );

		}

		// Send final sort direction to usort
		return ( $order === 'asc' ) ? $result : - $result;

	}

}
