<?php
/*
Plugin Name: Asirra (AVH F.D.A.S Component)
Plugin URI: http://premium.wpmudev.org/
Description: Protects your comments from spam by adding an Asirra challenge - Asirra is a human interactive proof that asks users to identify photos of cats and dogs.
Version: 0.2
Author: Ve Bailovity (Incsub)
Author URI: http://premium.wpmudev.org

Copyright 2009-2011 Incsub (http://incsub.com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License (Version 2 - GPLv2) as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

class AVH_Asirra {

	private $_data;

	public function __construct () {
		if (!class_exists('AVH_FormsRenderer')) require_once (dirname(__FILE__) . '/avh-files/plugins/avh-fdas.forms.php');
		require_once (dirname(__FILE__) . '/avh-files/plugins/avh-fdas.asirra.forms.php');
		$this->_data = get_site_option('avhfdas-asirra');
	}

	public static function serve () {
		$me = new AVH_Asirra;
		$me->_add_hooks();
	}

	public function register_settings () {
		$form = new AVH_Asirra_AdminFormRenderer;

		register_setting('avh-fdas-asirra', 'avh-fdas-asirra');
		add_settings_section('avh-fdas_settings', __('Settings', 'avh-fdas'), create_function('', ''), 'avh-fdas_asirra_page');
		add_settings_field('avh-fdas-asirra-disable', __('Disable Asirra', 'avh-fdas'), array($form, 'create_disable_box'), 'avh-fdas_asirra_page', 'avh-fdas_settings');
		add_settings_field('avh-fdass-asirra-position', __('Enlarged images position', 'avh-fdas'), array($form, 'create_position_box'), 'avh-fdas_asirra_page', 'avh-fdas_settings');
		add_settings_field('avh-fdass-asirra-cells', __('Images per row', 'avh-fdas'), array($form, 'create_cells_box'), 'avh-fdas_asirra_page', 'avh-fdas_settings');
	}

	public function create_menu_entry () {
		if (@$_POST && isset($_POST['option_page'])) {
			$changed = false;
			if('avh-fdas-asirra' == @$_POST['option_page']) {
				update_site_option('avhfdas-asirra', $_POST['avh-asirra']);
				$changed = true;
			}

			if ($changed) {
				$goback = add_query_arg('settings-updated', 'true',  wp_get_referer());
				wp_redirect($goback);
				die;
			}
		}
		add_submenu_page('avh-settings', 'AVH First Defense Against Spam - WPMU DEV Version: ' . __( 'Asirra', 'avh-fdas' ), __( 'Asirra', 'avh-fdas' ), 'manage_network_options', 'avh-fdas-asirra', array ($this, 'create_settings_page'));
	}

	public function create_settings_page () {
		include (dirname(__FILE__) . '/avh-files/plugins/forms/asirra_settings.php');
	}

	public function place_asirra () {
		global $user_ID;
		if ($user_ID) return false;

		$pos = $this->_data['position'];
		$pos = $pos ? esc_js($pos) : 'top';

		$cells = (int)$this->_data['cells'];
		$cells = $cells ? $cells : 5;

		echo <<<EOAsirraJs
<script type="text/javascript" src="http://challenge.asirra.com/js/AsirraClientSide.js"></script>
<script type="text/javascript">
asirraState.SetEnlargedPosition("{$pos}");
asirraState.SetCellsPerRow({$cells});

(function ($) {
var __asirra_request_flag = false;
$(function () {
$("form").each(function () {
	var me = $(this);
	if (!me.attr("action").match(/wp-comments-post/)) return true;

	me.on("submit", function () {
		if (__asirra_request_flag) return false;
		__asirra_request_flag = true;
		return Asirra_CheckIfHuman(function (is_human) {
			__asirra_request_flag = false;
			if (!is_human) return false;

			me.unbind("submit");
			var sb = me.find(":submit");
			if (sb.length) sb.click();
			else me.submit();

			return false;
		});
		return false;
	});
});
});
})(jQuery);
</script>
EOAsirraJs;
	}

	public function process_asirra_challenge ($comment) {
		global $user_ID;
		if ($user_ID) return $comment;
		if (in_array($comment['comment_type'], array('trackback', 'pingback'))) return $comment; // Only process comments
		if (
			defined('DOING_AJAX')
			&& DOING_AJAX
			&& class_exists('Wdcp_CommentsWorker')
			&& isset($_POST['action'])
			&& preg_match('/wdcp_post_\w+_comment/', $_POST['action'])
		) return $comment; // Do not intercept Comments Plus comments

		if (isset($_POST['Asirra_Ticket'])) {
			$resp = wp_remote_get('http://challenge.asirra.com/cgi/Asirra?action=ValidateTicket&ticket=' . stripslashes($_POST['Asirra_Ticket']), array(
				'method' 		=> 'GET',
				'timeout' 		=> '5',
				'redirection' 	=> '5',
				'user-agent' 	=> 'avh-fdas',
				'blocking'		=> true,
				'compress'		=> false,
				'decompress'	=> true,
				'sslverify'		=> false
			));
			if(is_wp_error($resp)) wp_die(__('Error contacting verification server.', 'avh-fdas'));; // Request fail
			if ((int)$resp['response']['code'] != 200) wp_die(__('Error: could not verify the request.', 'avh-fdas'));; // Request fail
			$page = new SimpleXmlElement($resp['body']);
			if ('Fail' == $page->Result) wp_die(__('Error: Please select the correct anti-spam images. Press the back button and try again.', 'avh-fdas'));
		}
		return $comment;
	}

	private function _add_hooks () {
		add_action('admin_init', array($this, 'register_settings'));
		add_action('network_admin_menu', array($this, 'create_menu_entry'), 25);

		if (!@$this->_data['disable_asirra']) {
			add_action('wp_print_scripts', create_function('', 'wp_enqueue_script("jquery");'));
			add_action('comment_form', array($this, 'place_asirra'));
			add_action('preprocess_comment', array($this, 'process_asirra_challenge'));
		}
	}
}

AVH_Asirra::serve();