<?php

class Tac_CustomImgCaptcha_Model_Log extends XenForo_Model
{

	
	protected $_request;
	protected $_input;
	protected $_filtered = null;
	protected $_driveId;
	protected $_userId;

		
	public function logRegistrationAttempt(array $log_details = array())
	{

		$this->_input = new XenForo_Input($_REQUEST);

		$input = $this->_filtered = $this->_input->filter(array(
			'custom_img_captcha_response_field' => XenForo_Input::STRING,
		));
	
		

		$log_details['user_answer'] = $input['custom_img_captcha_response_field'];
		
		
		$log_details['log_date'] = XenForo_Application::$time;
		$log_details['full_url'] =  "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];		
		
		$writer = XenForo_DataWriter::create('Tac_CustomImgCaptcha_DataWriter_Log'); 
		$writer->bulkSet($log_details);       
   		$writer->save();		
	}
	
	
	
	public function getLogById($log_id)
	{
		return $this->_getDb()->fetchRow('
			SELECT log.*
			FROM sf_customimgcaptcha_log AS log
			WHERE log.log_id = ?
		', $log_id);
	}

	public function getLogByEmail($email)
	{
		return $this->_getDb()->fetchRow('
			SELECT log.*
			FROM sf_customimgcaptcha_log AS log
			WHERE log.email = ?
		', $email);
	}
	
	public function getLogByIP($ip)
	{
		return $this->_getDb()->fetchRow('
			SELECT log.*
			FROM sf_customimgcaptcha_log AS log
			WHERE log.ip_address = ?
		', $ip);
	}
	
	public function getLogByUsername($username)
	{
		return $this->_getDb()->fetchRow('
			SELECT log.*
			FROM sf_customimgcaptcha_log AS log
			WHERE log.username = ?
		', $username);
	}
		
	
	
	public function getLogs(array $fetchOptions = array())
	{
		$limitOptions = $this->prepareLimitFetchOptions($fetchOptions);

		return $this->fetchAllKeyed($this->limitQueryResults(
			'
				SELECT *
				FROM sf_customimgcaptcha_log
				ORDER BY log_date DESC
			', $limitOptions['limit'], $limitOptions['offset']
		), ';log_id');
	}

	public function countLogs()
	{
		return $this->_getDb()->fetchOne('
			SELECT COUNT(*)
			FROM sf_customimgcaptcha_log
		');
	}

	public function deleteLog($id)
	{
		$db = $this->_getDb();
		$db->delete('sf_customimgcaptcha_log', 'log_id = ' . $db->quote($id));
	}

	public function clearLog()
	{
		$this->_getDb()->query('TRUNCATE TABLE sf_customimgcaptcha_log');
	}



	public function LogEvent(array $input = array())
	{
		$options = XenForo_Application::get('options');
		$logEvents = $options->cicLogEvents;
		$addOnModel = XenForo_Model::create('XenForo_Model_AddOn');
		$catpchaModel = XenForo_Model::create('Tac_CustomImgCaptcha_Model_Captcha');
		$uuidsModel = XenForo_Model::create('Tac_CustomImgCaptcha_Model_Uuids');		
		$loginModel = XenForo_Model::create('XenForo_Model_Login');
		$username = (isSet($input['username']))? $input['username'] : "";
		$email = (isSet($input['email']))? $input['email'] : "";
		
		if($logEvents == "noLog")
		{
			return;
		}
			
		if ((!$addon = $addOnModel->getAddOnById('FoolBotHoneyPot')) || empty($addon['active']) || isSet($input['username_email']) || isSet($input['_guestUsername'])  )
		{
			// FoolBotHoneyPot is either not installed or not active (easy to get username / email address )
			
			if (isSet($input['username_email']))  // try to log email / username from different captcha areas (contact us, logged out posts, registration, new FB register)
			{
				$username = $input['username_email'];
				$email = "";
			}
			else if(isSet($input['_guestUsername']))
			{
				$username = $input['_guestUsername'];
				$email = "";
			}
			else if(isSet($input['fb_token']))
			{
				$username = (isSet($input['username']))? $input['username'] : "";
				$email = "Via FaceBook";	
			}

		}
		else {		
			// FoolBotHoneyPot is installed, the keys have been obfuscated, input needs to be checked via array order
			$username = $catpchaModel->getObsfucatedUsername($input);
			$email = $catpchaModel->getObsfucatedEmail($input);
		}

		
		if (XenForo_Application::$versionId >= 1030000)
		{
			$ipAddress = XenForo_Helper_Ip::getBinaryIp(); 		
		}
		else
		{
			$ipAddress = $this->_getLoginModel()->convertIpToLong();
		}		
		
		$log_details = array(
					'username' => $username,
					'email' => $email,
					'file_name'	=> 'Unknown',
					'passed'	=> 0,
					'possible_human'	=> 1,
					'ip_address' => $ipAddress,
					'user_answer' => '', 
					'expected_answer' => 'Unknown',
					'message' => '',
					'details' => ''	
				); 
		
	
		if(!isSet($input['custom_img_captcha_response_field']))
		{
			if($logEvents == "logAll" || $logEvents == "LogAllFailed")  // just return if logAllNonObviousBot
			{
			
				$lastUUID = $uuidsModel->getLastUUID();
				$log_details['private_uuid'] =  $lastUUID['private_uuid'];
				$log_details['expected_answer'] =  $lastUUID['answers'];
				$log_details['file_name'] =  $lastUUID['file_name'];
						
				$log_details['details'] = "custom_img_captcha_response_field was not set: ".
				"This can happen when a post request is sent directly to the page without sending all the fields found on the page, ".
				"this will happen if an automated program expects to be able to send only standard form fields";			
				$log_details['message'] = "Bot Attempt: custom_img_captcha_response_field was not set";							
				$log_details['possible_human'] = 0;
				
				$this->logRegistrationAttempt($log_details);

				
			}
			$uuidsModel->deleteUuidsBeforeTime(time());	
			return;		
		}
		
		
		if(!isSet($input['public_uuid']))
		{
			if($logEvents == "logAll" || $logEvents == "LogAllFailed") // just return if logAllNonObviousBot
			{	
				$lastUUID = $uuidsModel->getLastUUID();
				$log_details['private_uuid'] =  $lastUUID['private_uuid'];
				$log_details['expected_answer'] =  $lastUUID['answers'];
				$log_details['file_name'] =  $lastUUID['file_name'];
									
				$log_details['details'] = "public_uuid was not set: ".
				"This can happen when a post request is sent directly to the page without sending all the fields found on the page, ".
				"this will happen if an automated program expects to be able to send only the standard form fields";		
				$log_details['message'] = "Bot Attempt: custom_img_captcha_response_field was not set";			
				$log_details['possible_human'] = 0;
				
				$this->logRegistrationAttempt($log_details);
								
			}
			$uuidsModel->deleteUuidsBeforeTime(time());
			return;
		}	
		
				
		$public_uuid = $input['public_uuid'];	
		$uuids = $uuidsModel->getUuidsByPublicUuid($public_uuid);				
		$allPossibleCorectAnswers = array_map('trim', explode(",",$uuids['answers']));
		$allPossibleCorectAnswers = unserialize(strtolower(serialize($allPossibleCorectAnswers)));
		
		$log_details['user_answer'] = strtolower($input['custom_img_captcha_response_field']);
		$log_details['expected_answer'] = serialize($allPossibleCorectAnswers);
		$log_details['file_name'] = $uuids['file_name'];
		$log_details['private_uuid'] =  $uuids['private_uuid'];
		
			
		if($log_details['user_answer'] == "")
		{
			if($logEvents != "noLog")
			{

				$log_details['details'] = "No answer was provided: ".
				"The CAPTCHA image answer was sent as empty field";			
				$log_details['message'] = "No answer was provided";			
				
				$this->logRegistrationAttempt($log_details);
			}

			
			$uuidsModel->deleteUuidsBeforeTime(time());
			return;
		
		}
		
		
		if(in_array($log_details['user_answer'], $allPossibleCorectAnswers)){	
			if($logEvents == "logAll" || $logEvents == "logAllNonObviousBot")
			{				
				$log_details['details'] = "The correct answer was provided: ";		
				$log_details['message'] = "The correct answer was provided";
				$log_details['passed'] = 1;			
 
				$this->logRegistrationAttempt($log_details);
			}	
			return;		
		}

		else {			
				if($logEvents != "noLog")			
				{	
													
					$log_details['details'] = "An incorrect answer was provided: ";			
					$log_details['message'] = "An incorrect answer was provided";			
	 			
					$this->logRegistrationAttempt($log_details);
				}			
		

			return;			
			}
		
		if($logEvents != "noLog")
		{				
			$log_details['details'] = "An unknown event occured";		
			$log_details['message'] = "An unknown event occured";	
			
			$this->logRegistrationAttempt($log_details);
		}
		return;		
	

	}
	
	
	public function runWeeklyCleanUp()
    {

    	// logs (no more than 3 months)
    	$log_date = (XenForo_Application::$time) - (3 * 28 * 24 * 60 * 60);
    	$this->_getDb()->fetchRow('
        	DELETE
        	FROM sf_customimgcaptcha_log
        	WHERE log_date < ?
       		', $log_date);
    }
	
	
	protected function _getLoginModel()
	{
		return $this->getModelFromCache('XenForo_Model_Login');
	}
	
	
	
}