PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.13.3
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.13.3
5.12.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 3 years ago Handler 5 years ago TableLogAction 5 years ago Visit 5 years ago Action.php 4 years ago ActionPageview.php 5 years ago Cache.php 4 years ago Db.php 4 years ago Failures.php 4 years ago FingerprintSalt.php 4 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 3 years ago Request.php 3 years ago RequestProcessor.php 5 years ago RequestSet.php 4 years ago Response.php 4 years ago ScheduledTasksRunner.php 5 years ago Settings.php 3 years ago TableLogAction.php 5 years ago TrackerCodeGenerator.php 3 years ago TrackerConfig.php 3 years ago Visit.php 4 years ago VisitExcluded.php 3 years ago VisitInterface.php 5 years ago Visitor.php 5 years ago VisitorNotFoundInDb.php 5 years ago VisitorRecognizer.php 4 years ago
TrackerCodeGenerator.php
321 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 * @param array $excludedReferrers
52 * @return string Javascript code.
53 */
54 public function generate(
55 $idSite,
56 $piwikUrl,
57 $mergeSubdomains = false,
58 $groupPageTitlesByDomain = false,
59 $mergeAliasUrls = false,
60 $visitorCustomVariables = null,
61 $pageCustomVariables = null,
62 $customCampaignNameQueryParam = null,
63 $customCampaignKeywordParam = null,
64 $doNotTrack = false,
65 $disableCookies = false,
66 $trackNoScript = false,
67 $crossDomain = false,
68 $excludedQueryParams = false,
69 $excludedReferrers = []
70 ) {
71 // changes made to this code should be mirrored in plugins/CoreAdminHome/javascripts/jsTrackingGenerator.js var generateJsCode
72
73 if (substr($piwikUrl, 0, 4) !== 'http') {
74 $piwikUrl = 'http://' . $piwikUrl;
75 }
76 preg_match('~^(http|https)://(.*)$~D', $piwikUrl, $matches);
77 $piwikUrl = rtrim(@$matches[2], "/");
78
79 // Build optional parameters to be added to text
80 $options = '';
81 $optionsBeforeTrackerUrl = '';
82 if ($groupPageTitlesByDomain) {
83 $options .= ' _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);' . "\n";
84 }
85 if ($crossDomain) {
86 // When enabling cross domain, we also need to call `setDomains`
87 $mergeAliasUrls = true;
88 }
89 if ($mergeSubdomains || $mergeAliasUrls) {
90 $options .= $this->getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls);
91 }
92
93 if ($crossDomain) {
94 $options .= ' _paq.push(["enableCrossDomainLinking"]);' . "\n";
95 }
96
97 if (Manager::getInstance()->isPluginActivated('CustomVariables')) {
98 $maxCustomVars = CustomVariables::getNumUsableCustomVariables();
99
100 if ($visitorCustomVariables && count($visitorCustomVariables) > 0) {
101 $options .= ' // you can set up to ' . $maxCustomVars . ' custom variables for each visitor' . "\n";
102 $index = 1;
103 foreach ($visitorCustomVariables as $visitorCustomVariable) {
104 if (empty($visitorCustomVariable)) {
105 continue;
106 }
107
108 $options .= sprintf(
109 ' _paq.push(["setCustomVariable", %d, %s, %s, "visit"]);%s',
110 $index++,
111 json_encode($visitorCustomVariable[0]),
112 json_encode($visitorCustomVariable[1]),
113 "\n"
114 );
115 }
116 }
117 if ($pageCustomVariables && count($pageCustomVariables) > 0) {
118 $options .= ' // you can set up to ' . $maxCustomVars . ' custom variables for each action (page view, download, click, site search)' . "\n";
119 $index = 1;
120 foreach ($pageCustomVariables as $pageCustomVariable) {
121 if (empty($pageCustomVariable)) {
122 continue;
123 }
124 $options .= sprintf(
125 ' _paq.push(["setCustomVariable", %d, %s, %s, "page"]);%s',
126 $index++,
127 json_encode($pageCustomVariable[0]),
128 json_encode($pageCustomVariable[1]),
129 "\n"
130 );
131 }
132 }
133 }
134
135 if ($customCampaignNameQueryParam) {
136 $options .= ' _paq.push(["setCampaignNameKey", '
137 . json_encode($customCampaignNameQueryParam) . ']);' . "\n";
138 }
139 if ($customCampaignKeywordParam) {
140 $options .= ' _paq.push(["setCampaignKeywordKey", '
141 . json_encode($customCampaignKeywordParam) . ']);' . "\n";
142 }
143 if ($doNotTrack) {
144 $options .= ' _paq.push(["setDoNotTrack", true]);' . "\n";
145 }
146
147 // Add any excluded query parameters to the tracker options
148 if ($excludedQueryParams) {
149 if (!is_array($excludedQueryParams)) {
150 $excludedQueryParams = explode(',', $excludedQueryParams);
151 }
152 $options .= ' _paq.push(["setExcludedQueryParams", ' . json_encode($excludedQueryParams) . ']);' . "\n";
153 }
154
155 // Add any ignored referrer to the tracker options
156 if ($excludedReferrers) {
157 if (!is_array($excludedReferrers)) {
158 $excludedReferrers = explode(',', $excludedReferrers);
159 }
160
161 $options .= ' _paq.push(["setExcludedReferrers", ' . json_encode($excludedReferrers) . ']);' . "\n";
162 }
163
164 if ($disableCookies) {
165 $options .= ' _paq.push(["disableCookies"]);' . "\n";
166 }
167
168 $codeImpl = array(
169 'idSite' => $idSite,
170 // TODO why sanitizeInputValue() and not json_encode?
171 'piwikUrl' => Common::sanitizeInputValue($piwikUrl),
172 'options' => $options,
173 'optionsBeforeTrackerUrl' => $optionsBeforeTrackerUrl,
174 'protocol' => '//',
175 'loadAsync' => true,
176 'trackNoScript' => $trackNoScript,
177 'matomoJsFilename' => $this->getJsTrackerEndpoint(),
178 'matomoPhpFilename' => $this->getPhpTrackerEndpoint(),
179 );
180
181 if (SettingsPiwik::isHttpsForced()) {
182 $codeImpl['protocol'] = 'https://';
183 }
184
185 $parameters = compact('mergeSubdomains', 'groupPageTitlesByDomain', 'mergeAliasUrls', 'visitorCustomVariables',
186 'pageCustomVariables', 'customCampaignNameQueryParam', 'customCampaignKeywordParam',
187 'doNotTrack');
188
189 /**
190 * Triggered when generating JavaScript tracking code server side. Plugins can use
191 * this event to customise the JavaScript tracking code that is displayed to the
192 * user.
193 *
194 * @param array &$codeImpl An array containing snippets of code that the event handler
195 * can modify. Will contain the following elements:
196 *
197 * - **idSite**: The ID of the site being tracked.
198 * - **piwikUrl**: The tracker URL to use.
199 * - **options**: A string of JavaScript code that customises
200 * the JavaScript tracker.
201 * - **optionsBeforeTrackerUrl**: A string of Javascript code that customises
202 * the JavaScript tracker inside of anonymous function before
203 * adding setTrackerUrl into paq.
204 * - **protocol**: Piwik url protocol.
205 * - **loadAsync**: boolean whether piwik.js should be loaded synchronous or asynchronous
206 *
207 * The **httpsPiwikUrl** element can be set if the HTTPS
208 * domain is different from the normal domain.
209 * @param array $parameters The parameters supplied to `TrackerCodeGenerator::generate()`.
210 */
211 Piwik::postEvent('Tracker.getJavascriptCode', array(&$codeImpl, $parameters));
212
213 $setTrackerUrl = 'var u="' . $codeImpl['protocol'] . '{$piwikUrl}/";';
214
215 if (!empty($codeImpl['httpsPiwikUrl'])) {
216 $setTrackerUrl = 'var u=((document.location.protocol === "https:") ? "https://{$httpsPiwikUrl}/" : "http://{$piwikUrl}/");';
217 $codeImpl['httpsPiwikUrl'] = rtrim($codeImpl['httpsPiwikUrl'], "/");
218 }
219 $codeImpl = array('setTrackerUrl' => htmlentities($setTrackerUrl, ENT_COMPAT | ENT_HTML401, 'UTF-8')) + $codeImpl;
220
221 $view = new View('@Morpheus/javascriptCode');
222 $view->disableCacheBuster();
223 $view->loadAsync = $codeImpl['loadAsync'];
224 $view->trackNoScript = $codeImpl['trackNoScript'];
225 $jsCode = $view->render();
226 $jsCode = htmlentities($jsCode, ENT_COMPAT | ENT_HTML401, 'UTF-8');
227
228 foreach ($codeImpl as $keyToReplace => $replaceWith) {
229 $jsCode = str_replace('{$' . $keyToReplace . '}', $replaceWith, $jsCode);
230 }
231
232 return $jsCode;
233 }
234
235 public function getJsTrackerEndpoint()
236 {
237 $name = 'matomo.js';
238 if ($this->shouldPreferPiwikEndpoint()) {
239 $name = 'piwik.js';
240 }
241 return $name;
242 }
243
244 public function getPhpTrackerEndpoint()
245 {
246 $name = 'matomo.php';
247 if ($this->shouldPreferPiwikEndpoint()) {
248 $name = 'piwik.php';
249 }
250 return $name;
251 }
252
253 public function shouldPreferPiwikEndpoint()
254 {
255 if ($this->shouldForceMatomoEndpoint) {
256 return false;
257 }
258
259 // only since 3.7.0 we use the default matomo.js|php... for all other installs we need to keep BC
260 return DbHelper::wasMatomoInstalledBeforeVersion('3.7.0-b1');
261 }
262
263 private function getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls)
264 {
265 try {
266 $websiteUrls = APISitesManager::getInstance()->getSiteUrlsFromId($idSite);
267 } catch (\Exception $e) {
268 return '';
269 }
270 // We need to parse_url to isolate hosts
271 $websiteHosts = array();
272 $firstHost = null;
273 foreach ($websiteUrls as $site_url) {
274 if (empty($site_url)) {
275 continue;
276 }
277
278 $referrerParsed = parse_url($site_url);
279
280 if (!isset($firstHost) && isset($referrerParsed['host'])) {
281 $firstHost = $referrerParsed['host'];
282 }
283
284 if (isset($referrerParsed['host'])) {
285 $url = $referrerParsed['host'];
286 } else {
287 $url = '';
288 }
289 if (!empty($referrerParsed['path'])) {
290 $url .= $referrerParsed['path'];
291 }
292
293 if (!empty($url)) {
294 $websiteHosts[] = $url;
295 }
296 }
297 $options = '';
298 if ($mergeSubdomains && !empty($firstHost)) {
299 $options .= ' _paq.push(["setCookieDomain", "*.' . $firstHost . '"]);' . "\n";
300 }
301 if ($mergeAliasUrls && !empty($websiteHosts)) {
302 $urls = '["*.' . implode('","*.', $websiteHosts) . '"]';
303 $options .= ' _paq.push(["setDomains", ' . $urls . ']);' . "\n";
304 }
305 return $options;
306 }
307
308 /**
309 * When including the JS tracking code in a mailto link, we need to strip the surrounding HTML tags off. This
310 * ensures consistent behaviour between mail clients that render the mailto body as plain text (as in the
311 * spec), and those which try to render it as HTML and therefore hide the tags.
312 * @param string $jsTrackingCode JS tracking code as returned from the generate() function.
313 * @return string
314 */
315 public static function stripTags($jsTrackingCode)
316 {
317 // Strip off open and close <script> tag and comments so that JS will be displayed in ALL mail clients
318 return trim(strip_tags(html_entity_decode($jsTrackingCode)));
319 }
320 }
321