Skip to content

Commit

Permalink
Merge pull request #6 from SahAssar/master
Browse files Browse the repository at this point in the history
Move from gapi to google/apiclient with a new backend view
  • Loading branch information
GwendolenLynch committed Oct 25, 2015
2 parents ed62b08 + 4bb2d5a commit 96af9c7
Show file tree
Hide file tree
Showing 142 changed files with 210,808 additions and 1,245 deletions.
219 changes: 77 additions & 142 deletions Extension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

namespace Bolt\Extension\Bolt\GoogleAnalytics;

use Bolt\Translation\Translator as Trans;
use Symfony\Component\HttpFoundation\Response,
Symfony\Component\Translation\Loader as TranslationLoader;
use Bolt\Extensions\Snippets\Location as SnippetLocation;

class Extension extends \Bolt\BaseExtension
Expand All @@ -15,12 +18,62 @@ public function getName()

function initialize() {

$this->addSnippet(SnippetLocation::END_OF_HEAD, 'insertAnalytics');
$this->path = $this->app['config']->get('general/branding/path') . '/extensions/google-analytics';

$additionalhtml = '<script type="text/javascript" src="https://www.google.com/jsapi"></script>';
$additionalhtml .= '<script>google.load("visualization", "1", {packages:["corechart"]}); </script>';
$this->app->match($this->path, array($this, 'GoogleAnalytics'));

if($this->config['widget']) $this->addWidget('dashboard', 'right_first', 'analyticsWidget', $additionalhtml, 3600);
$this->app['htmlsnippets'] = true;

if ($this->app['config']->getWhichEnd()=='frontend') {
$this->addSnippet('endofhead', 'insertAnalytics');
} else {
$this->app->before(array($this, 'before'));
}

if (isset($this->config['backend']) && $this->config['backend']) {
$this->addMenuOption(Trans::__('Statistics'), $this->app['paths']['bolt'] . 'extensions/google-analytics', "fa:area-chart");
}

}

public function before()
{
$this->translationDir = __DIR__.'/locales/' . substr($this->app['locale'], 0, 2);
if (is_dir($this->translationDir))
{
$iterator = new \DirectoryIterator($this->translationDir);
foreach ($iterator as $fileInfo)
{
if ($fileInfo->isFile())
{
$this->app['translator']->addLoader('yml', new TranslationLoader\YamlFileLoader());
$this->app['translator']->addResource('yml', $fileInfo->getRealPath(), $this->app['locale']);
}
}
}
}

public function GoogleAnalytics()
{

$this->addJavascript('assets/es6-promise.min.js', 1);
$this->addJavascript('assets/active-users.js', 1);
$this->addJavascript('assets/date-range-selector.js', 1);
$this->addJavascript('assets/moment-with-locales.min.js', 1);
$this->addJavascript('assets/Chart.min.js', 1);
$this->addJavascript('assets/googleanalytics.js', array('late' => true, 'priority' => 1000));
$this->addCss('assets/styles.css', 1);

$data = [
"locale" => substr($this->app['locale'], 0, 2),
"token" => $this->getService(),
"profile" => $this->config['ga_profile_id']
];

$this->app['twig.loader.filesystem']->addPath(__DIR__.'/views/', 'GoogleAnalytics');
$html = $this->app['render']->render("@GoogleAnalytics/base.twig", $data);

return new Response($html);

}

Expand All @@ -35,7 +88,6 @@ public function insertAnalytics()
if ($this->config['universal']) {

$html = <<< EOM
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
Expand Down Expand Up @@ -75,155 +127,38 @@ public function insertAnalytics()

}




public function analyticsWidget()
private function getService()
{
// http://ga-dev-tools.appspot.com/explorer/
// http://code.google.com/p/gapi-google-analytics-php-interface/
// http://www.codediesel.com/php/reading-google-analytics-data-from-php/
// http://code.google.com/p/gapi-google-analytics-php-interface/wiki/UsingFilterControl

if (empty($this->config['ga_email'])) { return "ga_email not set in config.yml."; }
if (empty($this->config['ga_password'])) { return "ga_password not set in config.yml."; }
if (empty($this->config['service_account_email'])) { return "service_account_email not set in config.yml."; }
if (empty($this->config['key_file_location'])) { return "key_file_location not set in config.yml."; }
if (empty($this->config['ga_profile_id'])) { return "ga_profile_id not set in config.yml."; }
if (!empty($this->config['filter_referral'])) {
$filter_referral = 'source !@ "'.$this->config['filter_referral'].'"';
} else {
$filter_referral = '';
}
if (empty($this->config['number_of_days'])) {
$this->config['number_of_days'] = 14;
}

require_once(__DIR__.'/gapi/gapi.class.php');

/* Create a new Google Analytics request and pull the results */
$ga = new \gapi($this->config['ga_email'], $this->config['ga_password']);
$ga->requestReportData(
$this->config['ga_profile_id'],
array('date'),
array('pageviews', 'visitors', 'uniquePageviews', 'pageviewsPerVisit', 'exitRate', 'avgTimeOnPage', 'entranceBounceRate', 'newVisits'),
'date',
'',
date('Y-m-d', strtotime('-' . $this->config['number_of_days'] .' day')),
date('Y-m-d')
);
require_once(__DIR__.'/Google/autoload.php');

$pageviews = array();
$service_account_email = $this->config['service_account_email']; //Email Address
$key_file_location = $this->config['key_file_location']; //key.p12

$tempresults = $ga->getResults();
// Create and configure a new client object.
$client = new \Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new \Google_Service_Analytics($client);

$aggr = array(
'pageviews' => 0,
'pageviewspervisit' => 0,
'visitors' => 0,
'uniquePageviews' => 0,
'timeonpage' => 0,
'bouncerate' => 0,
'exitrate' => 0
// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_email,
array(\Google_Service_Analytics::ANALYTICS_READONLY),
$key
);

// aggregate data:
foreach($tempresults as $result) {

$pageviews[] = array(
'date' => date('M j',strtotime($result->getDate())),
'pageviews' => $result->getPageviews(),
'visitors' => $result->getVisitors()
);

$aggr['pageviews'] += $result->getPageviews();
$aggr['pageviewspervisit'] += $result->getPageviewsPerVisit();
$aggr['visitors'] += $result->getVisitors();
$aggr['uniquePageviews'] += $result->getUniquepageviews();
$aggr['timeonpage'] += $result->getAvgtimeonpage();
$aggr['bouncerate'] += $result->getEntrancebouncerate();
$aggr['exitrate'] += $result->getExitrate();
}
$client->setAssertionCredentials($cred);

$aggr['pageviewspervisit'] = round($aggr['pageviewspervisit'] / count($tempresults), 1);
$aggr['timeonpage'] = $this->secondMinute(round($aggr['timeonpage'] / count($tempresults), 1));
$aggr['bouncerate'] = round($aggr['bouncerate'] / count($tempresults), 1);
$aggr['exitrate'] = round($aggr['exitrate'] / count($tempresults), 1);

// Get the 'populair sources'
$ga->requestReportData(
$this->config['ga_profile_id'],
array('source','referralPath'),
array('visits'),
'-visits',
$filter_referral,
date('Y-m-d', strtotime('-' . $this->config['number_of_days'] .' day')),
date('Y-m-d'),
1,
12
);
$results = $ga->getResults();

$sources = array();

foreach($results as $result) {
if ($result->getReferralPath() == "(not set)") {
$sources[] = array(
'link' => false,
'host' => $result->getSource(),
'visits' => $result->getVisits()
);
} else {
$sources[] = array(
'link' => true,
'host' => $result->getSource() . $result->getReferralPath(),
'visits' => $result->getVisits()
);
}
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}

// Get the 'popular pages'
$ga->requestReportData(
$this->config['ga_profile_id'],
array('hostname','pagePath'),
array('visits'),
'-visits',
'',
date('Y-m-d', strtotime('-' . $this->config['number_of_days'] .' day')),
date('Y-m-d'),
1,
12
);
$results = $ga->getResults();

$pages = array();

foreach($results as $result) {
$pages[] = array(
'host' => $result->gethostname() . $result->getPagePath(),
'visits' => $result->getVisits()
);
}

$caption = sprintf("Google Analytics for %s - %s.",
date('M d', strtotime('-' . $this->config['number_of_days'] .' day')),
date('M d')
);

$this->app['twig.loader.filesystem']->addPath(__DIR__, 'GoogleAnalytics');
$html = $this->app['render']->render("@GoogleAnalytics/widget.twig", array(
'caption' => $caption,
'aggr' => $aggr,
'pageviews' => $pageviews,
'sources' => $sources,
'pages' => $pages
));

return new \Twig_Markup($html, 'UTF-8');

}


private function secondMinute($seconds) {
return sprintf('%d:%02d', floor($seconds/60), $seconds % 60);
return $client->getAccessToken();
}

}
38 changes: 38 additions & 0 deletions Google/Auth/Abstract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}

/**
* Abstract class for the Authentication in the API client
* @author Chris Chabot <[email protected]>
*
*/
abstract class Google_Auth_Abstract
{
/**
* An utility function that first calls $this->auth->sign($request) and then
* executes makeRequest() on that signed request. Used for when a request
* should be authenticated
* @param Google_Http_Request $request
* @return Google_Http_Request $request
*/
abstract public function authenticatedRequest(Google_Http_Request $request);
abstract public function sign(Google_Http_Request $request);
}
Loading

0 comments on commit 96af9c7

Please sign in to comment.