<?php

class Tac_CustomImgCaptcha_ControllerAdmin_Options extends XenForo_ControllerAdmin_Abstract
{
	protected function _preDispatch($action)
	{
		$this->assertAdminPermission('option');
	}

	public function actionLogs()
	{
		$id = $this->_input->filterSingle('id', XenForo_Input::UINT);
		if ($id)
		{
			
			
			$entry = $this->_getLogModel()->getLogById($id);
			if (!$entry)
			{
				return $this->responseError(new XenForo_Phrase('sf_requested_log_entry_not_found'), 404);
			}

			if (XenForo_Application::$versionId >= 1030000)
			{
				$entry['ip_address'] = XenForo_Helper_Ip::convertIpBinaryToString($entry['ip_address']);
			}	
			else
			{
				$entry['ip_address'] = long2ip($entry['ip_address']);
			}
			
			$viewParams = array(
				'entry' => $entry
			);
			return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_Log_CustomImgCaptchaView', 'log_customimgcaptcha_view', $viewParams);
			
		}
		else
		{
			$page = $this->_input->filterSingle('page', XenForo_Input::UINT);
			$perPage = 20;
			$entries = $this->_getLogModel()->getLogs(array(
					'page' => $page,
					'perPage' => $perPage
				));
				
			foreach($entries as $key => $entry){
				
				
				if (XenForo_Application::$versionId >= 1030000)
				{		
					$entries[$key]['ip_address']= XenForo_Helper_Ip::convertIpBinaryToString($entry['ip_address']);
				}
				else
				{
					$entries[$key]['ip_address'] = long2ip($entry['ip_address']);
				}
				
				
			}
			
			$viewParams = array(
				'entries' => $entries,
				'page' => $page,
				'perPage' => $perPage,
				'total' => $this->_getLogModel()->countLogs()
			);
			
			
			return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_Log', 'customimgcaptcha_log', $viewParams);
		}
	}

	
	
	
	
	public function actionDelete()
	{
		$id = $this->_input->filterSingle('id', XenForo_Input::UINT);
		$entry = $this->_getLogModel()->getLogById($id);
		if (!$entry)
		{
			return $this->responseError(new XenForo_Phrase('sf_requested_captcha_log_entry_not_found'), 404);
		}

		if ($this->isConfirmedPost())
		{
			$this->_getLogModel()->deleteLog($id);

			return $this->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				XenForo_Link::buildAdminLink('customimgcaptcha/logs')
			);
		}
		else
		{
			$viewParams = array(
				'entry' => $entry
			);
			return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_Log_CustomImgCaptchaDelete', 'log_customimgcaptcha_delete', $viewParams);
		}
	}

	public function actionClear()
	{
		if ($this->isConfirmedPost())
		{
			$this->_getLogModel()->clearLog();

			return $this->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				XenForo_Link::buildAdminLink('customimgcaptcha/logs')
			);
		}
		else
		{
			$viewParams = array();
			return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_Log_CustomImgCaptchaClear', 'customimgcaptcha_log_clear', $viewParams);
		}
	}

	
	
	
	
	
	
	public function actionImportImgsDialogue(){
		// most of this is just unnecary until I can work out how
		// core also uploads image (similar to DoUpload)	
		$input = $this->_input->filter(array(
			'hash' => XenForo_Input::STRING,
			'content_type' => XenForo_Input::STRING,
			'content_data' => array(XenForo_Input::UINT, 'array' => true),
			'key' => XenForo_Input::STRING
		));
		if (!$input['hash'])
		{
			$input['hash'] = md5(uniqid('', true));
		}
		if (!$input['content_type'])
		{
			$input['content_type'] = "post";
		}
		

		
		$viewParams = array(
			'canUpload' => true,
			'hash' => $input['hash'],
			'contentType' => "post",
			'contentData' => $input['content_data'],
			'attachmentParams' => array(
				'hash' => $input['hash'],
				'content_type' => $input['content_type'],
				'content_data' => $input['content_data']
			),
			'key' => $input['key']
		);
		
		
		return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_UploadCaptchaView', 'customimgcaptcha_import_dialogue', $viewParams);	
		
	}
	
	public function actionUploadImgDialogue(){
		
		// most of this is just unnecary until I can work out how
		// core also uploads image (similar to DoUpload)	
		$input = $this->_input->filter(array(
			'hash' => XenForo_Input::STRING,
			'content_type' => XenForo_Input::STRING,
			'content_data' => array(XenForo_Input::UINT, 'array' => true),
			'key' => XenForo_Input::STRING
		));
		if (!$input['hash'])
		{
			$input['hash'] = md5(uniqid('', true));
		}
		if (!$input['content_type'])
		{
			$input['content_type'] = "post";
		}
		

		
		$viewParams = array(
			'canUpload' => true,
			'hash' => $input['hash'],
			'contentType' => "post",
			'contentData' => $input['content_data'],
			'attachmentParams' => array(
				'hash' => $input['hash'],
				'content_type' => $input['content_type'],
				'content_data' => $input['content_data']
			),
			'key' => $input['key']
		);
		
		
		return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_UploadCaptchaView', 'customimgcaptcha_upload_dialogue', $viewParams);			
	}
	
	public function actionEditCaptchaDialogue()
	{
		$private_uuid = $this->_input->filterSingle('private_uuid', XenForo_Input::STRING);
		$captcha = $this->_getCaptchaModel()->getCaptchaByUUID($private_uuid);
		
		
		$addonFBHP = $this->_getAddOnModel()->getAddOnById('FoolBotHoneyPot');
		$addonFBHPActive = $addonFBHP ? true : false; // check if FoolBotHoneyPot is installed (else return false)
		if($addonFBHPActive){
			$addonFBHPActive = empty($addonFBHP['active']) ? false : true;  // check that it's active
		}
		
		$counts = array();
		if($addonFBHPActive) 
		{		
			$counts = $this->_getCountsModel()->getCountsForCaptcha($private_uuid);	
			if($counts){			
				$counts['human_total'] = $counts['human_passed'] + $counts['human_failed'];
				$counts['bot_total'] = $counts['bot_passed'] + $counts['bot_failed'];
				$counts['counts_total'] = $counts['bot_total'] + $counts['human_total'];		
				if($counts['human_total'] == 0 || $counts['human_passed'] == 0){$counts['human_success'] = 0;}
				else {$counts['human_success'] = ($counts['human_passed']/$counts['human_total']) * 100;}
				if($counts['bot_total'] == 0 || $counts['bot_passed'] == 0){$counts['bot_success'] = 0;}
				else {$counts['bot_success'] = ($counts['bot_passed']/$counts['bot_total']) * 100;}
			}
			else{$counts == false;}
		}
		
		if (!$captcha){return $this->responseError(new XenForo_Phrase('sf_requested_captcha_not_found'), 404);}
			$viewParams = array(
				'entry' => $captcha,
				'counts' => $counts,
				'addonFBHPActive' => $addonFBHPActive					
			);
		

		return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_EditCaptchaView', 'captcha_customimgcaptcha_view', $viewParams);
	}

	public function actionDeleteCaptchaDialogue()
	{
		$private_uuid = $this->_input->filterSingle('private_uuid', XenForo_Input::STRING);
		$captcha = $this->_getCaptchaModel()->getCaptchaByUUID($private_uuid);
		if (!$captcha){return $this->responseError(new XenForo_Phrase('sf_requested_captcha_not_found'), 404);}
		$viewParams = array(
			'entry' => $captcha
		);
		return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_DeleteCaptcha', 'customimgcaptcha_delete_captcha', $viewParams);	
	}

	public function actionUpdateCaptchaDialogue()
	{		
		$private_uuid = $this->_input->filterSingle('private_uuid', XenForo_Input::STRING);
		$captcha = $this->_getCaptchaModel()->getCaptchaByUUID($private_uuid);
		

		if (!$captcha){return $this->responseError(new XenForo_Phrase('sf_requested_captcha_not_found'), 404);}
			$viewParams = array(
				'entry' => $captcha,				
			);
		return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_UpsateCaptcha', 'customimgcaptcha_update_captcha', $viewParams);
	}
	
	public function actionExportImgsDialogue()
	{
		// first thing we need to do is create an access key, so this can only be accessed using that key
		// (dont want for this to be used for easy DOS exploits) 
		// creating the key it's self requires admin option access
		$this->assertAdminPermission('option');
		
		$rand = md5(rand());
		$randomPrefix = substr($rand, 0, 12);
		$access_key = uniqid($randomPrefix);
		
		$keys = $this->_getAccessKeyModel()->getKeyByFileName('export');
		//var_dump($keys['file_name']);
		
		$writer = XenForo_DataWriter::create('Tac_CustomImgCaptcha_DataWriter_AccessKey'); 
		$writer->setExistingData($keys['id']);
		$writer->set('file_name', $keys['file_name']);    		
   		$writer->set('access_key', $access_key);   
   		$writer->set('update_time', time());         
   		$writer->save();
		
	
		$viewParams = array(
			'access_key' => $access_key
		);
		return $this->responseView('Tac_CustomImgCaptcha_ViewAdmin_EditCaptchaView', 'customimgcaptcha_export_captcha', $viewParams);
	}
	
	
	/******************************************************* End Of Dialogue Views *******************************************************/	
	
	
	

		public function actionImportImgs(){
		
		// uploading images to db via sql file, so make sure is admin 1st
		$this->assertAdminPermission('option');	
		

		if(!isset($_FILES['upload'])){return $this->responseError(new XenForo_Phrase('sf_upload_file_not_found'));}
		if($_FILES['upload']['size'] < 1){return $this->responseError(new XenForo_Phrase('sf_file_size_less_than_zero_bytes'));}
		
		$file_name = $_FILES['upload']['name']; 
		$tmp_name = $_FILES['upload']['tmp_name']; 
		$file_type = $_FILES['upload']['type']; 
		$file_size = $_FILES['upload']['size'];
		
		$upload = $_FILES['upload'];
				
		$acceptable_mime_types = array ('text/x-sql', 'text/plain', 'application/octet-stream');
		//var_dump($file_type);
		// possible future support of videos type & flash
		if(!in_array($file_type, $acceptable_mime_types)){return $this->responseError(new XenForo_Phrase('sf_mime_type_not_supported'));}
		
		$insert = $this->_getCaptchaModel()->RunCaptchaInsertSQL($tmp_name);
		
		if(!$insert)
		{
		return $this->responseError(new XenForo_Phrase('sf_data_failed_to_uploaded'));	
		}
			
   				
		return $this->responseRedirect(
			XenForo_ControllerResponse_Redirect::SUCCESS,
			XenForo_Link::buildAdminLink('options/list/customImgCaptcha')
		);		
	}
		
		
		
		
		
			

	
	public function actionUploadImg(){
		
		// uploading image to db, so make sure is admin 1st
		$this->assertAdminPermission('option');	
		
		/* I will need to look at this again to do the same as the core (actionDoUpload)
		*  but there are currently no instructions / manuals how to upload file
		*/
		
		
	
		
		$input = $this->_input->filter(array(
			'hash' => XenForo_Input::STRING,
			'content_type' => XenForo_Input::STRING,
			'content_data' => array(XenForo_Input::UINT, 'array' => true),
			'key' => XenForo_Input::STRING
		));
		
		
		if(!isset($_FILES['upload'])){return $this->responseError(new XenForo_Phrase('sf_upload_file_not_found'));}
		if($_FILES['upload']['size'] < 1){return $this->responseError(new XenForo_Phrase('sf_file_size_less_than_zero_bytes'));}
		
		$img_name = $_FILES['upload']['name']; 
		$tmp_name = $_FILES['upload']['tmp_name']; 
		$img_type = $_FILES['upload']['type']; 
		$img_size = $_FILES['upload']['size'];

		
		
		$acceptable_mime_types = array ('image/jpeg','image/png','image/gif','image/jpg');
		// possible future support of videos type & flash
		if(!in_array($img_type, $acceptable_mime_types)){return $this->responseError(new XenForo_Phrase('sf_mime_type_not_supported'));}
		
		$extract = fopen($tmp_name, 'r'); 
		$content = fread($extract, $img_size); 
		fclose($extract);


		$img = $content;
		
		$rand = md5(rand());
		$randomPrefix = substr($rand, 0, 12); // to avoid colision when the same uuid is created (from same milisec)
		$private_uuid = uniqid($randomPrefix);			
		
		$writer = XenForo_DataWriter::create('Tac_CustomImgCaptcha_DataWriter_Captcha'); 
   		$writer->set('private_uuid', $private_uuid); 
   		$writer->set('img', $img );
   		$writer->set('img_type', $img_type);
   		$writer->set('file_name', $img_name);
   		$writer->set('answers', '');      
   		$writer->set('insert_time', time());         
   		$writer->save();
				
		return $this->responseRedirect(
			XenForo_ControllerResponse_Redirect::SUCCESS,
			XenForo_Link::buildAdminLink('options/list/customImgCaptcha')
		);		
	}
		

		
	public function actionDeleteCaptcha()
	{
		$this->assertAdminPermission('option');
		$private_uuid = $this->_input->filterSingle('private_uuid', XenForo_Input::STRING);
		$captcha = $this->_getCaptchaModel()->getCaptchaByUUID($private_uuid);
		if (!$captcha){return $this->responseError(new XenForo_Phrase('sf_requested_captcha_not_found'), 404);}

		if ($this->isConfirmedPost())
		{
			$this->_getCaptchaModel()->deleteCaptchaByUUID($captcha['private_uuid']);

			return $this->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				XenForo_Link::buildAdminLink('options/list/customImgCaptcha')
			);
		}
	}

	
	public function actionUpdateCaptcha()
	{
		$this->assertAdminPermission('option');
		$private_uuid = $this->_input->filterSingle('private_uuid', XenForo_Input::STRING);
		$captcha = $this->_getCaptchaModel()->getCaptchaByUUID($private_uuid);
		if (!$captcha){return $this->responseError(new XenForo_Phrase('sf_requested_captcha_not_found'), 404);}

		if ($this->isConfirmedPost())
		{
	
			$answers = $this->_input->filterSingle('answers', XenForo_Input::STRING);
			$file_name = $this->_input->filterSingle('filename', XenForo_Input::STRING);
			$width = $this->_input->filterSingle('width', XenForo_Input::UINT);
			$height = $this->_input->filterSingle('height', XenForo_Input::UINT);
			
			$writer = XenForo_DataWriter::create('Tac_CustomImgCaptcha_DataWriter_Captcha');
      		$writer->setExistingData($captcha['id']);  
      		$writer->set('private_uuid', $captcha['private_uuid']); 
      		$writer->set('img', $captcha['img']);
      		$writer->set('file_name', $file_name);   
      		$writer->set('width', $width); 
      		$writer->set('height', $height); 
      		$writer->set('answers', $answers);   
 
      		$writer->set('insert_time', time());         
      		$writer->save();
			
			
			
			return $this->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				XenForo_Link::buildAdminLink('options/list/customImgCaptcha')
			);
		}
	}
	
	
	protected function _getUuidsModel()
	{
		return $this->getModelFromCache('Tac_CustomImgCaptcha_Model_Uuids');
	}	

	protected function _getCaptchaModel()
	{
		return $this->getModelFromCache('Tac_CustomImgCaptcha_Model_Captcha');
	}
	
	protected function _getAccessKeyModel()
	{
		return $this->getModelFromCache('Tac_CustomImgCaptcha_Model_AccessKey');
	}
	
	
	protected function _getLogModel()
	{
		return $this->getModelFromCache('Tac_CustomImgCaptcha_Model_Log');
	}
	
	protected function _getCountsModel()
	{
		return $this->getModelFromCache('Tac_CustomImgCaptcha_Model_Counts');
	}
	
	protected function _getAddOnModel()
	{
		return $this->getModelFromCache('XenForo_Model_AddOn');
	}		
	
	
}