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