forked from bolt/GoogleAnalytics
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExtension.php
More file actions
220 lines (177 loc) · 8.17 KB
/
Copy pathExtension.php
File metadata and controls
220 lines (177 loc) · 8.17 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<?php
// Google Analytics extension for Bolt
namespace Bolt\Extension\DanielKulbe\GoogleAnalytics;
use Bolt\Extensions\Snippets\Location as SnippetLocation;
class Extension extends \Bolt\BaseExtension
{
public function getName()
{
return "Google Analytics";
}
function initialize()
{
$this->addSnippet(SnippetLocation::END_OF_HEAD, 'insertAnalytics');
$additionalhtml = '<script type="text/javascript" src="https://www.google.com/jsapi"></script>';
$additionalhtml .= '<script>google.load("visualization", "1", {packages:["corechart"]}); </script>';
if($this->config['widget']) $this->addWidget('dashboard', 'right_first', 'analyticsWidget', $additionalhtml, 3600);
}
public function insertAnalytics()
{
if (empty($this->config['webproperty'])) {
$this->config['webproperty'] = "property-not-set";
}
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),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '%webproperty%', '%domainname%');%displayfeatures%
ga('send', 'pageview');
</script>
EOM;
} else {
$html = <<< EOM
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '%webproperty%']);
_gaq.push(['_setDomainName', '%domainname%']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
EOM;
}
$html = str_replace("%webproperty%", $this->config['webproperty'], $html);
$html = str_replace("%displayfeatures%", ( $this->config['universal_displayfeatures'] ? " ga('require','displayfeatures');" : '' ), $html);
$html = str_replace("%domainname%", ( $this->config['universal'] ? $this->config['universal_domainname'] : $_SERVER['HTTP_HOST'] ), $html);
return new \Twig_Markup($html, 'UTF-8');
}
public function analyticsWidget()
{
// https://developers.google.com/analytics/devguides/reporting/core/v3/
if (empty($this->config['profile_id'])) { return "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;
}
// API dependencies
require_once(__DIR__.DIRECTORY_SEPARATOR.'google-api-php-client'.DIRECTORY_SEPARATOR.'autoload.php');
// create client object and set app name
$client = new \Google_Client();
// use Oauth2 Service access
if (isset($this->config['app_email']) && isset($this->config['app_cert'])) {
$cert = $this->app['paths']['extensionsconfig'].DIRECTORY_SEPARATOR.$this->config['app_cert'];
if (!file_exists($cert)) {
return "OAuth2 app_cert file not found or set, please adjust your config.yml.";
} elseif (empty($this->config['app_email'])) {
return "OAuth2 app_mail not set, please adjust your config.yml.";
}
$client->setAssertionCredentials( new \Google_Auth_AssertionCredentials(
$this->config['app_email'],
array(\Google_Service_Analytics::ANALYTICS_READONLY),
file_get_contents($cert)
) );
}
else {
return "OAuth2 is not properly set up, please adjust your config.yml.";
}
$caption = array(
'start' => date('M d', strtotime('-' . $this->config['number_of_days'] .' day')),
'end' => date('M d')
);
// name of your app
$client->setApplicationName(empty($this->config['app_name']) ? 'bolt Google Analytics widget' : $this->config['app_name']);
// create service and get data
$service = new \Google_Service_Analytics($client);
$pageviews = $sources = $pages = array();
// Get the 'pageviews per date'
$request = $service->data_ga->get(
'ga:'.$this->config['profile_id'],
date('Y-m-d', strtotime('-' . $this->config['number_of_days'] .' day')), date('Y-m-d'),
'ga:pageviews,ga:visitors,ga:uniquePageviews,ga:pageviewsPerSession,ga:exitRate,ga:avgTimeOnPage,ga:bounceRate',
array(
'dimensions' => 'ga:date',
'sort' => 'ga:date',
)
);
foreach ($request->getRows() as $result) {
$pageviews[] = array( date('M j', strtotime($result[0])), (int)$result[1], (int)$result[2] );
}
// aggregate data:
$aggr = array(
'pageviews' => (int)$request->totalsForAllResults['ga:pageviews'],
'visitors' => (int)$request->totalsForAllResults['ga:visitors'],
'uniquePageviews' => (int)$request->totalsForAllResults['ga:uniquePageviews'],
'pageviewspervisit' => round((float)$request->totalsForAllResults['ga:pageviewsPerSession'], 1),
'exitrate' => round((float)$request->totalsForAllResults['ga:exitRate'], 1),
'timeonpage' => $this->secondMinute(round((float)$request->totalsForAllResults['ga:avgTimeOnPage'], 1)),
'bouncerate' => round((float)$request->totalsForAllResults['ga:bounceRate'], 1),
);
// Get the 'popular sources'
$request = $service->data_ga->get(
'ga:'.$this->config['profile_id'],
date('Y-m-d', strtotime('-' . $this->config['number_of_days'] .' day')), date('Y-m-d'),
'ga:sessions',
array(
'dimensions' => 'ga:source,ga:referralPath',
'sort' => '-ga:sessions',
'filters' => 'ga:source!='.$filter_referral.',ga:referralPath!='.$filter_referral,
'max-results' => '12'
)
);
foreach($request->getRows() as $result) {
if ($result[1] == "(not set)") {
$sources[] = array(
'link' => false,
'host' => $result[0],
'visits' => $result[2]
);
} else {
$sources[] = array(
'link' => true,
'host' => $result[0] . $result[1],
'visits' => $result[2]
);
}
}
// Get the 'popular pages'
$request = $service->data_ga->get(
'ga:'.$this->config['profile_id'],
date('Y-m-d', strtotime('-' . $this->config['number_of_days'] .' day')), date('Y-m-d'),
'ga:sessions',
array(
'dimensions' => 'ga:hostname,ga:referralPath',
'sort' => '-ga:sessions',
'filters' => 'ga:source!='.$filter_referral.',ga:referralPath!='.$filter_referral,
'max-results' => '12'
)
);
foreach($request->getRows() as $result) {
$pages[] = array(
'host' => $result[0] . ($result[1] != '(not set)' ? $result[1] : ''),
'visits' => $result[2]
);
}
$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);
}
}