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