/
Piwik.pm
570 lines (410 loc) · 12.8 KB
/
Piwik.pm
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package Mojolicious::Plugin::Piwik;
use Mojo::Base 'Mojolicious::Plugin';
use Mojo::ByteStream 'b';
use Mojo::UserAgent;
our $VERSION = '0.09';
# Todo:
# - Better test tracking API support
# See http://piwik.org/docs/javascript-tracking/
# http://piwik.org/docs/tracking-api/reference/
# - Support custom values in tracking api.
# - Add eCommerce support
# http://piwik.org/docs/ecommerce-analytics/
# - Improve error handling.
# Register plugin
sub register {
my ($plugin, $mojo, $plugin_param) = @_;
$plugin_param ||= {};
# Load parameter from Config file
if (my $config_param = $mojo->config('Piwik')) {
$plugin_param = { %$config_param, %$plugin_param };
};
# Embed tag
my $embed = $plugin_param->{embed} //
($mojo->mode eq 'production' ? 1 : 0);
# Add 'piwik_tag' helper
$mojo->helper(
piwik_tag => sub {
# Do not embed
return '' unless $embed;
# Controller
my $c = shift;
# Use opt-out tag
my %opt;
if ($_[0] && index(lc $_[0], 'opt-out') == 0) {
my $opt_out = shift;
# Get iframe content
my $cb = ref $_[-1] eq 'CODE' ? pop : 0;
# Accept parameters
%opt = @_;
$opt{out} = $opt_out;
$opt{cb} = $cb;
# Empty arguments
@_ = ();
};
my $site_id = shift || $plugin_param->{site_id} || 1;
my $url = shift || $plugin_param->{url};
# No piwik url
return b('<!-- No Piwik-URL given -->') unless $url;
# Clear url
for ($url) {
s{^https?:/*}{}i;
s{piwik\.(?:php|js)$}{}i;
s{(?<!/)$}{/};
};
# Render opt-out tag
if (my $opt_out = delete $opt{out}) {
# Get protocol
my $req_url = $c->req->url;
my $prot = $req_url->scheme ? lc $req_url->scheme : 'http';
my $cb = delete $opt{cb};
my $oo_url = "${prot}://${url}index.php?module=CoreAdminHome&action=optOut";
if ($opt_out eq 'opt-out-link') {
$opt{href} = $oo_url;
$opt{rel} //= 'nofollow';
return $c->tag('a', %opt, ($cb || sub { 'Piwik Opt-Out' }));
};
$opt{src} = $oo_url;
$opt{width} ||= '600px';
$opt{height} ||= '200px';
$opt{frameborder} ||= 'no';
return $c->tag('iframe', %opt, ($cb || sub { '' }));
};
# Create piwik tag
b(<<"SCRIPTTAG")->squish;
<script type="text/javascript">var _paq=_paq||[];(function(){var
u='http'+((document.location.protocol=='https:')?'s':'')+'://$url';
with(_paq){push(['setSiteId',$site_id]);push(['setTrackerUrl',u+'piwik.php']);
push(['trackPageView'])};var
d=document,g=d.createElement('script'),s=d.getElementsByTagName('script')[0];
if(!s){s=d.getElementsByTagName('head')[0].firstChild};
with(g){type='text/javascript';defer=async=true;
src=u+'piwik.js';s.parentNode.insertBefore(g,s)}})();</script>
<noscript><img src="http://${url}piwik.php?idSite=${site_id}&rec=1" alt=""
style="border:0" /></noscript>
SCRIPTTAG
});
# Add 'piwik_api' helper
$mojo->helper(
piwik_api => sub {
my ($c, $method, $param, $cb) = @_;
# Get api_test parameter
my $api_test = delete $param->{api_test};
# Get piwik url
my $url = delete $param->{url} || $plugin_param->{url};
$url =~ s{^https?://}{}i;
$url = ($param->{secure} ? 'https' : 'http') . '://' . $url;
# Create request URL
$url = Mojo::URL->new($url);
# Site id
my $site_id = $param->{site_id} ||
$param->{idSite} ||
$param->{idsite} ||
$plugin_param->{site_id} || 1;
# delete unused parameters
delete @{$param}{qw/site_id idSite idsite format module method/};
# Token Auth
my $token_auth = delete $param->{token_auth} ||
$plugin_param->{token_auth} || 'anonymous';
# Tracking API
if (lc $method eq 'track') {
$url->path('piwik.php');
# Request Headers
my $header = $c->req->headers;
# Respect do not track
return if $header->dnt;
# Set default values
for ($param) {
$_->{ua} //= $header->user_agent if $header->user_agent;
$_->{urlref} //= $header->referrer if $header->referrer;
$_->{rand} = int(rand(10_000));
$_->{rec} = 1;
$_->{apiv} = 1;
$_->{url} = delete $_->{action_url} || $c->url_for->to_abs;
# Todo: maybe make optional with parameter
# $_->{_id} = rand ...
};
# Resolution
if ($param->{res} && ref $param->{res}) {
$param->{res} = join 'x', @{$param->{res}}[0, 1];
};
$url->query(
idsite => ref $site_id ? $site_id->[0] : $site_id,
format => 'JSON'
);
$url->query({token_auth => $token_auth}) if $token_auth;
}
# Analysis API
else {
# Create request method
$url->query(
module => 'API',
method => $method,
format => 'JSON',
idSite => ref $site_id ? join(',', @$site_id) : $site_id,
token_auth => $token_auth
);
# Urls
if ($param->{urls}) {
# Urls is arrayref
if (ref $param->{urls}) {
my $i = 0;
foreach (@{$param->{urls}}) {
$url->query({ 'urls[' . $i++ . ']' => $_ });
};
}
# Urls as string
else {
$url->query({urls => $param->{urls}});
};
delete $param->{urls};
};
# Range with periods
if ($param->{period}) {
# Delete period
my $period = lc delete $param->{period};
# Delete date
my $date = delete $param->{date};
# Get range
if ($period eq 'range') {
$date = ref $date ? join(',', @$date) : $date;
};
if ($period =~ m/^(?:day|week|month|year|range)$/) {
$url->query({
period => $period,
date => $date
});
};
};
};
# Todo: Handle Filter
# Merge query
$url->query($param);
# Return string for api testing
return $url->to_string if $api_test;
# Create Mojo::UserAgent
my $ua = Mojo::UserAgent->new(max_redirects => 2);
# Todo: Handle json errors!
# Blocking
unless ($cb) {
my $tx = $ua->get($url);
return _treat_response($tx->res) if $tx->success;
return;
}
# Non-Blocking
else {
$ua->get(
$url => sub {
my ($ua, $tx) = @_;
my $json = {};
$json = _treat_response($tx->res) if $tx->success;
$cb->($json);
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
};
});
};
sub _treat_response {
my $res = shift;
my $ct = $res->headers->content_type;
if (index($ct, 'json') >= 0) {
return $res->json;
}
elsif (index($ct, 'html') >= 0) {
# Find error message in html
my $found = $res->dom->at('#contentsimple > p');
# Return unknown error
return { error => 'unknown' } unless $found;
# Return error message as json
return { error => $found->all_text };
}
elsif ($ct =~ m{^image/(gif|jpe?g)}) {
return {
image => 'data:image/' . $1 . ';base64,' . b($res->body)->b64_encode
};
};
return { error => 'Unknown response type' };
};
1;
__END__
=pod
=encoding utf8
=head1 NAME
Mojolicious::Plugin::Piwik - Use Piwik in Mojolicious
=head1 SYNOPSIS
# On startup
plugin 'Piwik' => {
url => 'piwik.khm.li',
site_id => 1
};
# In Template
%= piwik_tag
# In controller
my $json = $c->piwik_api('API.getPiwikVersion');
=head1 DESCRIPTION
L<Mojolicious::Plugin::Piwik> is a simple plugin for embedding
L<Piwik|http://piwik.org/> Analysis in your Mojolicious app.
Please respect the privacy of your visitors and do not track
more information than necessary!
=head1 METHODS
L<Mojolicious::Plugin::Piwik> inherits all methods from
L<Mojolicious::Plugin> and implements the following new ones.
=head2 register
# Mojolicious
$app->plugin(Piwik => {
url => 'piwik.khm.li',
site_id => 1
});
# Mojolicious::Lite
plugin 'Piwik' => {
url => 'piwik.khm.li',
site_id => 1
};
# Or in your config file
{
Piwik => {
url => 'piwik.khm.li',
site_id => 1
}
}
Called when registering the plugin.
Accepts the following parameters:
=over 2
=item
C<url> - URL of your Piwik instance.
=item
C<site_id> - The id of the site to monitor. Defaults to 1.
=item
C<embed> - Activates or deactivates the embedding of the script tag.
Defaults to C<true> if Mojolicious is in production mode,
defaults to C<false> otherwise.
=item
C<token_auth> - Token for authentication. Used only for the Piwik API.
=back
All parameters can be set either on registration or
as part of the configuration file with the key C<Piwik>.
=head1 HELPERS
=head2 piwik_tag
%= piwik_tag
%= piwik_tag 1
%= piwik_tag 1, 'piwik.khm.li'
Renders a script tag that asynchronously loads the Piwik
javascript file from your Piwik instance.
Accepts optionally a site id and the url of your Piwik
instance. Defaults to the site id and the url given when the plugin
was registered.
This tag should be included at the bottom
of the body tag of your website.
%= piwik_tag 'opt-out', width => 400
The special C<opt-out> tag renders an iframe helping
your visitors to disallow tracking via javascript.
See the L<default tag helper|Mojolicious::Plugin::TagHelpers/tag>
for explanation of usage.
<%= piwik_tag 'opt-out-link', begin %>Opt Out<% end %>
# <a href="..." rel="nofollow">Opt Out</a>
The special C<opt-out-link> renders an anchor link
to the opt-out page to be used if the visitor does
not allow third party cookies.
See the L<default tag helper|Mojolicious::Plugin::TagHelpers/tag>
for explanation of usage.
=head2 piwik_api
# In Controller - blocking ...
my $json = $c->piwik_api(
'Actions.getPageUrl' => {
token_auth => 'MyToken',
idSite => [4,7],
period => 'day',
date => 'today'
}
);
# ... or async
$c->piwik_api(
'Actions.getPageUrl' => {
token_auth => 'MyToken',
idSite => [4,7],
period => 'day',
date => 'today'
} => sub {
my $json = shift;
# ...
}
);
Sends an API request and returns the response as a hash
or array reference (the decoded JSON response).
Accepts the API method, a hash reference
with request parameters as described in the
L<Piwik API|http://piwik.org/docs/analytics-api/>, and
optionally a callback, if the request is meant to be non-blocking.
The L<Tracking API|http://piwik.org/docs/tracking-api/reference/>
uses the method name C<Track> and will forward user agent and
referrer information based on the controller request as well as the
url of the requested resource, unless Do-Not-Track is activated.
The ip address is not forwarded.
$c->piwik_api(
Track => {
idsite => '4',
res => [1024, 768],
action_url => 'http://khm.li/12',
action_name => 'Märchen/Rapunzel'
});
As the C<url> parameter is used to define the Piwik instance,
the url of the requested resource to be named C<action_url>.
Please remember that cookie-based opt-out can't be supported.
In addition to the parameters of the API references, the following
parameters are allowed:
=over 2
=item
C<url> - The url of your Piwik instance.
Defaults to the url given when the plugin was registered.
=item
C<secure> - Boolean value that indicates a request using the https scheme.
Defaults to false.
=item
C<api_test> - Boolean value that indicates a test request, that returns the
created request url instead of the JSON response. Defaults to false.
=back
C<idSite> is an alias of C<site_id> and C<idsite> and defaults to the id
of the plugin registration.
Some parameters are allowed to be array references instead of string values,
for example C<idSite> (for analysis), C<date> (for ranges) and C<res> (for tracking).
my $json = $c->piwik_api(
'API.get' => {
site_id => [4,5],
period => 'range',
date => ['2012-11-01', '2012-12-01'],
secure => 1
});
In case of an error, C<piwik_api> tries to response with a meaningsful
descriptin in the hash value of C<error>.
If an image is expected instead of a JSON object
(as for the Tracking or the C<ImageGraph> API), the image is base64
encoded and mime-type prefixed in the hash value of image.
=head1 LIMITATIONS
The plugin lacks support for eCommerce tracking.
=head1 TESTING
To test the plugin against your Piwik instance, create a configuration
file with the necessary information as a perl data structure in C<t/auth.pl>
and run C<make test>, for example:
{
token_auth => '123456abcdefghijklmnopqrstuvwxyz',
url => 'http://piwik.khm.li/',
site_id => 1,
action_url => 'http://khm.li/Test',
action_name => 'Märchen/Test'
};
The user agent to be ignored is called C<Mojo-Test>.
=head1 DEPENDENCIES
L<Mojolicious>.
=head1 AVAILABILITY
https://github.com/Akron/Mojolicious-Plugin-Piwik
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2012-2013, L<Nils Diewald|http://nils-diewald.de/>.
This program is free software, you can redistribute it
and/or modify it under the same terms as Perl.
Please make sure you are using Piwik in compliance to the law.
For german users,
L<this information|https://www.datenschutzzentrum.de/tracking/piwik/>
may help you to design your service correctly.
This plugin was developed for
L<khm.li - Kinder- und Hausmärchen der Brüder Grimm|http://khm.li/>.
=cut