<?php
/**
* @author Douglas Machado <douglas@focalizar.com.br>
* @copyright 2009 - Douglas Machado <douglas@focalizar.com.br>
**/

defined( '_VALID_MOS' ) or defined('_JEXEC') or die('Direct Access to this location is not allowed.');

$config		=& JFactory::getConfig();
/**
 * @var int	Will set error report to maximum if global settings is set to maximum, otherwise set error reporting to none this will avoid problems with Joom!Fish and some SEF extensions
 */
$error_reporting_level	= $config->getValue('config.error_reporting');
if($error_reporting_level != 6143){
	$error_reporting_level = 0;
}
error_reporting($error_reporting_level);

// Import library dependencies
jimport('joomla.event.plugin');
jimport('joomla.plugin.plugin');


class plgContentCaptcha extends JPlugin
{
	var $mollom		= null;
	var $registry	= null;
	var $session	= null;
	
	function plgContentCaptcha(&$subject)
    {
            // load plugin parameters
            $this->_plugin = JPluginHelper::getPlugin( 'content', 'captcha' );
            $this->_params = new JParameter( $this->_plugin->params );
            $lang =& JFactory::getLanguage(); 
			$lang->load('captcha');
			$lang->load('plg_content_captcha', JPATH_ADMINISTRATOR);
			//echo '<pre>'; print_r($this->_plugin); exit;
			parent::__construct( $subject );
			$this->session = JFactory::getSession();
    }

		
	function onAfterDisplayForm() {
		//echo '<pre>'; print_r(func_get_arg(1)); echo '</pre>'; exit;
		if(func_num_args() > 0){
			$args	= func_get_arg(0);
			if(is_object($args)){
				$this->_params->merge($args);
			}
		}
		$html	='';

		if($this->_params->get('captcha_systems') == 'secureimage'){
			$html = $this->displaySecureImageForm();
		}else if($this->_params->get('captcha_systems') == 'recaptcha'){
			$html = $this->displayRecaptchaForm();
		}else if($this->_params->get('captcha_systems') == 'mathguard'){
			$html = $this->displayMathGuardForm();
		}else if($this->_params->get('captcha_systems') == 'mollom'){
			$html = $this->displayMollom();
		}else{
			$html = $this->displaySecurImage2Form();
		}
		$html = '<div class="captcha-container">'.$html.'</div>';
		//echo '<pre>'; print_r($this->_params); echo '</pre>';
		
		if(func_num_args() > 1){
			if(func_get_arg(1) == 'return'){
				return $html;
			}
		} 
		echo $html;
	}
	
	function onValidateForm() {
		if(func_num_args() > 0){
			$args	= func_get_arg(0);
			if(is_object($args)){
				$this->_params->merge($args);
			}
		}
		
		/**/

		//echo '<pre>'; print_r($args); echo '</pre>'; exit; 
		//echo $this->_params->get('captcha_systems') ; exit;
		//echo 'Args: <pre>'; print_r(func_get_args()); echo '</pre>'; exit;
		$html	= '';
		$lang =& JFactory::getLanguage(); 
		$lang->load('captcha','administrator');
		if($this->_params->get('captcha_systems') == 'secureimage'){
			$html = $this->validateSecureImage();
		}else if($this->_params->get('captcha_systems') == 'recaptcha'){
			$html = $this->validateRecaptcha();
		}else if($this->_params->get('captcha_systems') == 'mathguard'){
			$html = $this->validateMathGuard();
		}else if($this->_params->get('captcha_systems') == 'mollom'){
			$html = $this->validateMollom();
		}else{
			$html = $this->validateSecurImage2();
		}
				//echo '<pre>'; print_r($_SESSION); exit;
		if($this->_params->get('returnType') == 'boolean'){
			return $html;
		}else if(!$html){
			echo '<script>alert("'.JText::_('Wrong Validation Code').'");history.back();</script>'; exit;
		}
		return $html;
	}
	
	function validateSecureImage(){
		require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'secureimage'.DS.'securimage.php');
		$securimage = new Securimage();
		// the code was incorrect
		if($securimage->check(JRequest::getVar('captcha_code','','POST')) == false) {
			return false;
		}
		return true;
	}
	
	function validateSecurImage2(){
		
		require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'securImage2'.DS.'securimage.php');
		$securimage = new Securimage();
		// the code was incorrect
		if($securimage->check(JRequest::getVar('captcha_code','','POST')) == false) {
//			echo '<pre>'; print_r($_SESSION); exit;
			return false;
		}
		return true;
	}
	
	function validateMathGuard(){
		require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'mathguard'.DS.'mathGuard.class.php');
		// the code was incorrect
		if(mathGuardImproved::checkResult(JRequest::getVar('captcha_code','','POST'),$this->_params->get('suffix')) == false) {
			return false;
		}
		return true;
	}

	function validateRecaptcha(){
		if(!defined('RECAPTCHA_API_SERVER')){
			require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'recaptchalib.php'); /**    reCAPTCHA Library   **/
		}
		$resp = recaptcha_check_answer ($this->_params->get('captcha_systems-recaptcha-PriKey',''),
										$_SERVER["REMOTE_ADDR"],
										JRequest::getVar("recaptcha_challenge_field",null, "POST"),
										JRequest::getVar("recaptcha_response_field",null, "POST") );		
		if(!$resp->is_valid) {
			/*echo "\n recaptcha_challenge_field: ".JRequest::getString("recaptcha_challenge_field",null, "POST");
			echo "\n recaptcha_response_field: ".JRequest::getString("recaptcha_response_field",null, "POST");
			echo "\n";
			//print_r($_POST); exit;
			echo $resp->error;*/
			return false;
		}
		return true;
	}
	
	function displaySecureImageForm(){
		$urlPath = JURI::base().'/plugins/content/captcha_systems/secureimage/';

		$html = '<br />';
		$html .= '<img id="captcha" name="captcha" src="'.$urlPath.'securimage_show.php?sid='.md5(uniqid(time())).'" alt="'.JText::_('CAPTCHA Image').'" />';
		$linkAttributes = array();
		$linkAttributes['onclick']	= "document.getElementById('captcha').src = '".$urlPath."securimage_show.php?' + Math.random(); return false";
		$linkAttributes['id']		= 'reloadImage';
		$image	= JHTML::_('image',$urlPath.'images/refresh.gif',JText::_('Reload Image') );
		$html .= JHTML::_('link', '#'.JText::_('Reload Image'),$image,$linkAttributes ); 
		//$html .= '<a href="#'.JText::_('Reload Image').'" id="reloadImage" onclick="document.'."getElementById('captcha').src = '".$urlPath."securimage_show.php?' + Math.random(); return false'>".JText::_('Reload Image').'</a>'; 
		$html .= '<br />';
		$html .= '<label for="captcha_code" class="requiredField">'.JText::_('Verification Code').': </label>';
		$html .= '<br />';
		$html .=  '<input type="text" name="captcha_code" id="captcha_code" class="inputbox captchacode required" size="10" maxlength="" />';
		$html .= '<br />';
		return $html;
	}
	
	function displaySecurImage2Form(){
		$urlPath = JURI::base().'plugins/content/captcha_systems/securImage2/';
		
		if(!defined('MULTIPLE_ENGINE_CAPTCHA_INSTANCE')){
			define('MULTIPLE_ENGINE_CAPTCHA_INSTANCE',1);
			$javascript	= "function updateCaptcha(){
				var captchas = document.getElementsByName('captcha'); 
				var imgURL	='".$urlPath."securimage_show.php?'+ Math.random();
				for (var i=0; i< captchas.length; i++) {
					captchas[i].src	= imgURL;
				}
			}
			window.addEvent('domready', function(){
				updateCaptcha();
			});

			";
			$doc =& JFactory::getDocument();
			$doc->addScriptDeclaration($javascript); //Conflicts with other extensions
			
		}
		$reloadLink	= '';
		if($this->_params->get('captcha_systems-securImage2-reloadbutton', 1)){
			$linkAttributes['onclick']	= 'updateCaptcha(); return false;';
			$linkAttributes['id']		= 'reloadImage';
			$image	= JHTML::_('image',$urlPath.'images/'.$this->_params->get('captcha_systems-securImage2-reloadimage', 'sync.png'),JText::_('Reload Image') );
			$reloadLink .= JHTML::_('link', '#'.JText::_('Reload Image'),$image,$linkAttributes ); 
		}
		$html = '<br />';
		
//			$html .= '<img id="captcha'.$this->_params->get('suffix','').'" name="captcha" src="" alt="'.JText::_('CAPTCHA Image').'" />';
// With the url
//'.$urlPath.'securimage_show.php?sid='.md5(uniqid(time())).'
			//I'm not sure why, but it  will not work with only one instance if I don't enter the url for the first time.
			$html .= '<img id="captcha'.$this->_params->get('suffix','').'" name="captcha" src="'.$urlPath.'securimage_show.php?sid='.md5(uniqid(time())).'" alt="'.JText::_('CAPTCHA Image').'" />';
			$html .= $reloadLink; 
			//$html .= '<a href="#'.JText::_('Reload Image').'" id="reloadImage" onclick="document.'."getElementById('captcha').src = '".$urlPath."securimage_show.php?' + Math.random(); return false'>".JText::_('Reload Image').'</a>'; 
			$html .= '<br />';
			$html .= '<label for="captcha_code" class="requiredField">'.JText::_('Verification Code').': </label>';
			$html .= '<br />';
		
			$html .=  '<input type="text" name="captcha_code" id="captcha_code" class="inputbox captchacode required" size="12" maxlength="" />';
			$html .= '<br />';
		
		
//		$session =& JFactory::getSession();
//		$html	.= '<br />code: '.($session->get('securimage_code_value'));
		//$html .= '<br style="clear:both" /><pre>'.var_export($_SESSION, true).'</pre>';
		
		return $html;
	}

	function displayMathGuardForm(){
		require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'mathguard'.DS.'mathGuard.class.php');
		
		$attributes		= array();
		$attributes['id']	= 'mathguard_answer'.$this->_params->get('suffix');
		
		$html = '';
		$html .= '<label for="mathguard_answer'.$this->_params->get('suffix').'" class="requiredField" id="label-mathguard_answer" >'.JText::_("Security question").'</label>';
		$html .= '<br />';
		$html .= mathGuardImproved::returnQuestion($attributes,$this->_params->get('suffix'));

		return $html;
	}
	
	
	//This function has been disabled for now
	function displayRecaptchaForm_NON_AJAX(){
		$document=& JFactory::getDocument();
		$config		=& JFactory::getConfig();
		if($config->getValue('config.force_ssl') > 1 ){
			$use_ssl = true;
		}else{
			$use_ssl = false;
		}
		$script	= "<script type=\"text/javascript\">var RecaptchaOptions = {theme : '" . $this->_params->get('recaptchaTheme','red') . "'};</script>";
		
		$document->addCustomTag($script);

		require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'recaptchalib.php'); /**    reCAPTCHA Library   **/
		/**   Generating CORE reCAPTCHA form   **/
		return recaptcha_get_html($this->_params->get('captcha_systems-recaptcha-PubKey',''),null,$use_ssl); 
	}
	
	function displayRecaptchaForm(){
		$document	=& JFactory::getDocument();
		$document->addScript('http://api.recaptcha.net/js/recaptcha_ajax.js');
		if(!defined('RECAPTCHA_API_SERVER')){
			require_once(JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'recaptchalib.php'); /**    reCAPTCHA Library   **/
		}
		
		$script		= 	"
						window.addEvent('domready', function() {
		
							Recaptcha.create('".$this->_params->get('captcha_systems-recaptcha-PubKey','')."',
								'recaptcha_div', 
								{	lang:'" . $this->_params->get('captcha_systems-recaptcha-Lang','en') . "',
								  	 theme:'" . $this->_params->get('captcha_systems-recaptcha-Theme','red') . "'
								});
						});
						";
		$document->addScriptDeclaration($script);
		
		
		/**   Generating CORE reCAPTCHA form   **/
		return '<div id="recaptcha_div" name="recaptcha_div"></div>'; 
	}
	
	function validateMollom(){
		$this->initializeMollom();
		if($this->_params->get('check_text') AND JRequest::getCMD('option') == 'com_contact_enhanced') {
			// get feedback
			$feedback = $this->mollom->checkContent(
							null, 
							JRequest::getVar('subject'), 
							JRequest::getVar('text'),
							JRequest::getVar('name'),
							null,
							JRequest::getVar('email'));
			
			// process feedback
			if($feedback['spam'] == 'spam'){
			    return false;
			}else{
				
				if($this->mollom->checkCaptcha(
						$this->session->get('captcha.mollom.session_id')
						, JRequest::getVar('captcha_code','','POST') )
				){
					return true;
				}
			}
		} elseif($this->mollom->checkCaptcha(
				$this->session->get('captcha.mollom.session_id')
				, JRequest::getVar('captcha_code','','POST') )
		){
			return true;
		}
		return false;
	}
	
	function displayMollom(){
		$this->initializeMollom();
		//initiate variables
		$captchaImage	= null;
		$captchaSound	= null;
		$html			= '';
		
		// get captcha
		switch ($this->_params->get('captcha_systems-mollom-CaptchaType')) {
			case "image":
				$captchaImage = $this->mollom->getImageCaptcha($this->session->get('captcha.mollom.session_id'));
				$this->session->set('captcha.mollom.session_id', $captchaImage['session_id']);
			break;
			
			case "sound":
				$captchaSound = $this->mollom->getAudioCaptcha($this->session->get('captcha.mollom.session_id'));
				$this->session->set('captcha.mollom.session_id', $captchaSound['session_id']);
			break;
			
			default:
				$captchaSound = $this->mollom->getAudioCaptcha($this->session->get('captcha.mollom.session_id'));
				$captchaImage = $this->mollom->getImageCaptcha($captchaSound['session_id']);
				$this->session->set('captcha.mollom.session_id', $captchaSound['session_id']);
			break;
		}

		if($captchaImage){
			$image	= JHTML::_('image',$captchaImage['url'],JText::_('CAPTCHA Image'));
			$html .= '<span class="mollom-captcha-content mollom-image-captcha">' . $image . '</span>';
			/*$html .= ' <small>(<a href="javascript:void();"  class="mollom-switch-captcha mollom-audio-captcha">' 
						. JText::_('Audio CAPTCHA'). '</a>)</small>';*/
		}
		/*if($captchaSound){
			$source	= JURI::base().'plugins/content/captcha_systems/mollom-audio-player.swf?url='
						.$captchaSound['url'];
				$html .= '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="110" height="50">';
			        $html .= '<param name="allowFullScreen" value="false" />';
			        $html .= '<param name="movie" value="' . $source . '" />';
			        $html .= '<param name="loop" value="false" />';
			        $html .= '<param name="menu" value="false" />';
			        $html .= '<param name="quality" value="high" />';
			        $html .= '<param name="wmode" value="transparent" />';
			        $html .= '<param name="bgcolor" value="#ffffff" />';
			        $html .= '<embed src="' . $source . '" loop="false" menu="false" quality="high" wmode="transparent" bgcolor="#ffffff" width="110" height="50" align="baseline" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_de" />';
			    $html .= '</object>';
		
		        $html = '<span class="mollom-captcha-content mollom-audio-captcha">' . $html . '</span>';
		        $html .= ' <small>(<a href="javascript:void();" class="mollom-switch-captcha mollom-image-captcha">' 
		        		. JText::_('Captcha image') . '</a>)</small>';
		        
		}
		*/
			$html .= '<br />';
			$html .= '<label for="captcha_code" class="requiredField">'.JText::_('Verification Code').': </label>';
			
			$html .=  '<input type="text" name="captcha_code" id="captcha_code" class="inputbox captchacode required" size="12" maxlength="" />';
			
		return $html;
	}
	
	function initializeMollom() {
		JLoader::register('Mollom', JPATH_PLUGINS.DS.'content'.DS.'captcha_systems'.DS.'mollom.php');
		//$session_id = $this->registry->get($scope);
		$params	= & $this->_params;
		//Initialize Mollom Class
		try {
			$config = array();
			$config['public_key'] 	= $params->get('captcha_systems-mollom-PubKey', '');
			$config['private_key'] 	= $params->get('captcha_systems-mollom-PriKey', '');
			$config['server_list'] 	= $params->get('server_list', array());
			$this->mollom =& Mollom::getInstance($config);
			$servers = $this->mollom->server_list;
			if(empty($servers)) {
				$servers = $this->mollom->getServerList();
			}
		} catch(Exception $e) {
			JDEBUG ? JError::raiseNotice(66503, JText::sprintf('Error Initializing Mollom Class: [%d] %s', $e->getCode(), $e->getMessage())) : '';
			$this->mollom = false;
			return false;
		}
	}
}
?>
