/home/arranoyd/eventrify/wp-content/plugins/exploit-scanner/exploit-scanner.php
<?php
/*
Plugin Name: Exploit Scanner
Plugin URI: https://wordpress.org/plugins/exploit-scanner/
Description: Scans your WordPress site for possible exploits.
Version: 1.5.2
Author: Automattic
Author URI: https://automattic.com/
*/

@ini_set( 'max_execution_time', 120 );

/**
 * Set up the menu item and register with hooks to print JS and help.
 */
function exploitscanner_menu() {
	$page_hook = add_management_page( 'Exploit Scanner', 'Exploit Scanner', 'manage_options', 'exploit-scanner', 'exploitscanner_admin_page' );
	if ( $page_hook ) {
		add_action( "admin_print_styles-$page_hook", 'add_thickbox' );
		add_action( "admin_footer-$page_hook", 'exploitscanner_admin_scripts' );
		add_action( "load-$page_hook", 'exploitscanner_help_tabs' );
	}
}
add_action( 'admin_menu', 'exploitscanner_menu' );

function exploitscanner_help_tabs() {
	$screen = get_current_screen();
	$screen->add_help_tab( array(
		'id' => 'interpreting-results',
		'title' => 'Interpreting the Results',
		'content' => '<p><strong>Interpreting the Results</strong></p>
<p>It is likely that this scanner will find false positives (i.e. files which do not contain malicious code). However, it is best to err
on the side of caution; if you are unsure then ask in the <a href="http://wordpress.org/support/" target="_blank">Support Forums</a>,
download a fresh copy of a plugin, search the Internet for similar situations, et cetera. You should be most concerned if the scanner is:
making matches around unknown external links; finding obfuscated text in modified core files or the <code>wp-config.php</code> file;
listing extra admin accounts; or finding content in posts which you did not put there.</p>
<p>Understanding the three different result levels:</p>
<ul>
    <li><strong>Severe:</strong> results that are often strong indicators of a hack (though they are not definitive proof)</li>
    <li><strong>Warning:</strong> these results are more commonly found in innocent circumstances than Severe matches, but they should still be treated with caution</li>
    <li><strong>Note:</strong> lowest priority, showing results that are very commonly used in legitimate code or notifications about events such as skipped files</li>
</ul>',
	) );

	$screen->add_help_tab( array(
		'id' => 'advice-for-the-owned',
		'title' => 'Help! I think I have been hacked!',
		'content' => '<p><strong>Help! I think I have been hacked!</strong></p>
<p>Follow the guides from the Codex:</p>
<ul>
    <li><a href="http://codex.wordpress.org/FAQ_My_site_was_hacked">Codex: FAQ - My site was hacked</a></li>
    <li><a href="http://codex.wordpress.org/Hardening_WordPress">Codex: Hardening WordPress</a></li>
</ul>
<p>Ensure that you change <strong>all</strong> of your WordPress related passwords (site, FTP, MySQL, etc.). A regular backup routine
(either manual or plugin powered) is extremely useful; if you ever find that your site has been hacked you can easily restore your site from
a clean backup and fresh set of files and, of course, use a new set of passwords.</p>',
	) );
}

/**
 * Print scripts that power paged scanning and diff modal.
 */
function exploitscanner_admin_scripts() { ?>
<script type="text/javascript">
	jQuery(document).ready(function($) {
		$('#run-scanner').click( function() {
			var fsl = $('#filesize_limit').val(),
				max = parseInt( $('#max_test_files').val(), 10 ),
				dis = ($('#display_pattern:checked').val() !== undefined);

			$.ajaxSetup({
				type: 'POST',
				url: ajaxurl,
				complete: function(xhr,status) {
					if ( status != 'success' ) {
						$('#scan-loader img').hide();
						$('#scan-loader span').html( 'An error occurred. Please try again later.' );
					}
				}
			});

			$('#scan-results').hide();
			$('#scan-loader').show();
			exploitscanner_file_scan(0, fsl, max, dis);
			return false;
		});

		$('#hide-skipped').toggle( function() {
			$('.skipped-file').hide();
			$(this).html('Show skipped files');
		}, function() {
			$('.skipped-file').show();
			$(this).html('Hide skipped files');
		});

		$('.view-diff').click( function() {
			// escaped ampersands returned by wp_nonce_url don't play nicely here
			var nonce = '_ajax_nonce=<?php echo wp_create_nonce( 'exploit-scanner_view_diff' ); ?>';
			tb_show( 'File changes', ajaxurl + '?action=exploit-scanner_view_diff&' + nonce + '&file=' + this.id, false );
			return false;
		});
	});

	var exploitscanner_nonce = '<?php echo wp_create_nonce( 'exploit-scanner_scan' ); ?>',
	exploitscanner_file_scan = function(s, fsl, max, dis) {
		jQuery.ajax({
			data: {
				action: 'exploit-scanner_file_scan',
				start: s,
				filesize_limit: fsl,
				max_batch_size: max,
				display_pattern: dis,
				_ajax_nonce: exploitscanner_nonce
			}, success: function(r) {
				var res = jQuery.parseJSON(r);
				if ( 'running' == res.status ) {
					jQuery('#scan-loader span').html(res.data);
					exploitscanner_file_scan(s+max, fsl, max, dis);
				} else if ( 'error' == res.status ) {
					// console.log( r );
					jQuery('#scan-loader img').hide();
					jQuery('#scan-loader span').html(
						'An error occurred: <pre style="overflow:auto">' + r.toString() + '</pre>'
					);
				} else {
					exploitscanner_db_scan();
				}
			}
		});
	}, exploitscanner_db_scan = function() {
		jQuery('#scan-loader span').html('Scanning database...');
		jQuery.ajax({
			data: {
				action: 'exploit-scanner_db_scan',
				_ajax_nonce: exploitscanner_nonce
			}, success: function(r) {
				jQuery('#scan-loader img').hide();
				jQuery('#scan-loader span').html('Scan complete. Refresh the page to view the results.');
				window.location.reload(false);
			}
		});
	};
</script>
<?php
}

/**
 * add_management_page callback
 */
function exploitscanner_admin_page() {
	// non-ajax scan form processing
	if ( isset($_POST['action']) && 'scan' == $_POST['action'] ) {
		check_admin_referer( 'exploitscanner-scan_all' );

		$fsl = ( ! isset($_POST['filesize_limit']) || ! is_numeric($_POST['filesize_limit']) ) ? 400 : (int) $_POST['filesize_limit'];
		$dis = isset( $_POST['display_pattern'] );

		$scanner = new File_Exploit_Scanner( ABSPATH, array( 'start' => 0, 'fsl' => $fsl, 'display_pattern' => $dis ) );
		$scanner->run();
		$scanner = new DB_Exploit_Scanner();
		$scanner->run();
	}

	echo '<div class="wrap">';
	echo '<h2>Exploit Scanner</h2>';

	if ( isset($_GET['view']) && 'diff' == $_GET['view'] )
		exploitscanner_diff_page();
	elseif ( isset( $_GET['action'] ) && 'fix' == $_GET['action'] )
		exploitscanner_fix_vulnerability_page();
	else
		exploitscanner_results_page();

	echo '</div>';
}

/**
 * Display scan initiation form and any stored results.
 */
function exploitscanner_results_page() {
	global $wp_version;
	delete_transient( 'exploitscanner_results_trans' );
	delete_transient( 'exploitscanner_files' );
	$results = get_option( 'exploitscanner_results' );
?>
	<p>This script searches through your WordPress install for signs that may indicate that your website has been compromised by hackers. It does <strong>NOT</strong> remove anything, this is left for the user to do.</p>
	<form action="<?php admin_url( 'tools.php?page=exploit-scanner' ); ?>" method="post">
		<?php wp_nonce_field( 'exploitscanner-scan_all' ); ?>
		<input type="hidden" name="action" value="scan" />
		<table class="form-table">
			<tr>
				<th scope="row"><label for="display_pattern">Search for suspicious styles:</label></th>
				<td><input type="checkbox" id="display_pattern" name="display_pattern" checked="checked" value="1" /> <span class="description">(<code>display:none</code> and <code>visibility:hidden</code> can be used to hide spam, but may cause many false positives)</span></td>
			</tr>
			<tr>
				<th scope="row"><label for="filesize_limit">Upper file size limit:</label></th>
				<td><input type="text" size="3" id="filesize_limit" name="filesize_limit" value="400" />KB <span class="description">(files larger than this are skipped and will be listed at the end of scan)</span></td>
			</tr>
			<tr class="hide-if-no-js">
				<th scope="row"><label for="max_test_files">Number of files per batch:</label></th>
				<td>
					<select id="max_test_files" name="max_test_files">
						<option value="100">100</option>
						<option value="150">150</option>
						<option value="250" selected="selected">250</option>
						<option value="500">500</option>
						<option value="1000">1000</option>
					</select>
					<span class="description">(to help reduce memory limit errors the scan processes a series of file batches)</span>
				</td>
			</tr>
		</table>
		<p class="submit"><input type="submit" id="run-scanner" class="button-primary" value="Run the Scan" /></p>
	</form>

	<div id="scan-loader" style="display:none;margin:10px;padding:10px;background:#f7f7f7;border:1px solid #c6c6c6;text-align:center">
		<p><strong>Searching your filesystem and database for possible exploit code</strong></p>
		<p><span style="margin-right:5px">Files scanned: 0...</span><img src="<?php echo plugins_url( 'loader.gif', __FILE__ ); ?>" height="16px" width="16px" alt="loading-icon" /></p>
	</div>

	<div id="scan-results">
	<?php if ( ! $results ) : ?>
		<h3>Results</h3><p>Nothing found.</p>
	<?php else : exploitscanner_show_results( $results ); endif; ?>
	</div>

	<h3>General Information</h3>
	<?php echo exploitscanner_list_admins(); ?>

	<h4>DISCLAIMER</h4>
	<p>Unfortunately it's impossible to catch every hack and it's all too easy to catch false positives (show a file as suspicious when in reality it is clean). If you have been hacked, this script may help you track down what files, comments or posts have been modified. On the other hand, if this script indicates your blog is clean, don't believe it. This is far from foolproof.</p>

	<p><strong>For the paranoid...</strong><br />
	To prevent someone hiding malicious code inside this plugin and to check that the signatures file hasn't been changed, here are the MD5 and SHA1 hashes of these files. Compare them with the references on the plugin homepage. You'll get extra points if you check this file has the actual md5_file() and sha1_file() calls.</p>
	<p style="text-align: center">MD5 of exploit-scanner.php: <code><?php echo md5_file( __FILE__ ); ?></code></p>
	<p style="text-align: center">SHA1 of exploit-scanner.php: <code><?php echo sha1_file( __FILE__ ); ?></code></p>
	<?php if ( file_exists( dirname( __FILE__ ) . '/hashes-' . $wp_version . '.php' ) ) : ?>
		<p style="text-align: center">MD5 of hashes-<?php echo $wp_version; ?>.php: <code><?php echo md5_file( dirname( __FILE__ ) . '/hashes-' . $wp_version . '.php' ); ?></code></p>
		<p style="text-align: center">SHA1 of hashes-<?php echo $wp_version; ?>.php: <code><?php echo sha1_file( dirname( __FILE__ ) . '/hashes-' . $wp_version . '.php' ); ?></code></p>
	<?php endif;
}

/**
 * Display table of results.
 */
function exploitscanner_show_results( $results ) {
	if ( ! is_array($results) ) {
		echo 'Unfortunately the results appear to be malformed/corrupted. Try scanning again.';
		return;
	}

	$result = '<h3>Results</h3>';

	foreach ( array('severe','warning','note') as $l ) {
		if ( ! empty($results[$l]) ) {
			if ( $l == 'note' ) $result .= '<div style="float:right;font-size:11px;margin-top:1.3em"><a href="#" id="hide-skipped" class="hide-if-no-js">Hide skipped files</a></div>';
			$result .= '<h4>Level ' . ucwords($l) . ' (' . count($results[$l]) . ' matches)</h4>';
			$result .= '<table class="widefat fixed">
			<thead>
			<tr>
				<th scope="col" style="width:50%">Location / Description</th>
				<th scope="col">What was matched</th>
			</tr>
			</thead>
			<tbody>';

			foreach ( $results[$l] as $r )
				$result .= exploitscanner_draw_row( $r );

			$result .= '</tbody></table>';
		}
	}

	echo $result;
}

/**
 * Draw a single result row.
 */
function exploitscanner_draw_row( $r ) {
	$class = ( ! empty($r['class']) ) ? ' class="'.$r['class'].'"' : '';

	$html = '<tr' . $class . '><td><strong>' . esc_html( $r['loc'] );

	if ( ! empty($r['line_no']) )
		$html .= ':' . $r['line_no'] . '</strong>';
	elseif ( ! empty($r['post_id']) )
		$html .= '</strong> <a href="' . get_edit_post_link($r['post_id']) . '" title="Edit this item">Edit</a>';
	elseif ( ! empty($r['comment_id']) )
		$html .= '</strong> <a href="' . admin_url( "comment.php?action=editcomment&amp;c={$r['comment_id']}" ) . '" title="Edit this comment">Edit</a>';
	else
		$html .= '</strong>';

	$html .= '<br />'.$r['desc'].'</td><td>';

	if ( ! empty($r['line']) ) {
		$html .= '<code>' . exploitscanner_hilight( esc_html($r['line']) ) . '</code>';
	} else if ( 'Modified core file' == $r['desc'] ) {
		$url = add_query_arg( array( 'view' => 'diff', 'file' => $r['loc'] ), menu_page_url( 'exploit-scanner', false ) );
		$url = wp_nonce_url( $url, 'exploit-scanner_view_diff' );
		$html .= '<a href="'.$url.'" id="'.esc_attr($r['loc']).'" class="view-diff">See what has been modified</a>';
	} else if ( ! empty( $r['vuln'] ) ) {
		$url = add_query_arg( array( 'action' => 'fix', 'vulnerability' => $r['vuln'], 'file' => $r['loc'] ), menu_page_url( 'exploit-scanner', false ) );
		$url = wp_nonce_url( $url, 'exploit-scanner_fix_' . $r['vuln'] . '_' . $r['loc'] );
		$html .= '<a href="'. esc_url( $url ) .'">Fix now</a>';
	}

	return $html . '</td></tr>';
}

/**
 * Display the modifications made to a core file.
 */
function exploitscanner_diff_page() {
	if ( ! current_user_can( 'manage_options' ) )
		die('-1');

	check_ajax_referer( 'exploit-scanner_view_diff' );

	$file = $_GET['file'];
	echo '<h3>Changes made to ' . esc_html($file) . '</h3>';
	echo exploitscanner_display_file_diff( $file );

	// exit if this was AJAX
	if ( isset($_GET['_ajax_nonce']) )
		exit;
	// otherwise display return link
	else
		echo '<p><a href="' . menu_page_url('exploit-scanner',false) . '">Go back.</a></p>';
}
add_action( 'wp_ajax_exploit-scanner_view_diff', 'exploitscanner_diff_page' );

/**
 * Generate the diff of a modified core file.
 */
function exploitscanner_display_file_diff( $file ) {
	global $wp_version;

	// core file names have a limited character set
	$file = preg_replace( '#[^a-zA-Z0-9/_.-]#', '', $file );
	if ( empty( $file ) || ! is_file( ABSPATH . $file ) )
		return '<p>Sorry, an error occured. This file might not exist!</p>';

	$key = $wp_version . '-' . $file;
	$cache = get_option( 'exploitscanner_diff_cache' );
	if ( ! $cache || ! is_array($cache) || ! isset($cache[$key]) ) {
		$url = "http://core.svn.wordpress.org/tags/$wp_version/$file";
		$response = wp_remote_get( $url );
		if ( is_wp_error( $response ) || 200 != $response['response']['code'] )
			return '<p>Sorry, an error occured. Please try again later.</p>';

		$clean = $response['body'];

		if ( is_array($cache) ) {
			if ( count($cache) > 4 ) array_shift( $cache );
			$cache[$key] = $clean;
		} else {
			$cache = array( $key => $clean );
		}
		update_option( 'exploitscanner_diff_cache', $cache );
	} else {
		$clean = $cache[$key];
	}

	$modified = file_get_contents( ABSPATH . $file );

	$text_diff = new Text_Diff( explode( "\n", $clean ), explode( "\n", $modified ) );
	$renderer = new ES_Text_Diff_Renderer();
	$diff = $renderer->render( $text_diff );

	$r  = "<table class='diff'>\n<col style='width:5px' /><col />\n";
	$r .= "<tbody>\n$diff\n</tbody>\n";
	$r .= "</table>";
	return $r;
}

function exploitscanner_fix_vulnerability_page() {
	if ( ! current_user_can( 'edit_plugins' ) )
		wp_die( 'You do not have sufficient permissions to perform this action.' );

	if ( ! in_array( $_GET['vulnerability'], array( 'timthumb' ) ) )
		wp_die( 'Unknown action.' );

	if ( validate_file( $_GET['file'] ) || ! is_file( ABSPATH . $_GET['file'] ) )
		wp_die( 'Invalid file.' );

	if ( ! File_Exploit_Scanner::is_vulnerable_file( $_GET['file'], ABSPATH ) )
		wp_die( 'Invalid file.' );

	check_admin_referer( 'exploit-scanner_fix_' . $_GET['vulnerability'] . '_' . $_GET['file'] );

	if ( $_GET['vulnerability'] == 'timthumb' ) {
		echo '<h3>Fixing TimThumb vulnerability</h3>';
		$contents = file_get_contents( ABSPATH . $_GET['file'] );
		$fix = '
		// Exploit Scanner security fix
		if ( ! defined( "ALLOW_EXTERNAL" ) || ! ALLOW_EXTERNAL ) {
			$isAllowedSite = false;
			foreach ( $allowedSites as $site ) {
				if ( preg_match (\'/(?:^|\.)\' . preg_quote( $site ) . \'$/i\', $url_info[\'host\'] ) )
					$isAllowedSite = true;
			}
		}
		// End fix
		if ($isAllowedSite) {
		';
		$contents = str_replace( 'if ($isAllowedSite) {', $fix, $contents );
		if ( file_put_contents( ABSPATH . $_GET['file'], $contents ) ) {
			echo '<p>This instance of TimThumb has had a security fix applied. It is recommended that you download the latest version of TimThumb and completely replace this file.</p>';
		} else {
			echo '<p>An error occurred. It was not possible to apply a fix to this file. It is recommended that you download the latest version of TimThumb and completely replace this file.</p>';
		}
	}

	echo '<p>The vulnerability will still show in your scan results until you run another scan.</p>';
	echo '<p><a href="' . menu_page_url('exploit-scanner',false) . '">Go back.</a></p>';
}

/**
 * AJAX callback to initiate a file scan.
 */
function exploitscanner_ajax_file_scan() {
	check_ajax_referer( 'exploit-scanner_scan' );

	if ( ! isset($_POST['start']) )
		die( json_encode( array( 'status' => 'error', 'data' => 'Error: start not set.' ) ) );
	else
		$start = (int) $_POST['start'];

	$fsl = ( ! isset($_POST['filesize_limit']) || ! is_numeric($_POST['filesize_limit']) ) ? 400 : (int) $_POST['filesize_limit'];
	$max = ( ! isset($_POST['max_batch_size']) || ! is_numeric($_POST['max_batch_size']) ) ? 100 : (int) $_POST['max_batch_size'];
	$display_pattern = ( $_POST['display_pattern'] != 'false' ) ? true : false;

	$args = compact( 'start', 'fsl', 'max', 'display_pattern' );

	$scanner = new File_Exploit_Scanner( ABSPATH, $args );
	$result = $scanner->run();
	if ( is_wp_error($result) ) {
		$message = $result->get_error_message();
		$data = $result->get_error_data();
		echo json_encode( array( 'status' => 'error', 'message' => $message, 'data' => $data ) );
	} else if ( $result ) {
		echo json_encode( array( 'status' => 'complete' ) );
	} else {
		echo json_encode( array( 'status' => 'running', 'data' => 'Files scanned: ' . ($start+$max) . '...' ) );
	}

	exit;
}
add_action( 'wp_ajax_exploit-scanner_file_scan', 'exploitscanner_ajax_file_scan' );

/**
 * AJAX callback to initiate a database scan.
 */
function exploitscanner_ajax_db_scan() {
	check_ajax_referer( 'exploit-scanner_scan' );

	$scanner = new DB_Exploit_Scanner();
	$scanner->run();

	echo 'Done';
	exit;
}
add_action( 'wp_ajax_exploit-scanner_db_scan', 'exploitscanner_ajax_db_scan' );

/**
 * Display a list of users with administrator capabilities.
 */
function exploitscanner_list_admins() {
	global $wpdb;

	if ( method_exists( $wpdb, 'get_blog_prefix' ) )
		$level_key = $wpdb->get_blog_prefix() . 'capabilities';
	else
		$level_key = $wpdb->prefix . 'capabilities';

	$user_ids = $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value LIKE %s", $level_key, '%administrator%') );

	ob_start();
	?>
	<h4>Users with admin privileges</h4>
	<table class="widefat">
		<thead>
			<tr>
				<th scope="col" style="width: 5%">ID</th>
				<th scope="col">Username</th>
				<th scope="col">Name</th>
				<th scope="col">Email</th>
			</tr>
		</thead>
		<tbody>
	<?php
	foreach ( $user_ids as $id ) {
		$user = get_userdata( $id );
		echo '<tr><td>' . intval($user->ID) . '</td><td>' . esc_html($user->user_login) . '</td><td>';
		if ( isset( $user->first_name ) ) echo esc_html($user->first_name) . ' ';
		if ( isset( $user->last_name ) ) echo esc_html($user->last_name);
		echo '</td><td>' . esc_html($user->user_email) . '</td></tr>';
	} ?>
		</tbody>
	</table>
	<?php
	$admin_table = ob_get_clean();
	return $admin_table;
}

/**
 * Insert highlighted <span> tags around content matched by a scan.
 */
function exploitscanner_hilight( $text ) {
	if ( strlen( $text ) > 200 ) {
		$start = strpos( $text, '$#$#' ) - 50;
		if ( $start < 0 )
			$start = 0;
		$end = strrpos( $text, '#$#$' ) + 50;
		$text = substr( $text, $start, $end - $start + 1 );
	}

	return str_replace( array('$#$#','#$#$'), array('<span style="background:#ff0">','</span>'), $text );
}

/**
 * Activation callback.
 *
 * Add database version info. Set up non-autoloaded options as there is no need
 * to load results or clean core files on any page other than the exploit scanner page.
 */
function exploitscanner_activate() {
	add_option( 'exploitscanner', 1 );
	add_option( 'exploitscanner_results', 0, '', 'no' );
	add_option( 'exploitscanner_diff_cache', 0, '', 'no' );
	register_uninstall_hook( __FILE__, 'exploitscanner_uninstall' );
}
register_activation_hook( __FILE__, 'exploitscanner_activate' );

/**
 * Deactivation callback. Remove transients.
 */
function exploitscanner_deactivate() {
	delete_transient( 'exploitscanner_results_trans' );
	delete_transient( 'exploitscanner_files' );
}
register_deactivation_hook( __FILE__, 'exploitscanner_deactivate' );

/**
 * Uninstall callback. Remove all data stored by the plugin.
 */
function exploitscanner_uninstall() {
	delete_option( 'exploitscanner' );
	delete_option( 'exploitscanner_results' );
	delete_option( 'exploitscanner_diff_cache' );
}

/**
 * Update routine to perform database cleanup and to ensure that newly
 * introduced settings and defaults are enforced.
 */
function exploitscanner_update() {
	$db_version = 1;
	$local_version = get_option( 'exploitscanner' );
	if ( false === $local_version || $local_version < $db_version ) {
		$count = get_option( 'exploit_scanner_result_count' );
		if ( $count ) {
			$opts = array('exploit_scanner_result_count','exploit_scanner_file_count','exploit_scanner_other','exploit_scanner_wp-admin','exploit_scanner_wp-content','exploit_scanner_wp-includes');
			foreach ( $opts as $opt )
				delete_option( $opt );

			for( $i = 0; $i < $count; $i++ )
				delete_option( 'exploit_scanner_results_' . $i );
		}
		delete_option( 'exploitscanner_results' );
		exploitscanner_activate();
	}
}
add_action( 'admin_init', 'exploitscanner_update' );

/**
 * Exploit Scanner base class. Scanners should extend this.
 */
class Exploit_Scanner {
	var $results;

	function __construct() {}

	function add_result( $level, $info ) {
		$this->results[$level][] = $info;
	}

	function store_results( $done = false ) {
		$stored = get_transient( 'exploitscanner_results_trans' );

		if ( empty($this->results) ) {
			if ( $done )
				update_option( 'exploitscanner_results', $stored );
			return;
		}

		if ( $stored && is_array($stored) )
			$this->results = array_merge_recursive( $stored, $this->results );

		if ( $done ) {
			update_option( 'exploitscanner_results', $this->results );
			delete_transient( 'exploitscanner_results_trans' );
		} else {
			set_transient( 'exploitscanner_results_trans', $this->results );
		}
	}
}

/**
 * File Scanner. Scans all files in given path for suspicious text.
 */
class File_Exploit_Scanner extends Exploit_Scanner {
	var $path;
	var $start;
	var $filesize_limit;
	var $max_batch_size;
	var $paged = true;
	var $files = array();
	var $modified_files = array();
	var $skip;
	var $complete = false;
	var $suspicious_patterns = array(
		'/(\$wpdb->|mysql_).+DROP/siU' => array( 'level' => 'note', 'desc' => 'Possible database table deletion' ),

		'/(echo|print|<\?=).+(\$GLOBALS|\$_SERVER|\$_GET|\$_REQUEST|\$_POST)/siU' => array( 'level' => 'note', 'desc' => 'Possible output of restricted variables' ),

		'/ShellBOT/i' => array( 'level' => 'severe', 'desc' => 'This may be a script used by hackers to get control of your server' ),
		'/uname -a/i' => array( 'level' => 'severe', 'desc' => 'Tells a hacker what operating system your server is running' ),
		'/YW55cmVzdWx0cy5uZXQ=/i' => array( 'level' => 'severe', 'desc' => 'base64 encoded text found in Search Engine Redirect hack <a href="http://blogbuildingu.com/wordpress/wordpress-search-engine-redirect-hack">[1]</a>' ),
		'/[^\w]eval\s*\(/i' => array( 'level' => 'severe', 'desc' => 'Often used to execute malicious code' ),
		'/\$_COOKIE\[\'yahg\'\]/i' => array( 'level' => 'severe', 'desc' => 'YAHG Googlerank.info exploit code' ),
		'/ekibastos/i' => array( 'level' => 'severe', 'desc' => 'Possible Ekibastos attack <a href="http://ocaoimh.ie/did-your-wordpress-site-get-hacked/">[1]</a>' ),
		'/base64_decode\s*\(/i' => array( 'level' => 'severe', 'desc' => 'Used by malicious scripts to decode previously obscured data/programs' ),
		'/<script>\/\*(GNU GPL|LGPL)\*\/ try\{window.onload.+catch\(e\) \{\}<\/script>/siU' => array( 'level' => 'severe', 'desc' => 'Possible "Gumblar" JavaScript attack <a href="http://threatinfo.trendmicro.com/vinfo/articles/securityarticles.asp?xmlfile=042710-GUMBLAR.xml">[1]</a> <a href="http://justcoded.com/article/gumblar-family-virus-removal-tool/">[2]</a>' ),
		'/php \$[a-zA-Z]*=\'as\';/i' => array( 'level' => 'severe', 'desc' => 'Symptom of the "Pharma Hack" <a href="http://blog.sucuri.net/2010/07/understanding-and-cleaning-the-pharma-hack-on-wordpress.html">[1]</a>' ),
		'/defined?\(\'wp_class_support/i' => array( 'level' => 'severe', 'desc' => 'Symptom of the "Pharma Hack" <a href="http://blog.sucuri.net/2010/07/understanding-and-cleaning-the-pharma-hack-on-wordpress.html">[1]</a>' ),
		'/str_rot13/i' => array( 'level' => 'severe', 'desc' => 'Decodes/encodes text using ROT13. Could be used to hide malicious code.' ),
		'/uudecode/i' => array( 'level' => 'severe', 'desc' => 'Decodes text using uuencoding. Could be used to hide malicious code.' ),
		//'/[^_]unescape/i' => array( 'level' => 'severe', 'desc' => 'JavaScript function to decode encoded text. Could be used to hide malicious code.' ),
		'/<!--[A-Za-z0-9]+--><\?php/i' => array( 'level' => 'warning', 'desc' => 'Symptom of a link injection attack <a href="http://www.kyle-brady.com/2009/11/07/wordpress-mediatemple-and-an-injection-attack/">[1]</a>' ),
		'/<iframe/i' => array( 'level' => 'warning', 'desc' => 'iframes are sometimes used to load unwanted adverts and code on your site' ),
		'/String\.fromCharCode/i' => array( 'level' => 'warning', 'desc' => 'JavaScript sometimes used to hide suspicious code' ),
		'/preg_replace\s*\(\s*(["\'])(.).*(?<!\\\\)(?>\\\\\\\\)*\\2([a-z]|\\\x[0-9]{2})*(e|\\\x65)([a-z]|\\\x[0-9]{2})*\\1/si' => array( 'level' => 'warning', 'desc' => 'The e modifier in preg_replace can be used to execute malicious code' ),
	);

	function __construct( $path, $args ) {
		$this->path = $path;

		if ( ! empty($args['max']) )
			$this->max_batch_size = $args['max'];
		else
			$this->paged = false;

		if ( $args['display_pattern'] ) {
			$this->suspicious_patterns['/visibility: ?hidden/i'] = array( 'level' => 'note', 'desc' => 'CSS style used to hide parts of a web page (often used legitimately)' );
			$this->suspicious_patterns['/display: ?none/i'] = array( 'level' => 'note', 'desc' => 'CSS style used to hide parts of a web page (often used legitimately)' );
		}

		$this->start = $args['start'];
		$this->filesize_limit = $args['fsl'];
		$this->skip = ltrim( str_replace( array( untrailingslashit( ABSPATH ), '\\' ), array( '', '/' ), __FILE__ ), '/' );
	}

	function File_Exploit_Scanner( $path, $args ) {
		$this->__construct( $path, $args );
	}

	function run() {
		$this->get_files( $this->start );
		$this->file_pattern_scan();
		$this->store_results();
		return $this->complete;
	}

	function get_files( $s ) {
		global $wp_version;

		if ( 0 == $s ) {
			unset( $filehashes );
			$hashes = dirname(__FILE__) . '/hashes-'. $wp_version .'.php';
			if ( file_exists( $hashes ) )
				include( $hashes );
			else
				$this->add_result( 'severe', array(
					'loc' => 'hashes-'. $wp_version .'.php missing',
					'desc' => 'The file containing hashes of all WordPress core files appears to be missing; modified core files will no longer be detected and a lot more suspicious strings will be detected'
				) );

			$this->recurse_directory( $this->path );

			foreach( $this->files as $k => $file ) {
				// don't scan unmodified core files
				if ( isset( $filehashes[$file] ) ) {
					if ( $filehashes[$file] == md5_file( $this->path.'/'.$file ) ) {
						unset( $this->files[$k] );
						continue;
					} else {
						$this->add_result( 'warning', array(
							'loc' => $file,
							'desc' => 'Modified core file'
						) );
					}
				} else {
					list( $dir ) = explode( '/', $file );
					if ( $dir == 'wp-includes' || $dir == 'wp-admin' ) {
						$severity = substr( $file, -4 ) == '.php' ? 'severe' : 'warning';
						$this->add_result( $severity, array(
							'loc' => $file,
							'desc' => 'Unknown file found in wp-includes/ or wp-admin/ directory.'
						) );
					}
				}

				// detect old export files
				if ( substr( $file, -9 ) == '.xml_.txt' ) {
					$this->add_result( 'warning', array(
						'loc' => $file,
						'desc' => 'It is likely that this is an old export file. If so it is recommended that you delete this file to stop it from exposing potentially private information.'
					) );
				}

				$vulnerable_file = $this->is_vulnerable_file( $file, $this->path . '/' );
				if ( $vulnerable_file ) {
					$this->add_result( 'severe', array(
						'loc' => $file,
						'desc' => $vulnerable_file['desc'],
						'vuln' => $vulnerable_file['vuln']
					) );
				}

				// don't scan files larger than given limit
				if ( filesize($this->path . $file) > ($this->filesize_limit * 1024) ) {
					unset( $this->files[$k] );
					$this->add_result( 'note', array(
						'loc' => $file,
						'desc' => 'File skipped due to size',
						'class' => 'skipped-file'
					) );
				}
			}

			$this->files = array_values( $this->files );
			$result = set_transient( 'exploitscanner_files', $this->files, 3600 );

			if ( ! $result ) {
				$this->paged = false;
				$data = array( 'files' => esc_html( serialize( $this->files ) ) );
				if ( ! empty($GLOBALS['EZSQL_ERROR']) )
					$data['db_error'] = $GLOBALS['EZSQL_ERROR'];
				$this->complete = new WP_Error( 'failed_transient', '$this->files was not properly saved as a transient', $data );
			}
		} else {
			$this->files = get_transient( 'exploitscanner_files' );
		}

		if ( ! is_array( $this->files ) ) {
			$data = array(
				'start' => $s,
				'files' => esc_html( serialize( $this->files ) ),
			);

			if ( ! empty( $GLOBALS['EZSQL_ERROR'] ) )
				$data['db_error'] = $GLOBALS['EZSQL_ERROR'];

			$this->complete = new WP_Error( 'no_files_array', '$this->files was not an array', $data );
			$this->files = array();
			return;
		}

		// use files list to get a batch if paged
		if ( $this->paged && (count($this->files) - $s) > $this->max_batch_size ) {
			$this->files = array_slice( $this->files, $s, $this->max_batch_size );
		} else {
			$this->files = array_slice( $this->files, $s );
			if ( ! is_wp_error( $this->complete ) )
				$this->complete = true;
		}
	}

	function recurse_directory( $dir ) {
		if ( $handle = @opendir( $dir ) ) {
			while ( false !== ( $file = readdir( $handle ) ) ) {
				if ( $file != '.' && $file != '..' ) {
					$file = $dir . '/' . $file;
					if ( is_dir( $file ) ) {
						$this->recurse_directory( $file );
					} elseif ( is_file( $file ) ) {
						$this->files[] = str_replace( $this->path.'/', '', $file );
					}
				}
			}
			closedir( $handle );
		}
	}

	function file_pattern_scan() {
		foreach ( $this->files as $file ) {
			if ( $file != $this->skip ) {
				$contents = file( $this->path . $file );
				foreach ( $contents as $n => $line ) {
					foreach ( $this->suspicious_patterns as $pattern => $p ) {
						$test = preg_replace_callback( $pattern, array( &$this, 'replace' ), $line );
						if ( $line !== $test ) {
							$test = trim( $test );

							$start = strpos( $test, '$#$#' ) - 50;
							if ( $start < 0 )
								$start = 0;

							$append = '';
							$end = strrpos( $test, '#$#$' );
							// if the text to display is longer than 150 characters truncate it
							if ( ( $end - $start ) > 150 ) {
								$end = $start + 150;
								$append = '#$#$ [line truncated]';
							} else {
								$end += 50;
							}

							$test = substr( $test, $start, $end - $start + 1 ) . $append;

							$this->add_result( $p['level'], array(
								'loc' => $file,
								'line' => esc_html( $test ),
								'line_no' => $n+1,
								'desc' => $p['desc']
							) );
						}
					}
				}
			}
		}
	}

	function replace( $matches ) {
		return '$#$#' . $matches[0] . '#$#$';
	}

	function is_vulnerable_file( $file, $path ) {
		$timthumb = array( 'timthumb.php', 'thumb.php', 'thumbs.php', 'thumbnail.php', 'thumbnails.php', 'thumnails.php', 'cropper.php', 'picsize.php', 'resizer.php' );
		if ( in_array( strtolower( basename( $file ) ), $timthumb ) ) {
			$contents = file_get_contents( $path . $file );
			if (
				false !== strpos( $contents, 'TimThumb' ) &&
				false !== strpos( $contents, '$allowedSites' ) &&
				false === strpos( $contents, 'Exploit Scanner security fix' ) &&
				false === strpos( $contents, 'VaultPress HotFix' )
			) {
				$version = 'unknown';
				if ( preg_match( "/define\s*\([\\'\"]VERSION[\\'\"]\s*,\s*[\\'\"](.*)[\\'\"]/", $contents, $matches ) )
					$version = $matches[1];

				if ( 'unknown' == $version || version_compare( $version, '1.34', '<' ) )
					return array(
						'desc' => sprintf( 'You are using an old version (%s) of TimThumb. This could allow attackers to take control of your site.', esc_html( $version ) ),
						'vuln' => 'timthumb'
					);
			}
		}

		return false;
	}
}

/**
 * Database Scanner. Scans WordPress database for suspicious post/comment text and plugins.
 */
class DB_Exploit_Scanner extends Exploit_Scanner {
	var $suspicious_text = array(
		'eval(' => array( 'level' => 'severe', 'desc' => 'Often used by hackers to execute malicious code' ),
		'<script' => array( 'level' => 'severe', 'desc' => 'JavaScript hidden in the database is normally a sign of a hack' ),
	);

	var $suspicious_post_text = array(
		'<iframe' => array( 'level' => 'warning', 'desc' => 'iframes are sometimes used to load unwanted adverts and code on your site' ),
		'<noscript' => array( 'level' => 'warning', 'desc' => 'Could be used to hide spam in posts/comments' ),
		'display:' => array( 'level' => 'warning', 'desc' => 'Could be used to hide spam in posts/comments' ),
		'visibility:' => array( 'level' => 'warning', 'desc' => 'Could be used to hide spam in posts/comments' ),
		'<script' => array( 'level' => 'severe', 'desc' => 'Malicious scripts loaded in posts by hackers perform redirects, inject spam, etc.' ),
	);

	function __construct() {}

	function DB_Exploit_Scanner() {
		$this->__construct();
	}

	function run() {
		$this->scan_posts();
		$this->scan_plugins();
		$this->store_results(true);
	}

	function replace( $content, $text ) {
		$s = strpos( $content, $text ) - 25;
		if ( $s < 0 ) $s = 0;

		$content = preg_replace( '/('.$text.')/', '$#$#\1#$#$', $content );
		$content = substr( $content, $s, 150 );
		return $content;
	}

	function scan_posts() {
		global $wpdb;

		foreach ( $this->suspicious_post_text as $text => $info ) {
			$posts = $wpdb->get_results( "SELECT ID, post_title, post_content FROM {$wpdb->posts} WHERE post_type<>'revision' AND post_content LIKE '%{$text}%'" );
			if ( $posts )
				foreach ( $posts as $post ) {
					$content = $this->replace( $post->post_content, $text );

					$this->add_result( $info['level'], array(
						'loc' => 'Post: ' . esc_html($post->post_title),
						'line' => esc_html($content),
						'post_id' => $post->ID,
						'desc' => $info['desc']
					) );
				}

			$comments = $wpdb->get_results( "SELECT comment_ID, comment_author, comment_content FROM {$wpdb->comments} WHERE comment_content LIKE '%{$text}%'" );
			if ( $comments )
				foreach ( $comments as $comment ) {
					$content = $this->replace( $comment->comment_content, $text );

					$this->add_result( $info['level'], array(
						'loc' => 'Comment by ' . esc_html($comment->comment_author),
						'line' => esc_html($content),
						'comment_id' => $comment->comment_ID,
						'desc' => $info['desc']
					) );
				}
		}
	}

	function scan_plugins() {
		$active_plugins = get_option( 'active_plugins' );
		if ( ! empty( $active_plugins ) && is_array( $active_plugins ) ) {
			foreach ( $active_plugins as $plugin ) {
				if ( strpos( $plugin, '..' ) !== false || substr( $plugin, -4 ) != '.php' ) {
					if ( $plugin == '' )
						$desc = 'Blank entry found. Should be removed. It will look like \'i:0;s:0:\"\";\' in the active_records field.';
					else
						$desc = 'Active plugin with a suspicious name.';

					$this->add_result( 'severe', array(
						'loc' => 'Plugin: ' . esc_html( $plugin ),
						'desc' => $desc
					) );
				}
			}
		}
	}
}

include_once( ABSPATH . WPINC . '/wp-diff.php' );

if ( class_exists( 'Text_Diff_Renderer' ) ) :
class ES_Text_Diff_Renderer extends Text_Diff_Renderer {
	function ES_Text_Diff_Renderer() {
		parent::Text_Diff_Renderer();
	}

	function _startBlock( $header ) {
		return "<tr><td></td><td><code>$header</code></td></tr>\n";
	}

	function _es_lines( $lines, $prefix, $class ) {
		$r = '';
		foreach ( $lines as $line ) {
			$line = esc_html( $line );
			$r .= "<tr><td>{$prefix}</td><td class='{$class}'>{$line}</td></tr>\n";
		}
		return $r;
	}

	function _added( $lines ) {
		return $this->_es_lines( $lines, '+', 'diff-addedline' );
	}

	function _deleted( $lines ) {
		return $this->_es_lines( $lines, '-', 'diff-deletedline' );
	}

	function _context( $lines ) {
		return $this->_es_lines( $lines, '', 'diff-context' );
	}

	function _changed( $orig, $final ) {
		return $this->_deleted( $orig ) . $this->_added( $final );
	}
}
endif;

function exploit_scanner_plugin_actions( $links, $file ) {
 	if( $file == 'exploit-scanner/exploit-scanner.php' && function_exists( "admin_url" ) ) {
		$settings_link = '<a href="' . admin_url( 'tools.php?page=exploit-scanner' ) . '">' . __('Scanner Settings') . '</a>';
		array_unshift( $links, $settings_link ); // before other links
	}
	return $links;
}
add_filter( 'plugin_action_links', 'exploit_scanner_plugin_actions', 10, 2 );