Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TrackerCodeGenerator.php « Tracker « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6bfba7894df1b178d7cf37ab3b0d3167112627e4 (plain)
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Tracker;

use Piwik\Common;
use Piwik\DbHelper;
use Piwik\Piwik;
use Piwik\Plugin\Manager;
use Piwik\Plugins\CustomVariables\CustomVariables;
use Piwik\Plugins\SitesManager\API as APISitesManager;
use Piwik\SettingsPiwik;
use Piwik\View;

/**
 * Generates the Javascript code to be inserted on every page of the website to track.
 */
class TrackerCodeGenerator
{
    /**
     * whether matomo.js|php should be forced over piwik.js|php
     * @var bool
     */
    private $shouldForceMatomoEndpoint = false;

    public function forceMatomoEndpoint()
    {
        $this->shouldForceMatomoEndpoint = true;
    }

    /**
     * @param int $idSite
     * @param string $piwikUrl http://path/to/piwik/site/
     * @param bool $mergeSubdomains
     * @param bool $groupPageTitlesByDomain
     * @param bool $mergeAliasUrls
     * @param array $visitorCustomVariables
     * @param array $pageCustomVariables
     * @param string $customCampaignNameQueryParam
     * @param string $customCampaignKeywordParam
     * @param bool $doNotTrack
     * @param bool $disableCookies
     * @param bool $trackNoScript
     * @param bool $crossDomain
     * @param bool $excludedQueryParams
     * @return string Javascript code.
     */
    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
    ) {
        // changes made to this code should be mirrored in plugins/CoreAdminHome/javascripts/jsTrackingGenerator.js var generateJsCode

        if (substr($piwikUrl, 0, 4) !== 'http') {
            $piwikUrl = 'http://' . $piwikUrl;
        }
        preg_match('~^(http|https)://(.*)$~D', $piwikUrl, $matches);
        $piwikUrl = rtrim(@$matches[2], "/");

        // Build optional parameters to be added to text
        $options = '';
        $optionsBeforeTrackerUrl = '';
        if ($groupPageTitlesByDomain) {
            $options .= '  _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);' . "\n";
        }
        if ($crossDomain) {
            // When enabling cross domain, we also need to call `setDomains`
            $mergeAliasUrls = true;
        }
        if ($mergeSubdomains || $mergeAliasUrls) {
            $options .= $this->getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls);
        }

        if ($crossDomain) {
            $options .= '  _paq.push(["enableCrossDomainLinking"]);' . "\n";
        }

        if (Manager::getInstance()->isPluginActivated('CustomVariables')) {
            $maxCustomVars = CustomVariables::getNumUsableCustomVariables();

            if ($visitorCustomVariables && count($visitorCustomVariables) > 0) {
                $options .= '  // you can set up to ' . $maxCustomVars . ' custom variables for each visitor' . "\n";
                $index   = 1;
                foreach ($visitorCustomVariables as $visitorCustomVariable) {
                    if (empty($visitorCustomVariable)) {
                        continue;
                    }

                    $options .= sprintf(
                        '  _paq.push(["setCustomVariable", %d, %s, %s, "visit"]);%s',
                        $index++,
                        json_encode($visitorCustomVariable[0]),
                        json_encode($visitorCustomVariable[1]),
                        "\n"
                    );
                }
            }
            if ($pageCustomVariables && count($pageCustomVariables) > 0) {
                $options .= '  // you can set up to ' . $maxCustomVars . ' custom variables for each action (page view, download, click, site search)' . "\n";
                $index   = 1;
                foreach ($pageCustomVariables as $pageCustomVariable) {
                    if (empty($pageCustomVariable)) {
                        continue;
                    }
                    $options .= sprintf(
                        '  _paq.push(["setCustomVariable", %d, %s, %s, "page"]);%s',
                        $index++,
                        json_encode($pageCustomVariable[0]),
                        json_encode($pageCustomVariable[1]),
                        "\n"
                    );
                }
            }
        }

        if ($customCampaignNameQueryParam) {
            $options .= '  _paq.push(["setCampaignNameKey", '
                . json_encode($customCampaignNameQueryParam) . ']);' . "\n";
        }
        if ($customCampaignKeywordParam) {
            $options .= '  _paq.push(["setCampaignKeywordKey", '
                . json_encode($customCampaignKeywordParam) . ']);' . "\n";
        }
        if ($doNotTrack) {
            $options .= '  _paq.push(["setDoNotTrack", true]);' . "\n";
        }

        // Add any excluded query parameters to the tracker options
        if ($excludedQueryParams) {

            if (!is_array($excludedQueryParams)) {
                $excludedQueryParams = explode(',',$excludedQueryParams);
            }
            $options .= '  _paq.push(["setExcludedQueryParams", '.json_encode($excludedQueryParams).']);'."\n";
        }

        if ($disableCookies) {
            $options .= '  _paq.push(["disableCookies"]);' . "\n";
        }

        $codeImpl = array(
            'idSite'                  => $idSite,
            // TODO why sanitizeInputValue() and not json_encode?
            'piwikUrl'                => Common::sanitizeInputValue($piwikUrl),
            'options'                 => $options,
            'optionsBeforeTrackerUrl' => $optionsBeforeTrackerUrl,
            'protocol'                => '//',
            'loadAsync'               => true,
            'trackNoScript'           => $trackNoScript,
            'matomoJsFilename'        => $this->getJsTrackerEndpoint(),
            'matomoPhpFilename'       => $this->getPhpTrackerEndpoint(),
        );

        if (SettingsPiwik::isHttpsForced()) {
            $codeImpl['protocol'] = 'https://';
        }

        $parameters = compact('mergeSubdomains', 'groupPageTitlesByDomain', 'mergeAliasUrls', 'visitorCustomVariables',
            'pageCustomVariables', 'customCampaignNameQueryParam', 'customCampaignKeywordParam',
            'doNotTrack');

        /**
         * Triggered when generating JavaScript tracking code server side. Plugins can use
         * this event to customise the JavaScript tracking code that is displayed to the
         * user.
         *
         * @param array &$codeImpl An array containing snippets of code that the event handler
         *                         can modify. Will contain the following elements:
         *
         *                         - **idSite**: The ID of the site being tracked.
         *                         - **piwikUrl**: The tracker URL to use.
         *                         - **options**: A string of JavaScript code that customises
         *                                        the JavaScript tracker.
         *                         - **optionsBeforeTrackerUrl**: A string of Javascript code that customises
         *                                        the JavaScript tracker inside of anonymous function before
         *                                        adding setTrackerUrl into paq.
         *                         - **protocol**: Piwik url protocol.
         *                         - **loadAsync**: boolean whether piwik.js should be loaded synchronous or asynchronous
         *
         *                         The **httpsPiwikUrl** element can be set if the HTTPS
         *                         domain is different from the normal domain.
         * @param array $parameters The parameters supplied to `TrackerCodeGenerator::generate()`.
         */
        Piwik::postEvent('Tracker.getJavascriptCode', array(&$codeImpl, $parameters));

        $setTrackerUrl = 'var u="' . $codeImpl['protocol'] . '{$piwikUrl}/";';

        if (!empty($codeImpl['httpsPiwikUrl'])) {
            $setTrackerUrl = 'var u=((document.location.protocol === "https:") ? "https://{$httpsPiwikUrl}/" : "http://{$piwikUrl}/");';
            $codeImpl['httpsPiwikUrl'] = rtrim($codeImpl['httpsPiwikUrl'], "/");
        }
        $codeImpl = array('setTrackerUrl' => htmlentities($setTrackerUrl, ENT_COMPAT | ENT_HTML401, 'UTF-8')) + $codeImpl;

        $view = new View('@Morpheus/javascriptCode');
        $view->disableCacheBuster();
        $view->loadAsync = $codeImpl['loadAsync'];
        $view->trackNoScript = $codeImpl['trackNoScript'];
        $jsCode = $view->render();
        $jsCode = htmlentities($jsCode, ENT_COMPAT | ENT_HTML401, 'UTF-8');

        foreach ($codeImpl as $keyToReplace => $replaceWith) {
            $jsCode = str_replace('{$' . $keyToReplace . '}', $replaceWith, $jsCode);
        }

        return $jsCode;
    }

    public function getJsTrackerEndpoint()
    {
        $name = 'matomo.js';
        if ($this->shouldPreferPiwikEndpoint()) {
            $name = 'piwik.js';
        }
        return $name;
    }

    public function getPhpTrackerEndpoint()
    {
        $name = 'matomo.php';
        if ($this->shouldPreferPiwikEndpoint()) {
            $name = 'piwik.php';
        }
        return $name;
    }

    public function shouldPreferPiwikEndpoint()
    {
        if ($this->shouldForceMatomoEndpoint) {
            return false;
        }

        // only since 3.7.0 we use the default matomo.js|php... for all other installs we need to keep BC
        return DbHelper::wasMatomoInstalledBeforeVersion('3.7.0-b1');
    }

    private function getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls)
    {
        try {
            $websiteUrls = APISitesManager::getInstance()->getSiteUrlsFromId($idSite);
        } catch (\Exception $e) {
            return '';
        }
        // We need to parse_url to isolate hosts
        $websiteHosts = array();
        $firstHost = null;
        foreach ($websiteUrls as $site_url) {
            if (empty($site_url)) {
                continue;
            }
            
            $referrerParsed = parse_url($site_url);

            if (!isset($firstHost) && isset($referrerParsed['host'])) {
                $firstHost = $referrerParsed['host'];
            }

            if (isset($referrerParsed['host'])) {
                $url = $referrerParsed['host'];
            } else {
                $url = '';
            }
            if (!empty($referrerParsed['path'])) {
                $url .= $referrerParsed['path'];
            }
            
            if (!empty($url)) {
                $websiteHosts[] = $url;
            }
        }
        $options = '';
        if ($mergeSubdomains && !empty($firstHost)) {
            $options .= '  _paq.push(["setCookieDomain", "*.' . $firstHost . '"]);' . "\n";
        }
        if ($mergeAliasUrls && !empty($websiteHosts)) {
            $urls = '["*.' . implode('","*.', $websiteHosts) . '"]';
            $options .= '  _paq.push(["setDomains", ' . $urls . ']);' . "\n";
        }
        return $options;
    }

    /**
     * When including the JS tracking code in a mailto link, we need to strip the surrounding HTML tags off. This
     * ensures consistent behaviour between mail clients that render the mailto body as plain text (as in the
     * spec), and those which try to render it as HTML and therefore hide the tags.
     * @param string $jsTrackingCode JS tracking code as returned from the generate() function.
     * @return string
     */
    public static function stripTags($jsTrackingCode)
    {
        // Strip off open and close <script> tag and comments so that JS will be displayed in ALL mail clients
        return trim(strip_tags(html_entity_decode($jsTrackingCode)));
    }
}