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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
|
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
/**
* global ajax queue
*
* @type {Array} array holding XhrRequests with automatic cleanup
*/
var globalAjaxQueue = [];
globalAjaxQueue.active = 0;
/**
* Removes all finished requests from the queue.
*
* @return {void}
*/
globalAjaxQueue.clean = function () {
for (var i = this.length; i--;) {
if (!this[i] || this[i].readyState == 4) {
this.splice(i, 1);
}
}
};
/**
* Extend Array.push with automatic cleanup for finished requests
*
* @return {Object}
*/
globalAjaxQueue.push = function () {
this.active += arguments.length;
// cleanup ajax queue
this.clean();
// call original array push
return Array.prototype.push.apply(this, arguments);
};
/**
* Extend with abort function to abort all queued requests
*
* @return {void}
*/
globalAjaxQueue.abort = function () {
// abort all queued requests
for (var i = this.length; i--;) {
this[i] && this[i].abort && this[i].abort(); // abort if possible
}
// remove all elements from array
this.splice(0, this.length);
this.active = 0;
};
/**
* Global ajax helper to handle requests within piwik
*
* @type {Object}
* @constructor
*/
function ajaxHelper() {
/**
* Format of response
* @type {String}
*/
this.format = 'json';
/**
* Should ajax request be asynchronous
* @type {Boolean}
*/
this.async = true;
/**
* A timeout for the request which will override any global timeout
* @type {Boolean}
*/
this.timeout = null;
/**
* Callback function to be executed on success
*/
this.callback = function () {};
/**
* Use this.callback if an error is returned
* @type {Boolean}
*/
this.useRegularCallbackInCaseOfError = false;
/**
* Callback function to be executed on error
*/
this.errorCallback = this.defaultErrorCallback;
this.withToken = false;
/**
* Callback function to be executed on complete (after error or success)
*/
this.completeCallback = function () {};
/**
* Params to be passed as GET params
* @type {Object}
* @see ajaxHelper._mixinDefaultGetParams
*/
this.getParams = {};
/**
* Base URL used in the AJAX request. Can be set by setUrl.
*
* It is set to '?' rather than 'index.php?' to increase chances that it works
* including for users who have an automatic 301 redirection from index.php? to ?
* POST values are missing when there is such 301 redirection. So by by-passing
* this 301 redirection, we avoid this issue.
*
* @type {String}
* @see ajaxHelper.setUrl
*/
this.getUrl = '?';
/**
* Params to be passed as GET params
* @type {Object}
* @see ajaxHelper._mixinDefaultPostParams
*/
this.postParams = {};
/**
* Element to be displayed while loading
* @type {String}
*/
this.loadingElement = null;
/**
* Element to be displayed on error
* @type {String}
*/
this.errorElement = '#ajaxError';
/**
* Handle for current request
* @type {XMLHttpRequest}
*/
this.requestHandle = null;
/**
* Adds params to the request.
* If params are given more then once, the latest given value is used for the request
*
* @param {object} params
* @param {string} type type of given parameters (POST or GET)
* @return {void}
*/
this.addParams = function (params, type) {
if (typeof params == 'string') {
params = broadcast.getValuesFromUrl(params);
}
for (var key in params) {
if(type.toLowerCase() == 'get') {
this.getParams[key] = params[key];
} else if(type.toLowerCase() == 'post') {
this.postParams[key] = params[key];
}
}
};
this.withTokenInUrl = function () {
this.withToken = true;
};
/**
* Sets the base URL to use in the AJAX request.
*
* @param {string} url
*/
this.setUrl = function (url) {
this.addParams(broadcast.getValuesFromUrl(url), 'GET');
};
/**
* Gets this helper instance ready to send a bulk request. Each argument to this
* function is a single request to use.
*/
this.setBulkRequests = function () {
var urls = [];
for (var i = 0; i != arguments.length; ++i) {
urls.push($.param(arguments[i]));
}
this.addParams({
module: 'API',
method: 'API.getBulkRequest',
urls: urls,
format: 'json'
}, 'post');
};
/**
* Set a timeout (in milliseconds) for the request. This will override any global timeout.
*
* @param {integer} timeout Timeout in milliseconds
* @return {void}
*/
this.setTimeout = function (timeout) {
this.timeout = timeout;
};
/**
* Sets the callback called after the request finishes
*
* @param {function} callback Callback function
* @return {void}
*/
this.setCallback = function (callback) {
this.callback = callback;
};
/**
* Set that the callback passed to setCallback() should be used if an application error (i.e. an
* Exception in PHP) is returned.
*/
this.useCallbackInCaseOfError = function () {
this.useRegularCallbackInCaseOfError = true;
};
/**
* Set callback to redirect on success handler
* &update=1(+x) will be appended to the current url
*
* @param {object} [params] to modify in redirect url
* @return {void}
*/
this.redirectOnSuccess = function (params) {
this.setCallback(function() {
piwikHelper.redirect(params);
});
};
/**
* Sets the callback called in case of an error within the request
*
* @param {function} callback Callback function
* @return {void}
*/
this.setErrorCallback = function (callback) {
this.errorCallback = callback;
};
/**
* Sets the complete callback which is called after an error or success callback.
*
* @param {function} callback Callback function
* @return {void}
*/
this.setCompleteCallback = function (callback) {
this.completeCallback = callback;
};
/**
* error callback to use by default
*
* @param deferred
* @param status
*/
this.defaultErrorCallback = function(deferred, status)
{
// do not display error message if request was aborted
if(status == 'abort') {
return;
}
$('#loadingError').show();
setTimeout( function(){
$('#loadingError').fadeOut('slow');
}, 2000);
};
/**
* Sets the response format for the request
*
* @param {string} format response format (e.g. json, html, ...)
* @return {void}
*/
this.setFormat = function (format) {
this.format = format;
};
/**
* Set the div element to show while request is loading
*
* @param {String} [element] selector for the loading element
*/
this.setLoadingElement = function (element) {
if (!element) {
element = '#ajaxLoadingDiv';
}
this.loadingElement = element;
};
/**
* Set the div element to show on error
*
* @param {String} element selector for the error element
*/
this.setErrorElement = function (element) {
if (!element) {
return;
}
this.errorElement = element;
};
/**
* Send the request
* @param {Boolean} [sync] indicates if the request should be synchronous (defaults to false)
* @return {void}
*/
this.send = function (sync) {
if (sync === true) {
this.async = false;
}
if ($(this.errorElement).length) {
$(this.errorElement).hide();
}
if (this.loadingElement) {
$(this.loadingElement).fadeIn();
}
this.requestHandle = this._buildAjaxCall();
globalAjaxQueue.push(this.requestHandle);
};
/**
* Aborts the current request if it is (still) running
* @return {void}
*/
this.abort = function () {
if (this.requestHandle && typeof this.requestHandle.abort == 'function') {
this.requestHandle.abort();
this.requestHandle = null;
}
};
/**
* Builds and sends the ajax requests
* @return {XMLHttpRequest}
* @private
*/
this._buildAjaxCall = function () {
var that = this;
var parameters = this._mixinDefaultGetParams(this.getParams);
var url = this.getUrl;
if (url[url.length - 1] != '?') {
url += '&';
}
// we took care of encoding &segment properly already, so we don't use $.param for it ($.param URL encodes the values)
if(parameters['segment']) {
url += 'segment=' + parameters['segment'] + '&';
delete parameters['segment'];
}
if(parameters['date']) {
url += 'date=' + decodeURIComponent(parameters['date']) + '&';
delete parameters['date'];
}
url += $.param(parameters);
var ajaxCall = {
type: 'POST',
async: this.async !== false,
url: url,
dataType: this.format || 'json',
complete: this.completeCallback,
error: function () {
--globalAjaxQueue.active;
if (that.errorCallback) {
that.errorCallback.apply(this, arguments);
}
},
success: function (response, status, request) {
if (that.loadingElement) {
$(that.loadingElement).hide();
}
if (response && response.result == 'error' && !that.useRegularCallbackInCaseOfError) {
var placeAt = null;
var type = 'toast';
if ($(that.errorElement).length && response.message) {
$(that.errorElement).show();
placeAt = that.errorElement;
type = null;
}
if (response.message) {
var UI = require('piwik/UI');
var notification = new UI.Notification();
notification.show(response.message, {
placeat: placeAt,
context: 'error',
type: type,
id: 'ajaxHelper'
});
notification.scrollToNotification();
}
} else {
that.callback(response, status, request);
}
--globalAjaxQueue.active;
var piwik = window.piwik;
if (piwik
&& piwik.ajaxRequestFinished
) {
piwik.ajaxRequestFinished();
}
},
data: this._mixinDefaultPostParams(this.postParams)
};
if (this.timeout !== null) {
ajaxCall.timeout = this.timeout;
}
return $.ajax(ajaxCall);
};
this._isRequestToApiMethod = function () {
return (this.getParams && this.getParams['module'] === 'API' && this.getParams['method']) ||
(this.postParams && this.postParams['module'] === 'API' && this.postParams['method']);
};
this._getDefaultPostParams = function () {
if (this.withToken || this._isRequestToApiMethod()) {
return {
token_auth: piwik.token_auth
};
}
return {};
};
/**
* Mixin the default parameters to send as POST
*
* @param {object} params parameter object
* @return {object}
* @private
*/
this._mixinDefaultPostParams = function (params) {
var defaultParams = this._getDefaultPostParams();
for (var index in defaultParams) {
if (!params[index]) {
params[index] = defaultParams[index];
}
}
return params;
};
/**
* Mixin the default parameters to send as GET
*
* @param {object} params parameter object
* @return {object}
* @private
*/
this._mixinDefaultGetParams = function (params) {
var defaultParams = {
idSite: piwik.idSite || broadcast.getValueFromUrl('idSite'),
period: piwik.period || broadcast.getValueFromUrl('period'),
segment: broadcast.getValueFromHash('segment', window.location.href.split('#')[1])
};
// never append token_auth to url
if (params.token_auth) {
params.token_auth = null;
delete params.token_auth;
}
for (var key in defaultParams) {
if (!params[key] && !this.postParams[key] && defaultParams[key]) {
params[key] = defaultParams[key];
}
}
// handle default date & period if not already set
if (!params.date && !this.postParams.date) {
params.date = piwik.currentDateString || broadcast.getValueFromUrl('date');
if (params.period == 'range' && piwik.currentDateString) {
params.date = piwik.startDateString + ',' + params.date;
}
}
return params;
};
return this;
}
|