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

Piwik_Overlay.js « javascripts « Overlay « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bccdd2aec508f477f5d09e503dcd4005cdccae32 (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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*!
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

var Piwik_Overlay = (function () {

    var DOMAIN_PARSE_REGEX = /^http(s)?:\/\/(www\.)?([^\/]*)/i;
    var ORIGIN_PARSE_REGEX = /^https?:\/\/[^\/]*/;
    var ALLOWED_API_REQUEST_WHITELIST = [
        'Overlay.getTranslations',
        'Overlay.getExcludedQueryParameters',
        'Overlay.getFollowingPages',
    ];

    var $body, $iframe, $sidebar, $main, $location, $loading, $errorNotLoading;
    var $rowEvolutionLink, $transitionsLink, $visitorLogLink;

    var idSite, period, date, segment;

    var iframeSrcBase;
    var iframeDomain = '';
    var iframeCurrentPage = '';
    var iframeCurrentPageNormalized = '';
    var iframeCurrentActionLabel = '';
    var updateComesFromInsideFrame = false;
    var iframeOrigin = '';

    /** Load the sidebar for a url */
    function loadSidebar(currentUrl) {
        showLoading();

        $location.html(' ').unbind('mouseenter').unbind('mouseleave');

        iframeCurrentPage = currentUrl;
        iframeDomain = currentUrl.match(DOMAIN_PARSE_REGEX)[3];

        var params = {
            module: 'Overlay',
            action: 'renderSidebar',
            currentUrl: currentUrl
        };

        if (segment) {
            params.segment = segment;
        }

        globalAjaxQueue.abort();
        var ajaxRequest = new ajaxHelper();
        ajaxRequest.addParams(params, 'get');
        ajaxRequest.setCallback(
            function (response) {
                hideLoading();

                var $response = $(response);

                var $responseLocation = $response.find('.overlayLocation');
                var $url = $responseLocation.find('span');
                iframeCurrentPageNormalized = $url.data('normalizedUrl');
                iframeCurrentActionLabel = $url.data('label');
                $url.html(piwikHelper.addBreakpointsToUrl($url.text()));
                $location.html($responseLocation.html()).show();
                $responseLocation.remove();

                var $locationSpan = $location.find('span');
                $locationSpan.html(piwikHelper.addBreakpointsToUrl($locationSpan.text()));
                if (iframeDomain) {
                    // use addBreakpointsToUrl because it also encoded html entities
                    $locationSpan.tooltip({
                        track: true,
                        items: '*',
                        tooltipClass: 'overlayTooltip',
                        content: '<strong>' + Piwik_Overlay_Translations.domain + ':</strong> ' +
                                  piwikHelper.addBreakpointsToUrl(iframeDomain),
                        show: false,
                        hide: false
                    });
                }

                $sidebar.empty().append($response).show();

                if (!$sidebar.find('.overlayNoData').length) {
                    $rowEvolutionLink.show();
                    $transitionsLink.show();
                    if ($('#segment').val() && piwik.visitorLogEnabled) {
                        $visitorLogLink.show();
                    }
                }

            }
        );
        ajaxRequest.setErrorCallback(function () {
            hideLoading();
            $errorNotLoading.show();
        });
        ajaxRequest.setFormat('html');
        ajaxRequest.send();
    }

    /** Adjust the dimensions of the iframe */
    function adjustDimensions() {
        $iframe.height($(window).height());
        $iframe.width($body.width() - $iframe.offset().left - 2); // -2 because of 2px border
    }

    /** Display the loading message and hide other containers */
    function showLoading() {
        $loading.show();

        $sidebar.hide();
        $location.hide();

        $rowEvolutionLink.hide();
        $transitionsLink.hide();
        $visitorLogLink.hide();

        $errorNotLoading.hide();
    }

    /** Hide the loading message */
    function hideLoading() {
        $loading.hide();
        $('#overlayDateRangeSelect').prop('disabled', false).material_select();
    }

    function getOverlaySegment(url) {
        var location = broadcast.getParamValue('segment', url);

        // angular will encode the value again since it is added as the fragment path, not the fragment query parameter,
        // so we have to decode it again after getParamValue
        location = decodeURIComponent(location);

        return location;
    }

    function getOverlayLocationFromHash(urlHash) {
        var location = broadcast.getParamValue('l', urlHash);

        // angular will encode the value again since it is added as the fragment path, not the fragment query parameter,
        // so we have to decode it again after getParamValue
        location = decodeURIComponent(location);

        return location;
    }

    function setIframeOrigin(location) {
        var m = location.match(ORIGIN_PARSE_REGEX);
        iframeOrigin = m ? m[0] : null;

        var foundValidSiteUrl = false;

        // unset iframe origin if it is not one of the site URLs
        var validSiteOrigins = Piwik_Overlay.siteUrls.map(function (url) {
            if (typeof url === 'string' && url !== "") {
                foundValidSiteUrl = true;
            }

            var siteUrlMatch = url.match(ORIGIN_PARSE_REGEX);
            if (!siteUrlMatch) {
                return null;
            }
            return siteUrlMatch[0].toLowerCase();
        });

        if (!foundValidSiteUrl) {
            $('#overlayErrorNoSiteUrls').show();
        }

        if (iframeOrigin && validSiteOrigins.indexOf(iframeOrigin.toLowerCase()) === -1) {
            try {
                console.log('Found invalid iframe origin in hash URL: ' + iframeOrigin);
            } catch (e) {
                // ignore
            }
            iframeOrigin = null;
        }
    }

    /** $.history callback for hash change */
    function hashChangeCallback(urlHash) {
        var location = getOverlayLocationFromHash(urlHash);
        location = Overlay_Helper.decodeFrameUrl(location);

        setIframeOrigin(location);

        if (location == iframeCurrentPageNormalized) {
            return;
        }

        if (!updateComesFromInsideFrame) {
            var iframeUrl = iframeSrcBase;
            if (location) {
                iframeUrl += '#' + location;
            }
            $iframe.attr('src', iframeUrl);
            showLoading();
        } else {
            loadSidebar(location);
        }

        updateComesFromInsideFrame = false;
    }

    function handleApiRequests() {
        window.addEventListener("message", function (event) {
            if (event.origin !== iframeOrigin || !iframeOrigin) {
                return;
            }

            if (typeof event.data !== 'string') {
                return; // some other message not intended for us
            }

            var strData = event.data.split(':', 3);
            if (strData[0] !== 'overlay.call') {
                return;
            }

            var requestId = strData[1];
            var url = decodeURIComponent(strData[2]);

            var params = broadcast.getValuesFromUrl(url);
            Object.keys(params).forEach(function (name) {
                params[name] = decodeURIComponent(params[name]);
            });
            params.module = 'API';
            params.action = 'index';

            if (ALLOWED_API_REQUEST_WHITELIST.indexOf(params.method) === -1) {
                sendResponse({
                    result: 'error',
                    message: "'" + params.method + "' method is not allowed.",
                });
                return;
            }

            angular.element(document).injector().invoke(['piwikApi', function (piwikApi) {
                piwikApi.fetch(params)
                    .then(function (response) {
                        sendResponse(response);
                    }).catch(function (err) {
                        sendResponse({
                            result: 'error',
                            message: err.message,
                        });
                    });
            }]);

            function sendResponse(data) {
                var message = 'overlay.response:' + requestId + ':' + encodeURIComponent(JSON.stringify(data));
                $iframe[0].contentWindow.postMessage(message, iframeOrigin);
            }
        }, false);
    }

    return {

        /** This method is called when Overlay loads  */
        init: function (iframeSrc, pIdSite, pPeriod, pDate, pSegment) {
            iframeSrcBase = iframeSrc;
            idSite = pIdSite;
            period = pPeriod;
            date = pDate;
            segment = pSegment;

            $body = $('body');
            $iframe = $('#overlayIframe');
            $sidebar = $('#overlaySidebar');
            $location = $('#overlayLocation');
            $main = $('#overlayMain');
            $loading = $('#overlayLoading');
            $errorNotLoading = $('#overlayErrorNotLoading');

            $rowEvolutionLink = $('#overlayRowEvolution');
            $transitionsLink = $('#overlayTransitions');
            $visitorLogLink = $('#overlaySegmentedVisitorLog');

            adjustDimensions();
            showLoading();

            // apply initial dimensions
            window.setTimeout(function () {
                adjustDimensions();
            }, 50);

            // handle window resize
            $(window).resize(function () {
                adjustDimensions();
            });

            angular.element(document).injector().invoke(function ($rootScope) {
                $rootScope.$on('$locationChangeSuccess', function () {
                    hashChangeCallback(broadcast.getHash());
                });

                hashChangeCallback(broadcast.getHash());
            });

            if (window.location.href.split('#').length == 1) {
                hashChangeCallback('');
            }

            handleApiRequests();

            // handle date selection
            var $select = $('select#overlayDateRangeSelect').change(function () {
                var parts = $(this).val().split(';');
                if (parts.length == 2) {
                    period = parts[0];
                    date = parts[1];
                    window.location.href = Overlay_Helper.getOverlayLink(idSite, period, date, segment, iframeCurrentPage);
                }
            });

            var optionMatchFound = false;
            $select.find('option').each(function () {
                if ($(this).val() == period + ';' + date) {
                    $(this).prop('selected', true);
                    optionMatchFound = true;
                }
            });

            if (optionMatchFound) {
                $select.material_select();
            } else {
                $select.prepend('<option selected="selected">');
            }

            // handle transitions link
            $transitionsLink.click(function () {
                var unescapedSegment = null;
                if (segment) {
                    unescapedSegment = unescape(segment);
                }
                if (window.DataTable_RowActions_Transitions) {
                    DataTable_RowActions_Transitions.launchForUrl(iframeCurrentPageNormalized, unescapedSegment);
                }
                return false;
            });

            // handle row evolution link
            $rowEvolutionLink.click(function () {
                if (window.DataTable_RowActions_RowEvolution) {
                    DataTable_RowActions_RowEvolution.launch('Actions.getPageUrls', iframeCurrentActionLabel);
                }
                return false;
            });

            // handle segmented visitor log link
            $visitorLogLink.click(function () {
                SegmentedVisitorLog.show('Actions.getPageUrls', $('#segment').val(), {});
                return false;
            });
        },

        /** This callback is used from within the iframe */
        setCurrentUrl: function (currentUrl) {
            showLoading();

            var locationParts = location.href.split('#');
            var currentLocation = '';
            if (locationParts.length > 1) {
                currentLocation = getOverlayLocationFromHash(locationParts[1]);
            }

            var newFrameLocation = Overlay_Helper.encodeFrameUrl(currentUrl);

            if (newFrameLocation != currentLocation) {
                updateComesFromInsideFrame = true;

                // available in global scope
                var currentHashStr = broadcast.getHash();

                if (currentHashStr.charAt(0) == '?') {
                    currentHashStr = currentHashStr.substr(1);
                }

                currentHashStr = broadcast.updateParamValue('l=' + newFrameLocation, currentHashStr);

                var newLocation = window.location.href.split('#')[0] + '#?' + currentHashStr;
                // window.location.replace changes the current url without pushing it on the browser's history stack
                window.location.replace(newLocation);
            } else {
                // happens when the url is changed by hand or when the l parameter is there on page load
                setIframeOrigin(currentUrl);
                loadSidebar(currentUrl);
            }
        }

    };

})();