Skip to content

Instantly share code, notes, and snippets.

@Dan0sz
Created September 18, 2019 20:58
Show Gist options
  • Save Dan0sz/60bb48d1260bb370c4143570acbb8c90 to your computer and use it in GitHub Desktop.
Save Dan0sz/60bb48d1260bb370c4143570acbb8c90 to your computer and use it in GitHub Desktop.
A WordPress REST Controller to pass-thru Google Analytics Data
<?php
/**
* @author : Daan van den Bergh
* @url : https://daan.dev/how-to/bypass-ad-blockers-caos/
* @copyright: (c) 2019 Daan van den Bergh
* @license : GPL2v2 or later
*/
class Analytics_Proxy extends WP_REST_Controller
{
/** @var string $namespace */
protected $namespace;
/** @var string $rest_base */
protected $rest_base;
public function __construct()
{
$this->namespace = 'analytics/v1';
$this->rest_base = 'proxy';
}
/**
* This function makes sure the controller is reachable at wp-json/analytics/v1/proxy/collect
*/
public function register_routes()
{
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/collect',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array($this, 'send_data'),
'permission_callback' => array($this, 'send_data_permissions_check')
),
'schema' => null,
)
);
}
/**
* @param $request
*
* @return bool
*/
public function send_data_permissions_check()
{
return true;
}
/**
* The uip-parameter is added to the query, to keep the location data accurate.
*
* @param WP_REST_Request $request
*
* @return mixed|WP_Error|WP_REST_Response
* @throws Exception
*/
public function send_data($request)
{
$params = $request->get_params();
$ip = $this->get_user_ip_address();
$paramIp = array('uip' => $ip);
$query = '?' . http_build_query($params + $paramIp);
$url = 'https://www.google-analytics.com/collect' . $query;
try {
$response = wp_remote_get(
$url
);
} catch (\Exception $error) {
throw new Exception($error->getMessage());
}
return $response;
}
/**
* Here we detect the User's IP address to make sure the location is still accurate.
* @return string
*/
private function get_user_ip_address()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
/**
* Some servers return multiple, comma-seapareted IP-addresses.
* The correct one is usually the first one.
*/
if (is_array(explode(',', $ip))) {
$ip = explode(',', $ip);
return $ip[0];
}
return $ip;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment