<?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 ( isset( $item['report'] ) ) {

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

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

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

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

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

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

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

					$content .= '<h3>' . __( 'Scan Details', 'it-l10n-better-wp-security' ) . '</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 ( isset( $item['report']['results']['positives'] ) ) {

			if ( $item['report']['results']['positives'] == 0 ) {
				$content = '<span style="color: green">' . __( 'Clean', 'it-l10n-better-wp-security' ) . '</span>';
			} else {
				$content = '<span style="color: red">' . __( 'Issues Detected', 'it-l10n-better-wp-security' ) . '</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-better-wp-security' ),
			'action'  => __( 'Action', 'it-l10n-better-wp-security' ),
			'results' => __( 'Results', 'it-l10n-better-wp-security' ),
			'user'    => __( 'User', 'it-l10n-better-wp-security' ),
			'details' => __( 'Details', 'it-l10n-better-wp-security' ),
		);

	}

	/**
	 * Define Sortable Columns
	 *
	 * @return array of column titles that can be sorted
	 */
	public function get_sortable_columns() {

		$order = ( empty( $_GET['order'] ) ) ? false : true;

		$sortable_columns = array(
			'user'   => array( 'user', $order ),
			'action' => array( 'action', $order ),
			'time'   => array( 'time', $order ),
		);

		return $sortable_columns;

	}

	/**
	 * Prepare data for table
	 *
	 * @return void
	 */
	public function prepare_items() {

		global $itsec_logger;

		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );

		$items = $itsec_logger->get_events( 'malware', array(), 10 );

		$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'] = isset( $log_data['type'] ) ? sanitize_text_field( $log_data['type'] ) : '';

			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' ) );

		$per_page     = 50; //20 items per page
		$current_page = $this->get_pagenum();
		$total_items  = count( $table_data );

		$table_data = array_slice( $table_data, ( ( $current_page - 1 ) * $per_page ), $per_page );

		$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;

	}

}