<?php
/*
Plugin Name: DCaptcha
Plugin URI: http://dimoning.ru
Description: Smart captcha for wordpress comments.
Author: DimoninG
Version: 0.2b
Author URI: http://dimoning.ru
*/

$file = str_replace ("dimoning.ru-captcha.php", "", __FILE__)."num/num.txt";

function get_num (){
	global $file;
	$f = fopen ($file, "r");
		$n = fread ($f, 256);
	fclose ($f);
	return $n;
}

add_action('comment_post', "comment_post");
add_action('comment_form', "dcaptcha_draw");

function comment_post ($id){
	global $user_ID;

	if ($user_ID){
		return $id;
	}

	if ($_POST['dcaptcha_sess'] != get_num()){
		wp_set_comment_status ($id, 'delete');
		echo "wrong captcha. no spam, please.";
		exit;
	}
}

function dcaptcha_draw ($id){
	global $user_ID;

	if ($user_ID){
		return $id;
	}

	$max = 4;
	$right = rand (0, $max);
	?>

	<script language="javascript">
	function dcaptcha_change(){
		document.getElementById('dcaptcha_sess').value = <?php echo get_num(); ?>;

	}

	<?php/*
	for ($i = 0; $i < $max); $i++){
	?>
	function dcaptcha_change<?php echo $i; ?>(){
		document.getElementById('dcaptcha_sess').value = <?php 
		
		if ($i == $right) echo get_num();
		else echo get_num() + rand(0, 500000);
		
		?>;
	}
	<?php
	*/
	?>
	</script>

	<div id="dcaptcha"><p>

		<input type="checkbox" id="dcaptcha_captcha1" onclick="dcaptcha_change();" value="Я не робот.">
		Я не робот.<br>
	</div>
	<input type="hidden" name="dcaptcha_sess" id="dcaptcha_sess" value="<?php echo rand(0, 500000); ?>">

	<script>
	var commentField = document.getElementById("url");
    var submitp = commentField.parentNode;
    var answerDiv = document.getElementById("dcaptcha");	    
    submitp.appendChild(answerDiv, commentField);
</script>
	<?php
}
?>