LittleDemon WebShell


Linux hosting5.siteguarding.com 3.10.0-962.3.2.lve1.5.88.el7.x86_64 #1 SMP Fri Sep 26 14:06:42 UTC 2025 x86_64
Path : /home/devsafetybis/op4103.dev.safetybis.com/admin1qw/controller/module/
File Upload :
Command :
Current File : /home/devsafetybis/op4103.dev.safetybis.com/admin1qw/controller/module/dashboard.php

<?php

namespace Opencart\Admin\Controller\Extension\siteguardinggeoprotection\Module;

require_once(DIR_EXTENSION . 'siteguardinggeoprotection' . DIRECTORY_SEPARATOR . 'system' . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR  . 'sggeo' . DIRECTORY_SEPARATOR . 'ocGeoProtectionGeoClass.php');

class Dashboard extends \Opencart\System\Engine\Controller
{
	private $error = array();
	private $moduleCode = 25;
	private $api = 'https://www.siteguarding.com/ext/plugin_api/index.php';
	private $geoPath = DIR_EXTENSION . 'siteguardinggeoprotection' . DIRECTORY_SEPARATOR . 'system' . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR  . 'sggeo' . DIRECTORY_SEPARATOR;
	
	public function index(): void
    {
		$this->load->language('extension/siteguardinggeoprotection/module/dashboard');
		
		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('setting/setting');
		
		$params = $this->Get_Params();
		
		if (isset($params['auto_geodb_update']) && $params['auto_geodb_update'] == 1) $this->UpdateGEOdb();
		
		$params['frontend_country_list'] = (isset($params['frontend_country_list']) && !empty($params['frontend_country_list'])) ? json_decode($params['frontend_country_list'], true) : array();
		$params['backend_country_list'] = (isset($params['backend_country_list']) && !empty($params['backend_country_list'])) ? json_decode($params['backend_country_list'], true) : array();
		$params['redirects'] = (isset($params['redirects']) && !empty($params['redirects'])) ? json_decode($params['redirects'], true) : array();
		
		$data['template'] = $this->config->get('config_theme');
		
		self::CheckBlockLog();
		
		$this->document->addStyle(HTTP_CATALOG . 'extension/siteguardinggeoprotection/admin/view/javascript/semantic/semantic.min.css');
		$this->document->addScript(HTTP_CATALOG . 'extension/siteguardinggeoprotection/admin/view/javascript/javascript.js');
		$this->document->addScript(HTTP_CATALOG . 'extension/siteguardinggeoprotection/admin/view/javascript/semantic/semantic.min.js');
		
		var_dump(HTTP_CATALOG . 'extension/siteguardinggeoprotection/admin/view/javascript/semantic/semantic.min.css'); exit;
		
		$url = $this->url->link('common/home');
		$domain = self::PrepareDomain($url);
		$aCode = strtoupper( md5( md5( md5($domain)."Version 2NY5DANTlYQ5WIZW" )."wNEzDQYT5NI3TdMj" ) );
		
		if (isset($params['registration_code']) && ($params['registration_code'] === $aCode)) {
			$data['isPRO'] = true;
		} else {
			$data['isPRO'] = false;
		}
		
		if (isset($this->request->post['ajax']) && $this->request->post['ajax'] == md5(date("YmdH"))) {
			if ($data['isPRO']) {
				print $this->blockPagePreview($this->request->post['data']);
			} else {
				print $this->blockPagePreview();
			}
			die;
		}
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate($params)) {

			$action = '';
			if (isset($_REQUEST['action'])) $action = trim($_REQUEST['action']);

			// Actions
			if ($action != '')
			{
				$action_message = '';
				$message_type = '';
				$settings = $this->Get_Params();
				switch ($action)
				{   
						
					case 'register_ext':

						if (isset($this->request->post['registration_code']) && $this->request->post['registration_code'] != '') $settings['registration_code'] = $this->request->post['registration_code'];
						if (isset($this->request->post['auto_geodb_update']) && $this->request->post['auto_geodb_update'] != '') $settings['auto_geodb_update'] = $this->request->post['auto_geodb_update'];
						
						if (!$data['isPRO']) {
                            $settings['auto_geodb_update'] = 0;
                        }
						$this->Set_Params($settings);
						break;
						
					case 'save_frontend_params':

						if (isset($this->request->post['frontend_country_list']) && count($this->request->post['frontend_country_list'])) $settings['frontend_country_list'] = $this->request->post['frontend_country_list'];
						
						$settings['frontend_ip_list'] = '';
						$settings['frontend_ip_list_allow'] = '';
						if ($data['isPRO'] && isset($this->request->post['frontend_ip_list'])) $settings['frontend_ip_list'] = $this->request->post['frontend_ip_list'];
						if ($data['isPRO'] && isset($this->request->post['frontend_ip_list_allow'])) $settings['frontend_ip_list_allow'] = $this->request->post['frontend_ip_list_allow'];
					
						$settings['frontend_country_list'] = @json_encode($settings['frontend_country_list']);
						
						$this->Set_Params($settings);

						break;
						
					case 'Save_backend_params':


						if (isset($this->request->post['backend_country_list'])) $settings['backend_country_list'] = $this->request->post['backend_country_list'];
						else $settings['backend_country_list'] = array();
						
						
						$settings['backend_ip_list'] = '';
						$settings['backend_ip_list_allow'] = '';
						if ($data['isPRO'] && isset($this->request->post['backend_ip_list'])) $settings['backend_ip_list'] = $this->request->post['backend_ip_list'];
						if ($data['isPRO'] && isset($this->request->post['backend_ip_list_allow'])) $settings['backend_ip_list_allow'] = $this->request->post['backend_ip_list_allow'];

						$settings['backend_country_list'] = @json_encode($settings['backend_country_list']);

						$this->Set_Params($settings);

						break;
					case 'Customization_save':
						

						if (isset($this->request->post['custom_status'])) $settings['custom_status'] = intval($this->request->post['custom_status']);
						else $settings['custom_status'] = 0;
						if (isset($this->request->post['logo_url'])) $settings['logo_url'] = ($this->request->post['logo_url']);
						if (isset($this->request->post['text_1'])) $settings['text_1'] = ($this->request->post['text_1']);
						if (isset($this->request->post['text_2'])) $settings['text_2'] = ($this->request->post['text_2']);
						if (isset($this->request->post['hide_ipinfo'])) $settings['hide_ipinfo'] = intval($this->request->post['hide_ipinfo']);
						else $settings['hide_ipinfo'] = 0;
						if (isset($this->request->post['hide_debug'])) $settings['hide_debug'] = intval($this->request->post['hide_debug']);
						else $settings['hide_debug'] = 0;

						$this->Set_Params($settings);

						break;
						
					case 'save_redirects':
						$settings['redirects'] = isset($this->request->post['redirects']) ? array_filter($this->request->post['redirects']) : array();


						$settings['redirects'] = @json_encode($settings['redirects']);
							
							
						$this->Set_Params($settings);


						break;


				}
			}	
			
			$this->checkIndexFiles();


			$this->session->data['success'] = $this->language->get('text_success');

			$this->response->redirect($this->url->link('extension/siteguardinggeoprotection/module/dashboard', 'user_token=' . $this->session->data['user_token'] . '&type=module', true));
		}
		
		$this->checkIndexFiles();
		
		$myIP = $this->getMyIP();
		
		if (filter_var($myIP, FILTER_VALIDATE_IP)) {
			$geo = new \GEO_OC_Geo_IP2Country();
			$data['myCountryCode'] = $geo->getCountryByIP($myIP);
			$data['myCountry'] = $geo->getNameByCountryCode($data['myCountryCode']) ? $geo->getNameByCountryCode($data['myCountryCode']) : '';
		}
		
		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_edit'] = $this->language->get('text_edit');
		$data['text_edit_secure'] = $this->language->get('text_edit_secure');
		$data['text_edit_extra'] = $this->language->get('text_edit_extra');
		$data['text_edit_captcha'] = $this->language->get('text_edit_captcha');
		$data['text_success'] = $this->language->get('text_success');
		$data['text_extension'] = $this->language->get('text_extension');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_instructions'] = $this->language->get('text_instructions');
		$data['text_disabled'] = $this->language->get('text_disabled');

		$data['security_tools'] = $this->language->get('security_tools');
		$data['includes'] = $this->language->get('includes');
		$data['secure_website_button'] = $this->language->get('secure_website_button');
		$data['you_have'] = $this->language->get('you_have');
		$data['pro_version'] = $this->language->get('pro_version');
		$data['free_version'] = $this->language->get('free_version');
		$data['free_version_limits'] = $this->language->get('free_version_limits');
		$data['upgrade'] = $this->language->get('upgrade');
		$data['already_purchased'] = $this->language->get('already_purchased');
		$data['here'] = $this->language->get('here');
		$data['put_code'] = $this->language->get('put_code');
		$data['geo_front_protection'] = $this->language->get('geo_front_protection');
		$data['geo_back_protection'] = $this->language->get('geo_back_protection');
		$data['customize'] = $this->language->get('customize');
		$data['geo_redirects'] = $this->language->get('geo_redirects');

		$data['block_by_country'] = $this->language->get('block_by_country');
		$data['quick_buttons'] = $this->language->get('quick_buttons'); 
		
		$data['select_all_exclude_own'] = $this->language->get('select_all_exclude_own');
		$data['uncheck_all'] = $this->language->get('uncheck_all');
		$data['select_all_exclude_us'] = $this->language->get('select_all_exclude_us');
		$data['select_all_exclude_eu'] = $this->language->get('select_all_exclude_eu');
		$data['select_all_exclude_3rd'] = $this->language->get('select_all_exclude_3rd');
		
		$data['redirect_description'] = $this->language->get('redirect_description');

		$data['country'] = $this->language->get('country');
		$data['redirect_url'] = $this->language->get('redirect_url');
		$data['redirect_placeholder'] = $this->language->get('redirect_placeholder');

		
		
		$data['code_placeholder'] = $this->language->get('code_placeholder');
		$data['save_and_apply'] = $this->language->get('save_and_apply');
		
		
		$data['code_not_correct'] = $this->language->get('desc_fail');


		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		
		
		
		$data['statistic'] = $this->language->get('statistic');
		$data['settings'] = $this->language->get('settings');
		$data['key'] = $this->language->get('key');
		$data['latest_logs'] = $this->language->get('latest_logs');
		$data['records'] = $this->language->get('records');
		$data['no_records'] = $this->language->get('no_records');
		$data['date'] = $this->language->get('date');
		$data['country'] = $this->language->get('country');
		$data['ip_address'] = $this->language->get('ip_address');
		$data['status'] = $this->language->get('status');
		$data['redirected'] = $this->language->get('redirected');
		$data['hours24'] = $this->language->get('hours24');
		$data['days7'] = $this->language->get('days7');
		$data['days30'] = $this->language->get('days30');
		$data['activity_for_the_last'] = $this->language->get('activity_for_the_last');
		$data['no_data'] = $this->language->get('no_data');
		$data['blocked_traffic'] = $this->language->get('blocked_traffic');
		$data['redirected_traffic'] = $this->language->get('redirected_traffic');
		$data['url'] = $this->language->get('url');
		$data['blocked'] = $this->language->get('blocked');
		
		$data['pies_data'] = $this->getPiesData();
		
		$data['block_class'] = '';		
		$data['amount_records'] = 50;		
		
		$data['latest_records_array'] = $this->GetLatestRecords($data['amount_records']);
		
		$data['updateDb'] = '';		
		
		if (isset($this->request->get['geo_update']) && intval($this->request->get['geo_update']) == 1)
        { 
            $this->UpdateGEOdb(1);
			$data['updateDb'] = 1;
        }
		
		$data['last_update_date'] = $this->Get_Last_Update_date_GEOdb();
		
		$data['do_update'] = false;
		
		if ($data['isPRO']) $data['do_update'] = true;
			elseif (time() - strtotime(trim($data['last_update_date'])) > 30 * 24 * 60 * 60) $data['do_update'] = true;

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}
		
		$data['domain'] = $domain;
		$data['ajaxurl'] = $_SERVER['REQUEST_URI'];
		$data['ajax_md5'] = md5(date("YmdH"));
		$data['free'] = (!$data['isPRO']) ? 'free' : '';
		$data['myIP'] = $myIP;
		$data['debugMode'] = (is_file( dirname(DIR_APPLICATION) . DIRECTORY_SEPARATOR . 'geodebug.txt')) ? true : false;
		
		if (isset($this->request->post['hide_debug'])) {
			$data['hide_debug'] = $this->request->post['hide_debug'];
		}  else {
			$data['hide_debug'] = $params['hide_debug'];
		}
		
		if (isset($this->request->post['auto_geodb_update'])) {
			$data['auto_geodb_update'] = $this->request->post['auto_geodb_update'];
		}  else {
			$data['auto_geodb_update'] = $params['auto_geodb_update'];
		}
		
		
		if (isset($this->request->post['hide_ipinfo'])) {
			$data['hide_ipinfo'] = $this->request->post['hide_ipinfo'];
		}  else {
			$data['hide_ipinfo'] = $params['hide_ipinfo'];
		}
		
		if (isset($this->request->post['text_2'])) {
			$data['text_2'] = $this->request->post['text_2'];
		}  else {
			$data['text_2'] = $params['text_2'];
		}
		
		if (isset($this->request->post['text_1'])) {
			$data['text_1'] = $this->request->post['text_1'];
		}  else {
			$data['text_1'] = $params['text_1'];
		}
		
		if (isset($this->request->post['logo_url'])) {
			$data['logo_url'] = $this->request->post['logo_url'];
		}  else {
			$data['logo_url'] = $params['logo_url'];
		}
		
		if (isset($this->request->post['custom_status'])) {
			$data['custom_status'] = $this->request->post['custom_status'];
		}  else {
			$data['custom_status'] = $params['custom_status'];
		}
		
		if (isset($this->request->post['backend_ip_list_allow'])) {
			$data['backend_ip_list_allow'] = $this->request->post['backend_ip_list_allow'];
		}  else {
			$data['backend_ip_list_allow'] = $params['backend_ip_list_allow'];
		}			


		if (isset($this->request->post['backend_ip_list'])) {
			$data['backend_ip_list'] = $this->request->post['backend_ip_list'];
		}  else {
			$data['backend_ip_list'] = $params['backend_ip_list'];
		}			

		if (isset($this->request->post['frontend_ip_list_allow']) ) {
			$data['frontend_ip_list_allow'] = $this->request->post['frontend_ip_list_allow'];
		}  else {
			$data['frontend_ip_list_allow'] = $params['frontend_ip_list_allow'];
		}		

		if (isset($this->request->post['frontend_ip_list'])) {
			$data['frontend_ip_list'] = $this->request->post['frontend_ip_list'];
		}  else {
			$data['frontend_ip_list'] = $params['frontend_ip_list'];
		}
		
		if (isset($this->request->post['frontend_country_list'])) {
			$data['frontend_country_list'] = $this->request->post['frontend_country_list'];
		}  else {
			$data['frontend_country_list'] = $params['frontend_country_list'];
		}
		
		if (isset($this->request->post['backend_country_list'])) {
			$data['backend_country_list'] = $this->request->post['backend_country_list'];
		}  else {
			$data['backend_country_list'] = $params['backend_country_list'];
		}
		
		$data['frontend_country_list_checkboxes'] = $this->CountryList_checkboxes( false, $data['isPRO'],$data['frontend_country_list']);
		$data['backend_country_list_checkboxes'] = $this->CountryList_checkboxes(true, $data['isPRO'],$data['backend_country_list']);
		
		if (isset($this->request->post['redirects'])) {
			$data['redirects'] = $this->request->post['redirects'];
		}  else {
			$data['redirects'] = $params['redirects'];
		}
		

		if (isset($this->request->post['registration_code'])) {
			$data['registration_code'] = $this->request->post['registration_code'];
		}  else {
			$data['registration_code'] = $params['registration_code'];
		}
		

		if (isset($this->error['frontend_country_list'])) {
			$data['error_country_list'] = $this->error['frontend_country_list'];
		} else {
			$data['error_country_list'] = '';
		}
		
		if (isset($this->error['redirects'])) {
			$data['error_redirects'] = $this->error['redirects'];
		} else {
			$data['error_redirects'] = '';
		}
		
		
		if (isset($this->error['registration_code'])) {
			$data['error_registration_code'] = $this->error['registration_code'];
		} else {
			$data['error_registration_code'] = '';
		}
		
		
		if (isset($this->request->get['tab_id'])) {
			$data['tab_id'] = $this->request->get['tab_id'];
		} else {
			$data['tab_id'] = 0;
		}

		
		$data['tab_array'][] = ''; 
		$data['tab_array'][] = '';
		$data['tab_array'][] = '';   
		$data['tab_array'][] = '';
		$data['tab_array'][$data['tab_id']] = 'active ';

		
		$data['breadcrumbs'] = [];
		$data['breadcrumbs'][] = [
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token']),
        ];
		$data['breadcrumbs'][] = [
            'text' => $this->language->get('text_extension'),
            'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module' . '&tab_id=', true),
        ];
		$data['breadcrumbs'][] = [
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('extension/siteguardinggeoprotection/module/dashboard', 'user_token=' . $this->session->data['user_token']),
        ];
		
		$data['action'] = $this->url->link('extension/siteguardinggeoprotection/module/dashboard', 'user_token=' . $this->session->data['user_token'], true);

		$data['cancel'] = $this->url->link('extension/siteguardinggeoprotection/module/dashboard', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);
		
		$data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('extension/siteguardinggeoprotection/module/dashboard', $data));
	}
	
	public function Get_Params() {
		$config_file = $this->geoPath . 'ocGeoProtectionSettings.php';
		if (!is_file($config_file)) $this->Set_Params(false);
		//include_once($config_file);

		$content = file_get_contents($config_file);
		return @json_decode($content, true);
		return $geo_oc_settings;
	}
	
	private function Set_Params($params = array()) 
	{

		$new = array();
		
		$new['frontend_ip_list'] = isset($params['frontend_ip_list'])? $params['frontend_ip_list'] : '';
		$new['frontend_ip_list_allow'] = isset($params['frontend_ip_list_allow'])? $params['frontend_ip_list_allow'] : '';
		$new['backend_ip_list'] = isset($params['backend_ip_list'])? $params['backend_ip_list'] : '';
		$new['backend_ip_list_allow'] = isset($params['backend_ip_list_allow'])? $params['backend_ip_list_allow'] : '';
		$new['backend_country_list'] = isset($params['backend_country_list'])? $params['backend_country_list'] : array();
		$new['frontend_country_list'] = isset($params['frontend_country_list'])? $params['frontend_country_list'] : array();
		$new['redirects'] = isset($params['redirects'])? $params['redirects'] : array();
		$new['registration_code'] = isset($params['registration_code'])? $params['registration_code'] : '';
		$new['auto_geodb_update'] = isset($params['auto_geodb_update'])? $params['auto_geodb_update'] : 0;
		
		$new['custom_status'] = isset($params['custom_status'])? $params['custom_status'] : 0;
		$new['logo_url'] = isset($params['logo_url'])? $params['logo_url'] : '';
		$new['text_1'] = isset($params['text_1'])? $params['text_1'] : '';
		$new['text_2'] = isset($params['text_2'])? $params['text_2'] : '';
		$new['hide_ipinfo'] = isset($params['hide_ipinfo'])? $params['hide_ipinfo'] : 0;
		$new['hide_debug'] = isset($params['hide_debug'])? $params['hide_debug'] : 0;
		

		
		$line = json_encode($new);
		
		$fp = fopen($this->geoPath . 'ocGeoProtectionSettings.php', 'w');
		fwrite($fp, $line);
		fclose($fp);
	}
	
	public function UpdateGEOdb($manual = 0, $days = 30)
    {
        $last_update_date = $this->Get_Last_Update_date_GEOdb();
        
        $date_days_ago = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")-$days, date("Y")));
        
		$url = $this->url->link('common/home');
		$domain = self::PrepareDomain($url);
        
        if ($last_update_date === false || $last_update_date <= $date_days_ago || $manual == 1)
        {
            $plg_name = 'oc-geo-website-protection';
            $SITEGUARDING_SERVER = 'https://www.siteguarding.com/ext/updater/updater.php';
            $request_url = $SITEGUARDING_SERVER.'?product=geo_db&domain='.$domain.'&plg_name='.$plg_name;
            $response = file_get_contents($request_url);
            $json = (array) @json_decode($response, true);

            if ($json === false || count($json) == 0) return;   // Error in answer
            
            if (trim($json['status']) != 'ok') return;   // Error

            $new_md5 = trim($json['md5']); 
            
            $geo_file = $this->geoPath . 'geo.mmdb';
            if ($new_md5 != md5_file($geo_file))
            {
                // Update
                $request_url = $SITEGUARDING_SERVER.'?product=geo_db&domain='.$domain.'&plg_name='.$plg_name.'&md5='.$new_md5.'&action=download';
                $file_save_tmp = dirname(__FILE__).'/geo.mmdb.tmp';
                $status = self::CreateRemote_file_contents($request_url, $file_save_tmp);
                if ($status !== false && md5_file($file_save_tmp) == $new_md5)
                {
                    unlink($geo_file);
                    copy($file_save_tmp, $geo_file);
                    unlink($file_save_tmp);
                }
            }
            
            // Save update date
            $file = $this->geoPath . 'geo_update.log';
            $fp = fopen($file, 'w');
            fwrite($fp, date("Y-m-d"));
            fclose($fp);
        }
    }

	public function Get_Last_Update_date_GEOdb()
    {
        $file = $this->geoPath . 'geo_update.log';
        if (!file_exists($file)) return false;
        
        $handle = fopen($file, "r");
        $contents = fread($handle, filesize($file));
        fclose($handle);
        
        return $contents;
    }

	public static function CreateRemote_file_contents($url, $dst)
    {
        if (extension_loaded('curl')) 
        {
            $dst = fopen($dst, 'w');
            
            $ch = curl_init();
            
            curl_setopt($ch, CURLOPT_URL, $url );
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
            curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
            curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3600000);
            curl_setopt($ch, CURLOPT_FILE, $dst);
            curl_setopt($ch, CURLOPT_FAILONERROR, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 10 sec
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 10000); // 10 sec
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            
            $a = curl_exec($ch);
            if ($a === false)  return false;
            
            $info = curl_getinfo($ch);
            
            curl_close($ch);
            fflush($dst);
            fclose($dst);
            
            return $info['size_download'];
        }
        else return false;
    }

	public static function PrepareDomain($domain)
	{
	    $host_info = parse_url($domain);
	    if ($host_info == NULL) return false;
	    $domain = $host_info['host'];
	    if ($domain[0] == "w" && $domain[1] == "w" && $domain[2] == "w" && $domain[3] == ".") $domain = str_replace("www.", "", $domain);
	    
	    return $domain;
	}

	public function CheckBlockLog()
    {
        $file_tmp_block_log = $this->geoPath . 'block.log';
        if (file_exists($file_tmp_block_log))
        {
            $handle = fopen($file_tmp_block_log, "r");
            $contents = fread($handle, filesize($file_tmp_block_log));
            fclose($handle);
            
            unlink($file_tmp_block_log);
            
            $contents = explode("\n", $contents);
            if (count($contents))
            {
                foreach ($contents as $row)
                {
                    $row = (array) @json_decode($row, true);
					
                    if ($row) $this->Save_Block_alert($row);
                }
            }
        }
    }

	public function Save_Block_alert($alert_data)
    {

        $table_name = DB_PREFIX . 'geo_oc_stats';
		         
		if (!$this->db->query("SELECT 1 FROM `$table_name` LIMIT 1")) $this->createStatsTable();
		
		$sql = "INSERT INTO " . $table_name . " SET time = '" . $this->db->escape(intval($alert_data['time'])) . "', ip = '" . $this->db->escape($alert_data['ip']) . "', country_code = '" . $this->db->escape($alert_data['country_code']) . "', url = '" . $this->db->escape(addslashes($alert_data['url'])) . "', type = '" . $this->db->escape(intval($alert_data['type'])) . "'";
        
        $this->db->query($sql);
    }

	public function createStatsTable(){

		$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "geo_oc_stats` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `time` int(11) NOT NULL,
              `ip` varchar(15) NOT NULL,
              `country_code` varchar(2) NOT NULL,
              `url` varchar(128) NOT NULL,
              `type` int(11) NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");
	}


	public function install(){
		$this->Set_Params();
		$this->createStatsTable();
		$this->apiRequest(1);
	}
	
	public function uninstall(){
		$this->PatchFile(false, false);
		if (is_file($this->geoPath . 'ocGeoProtectionSettings.php')) @unlink($this->geoPath . 'ocGeoProtectionSettings.php');
		$this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "geo_oc_stats`");
		$this->apiRequest(2);
	}
	
	private function apiRequest($type)
    {

		$url = $this->url->link('common/home');
		$website_url = self::PrepareDomain($url);

		$data = array(
                'action' => 'inform',
                'website_url' => $website_url,
                'action_code' => $type,
                'plugin_code' => $this->moduleCode,
            );

		
		$result = $this->sendRequest($this->api, $data);
		
		
    }
	
	private function PatchFile($f = false, $action = true)   // true - insert, false - remove
	{
		if (!defined('DIRSEP')) {
			if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && !defined('DIRSEP')) define('DIRSEP', '//');
			else define('DIRSEP', '/');
		}
        
		
		$file = $this->geoPath . "geo.check.php";
		$files = array();
		
        $integration_code = '<?php /* Siteguarding Block 6DBBJDS929DE-START */ if(file_exists("'.$file.'"))include_once("'.$file.'");/* Siteguarding Block 6DBBJDS929DE-END */?>';
        
		if ($f) {
			$files[] = $f;
		} else {
			$scan_path = str_replace(array('/', '\\'), DIRSEP, DIR_APPLICATION);
			$files[] = $scan_path.'config.php';
			$files[]= dirname(dirname($files[0])) . DIRSEP . 'config.php';
		}
        
        foreach ($files as $filename) {
			
			$handle = fopen($filename, "r");
			if ($handle === false) return false;
			$contents = fread($handle, filesize($filename));
			if ($contents === false) return false;
			fclose($handle);
			
			$pos_code = stripos($contents, '6DBBJDS929DE');
			
			if ($action === false)
			{
				// Remove block
				$contents = str_replace($integration_code, "", $contents);
			}
			else {
				// Insert block
				if ( $pos_code !== false/* && $pos_code == 0*/)
				{
					// Skip double code injection
					return true;
				}
				else {
					// Insert
					$contents = $integration_code.$contents;
				}
			}
			
			$handle = fopen($filename, 'w');
			if ($handle === false) 
			{
				// 2nd try , change file permssion to 666
				$status = chmod($filename, 0666);
				if ($status === false) return false;
				
				$handle = fopen($filename, 'w');
				if ($handle === false) return false;
			}
			
			$status = fwrite($handle, $contents);
			if ($status === false) return false;
			fclose($handle);
		}
        
        return true;
	}
	
	private function sendRequest($url, $request, $method = 'POST', $headers = false) 
	{
		

		if (is_array($request)) $request = http_build_query($request);
		$method = strtoupper($method);
		
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	
		switch($method) {
			case 'POST':
			case 'PATCH':
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
				break;
			case 'DELETE':
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
				break;
			
		}
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		if ($headers) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$response = curl_exec($ch);
		$ch_error = curl_error($ch);
		if (!empty($ch_error)) {
			return array('status' => 'error', 'reason' => $ch_error, 'report_url' => '');
		}
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		
		if ($method == 'DELETE') return $httpCode;
		
		return @json_decode($response, true);
	}
	
	protected function validate($params) {
		
		$url = $this->url->link('common/home');
		$domain = self::PrepareDomain($url);
		$aCode = strtoupper( md5( md5( md5($domain)."Version 2NY5DANTlYQ5WIZW" )."wNEzDQYT5NI3TdMj" ) );
	
		if (isset($this->request->post['registration_code']) && ($this->request->post['registration_code'] != '')) {

			if ($this->request->post['registration_code'] != $aCode) {
				
				$this->error['warning'] = $this->language->get('code_not_correct');
			} 
		}
		
		if (((isset($this->request->post['frontend_country_list']) && 5 < count($this->request->post['frontend_country_list'])) || (isset($this->request->post['redirects']) && 5 < count(array_filter($this->request->post['redirects'])))) && ($params['registration_code'] !== $aCode)) {
			$this->error['warning'] = 'Free version limit is 5 countries. Please get full version. <a target="_blank" href="https://www.siteguarding.com/en/buy-extention/opencart-geo-website-protection">Full Version</a>';
		}

		if (($params['registration_code'] !== $aCode) && isset($this->request->post['action']) && $this->request->post['action'] == 'Customization_save') {
			$this->error['warning'] = 'Settings not saved. Please <a href="https://www.siteguarding.com/en/buy-extention/wordpress-geo-website-protection" target="_blank">Get Full Version</a> to unlock all the features';
		}

		if (!$this->user->hasPermission('modify', 'extension/siteguardinggeoprotection/module/dashboard')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}
	
	public function checkIndexFiles()
	{
		if (!defined('DIRSEP')) {
			if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && !defined('DIRSEP')) define('DIRSEP', '//');
			else define('DIRSEP', '/');
		}

		$scan_path = str_replace(array('/', '\\'), DIRSEP, DIR_APPLICATION);
		$files[] = $scan_path.'config.php';
		$files[]= dirname(dirname($files[0])) . DIRSEP . 'config.php';

		foreach ($files as $filename) {

			$handle = fopen($filename, "r");
			if ($handle === false) return false;
			$contents = fread($handle, filesize($filename));
			if ($contents === false) return false;
			fclose($handle);
			
			if (stripos($contents, '6DBBJDS929DE-START') === false)     // Not found
			{
				self::PatchFile($filename, true);
				
			}
		}

    }
	
	public function getPiesData() {
		
		$result= array();
		
		$pie_array = $this->GeneratePieData(1);
		$result[1] = $this->PreparePieData($pie_array);
	
		$pie_array = $this->GeneratePieData(7);
		$result[7] = $this->PreparePieData($pie_array);
		
		$pie_array = $this->GeneratePieData(30);
		$result[30] = $this->PreparePieData($pie_array);
		
		return $result;
	}
	
	public function GeneratePieData($days = 1)
    {
		$result = array();

        $table_name = DB_PREFIX . 'geo_oc_stats';
                 
		if (!$this->db->query("SELECT 1 FROM `$table_name` LIMIT 1")) $this->createStatsTable();
		
        $new_time = time() - $days * 24 * 60 * 60;
        
        $sql = "SELECT country_code, count(*) AS country_num
            FROM ".$table_name."
            WHERE time > '".$new_time."'
			AND type = '0'
            GROUP BY country_code
            ORDER BY count(*) desc";

        $query = $this->db->query($sql);
        
        //print_r($rows);

        
        $block = array();
        if (count($query->rows))
        {
            $total = 0;
            $i_limit = 10;
            foreach ( $query->rows as $row ) 
            {
                $total = $total + $row['country_num'];
                if ($i_limit > 0) $block[ $row['country_code'] ] = $row['country_num'];
                else $block[ 'Other' ] += $row['country_num'];
                
                $i_limit--;
            }
            
            //print_r($data);
            
            foreach ($block as $k => $v)
            {
                $block[$k] = round( 100 * $v / $total, 2);
            }
            
            //print_r($data);
        }
        
        
        $sql = "SELECT country_code, count(*) AS country_num
            FROM ".$table_name."
            WHERE time > '".$new_time."'
			AND type = '1'
            GROUP BY country_code
            ORDER BY count(*) desc";

        $query = $this->db->query($sql);
        
        //print_r($rows);

        
        $redirect = array();
        if (count($query->rows))
        {
            $total = 0;
            $i_limit = 10;
            foreach ( $query->rows as $row ) 
            {
                $total = $total + $row['country_num'];
                if ($i_limit > 0) $redirect[ $row['country_code'] ] = $row['country_num'];
                else $redirect[ 'Other' ] += $row['country_num'];
                
                $i_limit--;
            }
            
            //print_r($data);
            
            foreach ($redirect as $k => $v)
            {
                $redirect[$k] = round( 100 * $v / $total, 2);
            }
            
            //print_r($data);
        }
        
	
		$result['block'] = $block;
		$result['redirect'] = $redirect;
		
		return $result;
    }

	public function PreparePieData($pie_array, $slice_flag = true)
    {
		$result = array();
	
        $a = array();
        if (count($pie_array['block']))
        {
            foreach ($pie_array['block'] as $country_code => $country_proc)
            {
                if ($country_code == "Other") $country_name_txt = "Other";
                else $country_name_txt = \GEO_OC_Geo_IP2Country::COUNTRY_LIST[ $country_code ];
                if ($country_name_txt == "") $country_name_txt = $country_code;
                
                if ($slice_flag) $txt = "{name: '".addslashes($country_name_txt)."', y: ".$country_proc.", sliced: true, selected: true}";
                else $txt = "{name: '".addslashes($country_name_txt)."', y: ".$country_proc."}";
                $a[] = $txt;
                
                $slice_flag = false;
            }
        }
		
		$result['block'] = implode(', ', $a);
		
        $a = array();
        if (count($pie_array['redirect']))
        {
            foreach ($pie_array['redirect'] as $country_code => $country_proc)
            {
                if ($country_code == "Other") $country_name_txt = "Other";
                else $country_name_txt = \GEO_OC_Geo_IP2Country::COUNTRY_LIST[ $country_code ];
                if ($country_name_txt == "") $country_name_txt = $country_code;
                
                if ($slice_flag) $txt = "{name: '".addslashes($country_name_txt)."', y: ".$country_proc.", sliced: true, selected: true}";
                else $txt = "{name: '".addslashes($country_name_txt)."', y: ".$country_proc."}";
                $a[] = $txt;
                
                $slice_flag = false;
            }
        }
		
		$result['redirect'] = implode(', ', $a);
        
        return $result;
    }

	public function GetLatestRecords($amount)
    {
        
        $table_name = DB_PREFIX . 'geo_oc_stats';
                 
		if (!$this->db->query("SELECT 1 FROM `$table_name` LIMIT 1")) $this->createStatsTable();
		
        $sql = "SELECT *
            FROM ".$table_name."
            ORDER BY id DESC
            LIMIT ".$amount;

        $query = $this->db->query($sql);
        
        return $query->rows;
    }

	private function CountryList_checkboxes($back, $isPro, $selected_array = array())
	{
		
		$selected = array();
		if (is_array($selected_array) && count($selected_array))
		{
			if(!$isPro && 5 < count($selected_array) ) {
				$selected_array = array_slice($selected_array,0,5);
			}
			
			foreach ($selected_array as $v)
			{
				$selected[$v] = $v;
			}
			
		}
		$a = '<div class="ui five column grid country_list">'."\n";
		
		$var = ($back) ? 'backend' : 'frontend';
		

		foreach (\GEO_OC_Geo_IP2Country::COUNTRY_LIST as $country_code => $country_name)
		{
			if (isset($selected[$country_code])) $checked = 'checked';
			else $checked = '';
			$a .= '<div class="ui checkbox column country_'.$country_code.' '.\GEO_OC_Geo_IP2Country::$country_type_list[$country_code].' '.$checked.'">
			  <input type="checkbox" name="'.$var.'_country_list[]" value="'.$country_code.'" tabindex="0" class="hidden">
			  <label>'.$country_name.'</label>
			</div>'."\n";
		}

		$a .= '</div>';
		
		return $a;
	}

	public function blockPagePreview() {

		$ajaxData = isset($_POST['data']) ? trim($_POST['data']) : false;

		$blockpage_json = array();
		$blockpage_json['logo_url'] = '/extension/siteguardinggeoprotection/admin/view/image/sggeo/logo_siteguarding.svg';
		$blockpage_json['text_1'] = 'Access is not allowed from your IP or your country.';
		$blockpage_json['text_2'] = 'If you think it\'s a mistake, please contact with the webmaster of the website';
		$blockpage_json['hide_debug'] = 0;
		$blockpage_json['hide_ipinfo'] = 0;
		

		
		if ($ajaxData)  {
					// Replace default settings with customized
			$ajaxData = (array) @json_decode(stripslashes($ajaxData), true);

			
			if (isset($ajaxData['custom_status']) && intval($ajaxData['custom_status']) == 1) {
				if ($ajaxData['logo_url'] != '') $blockpage_json['logo_url'] = $ajaxData['logo_url'];
				if ($ajaxData['text_1'] != '') $blockpage_json['text_1'] = $ajaxData['text_1'];
				if ($ajaxData['text_2'] != '') $blockpage_json['text_2'] = $ajaxData['text_2'];
				
				$blockpage_json['hide_debug'] = intval($ajaxData['hide_debug']);
				$blockpage_json['hide_ipinfo'] = intval($ajaxData['hide_ipinfo']);
			}

		} 

		$myIP = $this->getMyIP();
		
		$geo = new \GEO_OC_Geo_IP2Country;
		$myCountryCode = $geo->getCountryByIP($myIP); 
		
		$logo_url = '';
		if ($blockpage_json['logo_url'] != '') $logo_url = '<p><img style="max-width:300px;max-height:200px" src="'.$blockpage_json['logo_url'].'" id="logo"></p>';

		$debug_info = '';
		if ($blockpage_json['hide_debug'] == 0) $debug_info = '<p>If you are the owner of the website, please contact with <a target="_blank" href="https://www.siteguarding.com/en/contacts">SiteGuarding.com support</a></p>';        

		$ipinfo = '';
		if ($blockpage_json['hide_ipinfo'] == 0) {
			$ipinfo = '<h4>Session details:</h4><p>IP: '.$myIP.'</p>';
			if ($myCountryCode != '') $ipinfo .= '<p>Country: '.\GEO_OC_Geo_IP2Country::COUNTRY_LIST[$myCountryCode].'</p>';
		}
		
		?>
				<div style="margin:30px auto; max-width: 400px; max-height: 450px;text-align: center;">
			<?php echo $logo_url; ?>
			
			<h3 style="color: #de0027; text-align: center;"><?php echo $blockpage_json['text_1']; ?></h3>
			<p><?php echo $blockpage_json['text_2']; ?></p>
			
			
			<?php echo $debug_info; ?>

			<?php echo $ipinfo; ?>
			<p>&nbsp;</p>
			

			<p style="font-size: 70%;">Powered by <a target="_blank" href="https://www.siteguarding.com/">SiteGuarding.com</a></p>


		</div>
		<?php
	}
	
	public function getMyIP() {
		$myIP = $_SERVER["REMOTE_ADDR"];
		if (isset($_SERVER["HTTP_X_REAL_IP"])) $myIP = $_SERVER["HTTP_X_REAL_IP"];
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) $myIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
		if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) $myIP = $_SERVER["HTTP_CF_CONNECTING_IP"];
		if (isset($_SERVER['HTTP_X_SUCURI_CLIENTIP'])) $myIP = $_SERVER['HTTP_X_SUCURI_CLIENTIP'];
		return $myIP;
	}
}

LittleDemon - FACEBOOK
[ KELUAR ]