<?php
/**
 * @version		1.2 feedback $
 * @package		feedback
 * @copyright	Copyright © 2010 Mertonium. All rights reserved.
 * @license		GNU/GPL
 * @author		Mertonium
 * @author mail	john@mertonium.com
 * @website		http://mertonium.com
 *
 *
 * @MVC architecture generated by MVC generator tool at http://www.alphaplug.com
 */

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

jimport('joomla.application.component.controller');

class feedbackController extends JController
{
	function __construct() {
		parent::__construct();
	}
	
	function display() {
		parent::display();
	}
	
	function submitfeedback() {
		// Get the component parameters
		$params = &JComponentHelper::getParams('com_feedback');
		
		// Load the model
		$model =& $this->getModel('feedback');
		
		// Determine the submitted timestamp 
		//(I add it to the request variables so that it works easily with my store() function)		
		JRequest::setVar('submitted_ts',date('c'));
		
		// Check the bot trap and timer split
		$bottrap = JRequest::getVar('bottrap','');
		$time1 = JRequest::getInt('start_time');
		$time2 = (int) date("U");
		$split = $time2-$time1;
		JRequest::setVar('time_split',$split);
		
		// Get the validation parameters for the module
		$validation_array = unserialize(base64_decode(JRequest::getVar('vpms')));
		
		// Initialize our return message
		$msg = '';
		
		if($bottrap == '' && $split > $params->get('feedback_spamsplit',0)) {
			// Make sure the name & email were submitted (in case JS is disabled)
			$submitter_name = JRequest::getVar('submitter_name','');
			$submitter_email = JRequest::getVar('submitter_email','');
			$submitter_feedback = JRequest::getVar('feedback','');
			//$match = preg_match('/^^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/', $submitter_email);
			$match = ($validation_array['email_req']) ? $this->validEmail($submitter_email) : true;
			
			if($submitter_name == '' && $validation_array['name_req'] == 0) $submitter_name = '--';
			
			$comment_test = ($validation_array['comment_req'] && $submitter_feedback == '') ? false : true;
			
			if($submitter_name != '' && $match && $comment_test) {
				// Store the form fields in the DB
				$sucess = $model->store();
				
				// Start the status message
				$msg = ($sucess) ? JText::_( 'Feedback submitted' ) : JText::_( 'Error submitting' );
				$msg .= '<br />';
				
				
				if($sucess) {
					$mailer =& JFactory::getMailer();
					$config =& JFactory::getConfig();			
					
					// Set the 'sender' of the email
					$sender = array( 
						$config->getValue( 'config.mailfrom' ),
						$config->getValue( 'config.fromname' ) 
					);		 
					$mailer->setSender($sender);
					
					// Determine the email recipient(s) from the component options
					$feedback_adminemail = $params->get('feedback_adminemail',$sender[0]);
					$email_array = explode(',',$feedback_adminemail);
					foreach($email_array as $admin_email) {
						$mailer->addRecipient($admin_email);
					}
					
					// Generate the email message
					$body  = JText::sprintf('The following feedback for URL  was submitted', $config->getValue('config.sitename')) ."\n\n"
							 .JText::sprintf('Date THEDATE',date('j M Y -- H:i:s',strtotime(JRequest::getVar('submitted_ts','')))) . "\n"
							 .JText::sprintf('Name THENAME',$submitter_name) ."\n"
							 .JText::sprintf('Email THEEMAIL', $submitter_email) ."\n"
							 .JText::sprintf('URL THEURL',JRequest::getVar('url','')) . "\n"					 
							 .JText::sprintf('Feedback THEFEEDBACK',JRequest::getVar('feedback','')) . "\n\n"
							 ." -------------------- \n"
							 .JText::sprintf('Browser THEBROWSERVERSION',JRequest::getVar('browser','n/a') .' '. JRequest::getVar('browser_version','n/a')) ."\n"
							 .JText::sprintf('Operating System THEOS',JRequest::getVar('operating_system','n/a')) . "\n"
							 .JText::sprintf('Screen Resolution THERESOLUTION',JRequest::getVar('screen_resolution','n/a')) . "\n"
							 .JText::sprintf('Joomla url THESCRIPTNAME',JRequest::getVar('script_name','')) . "\n"
							 .JText::sprintf('Referer THEREFERER',JRequest::getVar('referer','')) . "\n"
							 .JText::sprintf('Time to fill out form THESPLIT seconds',$split) . "\n"
							 .JText::sprintf('User IP address THEIP', JRequest::getVar('user_ip','')) . "\n"
							 .JText::sprintf('User Agent THEUSERAGENT',JRequest::getVar('user_agent','')) . "\n";
					$mailer->setBody($body);
					
					// Set the email subject
					$mailer->setSubject(JText::sprintf('Feedback for SITENAME',$config->getValue('config.sitename')));
					
					// Optional file attached - As soon as I figure out how to get a screen shot!
					//$mailer->addAttachment(PATH_COMPONENT.DS.'assets'.DS.'document.pdf');
					
					// Send the email
					$send =& $mailer->Send();
					$msg .= ( $send !== true ) ? JText::sprintf('Error sending email THEERROR',$send->message) : JText::_('Mail sent');
				}
			} else {
				if($submitter_name == '') $msg .= JText::_('Please enter a name').'<br/>';
				if(!$match) $msg .= JText::_('Please enter a valid email address').'<br />'; 
				if(!$comment_test) $msg .= JText::_('Please enter some feedback').'<br />'; 
			}
		} else {
			// Spambot validation failed
			$msg = JText::_('I think you are a spambot').'<br />'.JText::_('Your feedback was not submitted');
		}
		echo $msg;
		
		// This is a method called by ajax so we need to bust out of Joomla
		exit();
	}
	
	/**
	Validate an email address.
	Provide email address (raw input)
	Returns true if the email address has the email 
	address format and the domain exists.
	http://www.linuxjournal.com/article/9585?page=0,3
	*/
	function validEmail($email) {
		$isValid = true;
		$atIndex = strrpos($email, "@");
		if (is_bool($atIndex) && !$atIndex) {
			$isValid = false;
		} else {
			$domain = substr($email, $atIndex+1);
			$local = substr($email, 0, $atIndex);
			$localLen = strlen($local);
			$domainLen = strlen($domain);
			if ($localLen < 1 || $localLen > 64) {
				// local part length exceeded
				$isValid = false;
			} else if ($domainLen < 1 || $domainLen > 255) {
				// domain part length exceeded
				$isValid = false;
			} else if ($local[0] == '.' || $local[$localLen-1] == '.') {
				// local part starts or ends with '.'
				$isValid = false;
			} else if (preg_match('/\\.\\./', $local)) {
				// local part has two consecutive dots
				$isValid = false;
			} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
				// character not valid in domain part
				$isValid = false;
			} else if (preg_match('/\\.\\./', $domain)) {
				// domain part has two consecutive dots
				$isValid = false;
			} else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local))) {
				// character not valid in local part unless 
				// local part is quoted
				if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
					$isValid = false;
				}
			}
			if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
				// domain not found in DNS
				$isValid = false;
			}
		}
		return $isValid;
	}
}

// checkdnsrr() support for Windows by HM2K <php [spat] hm2k.org>
function win_checkdnsrr($host, $type='MX') {
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { return; }
    if (empty($host)) { return; }
    $types=array('A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY');
    if (!in_array($type,$types)) {
        user_error("checkdnsrr() Type '$type' not supported", E_USER_WARNING);
        return;
    }
    @exec('nslookup -type='.$type.' '.escapeshellcmd($host), $output);
    foreach($output as $line){
        if (preg_match('/^'.$host.'/',$line)) { return true; }
    }
}

// Define
if (!function_exists('checkdnsrr')) {
    function checkdnsrr($host, $type='MX') {
        return win_checkdnsrr($host, $type);
    }
}