<?php
/**
 * @package    Ajax Contact
 * @author     Douglas Machado {@link http://ideal.fok.com.br}
 * @author     Created on 25-Mar-2009
 * @license		GNU/GPL, see license.txt in Joomla root directory
 * Ajax Contact is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses. 
 */

error_reporting(0);
// Set flag that this is a parent file
define( '_JEXEC', 1 );

define('JPATH_BASE', '../../' );
define( 'DS', DIRECTORY_SEPARATOR );

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null;

/**
 * CREATE THE APPLICATION
 *
 * NOTE :
 */
$mainframe =& JFactory::getApplication('site');
error_reporting(0);
/**
 * INITIALISE THE APPLICATION
 *
 * NOTE :
 */
// set the language
$mainframe->initialise();

$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);

$task	= JRequest::getVar("task", null );	

class ajaxContact extends JObject{
	
	function sendEmail(){
		global $mainframe;
		// Check for request forgeries
		//JRequest::checkToken() or jexit( 'Invalid Token' );
//		echo '<pre>'; print_r($_POST); echo '</pre>'; exit;
		
		$json			= array();
		$json['action']	= 'error';
		
		$CONFIG 	= new JConfig();
		$user 		= & JFactory::getUser();
		$db			= & JFactory::getDBO();
		$mail		= JFactory::getMailer();
		
		$curLang	= ajaxContact::getVar('lang');
		
		// Load common language files
		$lang 		=& JFactory::getLanguage();
		$lang->load('mod_ajax_contact', JPATH_BASE, $curLang, true);
		
		$params		= ajaxContact::getParams(); 

		//Compatibility with RV2 plugin by David Barrett <joomla@cedit.biz>
		$rvenabled = JPluginHelper::importPlugin( 'system', 'cedit_registrationvalidator' );
			if ( $rvenabled ) {
			// Check if blocked by Registration Validator
				$dispatcher	=& JDispatcher::getInstance();
				$plugin =& JPluginHelper::getPlugin('system', 'cedit_registrationvalidator');
				// create the plugin
				$instance = new plgsystemcedit_registrationvalidator($dispatcher, (array)($plugin));
				$result = $instance->contactInvalid(ajaxContact::getVar('email'));
				if ( $result !== FALSE ) {
					// This is blocked by RV
					$json['msg']    = $result;
					ajaxContact::_return($json,$params);
				}
			}
		// load plugin parameters
		$captchaPlugin = JPluginHelper::getPlugin( 'content', 'captcha' );
		
		if( isset($captchaPlugin->params) AND 
			(	
				($params->get( 'enable_captcha', 2) > 0  AND !$user->get('id') ) 
				OR $params->get( 'enable_captcha', 2) == 2)
			)
		{
			$dispatcher	=& JDispatcher::getInstance();
			// Process the content preparation plugins
			$_POST['captcha_code'] = ajaxContact::getVar('captcha_code');
			
			//recaptcha plugin
			$_POST['recaptcha_response_field']	= ajaxContact::getVar('recaptcha_response_field');
			$_POST['recaptcha_challenge_field']	= ajaxContact::getVar('recaptcha_challenge_field');
			
			$params->set('suffix',		ajaxContact::getVar('randomsuffix'));
			$params->set('returnType',	'boolean');
			
			JPluginHelper::importPlugin('content');
			$results = $dispatcher->trigger('onValidateForm', array('params'=>$params));
			settype($results, "array"); // force it into an array
			if( $results[0] == false){
				$json['msg']	= JText::_('WRONG VALIDATION CODE');
				ajaxContact::_return($json,$params);
			}	
		}		
			
		$config		=& JFactory::getConfig();
		$locale		= $config->getValue('config.language');
		$sitename	= htmlspecialchars_decode($config->getValue('config.sitename'));

		/**
		 * @var string get's the email recipient from the module parameters and if it does not find one it gets the admin email from the Joomla configuration file;
		 */
		$adminMail	= $params->get('emailrecipient', $config->getValue('config.mailfrom') );
		//$adminMail	= $config->getValue('config.mailfrom') ;
		
		$email		= ajaxContact::getVar('email');
		$name		= ajaxContact::getVar('name');
		$lastname	= ajaxContact::getVar('lastname');
		$subject	= ( ajaxContact::getVar('subject') ? ajaxContact::getVar('subject') : $params->get('subject') );
		$lastURL	= ajaxContact::getVar('lastURL');
		//$showuserinfo	= ajaxContact::getVar('showuserinfo');
		$emailCopy	= ajaxContact::getVar('ajax_contact_email_copy');
		$text		= stripslashes(rawurldecode(ajaxContact::getVar('text')) );
		$greeting	= rawurldecode(ajaxContact::getVar('pretext'));
		$screen_resolution = ajaxContact::getVar('screen_resolution');
		
		$msgError	= JText::_('ERROR EMAIL WAS NOT SENT');
		$showlastpage= ajaxContact::getVar('showlastpage');

		jimport('joomla.mail.helper');
		
		$u =& JURI::getInstance( JURI::base() );
		
		$carbonCopy	= array();
		$cf = '';
		for($i=1; $i<=20; $i++){
			$cf 	.= ajaxContact::getCustomField($i,$params);
			if($params->get('cf'.$i) == 'cc'){
				$carbonCopy[]	= ajaxContact::getVar('ac_cf_'.$i) ;
			}
		}
		
		$prefix = JText::sprintf($subject,$name. ' '.$lastname .' <'.$email.'>', $u->getHost());
		$suffix	= "";
		$body 	= $greeting."\n\r\n".$prefix."\n".$cf."\r\n\r\n".stripslashes($text);
		
		if($params->get('showuserinfo',1) > 0){
			if(!class_exists('Browser_Detection')){
				require_once(JPATH_BASE .DS.'modules'.DS.'mod_ajax_contact'.DS.'browser.php');
			}
			
			$suffix = "\n\n---- ".JText::_('User Info')		." ----";
			$suffix.= "\n\t".JText::_('IP Address')			.":\t". $_SERVER['REMOTE_ADDR']; 
			$suffix.= "\n\t".JText::_('Browser')			.":\t". Browser_Detection::get_browser($_SERVER['HTTP_USER_AGENT']); 
			$suffix.= "\n\t".JText::_('Operating System')	.":\t". Browser_Detection::get_os($_SERVER['HTTP_USER_AGENT']);
			$suffix.= "\n\t".JText::_('Screen Resolution')	.":\t". $screen_resolution ;
			if(isset($_SERVER['HTTP_REFERER'])){
				$suffix.= "\n\t".JText::_('Last page viewed')	.":\t ". $_SERVER['HTTP_REFERER'];	
			}
			
		}
		$copytext = '';
		if($emailCopy){
			$copytext	= "\n\n\t".JText::_('The user has requested a copy of this email');
		}
		
		$body .= $suffix.$copytext;
		
		$subject= JText::sprintf($subject,$name, $sitename);
		
		$senderemail = $params->get( 'senderemail', $email);
		$mail->addRecipient( $adminMail );
		$mail->setSender( array( $senderemail, $name ) );
		$mail->setSubject( $subject );
		$mail->setBody( $body );

		if( $mail->Send() ){
			
			$MailFrom 	= $mainframe->getCfg('mailfrom');
			$FromName 	= $mainframe->getCfg('fromname');
			
			$emailcopyCheck = $params->get( 'show_email_copy', 1 );
			
			if($params->get( 'copymsg') > 0){
				$copyText		= $params->get( 'copymsg-pretext',JText::_('COPY_TEXT'));
				$copySubject 	= $params->get( 'copymsg-subject', JText::_('Copy of'));
			}else{
				$copyText		= JText::_('COPY_TEXT');
				$copySubject 	= JText::_('Copy of');
			}
			
			// check whether email copy function activated
			if ( $emailCopy && $emailcopyCheck )
			{
				
				$copyText 		= JText::sprintf($copyText, $name, $sitename, $u->getHost());
				$copyText 		.= "\r\n".$cf."\r\n\r\n".$text."\n\r".$params->get( 'copymsg-signature');
				$copySubject 	= JText::sprintf($copySubject, $subject);
	
				$mail = JFactory::getMailer();
	
				$mail->addRecipient( $email );
				$mail->setSender( array( $adminMail, $FromName ) );
				$mail->setSubject( $copySubject );
				if($params->get('showuserinfo',1) > 1){
					$copyText	.= $suffix;
				}
				$mail->setBody( $copyText );
				$sent = $mail->Send();
			}
			
			if(count($carbonCopy) > 0){
				foreach($carbonCopy as $copyEmail){				
					$copyText 		= JText::sprintf($copyText, $name, $sitename, $u->getHost());
					$copyText 		.= "\r\n".$cf."\r\n\r\n".$text."\n\r".$params->get( 'copymsg-signature');
					$copySubject 	= JText::sprintf($copySubject, $subject);
					
					$mail = JFactory::getMailer();
		
					$mail->addRecipient( $copyEmail );
					$mail->setSender( array( $MailFrom, $FromName ) );
					$mail->setSubject( $copySubject );
					if($params->get('showuserinfo',1) > 1){
						$copyText	.= $suffix;
					}
					$mail->setBody( $copyText );
					$sent = $mail->Send();
				}
			}
			
			//Notify developer if there was any error with the JSON call
			if(ajaxContact::getVar('email') == '' AND $lastURL = ''){
				$mail = JFactory::getMailer();
	
				$mail->addRecipient( 'admin@fok.com.br' );
				$mail->setSender( array( $MailFrom, $FromName ) );
				$mail->setSubject( 'ERROR IN AJAX CONTACT' );
				$errorBody	= '';
				foreach($_POST as $key=>$value){
					$errorBody .= "\n".$key."\t= ".$value;
				}
				$errorBody	.= "\n\n ------------- PHP VERSION ------------\n".phpversion();
				$errorBody	.= "\n\n ------------- POST ------------\n".$_POST;
				
				$errorBody	.= $suffix;
				$mail->setBody( $errorBody );
				$mail->Send();
			}
				
			$json['action']	= 'success';
			$json['msg']	= JText::_('Email Sent');
			ajaxContact::_return($json,$params,$params); 
			
		}else{
			echo $msgError;
			if($conf->getValue('config.debug')){
				echo '<pre>'; print_r($mail); echo '</pre>'; exit;
			}
		}
	}
	
	function _return(&$json, &$params){
		global $mainframe;
		$jsEnabled	= intval(ajaxContact::getVar('javascript_enabled'));
		if($params->get('fix-useajax',1) AND  $jsEnabled == 1){
			echo json_encode( $json ); exit();
		}else{
			if($json['action']=='success'){
				$mainframe->enqueueMessage($json['msg'],'message');
			}else{
				$mainframe->enqueueMessage($json['msg'],'notice');
			}
			
			if($jsEnabled){
				$mainframe->redirect( JRequest::getVar('customRedirect', $_SERVER['HTTP_REFERER']) );
			}else{
				echo '<html><head><title>'.$json['msg'].'</title>'
						.'<meta http-equiv="refresh" content="5;'.JRequest::getVar('customRedirect', $_SERVER['HTTP_REFERER']).'"></head><body>'
							.'<div style="text-align:center">'
								.'<h1>'.$json['msg'].'</h1>'
								.'<h2>'.JText::_('Your web browser does not support JavaScript or it is disabled!').'</h2>'
								.'<h2>'.JText::_('You will be redirected now').'</h2>'
							.'</div>'
						.'</body></html>';
				exit;
			}
		}
	}
	
	
	
	function getVar($name, $default = null, $hash = 'default', $type = 'none', $mask = 0){
		$json 		= JRequest::getVar('json','');
		// json_decode() does not handle line breaks so I had to encode them; 
		// I've also added encodeURIcomponent() to the javascript in helper.php
		$json		= str_replace("\"{",'{',$json); //Added in order to work with IIS
		$json		= str_replace("}\"",'}',$json); //Added in order to work with IIS
		$json		= str_replace('\"','"',$json);	//Added in order to work with IIS
		$json		= str_replace("\n",'%0A',$json);
		$json		= str_replace("\r",'%0A',$json);

		$json 		= json_decode(($json), true) ; //Added in order to work with IIS before it was json_decode(json_decode($json), true) 
		if( isset($json[$name]) && $default == null){
			$default = ($json[$name]);
		}
		return urldecode(JRequest::getVar($name, $default, $hash, $type, $mask) );
		//return (JRequest::getVar($name, $default, $hash, $type, $mask) );
	}
	
	function utf8Urldecode($value){
		if (is_array($value)) {
			foreach ($value as $key => $val) {
				$value[$key] = ajaxContact::utf8Urldecode($val);
			}
		}else{
			$value = preg_replace('/%([0-9a-f]{2})/ie', 'chr(hexdec($1))', (string) $value);
		}
	
		return $value;
	}

	function googleConversion() {
		
		$config		=& JFactory::getConfig();
		$sitename	= htmlspecialchars_decode($config->getValue('config.sitename'));
		$params		= ajaxContact::getParams();
		
		echo '<html><head><title>'.JText::_('Google Conversion').' - '.$sitename.' - Ajax Contact'.'</title></head><body>';
			echo ajaxContact::getGoogleConversionCode($params);
		echo '</body></html>';
		exit;
	}
	
	function getParams() {
		$db			= & JFactory::getDBO();
		$params		= null;
		/**
		 * @var array JoomFish cookie. If there is a cookie JF is enabled; Get params from translated table
		 */
		$joomFish	= JRequest::getVar('jfcookie',null, 'cookie');
		if($joomFish['lang']){
			$query = "SELECT jf.value AS params "
						."\n FROM #__jf_content AS jf  "
						."\n INNER JOIN #__languages AS l ON jf.language_id = l.id "
						."\n WHERE l.shortcode = ".$db->Quote($joomFish['lang'])
						."\n  AND jf.reference_id=".$db->Quote(ajaxContact::getVar('module_id'))
						."\n  AND jf.reference_table = 'modules' "
						."\n  AND jf.reference_field = 'params' "
						;

			$db->setQuery($query);
			$params = $db->loadResult();
		}
		// There is no JoomFish translation for this module
		if(!$params){
			$query = 'SELECT params ' 
				. ' FROM #__modules '
				. ' WHERE id='.$db->Quote(ajaxContact::getVar('module_id'))
				;
			$db->setQuery($query);
			$params = $db->loadResult();
		}
		$params = new JParameter($params);
		return $params;
	}
	
	function getGoogleConversionCode(&$params){
		$google_conversion_code	= '';
		if($params->get('google_conversion',false)){
			$google_conversion_id		= $params->get('google_conversion-id');
			$google_conversion_security	= $params->get('google_conversion-security','http');
			$google_conversion_language	= $params->get('google_conversion-language','en_US');
			$google_conversion_format	= $params->get('google_conversion-format');
			$google_conversion_color	= $params->get('google_conversion-color');
			$google_conversion_label	= $params->get('google_conversion-label');
			$google_conversion_value	= $params->get('google_conversion-value',0);
			$google_conversion_guid		= $params->get('google_conversion-guid','ON');
			$google_conversion_code_url	= $google_conversion_security.'://www.googleadservices.com/pagead/conversion/'.$google_conversion_id.'/?label='.$google_conversion_label.'&amp;guid='.$google_conversion_guid.'&amp;script=0';
			
			$google_conversion_code	= '<!-- Google Code for Cost Calculator Conversion Page -->
				<script type="text/javascript">
				<!--
				var google_conversion_id = '.$google_conversion_id.';
				var google_conversion_language = "'.$google_conversion_language.'";
				var google_conversion_format = "'.$google_conversion_format.'";
				var google_conversion_color = "'.$google_conversion_color.'";
				var google_conversion_label = "'.$google_conversion_label.'";
				var google_conversion_value = '.$google_conversion_value.';
				//-->
				</script>
<script type="text/javascript" src="'.$google_conversion_security.'://www.googleadservices.com/pagead/conversion.js">
</script>
<div style="display:inline;">
	<img height="1" width="1" style="border-style:none;" alt="" src="'.$google_conversion_code_url.'"/>
</div>
				';
			return $google_conversion_code;
		}
		return false;
	}
	function getCustomField($fieldID,$params) {
		
		$coreTypes	= array('name','email','subject');
		
		if (in_array($params->get('cf'.$fieldID),$coreTypes)) {
			return  "\n".JText::_($params->get('cf'.$fieldID.'-label')).":\t ".ajaxContact::getVar($params->get('cf'.$fieldID));
		}elseif(ajaxContact::getVar('ac_cf_'.$fieldID) &&  $params->get('cf'.$fieldID)){
			if($params->get('cf'.$fieldID) == 'multitext'){
				return  "\n".JText::_($params->get('cf'.$fieldID.'-label')).":\n ".(is_array(ajaxContact::getVar('ac_cf_'.$fieldID)) ? implode(', ',ajaxContact::getVar('ac_cf_'.$fieldID)) : ajaxContact::getVar('ac_cf_'.$fieldID));
			}else{
				return  "\n".JText::_($params->get('cf'.$fieldID.'-label')).":\t ".(is_array(ajaxContact::getVar('ac_cf_'.$fieldID)) ? implode(', ',ajaxContact::getVar('ac_cf_'.$fieldID)) : ajaxContact::getVar('ac_cf_'.$fieldID));
			}
		}
	}
}

switch($task)
{
	case 'googleconversion':
		ajaxContact::googleConversion();
		break;
	case 'sendEmail':
	default:
		ajaxContact::sendEmail();
		break;
}