Skip to content

Commit

Permalink
updated google analytics plugin.
Browse files Browse the repository at this point in the history
  • Loading branch information
Glen Barnes committed Jul 25, 2009
1 parent 388dec3 commit 534cea0
Show file tree
Hide file tree
Showing 12 changed files with 1,280 additions and 207 deletions.
254 changes: 215 additions & 39 deletions plugins/google-analyticator/class.analytics.stats.php
Expand Up @@ -2,11 +2,7 @@

# Include SimplePie if it doesn't exist
if ( !class_exists('SimplePie') ) {
if ( function_exists('fetch_feed') ) {
require_once (ABSPATH . WPINC . '/class-feed.php');
} else {
require_once('simplepie.inc');
}
require_once (ABSPATH . WPINC . '/class-feed.php');
}

/**
Expand All @@ -21,54 +17,104 @@ class GoogleAnalyticsStats
var $baseFeed = 'https://www.google.com/analytics/feeds';
var $accountId;
var $token = false;
var $responseHash = array();
var $responseCode = '';

/**
* Constructor
*
* @param user - the google account's username
* @param pass - the google account's password
* @param token - a one-time use token to be exchanged for a real token
**/
function GoogleAnalyticsStats($user, $pass)
function GoogleAnalyticsStats($token = false)
{
# Encode the login details for sending over HTTP
$user = urlencode($user);
$pass = urlencode($pass);
# Increase the memory limit to prevent blank page errors
ini_set('memory_limit', '64M');

# Request authentication with Google
$response = $this->curl('https://www.google.com/accounts/ClientLogin', 'accountType=GOOGLE&Email=' . $user . '&Passwd=' . $pass);
# If we need to request a permanent token
if ( $token ) {

$this->token = $token;

# Request authentication with Google
$response = $this->http('https://www.google.com/accounts/AuthSubSessionToken', $post);

# Get the authentication token
$this->token = substr(strstr($response, "Auth="), 5);
# Get the authentication token
$this->token = substr(strstr($response, "Token="), 6);

# Save the token for future use
update_option('ga_google_token', $this->token);

# Remove the old username and password fields if they still exists
delete_option('google_stats_user');
delete_option('google_stats_password');

} else {
$this->token = get_option('ga_google_token');
}
}

/**
* Connects over cURL to get data
* Connects using the WordPress HTTP API to get data
*
* @param url - url to request
* @param post - post data to pass through curl
* @return the raw curl response
* @param post - post data to pass through WordPress
* @return the raw http response
**/
function curl($url, $post = false, $header = 1)
function http($url, $post = false)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, $url);
# Return false if the token has not been set
if ( trim($this->token) == '' )
return '';

# Set the arguments to pass to WordPress
$args = array(
'sslverify' => false
);

# Add the optional post values
if ( $post ) {
$post .= '&service=analytics&source=google-analyticator-' . GOOGLE_ANALYTICATOR_VERSION;
$args['body'] = $post;
}

# Set the content to form data
$args['headers'] = array('Content-Type' => 'application/x-www-form-urlencoded');

# Include the authentication token if known
# Add the token information
if ( $this->token ) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: GoogleLogin auth=' . $this->token));
$args['headers']['Authorization'] = 'AuthSub token="' . $this->token . '"';
}

# Disable the fopen transport since it doesn't work with the Google API
add_filter('use_fopen_transport', create_function('$a', 'return false;'));

# Make the connection
if ( $post )
$response = wp_remote_post($url, $args);
else
$response = wp_remote_get($url, $args);

# Check for WordPress error
if ( is_wp_error($response) ) {
$this->responseHash['error'] = __('WordPress HTTP error.', 'google-analyticator');
return '';
}

# Include optional post fields
if ( $post ) {
$post .= '&service=analytics&source=wp-google-stats';
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
# Set the message response
$this->responseCode = $response['response']['code'];

# Build an array of messages
foreach( explode("\n", $response['body']) as $line ) {
if ( trim($line) != '' ) {
$pos = strpos($line, '=');
if ( $pos !== false ) {
$this->responseHash[strtolower(substr($line, 0, $pos))] = substr($line, $pos+1);
}
}
}

return curl_exec($curl);
# Return the body of the response
return $response['body'];
}

/**
Expand Down Expand Up @@ -102,11 +148,11 @@ function setAccount($id)
function getAnalyticsAccounts()
{
# Request the list of accounts
$response = $this->curl($this->baseFeed . '/accounts/default', false, '0');
$response = $this->http($this->baseFeed . '/accounts/default');

# Check if the response received exists, else stop processing now
if ( $response == '' )
return array();
if ( $response == '' || $this->responseCode != '200' )
return false;

# Parse the XML using SimplePie
$simplePie = new SimplePie();
Expand All @@ -120,10 +166,24 @@ function getAnalyticsAccounts()
foreach ( $accounts AS $account ) {
$id = array();

$item_info = $account->get_item_tags('http://schemas.google.com/analytics/2009', 'tableId');
# Get the list of properties
$properties = $account->get_item_tags('http://schemas.google.com/analytics/2009', 'property');

# Loop through the properties
foreach ( $properties AS $property ) {

# Get the property information
$name = $property['attribs']['']['name'];
$value = $property['attribs']['']['value'];

# Add the propery data to the id array
$id[$name] = $value;

}

# Add the backward compatibility array items
$id['title'] = $account->get_title();
$id['id'] = $item_info[0]['data'];
$id['id'] = 'ga:' . $id['ga:profileId'];

$ids[] = $id;
}
Expand All @@ -141,8 +201,15 @@ function getAnalyticsAccounts()
**/
function getMetric($metric, $startDate, $endDate)
{
# Request the list of accounts
$response = $this->curl($this->baseFeed . "/data?ids=$this->accountId&start-date=$startDate&end-date=$endDate&metrics=$metric", false, '0');
# Ensure the start date is after Jan 1 2005
$startDate = $this->verifyStartDate($startDate);

# Request the metric data
$response = $this->http($this->baseFeed . "/data?ids=$this->accountId&start-date=$startDate&end-date=$endDate&metrics=$metric");

# Check if the response received exists, else stop processing now
if ( $response == '' || $this->responseCode != '200' )
return false;

# Parse the XML using SimplePie
$simplePie = new SimplePie();
Expand All @@ -158,6 +225,115 @@ function getMetric($metric, $startDate, $endDate)
}
}

/**
* Get a specific data metrics
*
* @param metrics - the metrics to get
* @param startDate - the start date to get
* @param endDate - the end date to get
* @param dimensions - the dimensions to grab
* @param sort - the properties to sort on
* @param filter - the property to filter on
* @param limit - the number of items to get
* @return the specific metrics in array form
**/
function getMetrics($metric, $startDate, $endDate, $dimensions = false, $sort = false, $filter = false, $limit = false)
{
# Ensure the start date is after Jan 1 2005
$startDate = $this->verifyStartDate($startDate);

# Build the query url
$url = $this->baseFeed . "/data?ids=$this->accountId&start-date=$startDate&end-date=$endDate&metrics=$metric";

# Add optional dimensions
if ( $dimensions )
$url .= "&dimensions=$dimensions";

# Add optional sort
if ( $sort )
$url .= "&sort=$sort";

# Add optional filter
if ( $filter )
$url .= "&filters=$filter";

# Add optional limit
if ( $limit )
$url .= "&max-results=$limit";

# Request the metric data
$response = $this->http($url);

# Check if the response received exists, else stop processing now
if ( $response == '' || $this->responseCode != '200' )
return false;

# Parse the XML using SimplePie
$simplePie = new SimplePie();
$simplePie->set_raw_data($response);
$simplePie->enable_order_by_date(false);
$simplePie->init();
$simplePie->handle_content_type();
$datas = $simplePie->get_items();

$ids = array();

# Read out the data until the metric is found
foreach ( $datas AS $data ) {
$metrics = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'metric');
$dimensions = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'dimension');
$id = array();

$id['title'] = $data->get_title();

# Loop through the dimensions
if ( is_array($dimensions) ) {
foreach ( $dimensions AS $property ) {

# Get the property information
$name = $property['attribs']['']['name'];
$value = $property['attribs']['']['value'];

# Add the propery data to the id array
$id[$name] = $value;

}
}

# Loop through the metrics
if ( is_array($metrics) ) {
foreach ( $metrics AS $property ) {

# Get the property information
$name = $property['attribs']['']['name'];
$value = $property['attribs']['']['value'];

# Add the propery data to the id array
$id[$name] = $value;

}
}

$ids[] = $id;
}

return $ids;
}

/**
* Checks the date against Jan. 1 2005 because GA API only works until that date
*
* @param date - the date to compare
* @return the correct date
**/
function verifyStartDate($date)
{
if ( strtotime($date) > strtotime('2005-01-01') )
return $date;
else
return '2005-01-01';
}

} // END class

?>

0 comments on commit 534cea0

Please sign in to comment.