forked from wpengine/geoip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeoip.php
90 lines (74 loc) · 2.12 KB
/
geoip.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/*
* Plugin Name: WP Engine Geo
* Version: 0.4
* Author: WP Engine Labs
*
* Examples use of how to add geoip information to post content:
function geoip_append_content( $content ) {
$geo = WPEngine\GeoIp::instance();
$content .= "How's the weather in {$geo->city()}, {$geo->region()} {$geo->country()}?<br /><br />";
return $content;
}
add_filter( 'the_content', 'geoip_append_content' );
*/
namespace WPEngine;
// Exit if this file is directly accessed
if ( ! defined( 'ABSPATH' ) ) exit;
class GeoIp {
// The single instance of this object. No need to have more than one.
private static $instance = null;
// The geographical data loaded from the environment
public $geos;
public static function init() {
add_action( 'init', array( self::instance(), 'setup' ) );
}
public static function instance() {
// create a new object if it doesn't exist.
is_null( self::$instance ) && self::$instance = new self;
return self::$instance;
}
public function setup() {
$this->geos = $this->get_actuals();
}
/**
* Here we extract the data from headers set by nginx -- lets only send them if they are part of the cache key
**/
public function get_actuals() {
return array(
'countrycode' => getenv( 'HTTP_GEOIP_COUNTRY_CODE' ),
'countrycode3' => getenv( 'HTTP_GEOIP_COUNTRY_CODE3' ),
'countryname' => getenv( 'HTTP_GEOIP_COUNTRY_NAME' ),
'latitude' => getenv( 'HTTP_GEOIP_LATITUDE' ),
'longitude' => getenv( 'HTTP_GEOIP_LONGITUDE' ),
'areacode' => getenv( 'HTTP_GEOIP_AREA_CODE' ),
'region' => getenv( 'HTTP_GEOIP_REGION' ),
'city' => getenv( 'HTTP_GEOIP_CITY' ),
'postalcode' => getenv( 'HTTP_GEOIP_POSTAL_CODE' ),
);
}
/**
* Examples of easy to use utility functions that we should have for each geo that is part of the cache key
*
* @return mixed
*/
public function country() {
return $this->geos['countrycode'];
}
/**
* @return mixed
*/
public function region() {
return $this->geos['region'];
}
/**
* @return mixed
*/
public function city() {
return $this->geos['city'];
}
}
/**
* Register to do the stuff
*/
GeoIp::init();