From f561aa4224dd0b7c4d1886faa86853b42a49859d Mon Sep 17 00:00:00 2001 From: Mike Jolley Date: Tue, 23 Dec 2014 18:49:37 +0000 Subject: [PATCH] Geolocation class --- includes/class-wc-geolocation.php | 130 ++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 includes/class-wc-geolocation.php diff --git a/includes/class-wc-geolocation.php b/includes/class-wc-geolocation.php new file mode 100644 index 00000000000..bbfb28695a8 --- /dev/null +++ b/includes/class-wc-geolocation.php @@ -0,0 +1,130 @@ +add( 'geolocation', 'Unable to open database file' ); + } + + @unlink( $tmp_database ); + } else { + $logger->add( 'geolocation', 'Unable to download GeoIP Database: ' . $tmp_database->get_message() ); + } + } + + /** + * Geolocation an IP address + * @param string $ip_address + * @return array + */ + public static function geolocate_ip( $ip_address ) { + $country_code = self::geolite_geolocation( $ip_address ); + + // Fallback to API + if ( empty( $country_code ) ) { + $country_code = self::freegeoip_geolocation( $ip_address ); + } + + return array( + 'country' => $country_code, + 'state' => '' + ); + } + + /** + * Use MAXMIND GeoLite database to geolocation the user. + * @param string $ip_address + * @return string + */ + private static function geolite_geolocation( $ip_address ) { + $country_code = ''; + $upload_dir = wp_upload_dir(); + $database = $upload_dir['basedir'] . '/GeoIP.dat'; + + if ( file_exists( $database ) ) { + if ( ! class_exists( 'GeoIP' ) ) { + include_once( 'libraries/geoip.php' ); + } + $gi = geoip_open( $database, GEOIP_STANDARD ); + $country_code = geoip_country_code_by_addr( $gi, $ip_address ); + geoip_close( $gi ); + } + + return $country_code; + } + + /** + * Use freegeoip.net + * @param string $ip_address + * @return string + */ + private static function freegeoip_geolocation( $ip_address ) { + $country_code = get_transient( 'geoip_' . $ip_address ); + + if ( false === $country_code ) { + $json_geo_ip = wp_remote_get( 'https://freegeoip.net/json/' . $ip_address ); + + if ( ! is_wp_error( $json_geo_ip ) ) { + $data = json_decode( $json_geo_ip['body'] ); + $country_code = sanitize_text_field( $data->country_code ); + set_transient( 'geoip_' . $ip_address, $country_code, WEEK_IN_SECONDS ); + } else { + $country_code = ''; + } + } + + return $country_code; + } +} + +WC_Geolocation::init();