Your IP : 216.73.216.85


Current Path : /home/smartconb/www/armencom33/administrator/components/com_geoprotection/
Upload File :
Current File : /home/smartconb/www/armencom33/administrator/components/com_geoprotection/geoprotection.php

<?php
/**
 * @package	Website GEO Protection for Joomla
 * @copyright	Copyright (C) 2018 SiteGuarding.com. All rights reserved.
 * @GNU General Public License
 */

defined( '_JEXEC' ) or die;

ini_set("display_errors", "Off");



if (version_compare(JVERSION, '3.0', '<'))
{
	if (JFactory::getApplication()->get('jquery') !== true)
	{
		// Load jQuery in no conflict mode with B/C support
		JHtml::script('../media/com_geoprotection/jquery.min.js');
		JHtml::script('../media/com_geoprotection/jquery-migrate.min.js');
		JHtml::script('../media/com_geoprotection/jquery-noconflict.js');
		JFactory::getApplication()->set('jquery', true);
	}
}
else
{
JHtml::_('jquery.framework'); // load jquery
}

$document = JFactory::getDocument();
$document->addStyleSheet('../media/com_geoprotection/semantic.min.css');
$document->addScript('../media/com_geoprotection/semantic.min.js');
$document->addScript('../media/com_geoprotection/javascript.js');

JToolBarHelper::title( JText::_( 'Website GEO Protection for Joomla' ));

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') define("DIRSEP", '\\');
else define("DIRSEP", '/');

$app = JFactory::getApplication();
$postData = $app->input->post->getArray();

if (isset($postData['ajax']) && $postData['ajax'] == md5(date("YmdH"))) {
	print gpjm_blockPagePreview($postData['data']);
	die;
}

$tab_id = isset($_GET['tab_id']) ? intval($_GET['tab_id']) : 0;
$tab_array = array(0 => '', 1 => '', 2 => '', 3 => '', 4 => '', 5 => '');
$tab_array[$tab_id] = 'active ';
$block_class = '';


if (isset($postData['submit'])) gpjm_check_action();

$params = gpjm_Get_Params();



if (!isset($params['frontend_ip_list'])) $params['frontend_ip_list'] = '';


$params['rewrite_lang_code_status'] = (isset($params['rewrite_lang_code_status'])) ? $params['rewrite_lang_code_status'] : 0;

if (!isset($params['frontend_ip_list_allow'])) $params['frontend_ip_list_allow'] = '';

if (!isset($params['backend_ip_list'])) $params['backend_ip_list'] = '';
if (!isset($params['backend_ip_list_allow'])) $params['backend_ip_list_allow'] = '';

if (!isset($params['redirect_ip_list_allow'])) $params['redirect_ip_list_allow'] = '';
if (!isset($params['redirect_url_list_allow'])) $params['redirect_url_list_allow'] = '';

$params['frontend_country_list'] = (isset($params['frontend_country_list']) && is_string($params['frontend_country_list'])) ? @json_decode($params['frontend_country_list'], true) : array();
$params['backend_country_list'] = (isset($params['backend_country_list']) && is_string($params['backend_country_list'])) ? @json_decode($params['backend_country_list'], true) : array();
$params['redirects'] = (isset($params['redirects']) && is_string($params['redirects'])) ? @json_decode($params['redirects'], true) : array();
$params['rewrite_lang_code'] = (isset($params['rewrite_lang_code']) && is_string($params['rewrite_lang_code'])) ? @json_decode($params['rewrite_lang_code'], true) : array();

gpjm_CheckBlockLog();
$isPRO = gpjm_CheckIfPRO();
$free = (!$isPRO) ? 'free' : '';
$pies_data = gpjm_getPiesData();

$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'];


$do_update = false;

if ($isPRO) $do_update = true;
else {
	$last_update_date = gpjm_Get_Last_Update_date_GEOdb();
	if (time() - strtotime(trim($last_update_date)) > 30 * 24 * 60 * 60) $do_update = true;
}


if (isset($_GET['geo_update']) && intval($_GET['geo_update']) == 1)
{
	if ($do_update)
	{
		gpjm_UpdateGEOdb(1);
		$action_message = 'GEO database updated successfully';
		$message_type = 'ok';
	}
	else {
		$action_message = 'GEO database is not updated. Free version limit: Update once per month. Please get full version.';
		$message_type = 'alert';
	}
			$message_data = array(
				'type' => $message_type,
				'header' => '',
				'message' => $action_message,
				'button_text' => '',
				'button_url' => '',
				'help_text' => ''
			);
	gpjm_PrintIconMessage($message_data);


}


if (!class_exists('GEO_JM_Geo_IP2Country')) {
	include_once 'geo.php';
}
	if (filter_var($myIP, FILTER_VALIDATE_IP)) {
		$geo = new GEO_JM_Geo_IP2Country();
		$myCountryCode = $geo->getCountryByIP($myIP);
		$myCountry = $geo->getNameByCountryCode($myCountryCode) ? $geo->getNameByCountryCode($myCountryCode) : '';
	}


   ?>
   <style>
   td.redirect, td.rewrite_lang_code {
	   padding: 5px!important;
   }
   .countrychk{margin:0 12px 0 0!important}
   .redirect .form input,.rewrite_lang_code .form input{height: 35px!important;}
	
   </style>
    <script>
	function BlockPage_Refresh()
	{ 
		jQuery('#geo_preview').html('<div style="margin:30px auto; max-width: 400px; max-height: 450px;text-align: center;">Please wait...</div>');
		jQuery('.modal.preview_show').modal('show');
		ajaxurl = '<?php JURI::root() . $_SERVER['PHP_SELF'] . $_SERVER['REQUEST_URI'];?>';
		var myObj = { 
				"custom_status": jQuery('#custom_status').checkbox('is checked'),
				"logo_url": jQuery('#logo_url').val(),
				"text_1": jQuery('#text_1').val(),
				"text_2": jQuery('#text_2').val(),
				"hide_debug": jQuery('#hide_debug').checkbox('is checked'),
				"hide_ipinfo": jQuery('#hide_ipinfo').checkbox('is checked'),
		}; 
		var jsonString = JSON.stringify(myObj);
		jQuery.post(
			ajaxurl, 
			{
				"ajax": '<?php echo md5(date("YmdH")); ?>',
				'data' : jsonString
			}, 
			function(response){
				jQuery('#geo_preview').html(response);
				
			}
		);  
	}	
	function ShowHideForm(v, el)
	{
		if (v == true) jQuery(el).show(300);
		else jQuery(el).hide(300);
	}
    function InfoBlock(id)
    {
        jQuery("#"+id).toggle();
    }
    function SelectCountries(select, uncheck)
    {
        if (select != '') jQuery(select).checkbox('check');
        
        if (uncheck != '') jQuery(uncheck).checkbox('set unchecked');
    }
	jQuery(document).ready(function() {
		jQuery('.ui.checkbox').checkbox();
		jQuery('.checked').checkbox('check');
		ShowHideForm(jQuery('#custom_status').checkbox('is checked'), '.show_active');
		jQuery('.free').click(function(e){
			e.preventDefault();
			jQuery('.modal.paid').modal('show');
		});
		jQuery('.cancel.button.paid').click(function(e){
			e.preventDefault();
			jQuery('.modal.paid').modal('hide');
		});
		
    jQuery("#filter_country_name").on("keyup change", function() {

      var value = this.value.toLowerCase().trim();
      jQuery(".filter_list .column").show().filter(function() {
                  console.log(jQuery(this).prop('id').toLowerCase().trim());
        return jQuery(this).prop('id').toLowerCase().trim().indexOf(value) == -1;
      }).hide();
    });
		
	});

  function ResetFilter()
  {
      jQuery('#filter_country_name').val('');
      jQuery('.filter_list .column').show();
  }
	
	function checkByContinent(code) {
		switch (code) {
			case 'AF': // Africa
				var c = [ 'AO', 'BF', 'BI', 'BJ', 'BW', 'CD', 'CF', 'CG', 'CI', 'CM', 'CV', 'DJ', 'DZ', 'EG', 'EH', 'ER', 'ET', 'GA', 'GH', 'GM', 'GN', 'GQ', 'GW', 'KE', 'KM', 'LR', 'LS', 'LY', 'MA', 'MG', 'ML', 'MR', 'MU', 'MW', 'MZ', 'NA', 'NE', 'NG', 'RE', 'RW', 'SC', 'SD', 'SH', 'SL', 'SN', 'SO', 'ST', 'SZ', 'TD', 'TG', 'TN', 'TZ', 'UG', 'YT', 'ZA', 'ZM', 'ZW' ];
				break;
				
			case 'AN': // Antarctica
				var c = [ 'AQ', 'BV', 'GS', 'HM', 'TF' ];
				break;
				
			case 'AS': // Asia
				var c = [ 'AE', 'AF', 'AM', 'AP', 'AZ', 'BD', 'BH', 'BN', 'BT', 'CC', 'CN', 'CX', 'CY', 'GE', 'HK', 'ID', 'IL', 'IN', 'IO', 'IQ', 'IR', 'JO', 'JP', 'KG', 'KH', 'KP', 'KR', 'KW', 'KZ', 'LA', 'LB', 'LK', 'MM', 'MN', 'MO', 'MV', 'MY', 'NP', 'OM', 'PH', 'PK', 'PS', 'QA', 'SA', 'SG', 'SY', 'TH', 'TJ', 'TL', 'TM', 'TW', 'UZ', 'VN', 'YE', 'TP' ];
				break;
				
			case 'EU': // Europe
				var c = [ 'AD', 'AL', 'AT', 'AX', 'BA', 'BE', 'BG', 'BY', 'CH', 'CZ', 'DE', 'DK', 'EE', 'ES', 'EU', 'FI', 'FO', 'FR', 'FX', 'GB', 'UK', 'GG', 'GI', 'GR', 'HR', 'HU', 'IE', 'IM', 'IS', 'IT', 'JE', 'LI', 'LT', 'LU', 'LV', 'MC', 'MD', 'ME', 'MK', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'RS', 'RU', 'SE', 'SI', 'SJ', 'SK', 'SM', 'TR', 'UA', 'VA' ];
				break;
				
			case 'NA': // North America
				var c = [ 'AG', 'AI', 'AN', 'AW', 'BB', 'BL', 'BM', 'BS', 'BZ', 'CA', 'CR', 'CU', 'DM', 'DO', 'GD', 'GL', 'GP', 'GT', 'HN', 'HT', 'JM', 'KN', 'KY', 'LC', 'MF', 'MQ', 'MS', 'MX', 'NI', 'PA', 'PM', 'PR', 'SV', 'TC', 'TT', 'US', 'VC', 'VG', 'VI' ];
				break;
				
			case 'OC': // Oceania
				var c = [ 'AS', 'AU', 'CK', 'FJ', 'FM', 'GU', 'KI', 'MH', 'MP', 'NC', 'NF', 'NR', 'NU', 'NZ', 'PF', 'PG', 'PN', 'PW', 'SB', 'TK', 'TO', 'TV', 'UM', 'VU', 'WF', 'WS' ];
				break;
				
			case 'SA': // South America
				var c = [ 'AR', 'BO', 'BR', 'CL', 'CO', 'EC', 'FK', 'GF', 'GY', 'PE', 'PY', 'SR', 'UY', 'VE' ];
				break;
				
			default:
				var c = [];
		}
		
		c.forEach(function(element){
			if (typeof jQuery("input:checkbox[value='"+element+"']") === 'object') {
				jQuery("input:checkbox[value='"+element+"']").prop( "checked", true ); // jQuery only
				//jQuery("input:checkbox[value='"+element+"']").checkbox( "check"); // Semantic UI
			}
		})
	}
	
    </script>



              <div class="sixteen wide column settblocks" id="block2">
                <div class="ui segment">
					<div class="welcome-panel-content">
					<h1 style="text-align: center;">Joomla Security Tools</h1>
					<p style="text-align: center;">
						<a target="_blank" href="https://www.siteguarding.com/en/security-dashboard?pgid=JGE2" target="_blank"><img src="<?php echo '../media/com_geoprotection/images/b10.png'; ?>" /></a>&nbsp;
						<a target="_blank" href="https://www.siteguarding.com/en/security-dashboard?pgid=JGE2" target="_blank"><img src="<?php echo '../media/com_geoprotection/images/b11.png'; ?>" /></a>&nbsp;
						<a target="_blank" href="https://www.siteguarding.com/en/security-dashboard?pgid=JGE2" target="_blank"><img src="<?php echo '../media/com_geoprotection/images/b12.png'; ?>" /></a>&nbsp;
						<a target="_blank" href="https://www.siteguarding.com/en/security-dashboard?pgid=JGE2" target="_blank"><img src="<?php echo '../media/com_geoprotection/images/b13.png'; ?>" /></a>&nbsp;
						<a target="_blank" href="https://www.siteguarding.com/en/security-dashboard?pgid=JGE2" target="_blank"><img src="<?php echo '../media/com_geoprotection/images/b14.png'; ?>" /></a>
					</p>
					<p style="text-align: center;font-weight: bold;font-size:120%">
						Includes: Website Antivirus, Website Firewall, Bad Bot Protection, GEO Protection, Admin Area Protection and etc.
					</p>
					<p style="text-align: center">
						<a class="ui green button" target="_blank" href="https://www.siteguarding.com/en/security-dashboard?pgid=JGE2">Secure Your Website</a>
					</p>
					</div>
				</div>
				
		
                   <h2 class="sg_center ui header">Website GEO Protection for Joomla</h2>
<?php
        if ($isPRO)
        {
            $box_text = 'You have <span class="ui green horizontal label">PRO version</span>';
        }
        else {
            $box_text = '<span style="color:#9f3a38">You have <span class="ui red horizontal label">Free version</span>. Please note free version has some limits. Please <a href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection" target="_blank">Upgrade</a></span><br>If you already purchased the extension, please go <a href="index.php?option=com_geoprotection&tab_id=2">here</a> and put your registration code';
        }
        ?>

        
        <div class="ui large ignored info message"><center><?php echo $box_text; ?></center></div>
				   
    <div class="ui six item top attached tabular menu" style="margin-top:0;">
            <a href="index.php?option=com_geoprotection&tab_id=0" class="<?php echo $tab_array[0]; ?> item"><i class="desktop icon"></i> Front-end Protection</a>
			<a href="index.php?option=com_geoprotection&tab_id=3" class="<?php echo $tab_array[3]; ?> item"><i class="lock icon"></i>Backend Protection</a>
			<a href="index.php?option=com_geoprotection&tab_id=1" class="<?php echo $tab_array[1]; ?> item"><i class="random icon"></i> GEO Redirects</a>
			<a href="index.php?option=com_geoprotection&tab_id=4" class="<?php echo $tab_array[4]; ?> item"><i class="pie chart icon"></i>Logs</a>
			<a href="index.php?option=com_geoprotection&tab_id=5" class="<?php echo $tab_array[5]; ?> item"><i class="cog icon"></i> Customize & Style</a>
			<a href="index.php?option=com_geoprotection&tab_id=2" class="<?php echo $tab_array[2]; ?> item"><i class="cogs icon"></i> Settings</a>
    </div>
    




    <div class="ui bottom attached segment">

        
        <form class="ui form" method="post" action="index.php?option=com_geoprotection&tab_id=<?php echo $tab_id; ?>">
        
		<?php if ($tab_id === 0) : ?>
        <p>
        <?php
        if (isset($params['protection_frontend']) && intval($params['protection_frontend']) == 1) { $block_class = ''; $protection_txt = '<span class="ui green horizontal label">Enabled</span>'; $protection_bttn_txt = 'Disable Protection'; }
        else { $block_class = 'class="hide"'; $protection_txt = '<span class="ui horizontal red label">Disabled</span>'; $protection_bttn_txt = 'Enable Protection'; }
        ?>
        GEO Protection is <?php echo $protection_txt; ?> Visitors from selected countried and selected IP addresses will not be able to visit your website.
        </p>
        <input type="submit" name="submit" id="submit" class="ui mini secondary button mrt-top-15" value="<?php echo $protection_bttn_txt; ?>">
		<?php if (!$isPRO) : ?>
		<a class="ui green mini button" target="_blank" href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection">Get Full Version</a>
		<?php endif; ?>
        <p>&nbsp;</p>
        
		<input type="hidden" name="action" value="EnableDisable_protection_frontend"/>
		</form>
        
        <form method="post" action="index.php?option=com_geoprotection&tab_id=<?php echo $tab_id; ?>">
        <div <?php echo $block_class; ?>>
        
			<div class="ui blue mini message"><center>Always remember about search engine bots. Add Google bot IP addresses to allow list. Use quick button below. </center></div>
            <h4 class="ui header">Block (blacklist) by IP or range (your IP is <?php echo $myIP; ?>)</h4>
            
            <div class="ui ignored message">
                  <i class="help circle icon"></i>e.g. 200.150.160.1 or 200.150.160.* or 200.150.*.*
            </div>
            
            <div class="ui input <?php echo $free; ?>" style="width: 100%;margin-bottom:10px">
                <textarea name="frontend_ip_list" style="width: 100%;height:200px" placeholder="Insert IP addresses or range you want to block, one by line"><?php echo $params['frontend_ip_list']; ?></textarea>
            </div>
            <center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button <?php echo $free; ?>" value="Save & Apply"></center>
            
            <h4 class="ui header">Block by country (your country is <?php echo $myCountry; ?>)</h4>
<div class="ui icon message">
  <div class="content">
    <div style="text-align:center" class="header">
      Quick buttons:
    </div>
    <p style="text-align:center"><a class="mini ui button bttn_bottom" href="javascript:SelectCountries('', '.all');">Uncheck All</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.all', '.country_<?php echo $myCountryCode; ?>');">Select All (exclude <?php echo $myCountryCode; ?>)</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.all', '.country_US,.country_CA');">Select All (exclude USA, Canada)</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.all', '.europe');">Select All (exclude EU countries)</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.3rdcountry', '');">Select All 3rd party countries</a></p><p></p>

                  <p style="text-align:center"><a class="mini ui button bttn_bottom" href="javascript:checkByContinent('AF');">Select Africa</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('OC');">Select Oceania</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('EU');">Select Europe</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('SA');">Select South America</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('NA');">Select North America</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('AS');">Select Asia</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('AN');">Select Antarctica</a></p>
  </div>
</div>
                    <p>Use filter to reduce the length of the country list</p>
                  <div class="field">
                    <div class="ui website">
                      <div class="ui mini input left icon">
                        <i class="search icon"></i>
                        <input type="text" name="filter_country_name" id="filter_country_name" placeholder="Filter by Country name" value="" autocomplete="off">
                        <div class="ui right floated button" onclick="ResetFilter()"><i class="times icon"></i>Reset</div>
                      </div>
                    </div>
                  </div>

                <hr> 
                  <br>
            <?php echo gpjm_CountryList_checkboxes($params['frontend_country_list']); ?>
            
            <p>&nbsp;</p>

            
        
        
		<input type="hidden" name="action" value="save_frontend_params"/>
		<center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button" value="Save & Apply"></center>
            <h4 class="ui header">Allow (whitelist) by IP or range (your IP is <?php echo $myIP; ?>)</h4>
            
            <div class="ui ignored message">
                  <i class="help circle icon"></i>e.g. 200.150.160.1 or 200.150.160.* or 200.150.*.*
            </div>
            <p>
				<span class="mini ui green button allow">Allow bots</span> Add IP addresses of Google, Bing, Yahoo to allow list 
			</p>
			<?php if (!$isPRO) : ?>
				<script>
				jQuery(document).ready(function(){
					jQuery('.allow').click(function(){
						jQuery('.modal.paid').modal('show');
					});

				}); 
				
				</script>

				

			<?php else : ?>
				<script>
				jQuery(document).ready(function(){
					jQuery('.allow').click(function(){
						content = jQuery('.frontend_ip_list_allow').val();
						if (content) content = content + "\n";
						jQuery('.frontend_ip_list_allow').val(content + "#GoogleBot\n64.233.*.*\n66.102.*.*\n66.249.*.*\n72.14.*.*\n74.125.*.*\n209.85.*.*\n216.239.*.*\n\n#BingBot\n104.146.*.*\n\n#MSNBot\n64.4.*.*\n65.52.*.*\n65.53.*.*\n65.54.*.*\n131.253.*.*\n157.54.*.*\n207.46.*.*\n207.68.*.*\n\n\n#Yahoo\n8.12.144.*\n66.196.*.*\n66.228.*.*\n67.195.*.*\n68.142.*.*\n72.30.*.*\n74.6.*.*\n98.136.*.*\n98.137.*.*\n98.138.*.*\n98.139.*.*\n202.160.*.*\n209.191.*.*\n#YandexBot\n100.43.*.*\n");
					});
				});
				
				</script>
			
			
			
			<?php endif; ?>
			<div class="ui input <?php echo $free; ?>" style="width: 100%;margin-bottom:10px">
				<textarea class="frontend_ip_list_allow" name="frontend_ip_list_allow" style="width: 100%;height:200px" placeholder="Insert IP addresses or range you want to allow, one by line"><?php echo $params['frontend_ip_list_allow']; ?></textarea>
			</div>
</div>
		<center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button <?php echo $free; ?>" value="Save & Apply"></center>
		<?php elseif ($tab_id === 3) : ?>
       <h4 class="ui header">Backend protection</h4>
        
        <form method="post" action="index.php?option=com_geoprotection&tab_id=<?php echo $tab_id; ?>">
        
        <p>
        <?php
        if (isset($params['protection_backend']) && intval($params['protection_backend']) == 1) { $block_class = ''; $protection_txt = '<span class="ui green horizontal label">Enabled</span>'; $protection_bttn_txt = 'Disable Protection'; }
        else { $block_class = 'class="hide"'; $protection_txt = '<span class="ui red horizontal label">Disabled</span>'; $protection_bttn_txt = 'Enable Protection'; }
        ?>
        GEO Protection for backend is <?php echo $protection_txt; ?> Visitors from selected countried and selected IP addresses will not be able to login to backend of your website.
        </p>
        <input type="submit" name="submit" id="submit" class="ui mini secondary button mrt-top-15" value="<?php echo $protection_bttn_txt; ?>">
		<?php if (!$isPRO) : ?>
		<a class="ui green mini button" target="_blank" href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection">Get Full Version</a>
		<?php endif; ?>
        <p>&nbsp;</p>


		<input type="hidden" name="action" value="EnableDisable_protection_backend"/>
		</form>
        
        <form method="post" action="index.php?option=com_geoprotection&tab_id=<?php echo $tab_id; ?>">
        <div <?php echo $block_class; ?>>
            <h4 class="ui header">Block (blacklist) by IP or range (your IP is <?php echo $myIP; ?>)</h4>
            
            <div class="ui ignored message">
                  <i class="help circle icon"></i>e.g. 200.150.160.1 or 200.150.160.* or 200.150.*.*
            </div>
            
            <div class="ui input <?php echo $free; ?>" style="width: 100%;margin-bottom:10px">
                <textarea name="backend_ip_list" style="width: 100%;height:200px" placeholder="Insert IP addresses or range you want to block, one by line"><?php echo $params['backend_ip_list']; ?></textarea>
            </div>
           <center><input type="submit" name="submit" id="submit" class="ui green button <?php echo $free; ?>" value="Save & Apply"></center>
            
            <h4 class="ui header">Block by country (your country is <?php echo $myCountry; ?>)</h4>
            
<div class="ui icon message">
  <div class="content">
    <div style="text-align:center" class="header">
      Quick buttons:
    </div>
    <p style="text-align:center"><a class="mini ui button bttn_bottom" href="javascript:SelectCountries('', '.all');">Uncheck All</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.all', '.country_<?php echo $myCountryCode; ?>');">Select All (exclude <?php echo $myCountryCode; ?>)</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.all', '.country_US,.country_CA');">Select All (exclude USA, Canada)</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.all', '.europe');">Select All (exclude EU countries)</a> <a class="mini ui button bttn_bottom" href="javascript:SelectCountries('.3rdcountry', '');">Select All 3rd party countries</a></p><p></p>

                  <p style="text-align:center"><a class="mini ui button bttn_bottom" href="javascript:checkByContinent('AF');">Select Africa</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('OC');">Select Oceania</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('EU');">Select Europe</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('SA');">Select South America</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('NA');">Select North America</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('AS');">Select Asia</a> <a class="mini ui button bttn_bottom" href="javascript:checkByContinent('AN');">Select Antarctica</a></p>
  </div>
</div>
        <p>Use filter to reduce the length of the country list</p>
                  <div class="field">
                    <div class="ui website">
                      <div class="ui mini input left icon">
                        <i class="search icon"></i>
                        <input type="text" name="filter_country_name" id="filter_country_name" placeholder="Filter by Country name" value="" autocomplete="off">
                        <div class="ui right floated button" onclick="ResetFilter()"><i class="times icon"></i>Reset</div>
                      </div>
                    </div>
                  </div>

                <hr> 
                  <br>
            <?php echo gpjm_CountryList_checkboxes($params['backend_country_list']); ?>
            
            <p>&nbsp;</p>
            <center><input type="submit" name="submit" id="submit" class="ui green button" value="Save & Apply"></center>
            
            
            <h4 class="ui header">Allow (whitelist) by IP or range (your IP is <?php echo $myIP; ?>)</h4>

            <div class="ui ignored message">
                  <i class="help circle icon"></i>e.g. 200.150.160.1 or 200.150.160.* or 200.150.*.*
            </div>

            <div class="ui input <?php echo $free; ?>" style="width: 100%;margin-bottom:10px">
                <textarea name="backend_ip_list_allow" style="width: 100%;height:200px" placeholder="Insert IP addresses or range you want to allow, one by line"><?php echo $params['backend_ip_list_allow']; ?></textarea>
            </div>

            
            
        </div>
        

		<input type="hidden" name="action" value="Save_backend_params"/>
		<center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button <?php echo $free; ?>" value="Save & Apply"></center>
		<?php
            //Logs
            elseif ($tab_id === 4) :
        ?>
		
        <div>
			
        <?php 
		$block_class = 'class="hide"';
		foreach ($pies_data as $id => $data) : 
			switch($id) {
				case 1:
					$txt = '24 hours.';
					break;
				case 7:
					$txt = '7 days.';
					break;
				case 30:
					$txt = '30 days.';
					break;
			}
		
		?>
		
		<script type="text/javascript">
        jQuery(function () {
            jQuery('#pie_container_<?php echo $id; ?>').highcharts({
                credits: false,
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie',
                },
                title: {
                    text: 'Activity for the last <?php echo $txt; ?>'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: ('Highcharts'.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
				labels: {
					items: [{
						html: 'Blocked Traffic',
						style: {
							left: '260px',
							top: '330px',
							fontSize: '16px'
						}},
					{
						html: 'Redirected Traffic',
						style: {
							left: '790px',
							top: '330px',
							fontSize: '16px'
						}}]
				},
				<?php if (!$data['block'] && !$data['redirect']) : ?>
				title: {
					text: 'No data found'
				},
				<?php endif; ?>
				series: [{
					size: 250,
					name: 'Blocked',
					center: [300, 100],
					data: [<?php echo $data['block']; ?>]
				},{
					size: 250,
					name: 'Redirected',
					center: [830, 100],
					data: [<?php echo $data['redirect']; ?>]
				}]
            });
        });
		

        		</script>
        
        <div id="pie_container_<?php echo $id; ?>" style="min-width: 310px; height: 400px; max-width: 80%; margin: 0 auto"></div>
        
        <hr />

		<?php endforeach; ?>

        <?php
        $amount_records = 50;
        $latest_records_array = gpjm_GetLatestRecords($amount_records);
        ?>
        <h4 class="ui header">Latest Logs (latest <?php echo $amount_records; ?> records)</h4>
        <?php
        if (count($latest_records_array) == 0) echo '<p>No records</p>';
        else {
            ?>
            <table class="ui sortable celled table small">
              <thead>
                <tr><th class="two wide">Date</th>
                <th class="eight wide">URL</th>
                <th class="two wide">IP address</th>
                <th class="two wide">Country</th>
                <th class="two wide">Status</th>
              </tr></thead>
              <tbody>
                <?php
                foreach ($latest_records_array as $v) {
                ?>
                <tr>
                  <td>
				  <?php
						$time_object = new DateTime(date('Y-m-d H:i:s', $v->time), new DateTimeZone('UTC'));
						$time_object->setTimezone(new DateTimeZone(JFactory::getUser()->getParam('timezone','UTC')));
						echo $time_object->format('Y-m-d H:i:s');
				  ?>
				  </td>
                  <td class="tbl_urlrow"><a target="_blank" href="<?php echo $v->url; ?>"><?php echo $v->url; ?></a></td>
                  <td><?php echo GEO_JM_Geo_IP2Country::$country_list[ $v->country_code ].' ['.$v->country_code.']'; ?></td>
                  <td><?php echo $v->ip; ?></td>
				  <td>
				  <?php 
				  switch ($v->type) {
					  case 0:
						echo 'Blocked';
						break;
					  case 1:
						echo 'Redirected';
						break;
				  }
				  
				  ?>
				  </td>
                </tr>
                <?php
                }
                ?>
              </tbody>
            </table>
            
            <?php
        }
?>
        </div>

		
		
		
		<?php

        //Redirects
        elseif ($tab_id === 1) :

        ?>
		<p>You can redirect the visitors from selected countries to specific page of your website or another domain.</p>

		<?php if (!$isPRO) : ?>
		<a class="ui green mini button" target="_blank" href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection">Get Full Version</a>
		<?php endif; ?>

        <h4 class="ui header">Don't redirect by IP or range (your IP is <?php echo $myIP; ?>). Visitors from these IP addresses will not be redirected.</h4>

        <div class="ui ignored message">
            <i class="help circle icon"></i>e.g. 200.150.160.1 or 200.150.160.* or 200.150.*.*
        </div>

        <div class="ui input <?php echo $free; ?>" style="width: 100%;margin-bottom:10px">
            <textarea name="redirect_ip_list_allow" style="width: 100%;height:200px" placeholder=" Insert IP addresses or range you want to skip for redirection, one by line"><?php echo $params['redirect_ip_list_allow']; ?></textarea>
        </div>

        <h4 class="ui header">Exclude redirect by URL</h4>

        <div class="ui ignored message">
            <i class="help circle icon"></i>e.g. /administrator or /contact
        </div>

        <div class="ui input <?php echo $free; ?>" style="width: 100%;margin-bottom:10px">
            <textarea name="redirect_url_list_allow" style="width: 100%;height:200px" placeholder="Insert URL you want to exclude, one by line"><?php echo $params['redirect_url_list_allow']; ?></textarea>
        </div>

        <input type="hidden" name="action" value="save_redirects"/>
        <center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button" value="Save & Apply"></center>


        <h4 class="ui dividing header">Redirection and language URL rewriter</h4>
        <script>
        jQuery(document).ready(function(){
            jQuery('.ui.checkbox').checkbox();
            
            jQuery('.land_code_switch.checkbox')
              .checkbox({
                // check all children
                onChecked: function() {
                  jQuery(".rewrite_lang_code").removeClass("hide");
                },
                // uncheck all children
                onUnchecked: function() {
                  jQuery(".rewrite_lang_code").addClass("hide");
                }
              });
              
              <?php
              if (isset($params['rewrite_lang_code_status']) && intval($params['rewrite_lang_code_status']) == 1) echo 'jQuery(".rewrite_lang_code").removeClass("hide");';
              else echo 'jQuery(".rewrite_lang_code").addClass("hide");';
              ?>
        });
        </script>
        <div class="ui form">
          <div class="inline field">
            <div class="land_code_switch ui toggle checkbox ">
              <input name="rewrite_lang_code_status" type="checkbox" tabindex="0" class="hidden" <?php if (isset($params['rewrite_lang_code_status']) && intval($params['rewrite_lang_code_status']) == 1) echo 'checked'; ?>>
              <label>Enable language URL rewrite</label>
            </div>
          </div>
        </div>
        <div class="ui ignored message">
            <h4 class="ui header"><i class="info icon"></i>Language URL rewrite</h4>
            <br />
            If your website links have multi language structure E.g. https://www.site.com/en/contact-us (where EN is english language) You can enable Language URL rewrite feature and GEO component will automatically change the language code in your links depends of the country.<br />
            <br />
            If language code is absent in URL, the regular redirection rules will be applied.
        </div>
        


        <div class="ui ignored message">
            <h4 class="ui header"><i class="help circle icon"></i>Redirection (Samples and Syntax)</h4>
            <br />
            <b>Redirect to local page</b>. If you need to redirect all visitors e.g. from Italy to special contact us page on your website.<br>
            <br>
            Sample of syntax: /it/contact-us<br>
            <br>
            <b>Redirect to another website</b>. If you need to redirect all visitors e.g. from Italy to another website.<br>
            <br>
            Sample of syntax: https://www.site.it<br>
            <br>
            <b>Redirect to another website and keep URL</b>. If you need to redirect all visitors e.g. from Italy to another website and keep the same links structure.<br>
            <br>
            Sample of syntax: https://www.site.it%PATH%<br>
            <br>
            E.g. your website is https://www.mysite.com. When visitor from Italy opens https://www.mysite.com , he will be redirected to https://www.site.it (home page) , but if visitor opens https://www.mysite.com/contact-us , he will be redirected to https://www.site.it/contact-us (URL will keep /contact-us, the same links structure as on your original website)
        </div>





        <p>Use filter to reduce the length of the country list</p>
                  <div class="field" style="width:0;">
                    <div class="ui website">
                      <div class="ui mini input left icon">
                        <i class="search icon"></i>
                        <input type="text" name="filter_country_name" id="filter_country_name" placeholder="Filter by Country name" value="" autocomplete="off">
                        <div class="ui right floated button" onclick="ResetFilter()"><i class="times icon"></i>Reset</div>
                      </div>
                    </div>
                  </div>

		<table class="ui single line selectable table">
		  <thead>
			<tr>
			  <th>Country</th>
			  <th class="rewrite_lang_code">Language Code</th>
			  <th>Redirect URL</th>
			</tr>
		  </thead>
		  <tbody class="filter_list">
			<?php
			foreach (GEO_JM_Geo_IP2Country::$country_list as $country_code => $country_name)
			{
				?>
				<tr id="id_<?=str_replace(' ', '_', $country_name);?>" class="column">
				  <td class="two wide"><?php echo $country_name; ?></td>
				  <td class="one wide rewrite_lang_code">
						<div class="ui form">
							  <input class="ui input ten wide field" placeholder="e.g. en" type="text" name="rewrite_lang_code[<?php echo $country_code; ?>]" value="<?php if (isset($params['rewrite_lang_code'][$country_code])) echo $params['rewrite_lang_code'][$country_code]; ?>">
						</div>
				  </td>
				  <td class="redirect">
						<div class="ui form">
							  <input class="ui input sixteen wide field" placeholder="e.g. /contact-us   or   http://www.google.com/search" type="text" name="redirects[<?php echo $country_code; ?>]" value="<?php if (isset($params['redirects'][$country_code])) echo $params['redirects'][$country_code]; ?>">
						</div>
				  </td>
				</tr>
				<?php
			}
			?>
		  </tbody>
		</table>


		
				<input type="hidden" name="action" value="save_redirects"/>
		<center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button" value="Save & Apply"></center>
		<?php 
		
		elseif ($tab_id === 2): 
		
		$isPRO = gpjm_CheckIfPRO();
        
        $do_update = false;
		$last_update_date = gpjm_Get_Last_Update_date_GEOdb();
        
        if ($isPRO) $do_update = true;
			elseif (time() - strtotime(trim($last_update_date)) > 30 * 24 * 60 * 60) $do_update = true;

        
        if (!$isPRO) $params['protected_by'] = 1;
		
		?>
		
			<div class="ui fluid form sg_center">
			
			<center>
				  <div class="field" style="width:350px">
					<label>Registration Key</label>
					<input size="40" class="ui input sg_center" placeholder="Enter your registration code" type="text" name="registration_code" value="<?php if (isset($params['registration_code'])) echo $params['registration_code']; ?>">
					<input type="hidden" name="action" value="register_ext"/>
				  </div>
				  <div class="ui checkbox ui-form-row">
					<input type="checkbox" name="auto_geodb_update" value="1" <?php if (!$isPRO) echo 'disabled="disabled"'; ?> <?php if ($params['auto_geodb_update'] == 1) echo 'checked="checked"'; ?>>
					<label>Automatically Update GEO database</label>
				  </div>
				  <?php
				  if ($last_update_date !== false) echo ' (Last update was: '.$last_update_date.') ';
				  ?>
				  <a class="mini ui button allow <?php if (!$do_update) echo $free; ?>" href="<?php if ($do_update) echo 'index.php?option=com_geoprotection&tab_id=2&geo_update=1'; else echo 'javascript:;'; ?>">Update Manually</a>

				  <br>
				  
				  <div class="ui checkbox ui-form-row">
					<input type="checkbox" name="protected_by" value="1" <?php if (!$isPRO) echo 'disabled="disabled"'; ?> <?php if ($params['protected_by'] == 1) echo 'checked="checked"'; ?>>
					<label>Enable 'Protected by' sign</label>
				  </div>
			  
			</center>

			


				
			</div>
		
						<br>
		<center><input <?php echo $block_class; ?> type="submit" name="submit" id="submit" class="ui green button" value="Save & Apply"></center>
		<?php elseif ($tab_id === 5): 
		
        if (!$isPRO) $params['protection_by'] = 1;
        
        ?>

		<h4 class="ui header">Customize Block page</h4>
        
          <div class="inline field">
            <div id="custom_status" class="ui slider checkbox <?php if(!$isPRO) echo 'disabled'; ?>">
              <input <?php if($isPRO && isset($params['custom_status']) && intval($params['custom_status']) == 1) echo 'checked'; ?> value="1" type="checkbox" tabindex="0" name="custom_status" class="" onchange="ShowHideForm(jQuery(this).is(':checked'), '.show_active')">
              <label>Enable custom design</label>
            </div>
          </div>
     
          <div class="field show_active ">
            <label>URL to your logo image</label>
            <input  type="text" name="logo_url" id="logo_url" placeholder="URL to your logo image (e.g. <?php echo JURI::root(); ?>/images/logo.jpg)" value="<?php if(isset($params['logo_url'])) echo $params['logo_url']; ?>">
          </div>
          
          <div class="field show_active ">
            <label>Text line 1</label>
            <input  type="text" id="text_1"  name="text_1" placeholder="Default: Access is not allowed from your IP or your country." value="<?php if(isset($params['text_1'])) echo $params['text_1']; ?>">
          </div>
          
          <div class="field show_active ">
            <label>Text line 2</label>
            <input  type="text" id="text_2" name="text_2" placeholder="Default: If you think it's a mistake, please contact with the websmater of the website." value="<?php if(isset($params['text_2'])) echo $params['text_2']; ?>">
          </div>
          
          <div class="inline field show_active ">
            <div class="ui slider checkbox" id="hide_debug">
              <input <?php if(isset($params['hide_debug']) && intval($params['hide_debug']) == 1) echo 'checked'; ?> value="1"  type="checkbox" tabindex="0" name="hide_debug" class="">
              <label>Hide text: If you are the owner of the website, please contact with SiteGuarding.com support</label>
            </div>
          </div>
          
          <div class="inline field show_active ">
            <div class="ui slider checkbox" id="hide_ipinfo">
              <input <?php if(isset($params['hide_ipinfo']) && intval($params['hide_ipinfo']) == 1) echo 'checked'; ?> value="1" type="checkbox" tabindex="0" id="hide_ipinfo" name="hide_ipinfo" class="">
              <label>Hide session information: Your IP: xxx.xxx.xxx.xxx, Country</label>
            </div>
          </div>
          

          
            <?php if ($isPRO) : ?>
            <div class="ui mini positive message">
              <b>
                Help & Tips
              </b>
              <p>If you need help to customize GEO block page for your website, please contact with our support. It's free of charge.</p>
            </div>
			<?php else : ?>
			<div class="ui mini negative message">
              <b>
                Help & Tips
              </b>
              <p>This feature is available in the full version only.</p>
            </div>
        <?php endif; ?>

              <input class="ui right floated green button  <?php if(!$isPRO) echo 'disabled'; ?>" type="submit" name="submit" value="Save & Apply" />
<span class="ui right floated button" data-inverted="" data-tooltip="Preview only. It will not save the settings." onclick="BlockPage_Refresh()"><i class="tv icon"></i>Block Page Preview</span>
              

            <input type="hidden" name="action" id="action" value="Customization_save" />

		<br>
		<?php endif; ?>
		
		</form>
  

    </div>	
    
				<div style="z-index:99999;top:25%;left:35%;" class="tiny ui modal preview_show">
				  <div class="content">
						 <center><h4 class="ui header" data-inverted="" data-tooltip="Preview only. It will not save the settings."><i class="tv icon"></i>GEO Block Page Preview</h4></center><hr>
						<div id="geo_preview">	
						</div>
				  </div>
				  <div class="actions">
					<button onclick="jQuery('.modal.preview_show').modal('hide');" class="medium ui cancel button preview">Close Preview</button>
				  </div>
				</div>

				<div style="z-index:99999;top:40%;left:35%;" class="tiny ui modal paid">
				  <div class="header c_red">Alert</div>
				  <div class="content">
					<p><b>Available in full version only. <?php if ($tab_id === 2) echo ' Free version limit: Update once per month.'; ?></b></p>
				  </div>
				  <div class="actions">
					<button class="medium ui cancel button paid">Close</button>
				  </div>
				</div>                       

  </div>
              
<?php

           
function gpjm_CountryList_checkboxes($selected_array = array())
{
	$selected = array();
	if (is_array($selected_array) && count($selected_array))
	{
		foreach ($selected_array as $v)
		{
			$selected[$v] = $v;
		}
		
	}
	$a = '<div class="ui five column grid country_list filter_list">'."\n";

	foreach (GEO_JM_Geo_IP2Country::$country_list as $country_code => $country_name)
	{
		if (isset($selected[$country_code])) $checked = 'checked';
		else $checked = '';
		$a .= '<div id="id_'.str_replace(' ', '_', $country_name).'" class="ui checkbox column country_'.$country_code.' '.GEO_JM_Geo_IP2Country::$country_type_list[$country_code].' '.$checked.'">
			  <input type="checkbox" name="country_list[]" value="'.$country_code.'" tabindex="0" class="hidden">
			  <label>'.$country_name.'</label>
			</div>'."\n";
	}

	$a .= '</div>';
	
	return $a;
}
    
	
function gpjm_check_action() 
{
	
	$app = JFactory::getApplication();
	$postData = $app->input->post->getArray();
	$isPRO = gpjm_CheckIfPRO();

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

	// Actions
	if ($action != '')
	{
		$action_message = '';
		$message_type = '';
		$params = gpjm_Get_Params();
		switch ($action)
		{   
			case 'EnableDisable_protection_backend':

				$params['protection_backend'] = round(1 - $params['protection_backend']);
				gpjm_Set_Params($params);

				break;
				
			case 'EnableDisable_protection_frontend':

				$params['protection_frontend'] = round(1 - $params['protection_frontend']);
				gpjm_Set_Params($params);

				break;
				
			case 'register_ext':
				if (isset($postData['protected_by'])) $params['protected_by'] = intval($postData['protected_by']);
				else $params['protected_by'] = 0;
				
				if (!$isPRO) $params['protected_by'] = 1;
				
				if (isset($postData['auto_geodb_update'])) $params['auto_geodb_update'] = intval($postData['auto_geodb_update']);
				else $params['auto_geodb_update'] = 0;
				
				if (isset($postData['registration_code'])) $params['registration_code'] = trim($postData['registration_code']);
				else $params['registration_code'] = '';
				
				$action_message = 'Settings saved';
				$message_type = 'ok';
					
				gpjm_Set_Params($params);
				break;
				
			case 'save_frontend_params':
				$params['frontend_country_list'] = (isset($postData['country_list'])) ? $postData['country_list'] : array();
				if (!$isPRO && count($params['frontend_country_list']) > 5)
				{
					$action_message = 'Free version limit is 5 countries, ' . count($postData['country_list']) . ' countries selected. Please get full version. <a target="_blank" href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection">Full Version</a>';
					$message_type = 'alert';
				}
				else {
					
					$params['frontend_ip_list'] = '';
					$params['frontend_ip_list_allow'] = '';
					if ($isPRO && isset($postData['frontend_ip_list'])) $params['frontend_ip_list'] = $postData['frontend_ip_list'];
					if ($isPRO && isset($postData['frontend_ip_list_allow'])) $params['frontend_ip_list_allow'] = $postData['frontend_ip_list_allow'];
				
					$params['frontend_country_list'] = json_encode($params['frontend_country_list']);
					
					$action_message = 'Front-end protection settings saved';
					$message_type = 'ok';
									
					
					
					gpjm_Set_Params($params);
				}

				break;
				
			case 'Save_backend_params':
				$params['backend_country_list'] = (isset($postData['country_list'])) ? $postData['country_list'] : array();
				
				if (!$isPRO && count($postData['backend_country_list']) > 5)
				{
					$action_message = 'Free version limit is 5 countries, ' . count($postData['country_list']) . ' countries selected. Please get full version. <a target="_blank" href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection">Full Version</a>';
					$message_type = 'alert';
				}
				else {
					
					
					$params['backend_ip_list'] = '';
					$params['backend_ip_list_allow'] = '';
					if ($isPRO && isset($postData['backend_ip_list'])) $params['backend_ip_list'] = $postData['backend_ip_list'];
					if ($isPRO && isset($postData['backend_ip_list_allow'])) $params['backend_ip_list_allow'] = $postData['backend_ip_list_allow'];

				
					$params['backend_country_list'] = @json_encode($params['backend_country_list']);
					
					$action_message = 'Backend protection settings saved';
					$message_type = 'ok';
					
					gpjm_Set_Params($params);
				}

				break;
			case 'Customization_save':
				
				if (!$isPRO)
				{
					$action_message = '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';
					$message_type = 'alert';
				}
				else {
					if (isset($postData['custom_status'])) $params['custom_status'] = intval($postData['custom_status']);
					else $params['custom_status'] = 0;
					if (isset($postData['logo_url'])) $params['logo_url'] = ($postData['logo_url']);
					if (isset($postData['text_1'])) $params['text_1'] = ($postData['text_1']);
					if (isset($postData['text_2'])) $params['text_2'] = ($postData['text_2']);
					if (isset($postData['hide_ipinfo'])) $params['hide_ipinfo'] = intval($postData['hide_ipinfo']);
					else $params['hide_ipinfo'] = 0;
					if (isset($postData['hide_debug'])) $params['hide_debug'] = intval($postData['hide_debug']);
					else $params['hide_debug'] = 0;
					$action_message = 'Settings saved';
					$message_type = 'ok';
					gpjm_Set_Params($params);
				}
				break;
				
			case 'save_redirects':

				$params['redirects'] = isset($postData['redirects']) ? array_filter($postData['redirects']) : array();
				$params['rewrite_lang_code_status'] = isset($postData['rewrite_lang_code_status']) ? 1 : 0;
				$params['rewrite_lang_code'] = isset($postData['rewrite_lang_code']) ? array_filter($postData['rewrite_lang_code']) : array();

				if (count($params['redirects'])) {
					foreach ($params['redirects'] as $code => $redirect) {
						$params['redirects'][$code] = str_replace(substr(JURI::root(), 0, -1), '', $redirect);
					}
				}

				if (!gpjm_CheckIfPRO() && (count($params['redirects']) > 5 || count($params['rewrite_lang_code']) > 5 ))
				{
					$action_message = 'Free version limit is 5 countries, ' . count($params['redirects']) . ' countries selected. Please get full version. <a target="_blank" href="https://www.siteguarding.com/en/buy-extention/joomla-geo-website-protection">Full Version</a>';
					$message_type = 'alert';
				}
				else {

					$params['redirects'] = json_encode($params['redirects']);
					$params['rewrite_lang_code'] = json_encode($params['rewrite_lang_code']);
					$params['redirect_url_list_allow'] = '';
					$params['redirect_ip_list_allow'] = '';
					if ($isPRO && isset($postData['redirect_url_list_allow'])) $params['redirect_url_list_allow'] = $postData['redirect_url_list_allow'];
					if ($isPRO && isset($postData['redirect_ip_list_allow'])) $params['redirect_ip_list_allow'] = $postData['redirect_ip_list_allow'];


					$action_message = 'GEO Redirects settings saved';
					$message_type = 'ok';
					
					gpjm_Set_Params($params);
				}

				break;


		}
		

		if ($action_message != '')
		{
			$message_data = array(
				'type' => 'info_white',
				'header' => '',
				'message' => $action_message,
				'button_text' => '',
				'button_url' => '',
				'help_text' => ''
			);
			
			if ($message_type != '') $message_data['type'] = $message_type;

			gpjm_PrintIconMessage($message_data);

		}
	}
	
	return gpjm_Get_Params();
	
}
    
	
function gpjm_PrintIconMessage($data)
{
	$rand_id = "id_".rand(1,10000).'_'.rand(1,10000);
	if ($data['type'] == '' || $data['type'] == 'alert') {$type_message = 'negative'; $icon = 'warning sign';}
	if ($data['type'] == 'ok') {$type_message = 'green'; $icon = 'checkmark box';}
	if ($data['type'] == 'info') {$type_message = 'yellow'; $icon = 'info';}
	if ($data['type'] == 'info_white') {$type_message = ''; $icon = 'info';}
	?>
	<div style="width:100%;margin-top: 10px;margin-bottom: 30px;">
	<div class="ui large icon <?php echo $type_message; ?> message">
		<i class="<?php echo $icon; ?> icon"></i>
		<div class="msg_block_row">
			<?php
			if ((isset($data['button_text']) && $data['button_text'] != '') || (isset($data['help_text']) && $data['help_text'] != '')) {
			?>
			<div class="msg_block_txt">
				<?php
				if ($data['header'] != '') {
				?>
				<div class="header"><?php echo $data['header']; ?></div>
				<?php
				}
				?>
				<?php
				if ($data['message'] != '') {
				?>
				<p><?php echo $data['message']; ?></p>
				<?php
				}
				?>
			</div>
			<div class="msg_block_btn">
				<?php
				if ($data['help_text'] != '') {
				?>
				<a class="link_info" href="javascript:;" onclick="InfoBlock('<?php echo $rand_id; ?>');"><i class="help circle icon"></i></a>
				<?php
				}
				?>
				<?php
				if ($data['button_text'] != '') {
					if (!isset($data['button_url_target']) || $data['button_url_target'] == true) $new_window = 'target="_blank"';
					else $new_window = '';
				?>
				<a class="mini ui green button" <?php echo $new_window; ?> href="<?php echo $data['button_url']; ?>"><?php echo $data['button_text']; ?></a>
				<?php
				}
				?>
			</div>
				<?php
				if ($data['help_text'] != '') {
				?>
					<div style="clear: both;"></div>
					<div id="<?php echo $rand_id; ?>" style="display: none;">
						<div class="ui divider"></div>
						<p><?php echo $data['help_text']; ?></p>
					</div>
				<?php
				}
				?>
			<?php
			} else {
			?>
				<?php
				if (isset($data['header']) && $data['header'] != '') {
				?>
				<div class="header"><?php echo $data['header']; ?></div>
				<?php
				}
				?>
				<?php
				if ($data['message'] != '') {
				?>
				<p><?php echo $data['message']; ?></p>
				<?php
				}
				?>
			<?php
			}
			?>
		</div> 
	</div>
	</div>
	<?php
}



function gpjm_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;
}

function gpjm_CheckIfPRO()
{
	$domain = gpjm_PrepareDomain(JURI::root());
	
	$params = gpjm_Get_Params();
	if (!empty($params) && isset($params['registration_code'])) $registration_code = strtoupper( $params['registration_code'] );
	else return false;
	
	$check_code = strtoupper( md5( md5( md5($domain)."Version 2NY5DANTlYQ5WIZW" )."wNEzDQYT5NI3TdMj" ) );
	
	if ($check_code == $registration_code) return true;
	else return false;
}


function gpjm_Get_Params() {
	if (!is_file(__DIR__ . DIRSEP . 'settings.php')) gpjm_Set_Params(false);
	$content = file_get_contents(__DIR__ . DIRSEP . 'settings.php');
	return json_decode($content, true);
}


function gpjm_Set_Params($params) {
	
	$new = array();

	$new['protection_frontend'] = isset($params['protection_frontend'])? $params['protection_frontend'] : 0;
	$new['rewrite_lang_code_status'] = isset($params['rewrite_lang_code_status']) ? $params['rewrite_lang_code_status'] : 0;
	$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['protection_backend'] = isset($params['protection_backend'])? $params['protection_backend'] : 0;
	$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['redirect_ip_list_allow'] = isset($params['redirect_ip_list_allow'])? $params['redirect_ip_list_allow'] : '';
	$new['redirect_url_list_allow'] = isset($params['redirect_url_list_allow'])? $params['redirect_url_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['rewrite_lang_code'] = isset($params['rewrite_lang_code'])? $params['rewrite_lang_code'] : array();
	$new['registration_code'] = isset($params['registration_code'])? $params['registration_code'] : '';
	$new['protected_by'] = isset($params['protected_by'])? $params['protected_by'] : 1;
	$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(dirname(__FILE__).'/settings.php', 'w');
	fwrite($fp, $line);
	fclose($fp);
}


function gpjm_GetMyIP()
{
	$ip_address = $_SERVER["REMOTE_ADDR"];
	if (isset($_SERVER["HTTP_X_REAL_IP"])) $ip_address = $_SERVER["HTTP_X_REAL_IP"];
	if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) $ip_address = $_SERVER["HTTP_X_FORWARDED_FOR"];
	if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) $ip_address = $_SERVER["HTTP_CF_CONNECTING_IP"];
	if (isset($_SERVER['HTTP_X_SUCURI_CLIENTIP'])) $ip_address = $_SERVER['HTTP_X_SUCURI_CLIENTIP'];
	return $ip_address;
}


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

	$blockpage_json = array();
	$blockpage_json['logo_url'] = '/media/com_geoprotection/images/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 && gpjm_CheckIfPRO())  {
				// Replace default settings with customized
		$ajaxData = (array)json_decode(stripslashes( (string) $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 = gpjm_GetMyIP();
	if (!class_exists('GEO_JM_Geo_IP2Country'))
	{
		include_once(dirname(__FILE__).DIRSEP.'geo.php');
	}
	
	$geo = new GEO_JM_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_JM_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
}


function gpjm_GeneratePieData($days = 1)
{
	$result = array();
	
	$new_time = time() - $days * 24 * 60 * 60;
	
	$db = JFactory::getDbo();

	// Create a new query object.
	$query = $db->getQuery(true);
	
	$query
		->select(array('country_code', 'count(*)'))
		->from($db->quoteName('#__geo_oc_stats'))
		->where(array($db->quoteName('time') . ' > ' . $db->quote($new_time), $db->quoteName('type') . ' = 0'))
		->group($db->quoteName('country_code'))
		->order('count(*) DESC');

	$db->setQuery($query);

	// Load the results as a list of stdClass objects (see later for more options on retrieving data).
	$results = $db->loadAssocList();

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

	// Create a new query object.
	$query = $db->getQuery(true);
	
	$query
		->select(array('country_code', 'count(*)'))
		->from($db->quoteName('#__geo_oc_stats'))
		->where(array($db->quoteName('time') . ' > ' . $db->quote($new_time), $db->quoteName('type') . ' = 1'))
		->group($db->quoteName('country_code'))
		->order('count(*) DESC');

	$db->setQuery($query);

	// Load the results as a list of stdClass objects (see later for more options on retrieving data).
	$results = $db->loadAssocList();

	
	
	$redirect = array();
	if (count($results))
	{
		$total = 0;
		$i_limit = 10;
		foreach ( $results as $row ) 
		{
			$total = $total + $row['count(*)'];
			if ($i_limit > 0) $redirect[ $row['country_code'] ] = $row['count(*)'];
			else $redirect[ 'Other' ] += $row['count(*)'];
			
			$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;
}


function gpjm_PreparePieData($pie_array, $slice_flag = true)
{
	$result = array();
	
	if (!class_exists('GEO_JM_Geo_IP2Country'))
	{
		include_once(dirname(__FILE__).DIRSEP.'geo.php');
	}	
	
	$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_JM_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_JM_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;
}

function gpjm_GetLatestRecords($amount)
{		
	$db = JFactory::getDbo();

	// Create a new query object.
	$query = $db->getQuery(true);
	
	$query
		->select('*')
		->from($db->quoteName('#__geo_oc_stats'))
		->setLimit($amount)
		->order('id DESC');

	$db->setQuery($query);

	// Load the results as a list of stdClass objects (see later for more options on retrieving data).
	$results = $db->loadObjectList();
	
	return $results;
}	



function gpjm_Save_Block_alert($alert_data)
{
	$db = JFactory::getDbo();

	$query = $db->getQuery(true);

	$columns = array('time', 'ip', 'country_code', 'url', 'type');

	$values = array(intval($alert_data['time']), $db->quote($alert_data['ip']), $db->quote($alert_data['country_code']), $db->quote(addslashes($alert_data['url'])), intval($alert_data['type']));


	$query
		->insert($db->quoteName('#__geo_oc_stats'))
		->columns($db->quoteName($columns))
		->values(implode(',', $values));


	$db->setQuery($query);
	$db->execute();

}


function gpjm_Delete_old_logs($days)
{
	$old_time = time() - $days*24*60*60;
	
	$db = JFactory::getDbo();

	$query = $db->getQuery(true);

	$conditions = array(
		$db->quoteName('time') . ' < ' . $old_time, 
	);

	$query->delete($db->quoteName('#__geo_oc_stats'));
	$query->where($conditions);

	$db->setQuery($query);

	$result = $db->execute();
	
}

function gpjm_CheckBlockLog()
{
	$file_tmp_block_log = dirname(__FILE__).'/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( (string) $row, true);
				
				if ($row) gpjm_Save_Block_alert($row);
			}
		}
	}
}

function gpjm_getPiesData() {
	
	$result = array();
	
	$pie_array = gpjm_GeneratePieData(1);
	$result[1] = gpjm_PreparePieData($pie_array); 
	
	$pie_array = gpjm_GeneratePieData(7);
	$result[7] = gpjm_PreparePieData($pie_array);
	
	$pie_array = gpjm_GeneratePieData(30);
	$result[30]= gpjm_PreparePieData($pie_array);

	
	return $result;
}

function gpjm_UpdateGEOdb($manual = 0, $days = 30)
{
	$last_update_date = gpjm_Get_Last_Update_date_GEOdb();
	
	$date_days_ago = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")-$days, date("Y")));
	
	$domain = gpjm_PrepareDomain(JURI::root());
	
	if ($last_update_date === false || $last_update_date <= $date_days_ago || $manual == 1)
	{
		$plg_name = 'joomla-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 = gpjm_get_url_response($request_url);
		$json = (array)json_decode( (string) $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 = dirname(__FILE__).'/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 = gpjm_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 = dirname(__FILE__).'/geo_update.log';
		$fp = fopen($file, 'w');
		fwrite($fp, date("Y-m-d"));
		fclose($fp);
	}
}

function gpjm_Get_Last_Update_date_GEOdb()
{
	$file = dirname(__FILE__).'/geo_update.log';
	if (!file_exists($file)) return false;
	
	$handle = fopen($file, "r");
	$contents = fread($handle, filesize($file));
	fclose($handle);
	
	return $contents;
}

function gpjm_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;
}

function gpjm_get_url_response($url, $post = false, $data = false) {
	
	if (function_exists('curl_init')) {
		
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'); 
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_URL, $url); 
		if ($post && is_array($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
		}
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		$code = curl_exec($curl); 
		curl_close($curl); 
	} elseif (function_exists('file_get_contents')) {
		if ($post && is_array($data)) {
			$opts = array('http' =>
				array(
					'method'  => 'POST',
					'header'  => 'Content-type: application/x-www-form-urlencoded',
					'content' => http_build_query($data)
				)
			);
			$context  = stream_context_create($opts);
			$code = file_get_contents($url, false, $context);
		} else {
			$code = file_get_contents($url);
		}
	} else {
		$code = false;
	}
		return $code;
}