<?php

/* Copyright 2007, 2008 Tobias Frost <tobi@coldtobi.de> http://blog.coldtobi.de

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

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
*/

lt_include( PLOG_CLASS_PATH."class/security/pipelinefilter.class.php" );

require_once(PLOG_CLASS_PATH."plugins/recaptcha/library/recaptchalib.php");

// custom error code that will be returned to the pipeline whenever an
// error is found... Be careful so as to not to have two different modules
// use the same code!!
define( "RECAPTCHA_SPAM", 43534 );

class ReCaptchaFilter extends PipelineFilter 
{

	function ReCaptchaFilter( $pipelineRequest )
	{
		$this->PipelineFilter( $pipelineRequest );
	}

	function filter()
	{

		$blogInfo = $this->_pipelineRequest->getBlogInfo();
		// check if this section has been enabled or disabled
		$blogSettings = $blogInfo->getSettings();
		$pluginEnabled = $blogSettings->getValue( "plugin_recaptcha_enabled" );
		if( !$pluginEnabled) {
			return new PipelineResult();
		}

		// we only have to filter the contents if the user is posting a comment
		// so there's no point in doing anything else if that's not the case
		$request  = $this->_pipelineRequest->getHttpRequest();
		if( $request->getValue( "op" ) != "AddComment" ) {
			return new PipelineResult();
		}

		// if this is already rejected, there is no reason to do anything here
		if ( $this->_pipelineRequest->getRejectedState() )
		{
			return new PipelineResult();
		}

		// Obtain all parameters needed for the response checking. 
		$clientIp = Client::getIp();
		$challenge= $request->getValue("recaptcha_challenge_field");
		$response = $request->getValue("recaptcha_response_field");
		$privatekey = $blogSettings->getValue("plugin_recaptcha_privkey");

		$resp = recaptcha_check_answer ($privatekey, $clientIp, $challenge, $response);

		if (! $resp->is_valid)
		{
			$locale = $blogInfo->getLocale();
			return new PipelineResult( false, RECAPTCHA_SPAM, $locale->tr("recaptcha_captcha_wrong"));
		}
		
		// human after all !?
		return new PipelineResult();	
	}

}

?>
