-
Notifications
You must be signed in to change notification settings - Fork 16
/
Extension.php
98 lines (83 loc) · 2.89 KB
/
Extension.php
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
<?php
namespace Webfactory\Bundle\PiwikBundle\Twig;
class Extension extends \Twig_Extension
{
protected $disabled;
protected $siteId;
protected $piwikHost;
protected $trackerPath;
protected $paqs = array();
function __construct($disabled, $siteId, $piwikHost, $trackerPath)
{
$this->disabled = $disabled;
$this->siteId = $siteId;
$this->piwikHost = rtrim($piwikHost, '/');
$this->trackerPath = ltrim($trackerPath, '/');
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('piwik_code', array($this, 'piwikCode'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('piwik', array($this, 'piwikPush'))
);
}
public function piwikPush()
{
$this->paqs[] = func_get_args();
}
public function piwikCode()
{
if ($this->disabled) {
return '<!-- Piwik is disabled due to webfactory_piwik.disabled=true in your configuration -->';
}
$this->addDefaultApiCalls();
$paq = json_encode($this->paqs);
$piwikCode = <<<EOT
<!-- Piwik -->
<script type="text/javascript">//<![CDATA[
var _paq = (_paq||[]).concat({$paq});
_paq.push(["setDoNotTrack", true]);
_paq.push(['trackPageView']);
(function() {
var u=(("https:" == document.location.protocol) ? "https" : "http") + "://{$this->piwikHost}/";
_paq.push(["setTrackerUrl", u+"{$this->trackerPath}"]);
_paq.push(["setSiteId", "{$this->siteId}"]);
EOT;
if($this->trackerPath !== 'piwik.php') {
$piwikCode .= <<<EOT
_paq.push(['setAPIUrl', u]);
EOT;
}
$piwikCode .= <<<EOT
var d=document, g=d.createElement("script"), s=d.getElementsByTagName("script")[0]; g.type="text/javascript";
g.defer=true; g.async=true; g.src=u+"{$this->trackerPath}"; s.parentNode.insertBefore(g,s);
})();
//]]></script>
<noscript><p><img src="//{$this->piwikHost}/piwik.php?idsite={$this->siteId}&rec=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
EOT;
return $piwikCode;
}
protected function addDefaultApiCalls()
{
$this->paqs[] = array('enableLinkTracking');
foreach ($this->paqs as $paq) {
if ($paq[0] == 'trackSiteSearch') {
/*
* It is recommended *not* to "trackPageView" for "trackSiteSearch" pages.
* See http://developer.piwik.org/api-reference/tracking-javascript#tracking-internal-search-keywords-categories-and-no-result-search-keywords
* or http://piwik.org/docs/site-search/#track-site-search-using-the-javascript-tracksitesearch-function.
*/
return; // Do not add 'trackPageView'
}
}
$this->paqs[] = array('trackPageView');
}
/**
* @inheritdoc
*/
public function getName()
{
return 'webfactory_piwik';
}
}