<?php

// ------------------------------------------------------------------------------------
//GeoIP
include_once('geoip/geoipcity.inc'); 


/**
 * Returns the name of the country the current user connects from
 * @return string
 *
 * Maxmind: http://geolite.maxmind.com/download/geoip/api/php/ 
 */
function em_get_event_user_country_name(){
	
	$result = '';
	$hash = $_SERVER['REMOTE_ADDR'] . '.COUNTRY_NAME'; // key for transient storage
	
	/* We use the Transient API*/
	if ( false === ( $result = get_transient($hash))) {
		
		$gi = geoip_open(EM_GEOIP_DIR . "\geoip\GeoIP.dat", GEOIP_STANDARD); 
		$result = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']); 
	    geoip_close($gi);
	
     	set_transient($hash, $result, 60*60*1 /* one hour */ );
	}
	
	return $result;
}
add_shortcode ( 'event_user_country_name', 'em_get_event_user_country_name');





/**
 * Shows a list of events according to given specifications. Accepts any event query attribute.
 * @param array $atts
 * @return string
 */
function em_get_events_list_geoip_shortcode($atts, $format='') {
	

	$code = '';
	$hash = $_SERVER['REMOTE_ADDR'] . '.COUNTRY_CODE';
	
	/**/
	if ( false === ( $code = get_transient($hash))) {
		
		$gi = geoip_open(EM_GEOIP_DIR . "\geoip\GeoIP.dat",GEOIP_STANDARD); 
		$code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']); 
		geoip_close($gi);
		
		set_transient($hash, $code, 60*60*1 /* one hour */ );
	}
	
	$atts = (array) $atts;
	$atts['format'] = ($format != '' || empty($atts['format'])) ? $format : $atts['format']; 
	$atts['format'] = html_entity_decode($atts['format']); //shorcode doesn't accept html
	$atts['page'] = ( !empty($atts['page']) && is_numeric($atts['page']) )? $atts['page'] : 1;
	$atts['page'] = ( !empty($_GET['pno']) && is_numeric($_GET['pno']) )? $_GET['pno'] : $atts['page'];
	$atts['country'] = $code;
	
	return EM_Events::output( $atts );
}
add_shortcode ( 'events_geo_list', 'em_get_events_list_geoip_shortcode' );

?>