PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.6.0
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.6.0
5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / Tracker / TrackerCodeGenerator.php
matomo / app / core / Tracker Last commit date
Db 4 years ago Handler 5 years ago TableLogAction 5 years ago Visit 5 years ago Action.php 5 years ago ActionPageview.php 5 years ago Cache.php 5 years ago Db.php 4 years ago Failures.php 4 years ago FingerprintSalt.php 6 years ago GoalManager.php 4 years ago Handler.php 5 years ago IgnoreCookie.php 4 years ago LogTable.php 5 years ago Model.php 5 years ago PageUrl.php 4 years ago Request.php 4 years ago RequestProcessor.php 5 years ago RequestSet.php 4 years ago Response.php 4 years ago ScheduledTasksRunner.php 5 years ago Settings.php 5 years ago TableLogAction.php 5 years ago TrackerCodeGenerator.php 4 years ago TrackerConfig.php 4 years ago Visit.php 4 years ago VisitExcluded.php 5 years ago VisitInterface.php 5 years ago Visitor.php 5 years ago VisitorNotFoundInDb.php 5 years ago VisitorRecognizer.php 4 years ago
TrackerCodeGenerator.php
311 lines
1 <?php
2 /**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 */
8
9 namespace Piwik\Tracker;
10
11 use Piwik\Common;
12 use Piwik\DbHelper;
13 use Piwik\Piwik;
14 use Piwik\Plugin\Manager;
15 use Piwik\Plugins\CustomVariables\CustomVariables;
16 use Piwik\Plugins\SitesManager\API as APISitesManager;
17 use Piwik\SettingsPiwik;
18 use Piwik\View;
19
20 /**
21 * Generates the Javascript code to be inserted on every page of the website to track.
22 */
23 class TrackerCodeGenerator
24 {
25 /**
26 * whether matomo.js|php should be forced over piwik.js|php
27 * @var bool
28 */
29 private $shouldForceMatomoEndpoint = false;
30
31 public function forceMatomoEndpoint()
32 {
33 $this->shouldForceMatomoEndpoint = true;
34 }
35
36 /**
37 * @param int $idSite
38 * @param string $piwikUrl http://path/to/piwik/site/
39 * @param bool $mergeSubdomains
40 * @param bool $groupPageTitlesByDomain
41 * @param bool $mergeAliasUrls
42 * @param array $visitorCustomVariables
43 * @param array $pageCustomVariables
44 * @param string $customCampaignNameQueryParam
45 * @param string $customCampaignKeywordParam
46 * @param bool $doNotTrack
47 * @param bool $disableCookies
48 * @param bool $trackNoScript
49 * @param bool $crossDomain
50 * @param bool $excludedQueryParams
51 * @return string Javascript code.
52 */
53 public function generate(
54 $idSite,
55 $piwikUrl,
56 $mergeSubdomains = false,
57 $groupPageTitlesByDomain = false,
58 $mergeAliasUrls = false,
59 $visitorCustomVariables = null,
60 $pageCustomVariables = null,
61 $customCampaignNameQueryParam = null,
62 $customCampaignKeywordParam = null,
63 $doNotTrack = false,
64 $disableCookies = false,
65 $trackNoScript = false,
66 $crossDomain = false,
67 $excludedQueryParams = false
68 ) {
69 // changes made to this code should be mirrored in plugins/CoreAdminHome/javascripts/jsTrackingGenerator.js var generateJsCode
70
71 if (substr($piwikUrl, 0, 4) !== 'http') {
72 $piwikUrl = 'http://' . $piwikUrl;
73 }
74 preg_match('~^(http|https)://(.*)$~D', $piwikUrl, $matches);
75 $piwikUrl = rtrim(@$matches[2], "/");
76
77 // Build optional parameters to be added to text
78 $options = '';
79 $optionsBeforeTrackerUrl = '';
80 if ($groupPageTitlesByDomain) {
81 $options .= ' _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);' . "\n";
82 }
83 if ($crossDomain) {
84 // When enabling cross domain, we also need to call `setDomains`
85 $mergeAliasUrls = true;
86 }
87 if ($mergeSubdomains || $mergeAliasUrls) {
88 $options .= $this->getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls);
89 }
90
91 if ($crossDomain) {
92 $options .= ' _paq.push(["enableCrossDomainLinking"]);' . "\n";
93 }
94
95 if (Manager::getInstance()->isPluginActivated('CustomVariables')) {
96 $maxCustomVars = CustomVariables::getNumUsableCustomVariables();
97
98 if ($visitorCustomVariables && count($visitorCustomVariables) > 0) {
99 $options .= ' // you can set up to ' . $maxCustomVars . ' custom variables for each visitor' . "\n";
100 $index = 1;
101 foreach ($visitorCustomVariables as $visitorCustomVariable) {
102 if (empty($visitorCustomVariable)) {
103 continue;
104 }
105
106 $options .= sprintf(
107 ' _paq.push(["setCustomVariable", %d, %s, %s, "visit"]);%s',
108 $index++,
109 json_encode($visitorCustomVariable[0]),
110 json_encode($visitorCustomVariable[1]),
111 "\n"
112 );
113 }
114 }
115 if ($pageCustomVariables && count($pageCustomVariables) > 0) {
116 $options .= ' // you can set up to ' . $maxCustomVars . ' custom variables for each action (page view, download, click, site search)' . "\n";
117 $index = 1;
118 foreach ($pageCustomVariables as $pageCustomVariable) {
119 if (empty($pageCustomVariable)) {
120 continue;
121 }
122 $options .= sprintf(
123 ' _paq.push(["setCustomVariable", %d, %s, %s, "page"]);%s',
124 $index++,
125 json_encode($pageCustomVariable[0]),
126 json_encode($pageCustomVariable[1]),
127 "\n"
128 );
129 }
130 }
131 }
132
133 if ($customCampaignNameQueryParam) {
134 $options .= ' _paq.push(["setCampaignNameKey", '
135 . json_encode($customCampaignNameQueryParam) . ']);' . "\n";
136 }
137 if ($customCampaignKeywordParam) {
138 $options .= ' _paq.push(["setCampaignKeywordKey", '
139 . json_encode($customCampaignKeywordParam) . ']);' . "\n";
140 }
141 if ($doNotTrack) {
142 $options .= ' _paq.push(["setDoNotTrack", true]);' . "\n";
143 }
144
145 // Add any excluded query parameters to the tracker options
146 if ($excludedQueryParams) {
147
148 if (!is_array($excludedQueryParams)) {
149 $excludedQueryParams = explode(',',$excludedQueryParams);
150 }
151 $options .= ' _paq.push(["setExcludedQueryParams", '.json_encode($excludedQueryParams).']);'."\n";
152 }
153
154 if ($disableCookies) {
155 $options .= ' _paq.push(["disableCookies"]);' . "\n";
156 }
157
158 $codeImpl = array(
159 'idSite' => $idSite,
160 // TODO why sanitizeInputValue() and not json_encode?
161 'piwikUrl' => Common::sanitizeInputValue($piwikUrl),
162 'options' => $options,
163 'optionsBeforeTrackerUrl' => $optionsBeforeTrackerUrl,
164 'protocol' => '//',
165 'loadAsync' => true,
166 'trackNoScript' => $trackNoScript,
167 'matomoJsFilename' => $this->getJsTrackerEndpoint(),
168 'matomoPhpFilename' => $this->getPhpTrackerEndpoint(),
169 );
170
171 if (SettingsPiwik::isHttpsForced()) {
172 $codeImpl['protocol'] = 'https://';
173 }
174
175 $parameters = compact('mergeSubdomains', 'groupPageTitlesByDomain', 'mergeAliasUrls', 'visitorCustomVariables',
176 'pageCustomVariables', 'customCampaignNameQueryParam', 'customCampaignKeywordParam',
177 'doNotTrack');
178
179 /**
180 * Triggered when generating JavaScript tracking code server side. Plugins can use
181 * this event to customise the JavaScript tracking code that is displayed to the
182 * user.
183 *
184 * @param array &$codeImpl An array containing snippets of code that the event handler
185 * can modify. Will contain the following elements:
186 *
187 * - **idSite**: The ID of the site being tracked.
188 * - **piwikUrl**: The tracker URL to use.
189 * - **options**: A string of JavaScript code that customises
190 * the JavaScript tracker.
191 * - **optionsBeforeTrackerUrl**: A string of Javascript code that customises
192 * the JavaScript tracker inside of anonymous function before
193 * adding setTrackerUrl into paq.
194 * - **protocol**: Piwik url protocol.
195 * - **loadAsync**: boolean whether piwik.js should be loaded synchronous or asynchronous
196 *
197 * The **httpsPiwikUrl** element can be set if the HTTPS
198 * domain is different from the normal domain.
199 * @param array $parameters The parameters supplied to `TrackerCodeGenerator::generate()`.
200 */
201 Piwik::postEvent('Tracker.getJavascriptCode', array(&$codeImpl, $parameters));
202
203 $setTrackerUrl = 'var u="' . $codeImpl['protocol'] . '{$piwikUrl}/";';
204
205 if (!empty($codeImpl['httpsPiwikUrl'])) {
206 $setTrackerUrl = 'var u=((document.location.protocol === "https:") ? "https://{$httpsPiwikUrl}/" : "http://{$piwikUrl}/");';
207 $codeImpl['httpsPiwikUrl'] = rtrim($codeImpl['httpsPiwikUrl'], "/");
208 }
209 $codeImpl = array('setTrackerUrl' => htmlentities($setTrackerUrl, ENT_COMPAT | ENT_HTML401, 'UTF-8')) + $codeImpl;
210
211 $view = new View('@Morpheus/javascriptCode');
212 $view->disableCacheBuster();
213 $view->loadAsync = $codeImpl['loadAsync'];
214 $view->trackNoScript = $codeImpl['trackNoScript'];
215 $jsCode = $view->render();
216 $jsCode = htmlentities($jsCode, ENT_COMPAT | ENT_HTML401, 'UTF-8');
217
218 foreach ($codeImpl as $keyToReplace => $replaceWith) {
219 $jsCode = str_replace('{$' . $keyToReplace . '}', $replaceWith, $jsCode);
220 }
221
222 return $jsCode;
223 }
224
225 public function getJsTrackerEndpoint()
226 {
227 $name = 'matomo.js';
228 if ($this->shouldPreferPiwikEndpoint()) {
229 $name = 'piwik.js';
230 }
231 return $name;
232 }
233
234 public function getPhpTrackerEndpoint()
235 {
236 $name = 'matomo.php';
237 if ($this->shouldPreferPiwikEndpoint()) {
238 $name = 'piwik.php';
239 }
240 return $name;
241 }
242
243 public function shouldPreferPiwikEndpoint()
244 {
245 if ($this->shouldForceMatomoEndpoint) {
246 return false;
247 }
248
249 // only since 3.7.0 we use the default matomo.js|php... for all other installs we need to keep BC
250 return DbHelper::wasMatomoInstalledBeforeVersion('3.7.0-b1');
251 }
252
253 private function getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls)
254 {
255 try {
256 $websiteUrls = APISitesManager::getInstance()->getSiteUrlsFromId($idSite);
257 } catch (\Exception $e) {
258 return '';
259 }
260 // We need to parse_url to isolate hosts
261 $websiteHosts = array();
262 $firstHost = null;
263 foreach ($websiteUrls as $site_url) {
264 if (empty($site_url)) {
265 continue;
266 }
267
268 $referrerParsed = parse_url($site_url);
269
270 if (!isset($firstHost) && isset($referrerParsed['host'])) {
271 $firstHost = $referrerParsed['host'];
272 }
273
274 if (isset($referrerParsed['host'])) {
275 $url = $referrerParsed['host'];
276 } else {
277 $url = '';
278 }
279 if (!empty($referrerParsed['path'])) {
280 $url .= $referrerParsed['path'];
281 }
282
283 if (!empty($url)) {
284 $websiteHosts[] = $url;
285 }
286 }
287 $options = '';
288 if ($mergeSubdomains && !empty($firstHost)) {
289 $options .= ' _paq.push(["setCookieDomain", "*.' . $firstHost . '"]);' . "\n";
290 }
291 if ($mergeAliasUrls && !empty($websiteHosts)) {
292 $urls = '["*.' . implode('","*.', $websiteHosts) . '"]';
293 $options .= ' _paq.push(["setDomains", ' . $urls . ']);' . "\n";
294 }
295 return $options;
296 }
297
298 /**
299 * When including the JS tracking code in a mailto link, we need to strip the surrounding HTML tags off. This
300 * ensures consistent behaviour between mail clients that render the mailto body as plain text (as in the
301 * spec), and those which try to render it as HTML and therefore hide the tags.
302 * @param string $jsTrackingCode JS tracking code as returned from the generate() function.
303 * @return string
304 */
305 public static function stripTags($jsTrackingCode)
306 {
307 // Strip off open and close <script> tag and comments so that JS will be displayed in ALL mail clients
308 return trim(strip_tags(html_entity_decode($jsTrackingCode)));
309 }
310 }
311