<?php
/**
* @version 1.2.0
* @package RSform!Pro 1.2.0
* @copyright (C) 2007-2009 www.rsjoomla.com
* @license Commercial License, http://www.rsjoomla.com/terms-and-conditions.html
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * RSForm! Pro system plugin
 */
/* Get the recaptcha library */
require_once (JPATH_SITE.DS.'plugins'.DS.'system'.DS.'recaptchalib.php');

class plgSystemrsfprecaptcha extends JPlugin
{
	/**
	 * Constructor
	 *
	 * For php4 compatibility we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @access	protected
	 * @param	object	$subject The object to observe
	 * @param 	array   $config  An array that holds the plugin configuration
	 * @since	1.0
	 */
	function plgSystemrsfprecaptcha( &$subject, $config )
	{
		parent::__construct( $subject, $config );
		$this->loadLanguage( 'plg_system_rsfprecaptcha' );
		$this->newComponents = array(24);
		
	}
	
	/*
		Event Triggered Functions
	*/
	function rsfp_bk_onInit()
	{
		global $RSadapter;
		$RSadapter->config['component_ids'] = array_merge($RSadapter->config['component_ids'],$this->newComponents);
	}
	
	function rsfp_bk_onAfterShowComponents()
	{
		global $mainframe; 
		$db = JFactory::getDBO();
		$formId = intval(JRequest::getVar('formId'));
		
		$link = '';
		if($this->rsfp_containsComponents($formId,array(24)))
		{
			$db->setQuery("SELECT ComponentId FROM #__rsform_components WHERE ComponentTypeId = 24");
			$link = ",'".$db->loadResult()."'";
		}
		
		?>
		<strong><?php echo JText::_('RSFP_RECAPTCHA_LABEL');?></strong>
			<a href="#" onclick="displayTemplate('24'<?php echo $link;?>);return false;" class="component" id="captcha">
	                        <?php echo JText::_('RSFP_RECAPTCHA_SPRODUCT');?>
	        </a><div title="componentEdit" id="componentEdit24" class="componentEdit"></div>
		<?php
	}
	
	
	function rsfp_bk_onAfterCreateComponentPreview($args = array())
	{
		global $RSadapter;
		switch($args['ComponentTypeName']){
			case 'recaptcha':
				// Get a key from http://recaptcha.net/api/getkey
				$publickey = $RSadapter->config['recaptcha.public.key'];
				
				// the response from reCAPTCHA
				$resp = null;
				// the error code from reCAPTCHA, if any
				$error = null;
				$args['out']=' <script type="text/javascript">
						var RecaptchaOptions = {
						   theme : "'.$RSadapter->config['recaptcha.theme'].'"
						};
						</script> 
					';
				$args['out'].='<td>'.$args['data']['CAPTION'].'</td>';
				$args['out'].='<td>'.recaptcha_get_html($publickey, $error).'</td>';
			break;
			
		}
		$out = $args['out'];
	}
	
	function rsfp_bk_onAfterShowConfigurationTabs()
	{
		global $RSadapter;
		
		$formId = intval(JRequest::getVar('formId'));
		
		$RSadapter->startTab(JText::_('RSFP_RECAPTCHA_LABEL'),"recaptcha");
		$this->recaptchaConfigurationScreen($formId);
		$RSadapter->endTab();		
	}
	
	function rsfp_bk_onAfterCreateFrontComponentBody($args)
	{
		global $RSadapter;
		
		switch($args['r']['ComponentTypeId']){
			case 24:
				// Get a key from http://recaptcha.net/api/getkey
				$publickey = $RSadapter->config['recaptcha.public.key'];
				
				// the response from reCAPTCHA
				$resp = null;
				// the error code from reCAPTCHA, if any
				$error = null;
				$args['out']=' <script type="text/javascript">
						var RecaptchaOptions = {
						   theme : "'.$RSadapter->config['recaptcha.theme'].'"
						};
						</script> 
					';
				$args['out'].= recaptcha_get_html($publickey, $error);
			break;
		}
	}
	
	/*
		Task Functions
	*/
	
	function rsfp_bk_validate_onSubmitValidateRecaptcha($args)
	{	
		global $RSadapter;
		$privatekey = $RSadapter->config['recaptcha.private.key'];
		
		// the response from reCAPTCHA
		$resp = null;
		// the error code from reCAPTCHA, if any
		$error = null;
		
		if(isset($_POST["recaptcha_challenge_field"]) && isset($_POST["recaptcha_response_field"]))
		$resp = recaptcha_check_answer ($privatekey,
											$_SERVER["REMOTE_ADDR"],
											$_POST["recaptcha_challenge_field"],
											$_POST["recaptcha_response_field"]);
		if($privatekey != '')
			if (empty($resp->is_valid))
				$args['invalid'][] = $args['data']['componentId'];
	}
	
	/*
		Additional Functions
	*/	
	
	function recaptchaConfigurationScreen()
	{
		global $RSadapter;
		
		$themes[] = JHTML::_('select.option', 'red', JText::_( 'RSFP_RED_THEME' ) );
		$themes[] = JHTML::_('select.option', 'white', JText::_( 'RSFP_WHITE_THEME' ) );
		$themes[] = JHTML::_('select.option', 'clean', JText::_( 'RSFP_CLEAN_THEME' ) );
		$themes[] = JHTML::_('select.option', 'blackglass', JText::_( 'RSFP_BLACKGLASS_THEME' ) );
		$theme = JHTML::_('select.genericlist', $themes, 'rsformConfig[recaptcha.theme]', 'size="1" class="inputbox"', 'value', 'text', $RSadapter->config['recaptcha.theme'] );
		?>
		<div id="page-recaptcha">
		<table cellspacing="0" cellpadding="0" border="0" width="100%">
				<tr>
					<td valign="top">
						<table  class="adminform">
							<tr>
								<td width="150">
									<label for="public">
										<?php echo JText::_( 'RSFP_RECAPTCHA_PBKEY' ).':'; ?>
									</label>
								</td>
								<td>
									<input type="text" name="rsformConfig[recaptcha.public.key]" value="<?php echo $RSadapter->config['recaptcha.public.key'];  ?>" size="30" maxlength="100">
								</td>
							</tr>
							<tr>
								<td width="150">
									<label for="private">
										<?php echo JText::_( 'RSFP_RECAPTCHA_PRKEY' ).':'; ?>
									</label>
								</td>
								<td>
									<input type="text" name="rsformConfig[recaptcha.private.key]" value="<?php echo $RSadapter->config['recaptcha.private.key'];  ?>" size="30" maxlength="100">
								</td>
							</tr>
							<tr>
								<td width="150">
									<label for="theme">
										<?php echo JText::_( 'RSFP_RECAPTCHA_THEME' ).':'; ?>
									</label>
								</td>
								<td>
									<?php echo $theme; ?>
								</td>
							</tr>
						</table>
					</td>
				</tr>
		</table>
		</div>
		<?php
	}
	
	function rsfp_containsComponents($formId, $components)
	{
		global $RSadapter;
		$db = JFactory::getDBO();
		
		$db->setQuery("SELECT count(*) CNT FROM #__rsform_components WHERE FormId='".$formId."' AND ComponentTypeId IN (".implode(',',$components).")");
		return $db->loadResult();
	}
	
}