update Piwik to version 2.16 (fixes #91)

This commit is contained in:
oliver 2016-04-10 18:55:57 +02:00
commit d885a4baa9
5833 changed files with 418860 additions and 226988 deletions

View file

@ -1,5 +1,5 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -15,28 +15,39 @@
* <div piwik-autocomplete-matched="searchTerm">{{ name }}</div>
* <input type="text" ng-model="searchTerm">
*/
angular.module('piwikApp.directive').directive('piwikAutocompleteMatched', function() {
return function(scope, element, attrs) {
var searchTerm;
(function () {
angular.module('piwikApp.directive').directive('piwikAutocompleteMatched', piwikAutocompleteMatched);
scope.$watch(attrs.piwikAutocompleteMatched, function(value) {
searchTerm = value;
updateText();
});
piwikAutocompleteMatched.$inject = ['piwik', '$sanitize'];
function updateText () {
if (!searchTerm || !element) {
return;
function piwikAutocompleteMatched(piwik, $sanitize) {
return {
priority: 10, // makes sure to render after other directives, otherwise the content might be overwritten again see https://github.com/piwik/piwik/pull/8467
link: function (scope, element, attrs) {
var searchTerm;
scope.$watch(attrs.piwikAutocompleteMatched, function (value) {
searchTerm = value;
updateText();
});
function updateText() {
if (!searchTerm || !element) {
return;
}
var content = piwik.helper.htmlEntities(element.text());
var startTerm = content.toLowerCase().indexOf(searchTerm.toLowerCase());
if (-1 !== startTerm) {
var word = content.substr(startTerm, searchTerm.length);
var escapedword = $sanitize(piwik.helper.htmlEntities(word));
content = content.replace(word, '<span class="autocompleteMatched">' + escapedword + '</span>');
element.html(content);
}
}
}
var content = element.html();
var startTerm = content.toLowerCase().indexOf(searchTerm.toLowerCase());
if (-1 !== startTerm) {
var word = content.substr(startTerm, searchTerm.length);
content = content.replace(word, '<span class="autocompleteMatched">' + word + '</span>');
element.html(content);
}
}
};
});
};
}
})();

View file

@ -1,43 +0,0 @@
/*!
* Piwik - Web Analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
describe('piwikAutocompleteMatchedDirective', function() {
var $compile;
var $rootScope;
beforeEach(module('piwikApp.directive'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
function assertRenderedContentIs(query, expectedResult) {
var template = '<div piwik-autocomplete-matched="\'' + query + '\'">My Content</div>';
var element = $compile(template)($rootScope);
$rootScope.$digest();
expect(element.html()).to.eql(expectedResult);
}
describe('#piwikAutocompleteMatched()', function() {
it('should not change anything if query does not match the text', function() {
assertRenderedContentIs('Whatever', 'My Content');
});
it('should wrap the matching part and find case insensitive', function() {
assertRenderedContentIs('y cont', 'M<span class="autocompleteMatched">y Cont</span>ent');
});
it('should be able to wrap the whole content', function() {
assertRenderedContentIs('my content', '<span class="autocompleteMatched">My Content</span>');
});
it('should find matching content case sensitive', function() {
assertRenderedContentIs('My Co', '<span class="autocompleteMatched">My Co</span>ntent');
});
});
});

View file

@ -1,5 +1,5 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -15,27 +15,36 @@
* </div>
* Will execute the "executeMyFunction" function in the current scope once the yes button is pressed.
*/
angular.module('piwikApp.directive').directive('piwikDialog', function(piwik) {
(function () {
angular.module('piwikApp.directive').directive('piwikDialog', piwikDialog);
return {
restrict: 'A',
link: function(scope, element, attrs) {
piwikDialog.$inject = ['piwik', '$parse'];
element.css('display', 'none');
function piwikDialog(piwik, $parse) {
element.on( "dialogclose", function() {
scope.$eval(attrs.piwikDialog+'=false');
});
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.piwikDialog, function(newValue, oldValue) {
if (newValue) {
piwik.helper.modalConfirm(element, {yes: function() {
if (attrs.yes) {
scope.$eval(attrs.yes);
}
}});
}
});
}
};
});
element.css('display', 'none');
element.on( "dialogclose", function() {
setTimeout(function () {
scope.$apply($parse(attrs.piwikDialog).assign(scope, false));
}, 0);
});
scope.$watch(attrs.piwikDialog, function(newValue, oldValue) {
if (newValue) {
piwik.helper.modalConfirm(element, {yes: function() {
if (attrs.yes) {
scope.$eval(attrs.yes);
setTimeout(function () { scope.$apply(); }, 0);
}
}});
}
});
}
};
}
})();

View file

@ -0,0 +1,9 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.directive', []);
})();

View file

@ -1,5 +1,5 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -12,29 +12,35 @@
* Example:
* <div piwik-focus-anywhere-but-here="closeDialog()">my dialog</div>
*/
angular.module('piwikApp.directive').directive('piwikFocusAnywhereButHere', function($document){
return {
restrict: 'A',
link: function(scope, element, attr, ctrl) {
(function () {
angular.module('piwikApp.directive').directive('piwikFocusAnywhereButHere', piwikFocusAnywhereButHere);
function onClickOutsideElement (event) {
if (element.has(event.target).length === 0) {
scope.$apply(attr.piwikFocusAnywhereButHere);
piwikFocusAnywhereButHere.$inject = ['$document'];
function piwikFocusAnywhereButHere($document){
return {
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function onClickOutsideElement (event) {
if (element.has(event.target).length === 0) {
scope.$apply(attr.piwikFocusAnywhereButHere);
}
}
}
function onEscapeHandler (event) {
if (event.which === 27) {
scope.$apply(attr.piwikFocusAnywhereButHere);
function onEscapeHandler (event) {
if (event.which === 27) {
scope.$apply(attr.piwikFocusAnywhereButHere);
}
}
}
$document.on('keyup', onEscapeHandler);
$document.on('mouseup', onClickOutsideElement);
scope.$on('$destroy', function() {
$document.off('mouseup', onClickOutsideElement);
$document.off('keyup', onEscapeHandler);
});
}
};
});
$document.on('keyup', onEscapeHandler);
$document.on('mouseup', onClickOutsideElement);
scope.$on('$destroy', function() {
$document.off('mouseup', onClickOutsideElement);
$document.off('keyup', onEscapeHandler);
});
}
};
}
})();

View file

@ -1,5 +1,5 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -11,17 +11,23 @@
* Example:
* <input type="text" piwik-focus-if="view.editName">
*/
angular.module('piwikApp.directive').directive('piwikFocusIf', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.piwikFocusIf, function(newValue, oldValue) {
if (newValue) {
$timeout(function () {
element[0].focus();
}, 5);
}
});
}
};
});
(function () {
angular.module('piwikApp.directive').directive('piwikFocusIf', piwikFocusIf);
piwikFocusIf.$inject = ['$timeout'];
function piwikFocusIf($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.piwikFocusIf, function(newValue, oldValue) {
if (newValue) {
$timeout(function () {
element[0].focus();
}, 5);
}
});
}
};
}
})();

View file

@ -1,5 +1,5 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -12,10 +12,14 @@
* Example
* <a piwik-ignore-click ng-click="doSomething()" href="/">my link</a>
*/
angular.module('piwikApp.directive').directive('piwikIgnoreClick', function() {
return function(scope, element, attrs) {
$(element).click(function(event) {
event.preventDefault();
});
};
});
(function () {
angular.module('piwikApp.directive').directive('piwikIgnoreClick', piwikIgnoreClick);
function piwikIgnoreClick() {
return function(scope, element, attrs) {
$(element).click(function(event) {
event.preventDefault();
});
};
}
})();

View file

@ -1,5 +1,5 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
@ -12,16 +12,20 @@
* <div piwik-onenter="save()">
* <div piwik-onenter="showList=false">
*/
angular.module('piwikApp.directive').directive('piwikOnenter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.piwikOnenter, {'event': event});
});
(function () {
angular.module('piwikApp.directive').directive('piwikOnenter', piwikOnenter);
event.preventDefault();
}
});
};
});
function piwikOnenter() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.piwikOnenter, {'event': event});
});
event.preventDefault();
}
});
};
}
})();

View file

@ -0,0 +1,36 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
/**
* Directive for easy & safe complex internationalization. This directive allows
* users to embed the sprintf arguments used in internationalization inside an HTML
* element. Since the HTML will eventually be sanitized by AngularJS, HTML can be used
* within the sprintf args. Using the filter, this is not possible w/o manually sanitizing
* and creating trusted HTML, which is not as safe.
*
* Note: nesting this directive is not supported.
*
* Usage:
* <span piwik-translate="Plugin_TranslationToken">
* first arg::<strong>second arg</strong>::{{ unsafeDataThatWillBeSanitized }}
* </span>
*/
(function () {
angular.module('piwikApp.directive').directive('piwikTranslate', piwikTranslate);
function piwikTranslate() {
return {
priority: 1,
restrict: 'A',
compile: function(element, attrs) {
var parts = element.html().split('::'),
translated = _pk_translate(attrs.piwikTranslate, parts);
element.html(translated);
}
};
}
})();

View file

@ -1,44 +1,49 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('evolution', evolutionFilter);
angular.module('piwikApp.filter').filter('evolution', function() {
function evolutionFilter() {
function calculateEvolution(currentValue, pastValue)
{
pastValue = parseInt(pastValue, 10);
currentValue = parseInt(currentValue, 10) - pastValue;
function calculateEvolution(currentValue, pastValue)
{
pastValue = parseInt(pastValue, 10);
currentValue = parseInt(currentValue, 10) - pastValue;
if (currentValue === 0 || isNaN(currentValue)) {
evolution = 0;
} else if (pastValue === 0 || isNaN(pastValue)) {
evolution = 100;
} else {
evolution = (currentValue / pastValue) * 100;
var evolution;
if (currentValue === 0 || isNaN(currentValue)) {
evolution = 0;
} else if (pastValue === 0 || isNaN(pastValue)) {
evolution = 100;
} else {
evolution = (currentValue / pastValue) * 100;
}
return evolution;
}
return evolution;
}
function formatEvolution(evolution)
{
evolution = Math.round(evolution);
function formatEvolution(evolution)
{
evolution = Math.round(evolution);
if (evolution > 0) {
evolution = '+' + evolution;
}
if (evolution > 0) {
evolution = '+' + evolution;
evolution += '%';
return evolution;
}
evolution += '%';
return function(currentValue, pastValue) {
var evolution = calculateEvolution(currentValue, pastValue);
return evolution;
return formatEvolution(evolution);
};
}
return function(currentValue, pastValue) {
var evolution = calculateEvolution(currentValue, pastValue);
return formatEvolution(evolution);
};
});
})();

View file

@ -1,7 +0,0 @@
/*!
* Piwik - Web Analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
angular.module('piwikApp.filter', []);

View file

@ -1,8 +1,9 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
angular.module('piwikApp.service', []);
(function () {
angular.module('piwikApp.filter', []);
})();

View file

@ -0,0 +1,26 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('htmldecode', htmldecode);
htmldecode.$inject = ['piwik'];
/**
* Be aware that this filter can cause XSS so only use it when you're sure it is safe.
* Eg it should be safe when it is afterwards escaped by angular sanitize again.
*/
function htmldecode(piwik) {
return function(text) {
if (text && text.length) {
return piwik.helper.htmlDecode(text);
}
return text;
};
}
})();

View file

@ -0,0 +1,21 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('length', length);
function length() {
return function(stringOrArray) {
if (stringOrArray && stringOrArray.length) {
return stringOrArray.length;
}
return 0;
};
}
})();

View file

@ -0,0 +1,16 @@
/*!
* Piwik - Web Analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('prettyUrl', prettyUrl);
function prettyUrl() {
return function(input) {
return input.trim().replace('http://', '');
};
}
})();

View file

@ -1,13 +1,16 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('startFrom', startFrom);
angular.module('piwikApp.filter').filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
};
});
function startFrom() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
};
}
})();

View file

@ -0,0 +1,41 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
describe('startFromFilter', function() {
var startFrom;
beforeEach(module('piwikApp.filter'));
beforeEach(inject(function($injector) {
var $filter = $injector.get('$filter');
startFrom = $filter('startFrom');
}));
describe('#startFrom()', function() {
it('should return all entries if index is zero', function() {
var result = startFrom([1,2,3], 0);
expect(result).to.eql([1,2,3]);
});
it('should return only partial entries if filter is higher than zero', function() {
var result = startFrom([1,2,3], 2);
expect(result).to.eql([3]);
});
it('should return no entries if start is higher than input length', function() {
var result = startFrom([1,2,3], 11);
expect(result).to.eql([]);
});
});
});
})();

View file

@ -1,40 +0,0 @@
/*!
* Piwik - Web Analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
describe('startFromFilter', function() {
var startFrom;
beforeEach(module('piwikApp.filter'));
beforeEach(inject(function($injector) {
var $filter = $injector.get('$filter');
startFrom = $filter('startFrom');
}));
describe('#startFrom()', function() {
it('should return all entries if index is zero', function() {
var result = startFrom([1,2,3], 0);
expect(result).to.eql([1,2,3]);
});
it('should return only partial entries if filter is higher than zero', function() {
var result = startFrom([1,2,3], 2);
expect(result).to.eql([3]);
});
it('should return no entries if start is higher than input length', function() {
var result = startFrom([1,2,3], 11);
expect(result).to.eql([]);
});
});
});

View file

@ -1,19 +1,22 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('translate', translate);
angular.module('piwikApp.filter').filter('translate', function() {
function translate() {
return function(key, value1, value2, value3) {
var values = [];
if (arguments && arguments.length > 1) {
for (var index = 1; index < arguments.length; index++) {
values.push(arguments[index]);
return function(key, value1, value2, value3) {
var values = [];
if (arguments && arguments.length > 1) {
for (var index = 1; index < arguments.length; index++) {
values.push(arguments[index]);
}
}
}
return _pk_translate(key, values);
};
});
return _pk_translate(key, values);
};
}
})();

View file

@ -0,0 +1,20 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('trim', trim);
function trim() {
return function(string) {
if (string) {
return $.trim('' + string);
}
return string;
};
}
})();

View file

@ -0,0 +1,21 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('ucfirst', ucfirst);
function ucfirst() {
return function(value) {
if (!value) {
return value;
}
var firstLetter = (value + '').charAt(0).toUpperCase();
return firstLetter + value.substr(1);
};
}
})();

View file

@ -1,186 +1,305 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
angular.module('piwikApp.service').factory('piwikApi', function ($http, $q, $rootScope, piwik, $window) {
// see https://github.com/piwik/piwik/issues/5094 used to detect an ad blocker
var hasBlockedContent = false;
var url = 'index.php';
var format = 'json';
var getParams = {};
var postParams = {};
var requestHandle = null;
(function () {
angular.module('piwikApp.service').factory('piwikApi', piwikApiService);
var piwikApi = {};
piwikApiService.$inject = ['$http', '$q', '$rootScope', 'piwik', '$window'];
/**
* Adds params to the request.
* If params are given more then once, the latest given value is used for the request
*
* @param {object} params
* @return {void}
*/
function addParams (params) {
if (typeof params == 'string') {
params = piwik.broadcast.getValuesFromUrl(params);
function piwikApiService ($http, $q, $rootScope, piwik, $window) {
var url = 'index.php';
var format = 'json';
var getParams = {};
var postParams = {};
var allRequests = [];
/**
* Adds params to the request.
* If params are given more then once, the latest given value is used for the request
*
* @param {object} params
* @return {void}
*/
function addParams (params) {
if (typeof params == 'string') {
params = piwik.broadcast.getValuesFromUrl(params);
}
for (var key in params) {
getParams[key] = params[key];
}
}
for (var key in params) {
getParams[key] = params[key];
function reset () {
getParams = {};
postParams = {};
}
}
function reset () {
getParams = {};
postParams = {};
}
function isErrorResponse(response) {
return response && response.result == 'error';
}
/**
* Send the request
* @return $promise
*/
function send () {
function createResponseErrorNotification(response, options) {
if (response.message
&& options.createErrorNotification
) {
var UI = require('piwik/UI');
var notification = new UI.Notification();
notification.show(response.message, {
context: 'error',
type: 'toast',
id: 'ajaxHelper',
placeat: options.placeat
});
notification.scrollToNotification();
}
}
var deferred = $q.defer();
var requestHandle = deferred;
/**
* Send the request
* @return $promise
*/
function send (options) {
if (!options) {
options = {};
}
var onError = function (message) {
deferred.reject(message);
requestHandle = null;
};
if (options.createErrorNotification === undefined) {
options.createErrorNotification = true;
}
var onSuccess = function (response) {
if (response && response.result == 'error') {
function onSuccess(response)
{
response = response.data;
if (response.message) {
onError(response.message);
if (!angular.isDefined(response) || response === null) {
return $q.reject(null);
var UI = require('piwik/UI');
var notification = new UI.Notification();
notification.show(response.message, {
context: 'error',
type: 'toast',
id: 'ajaxHelper'
});
notification.scrollToNotification();
} else if (isErrorResponse(response)) {
createResponseErrorNotification(response, options);
return $q.reject(response.message || null);
} else {
onError(null);
return response;
}
}
function onError(response)
{
var message = 'Something went wrong';
if (response && (response.status === 0 || response.status === -1)) {
message = 'Request was possibly aborted';
}
} else {
deferred.resolve(response);
return $q.reject(message);
}
requestHandle = null;
};
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
// ie 8,9,10 caches ajax requests, prevent this
'cache-control': 'no-cache'
};
var deferred = $q.defer(),
requestPromise = deferred.promise;
var ajaxCall = {
method: 'POST',
url: url,
responseType: format,
params: _mixinDefaultGetParams(getParams),
data: $.param(getPostParams(postParams)),
timeout: deferred.promise,
headers: headers
};
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
// ie 8,9,10 caches ajax requests, prevent this
'cache-control': 'no-cache'
};
$http(ajaxCall).success(onSuccess).error(onError);
var ajaxCall = {
method: 'POST',
url: url,
responseType: format,
params: _mixinDefaultGetParams(getParams),
data: $.param(getPostParams(postParams)),
timeout: requestPromise,
headers: headers
};
return deferred.promise;
}
var promise = $http(ajaxCall).then(onSuccess, onError);
// we can't modify requestPromise directly and add an abort method since for some reason it gets
// removed after then/finally/catch is called.
var addAbortMethod = function (to, deferred) {
return {
then: function () {
return addAbortMethod(to.then.apply(to, arguments), deferred);
},
'finally': function () {
return addAbortMethod(to['finally'].apply(to, arguments), deferred);
},
'catch': function () {
return addAbortMethod(to['catch'].apply(to, arguments), deferred);
},
abort: function () {
deferred.resolve();
return this;
}
};
};
var request = addAbortMethod(promise, deferred);
allRequests.push(request);
return request;
}
/**
* Get the parameters to send as POST
*
* @param {object} params parameter object
* @return {object}
* @private
*/
function getPostParams (params) {
params.token_auth = piwik.token_auth;
return params;
}
/**
* Mixin the default parameters to send as GET
*
* @param {object} getParamsToMixin parameter object
* @return {object}
* @private
*/
function _mixinDefaultGetParams (getParamsToMixin) {
var segment = piwik.broadcast.getValueFromHash('segment', $window.location.href.split('#')[1]);
// we have to decode the value manually because broadcast will not decode anything itself. if we don't,
// angular will encode it again before sending the value in an HTTP request.
segment = decodeURIComponent(segment);
var defaultParams = {
idSite: piwik.idSite || piwik.broadcast.getValueFromUrl('idSite'),
period: piwik.period || piwik.broadcast.getValueFromUrl('period'),
segment: segment
};
// never append token_auth to url
if (getParamsToMixin.token_auth) {
getParamsToMixin.token_auth = null;
delete getParamsToMixin.token_auth;
}
for (var key in defaultParams) {
if (!getParamsToMixin[key] && !postParams[key] && defaultParams[key]) {
getParamsToMixin[key] = defaultParams[key];
}
}
// handle default date & period if not already set
if (!getParamsToMixin.date && !postParams.date) {
getParamsToMixin.date = piwik.currentDateString || piwik.broadcast.getValueFromUrl('date');
if (getParamsToMixin.period == 'range' && piwik.currentDateString) {
getParamsToMixin.date = piwik.startDateString + ',' + getParamsToMixin.date;
}
}
return getParamsToMixin;
}
function abortAll() {
reset();
allRequests.forEach(function (request) {
request.abort();
});
allRequests = [];
}
function abort () {
abortAll();
}
/**
* Perform a reading API request.
* @param getParams
*/
function fetch (getParams, options) {
getParams.module = getParams.module || 'API';
getParams.format = 'JSON2';
addParams(getParams, 'GET');
var promise = send(options);
reset();
return promise;
}
function post(getParams, _postParams_, options) {
if (_postParams_) {
postParams = _postParams_;
}
return fetch(getParams, options);
}
/**
* Convenience method that will perform a bulk request using Piwik's API.getBulkRequest method.
* Bulk requests allow you to execute multiple Piwik requests with one HTTP request.
*
* @param {object[]} requests
* @param {object} options
* @return {HttpPromise} a promise that is resolved when the request finishes. The argument passed
* to the .then(...) callback will be an array with one element per request
* made.
*/
function bulkFetch(requests, options) {
var bulkApiRequestParams = {
urls: requests.map(function (requestObj) { return '?' + $.param(requestObj); })
};
var deferred = $q.defer(),
requestPromise = post({method: "API.getBulkRequest"}, bulkApiRequestParams, options).then(function (response) {
if (!(response instanceof Array)) {
response = [response];
}
// check for errors
for (var i = 0; i != response.length; ++i) {
var specificResponse = response[i];
if (isErrorResponse(specificResponse)) {
deferred.reject(specificResponse.message || null);
createResponseErrorNotification(specificResponse, options || {});
return;
}
}
deferred.resolve(response);
})['catch'](function () {
deferred.reject.apply(deferred, arguments);
});
return deferred.promise;
}
/**
* Get the parameters to send as POST
*
* @param {object} params parameter object
* @return {object}
* @private
*/
function getPostParams () {
return {
token_auth: piwik.token_auth
bulkFetch: bulkFetch,
post: post,
fetch: fetch,
/**
* @deprecated
*/
abort: abort,
abortAll: abortAll
};
}
/**
* Mixin the default parameters to send as GET
*
* @param {object} getParamsToMixin parameter object
* @return {object}
* @private
*/
function _mixinDefaultGetParams (getParamsToMixin) {
var defaultParams = {
idSite: piwik.idSite || piwik.broadcast.getValueFromUrl('idSite'),
period: piwik.period || piwik.broadcast.getValueFromUrl('period'),
segment: piwik.broadcast.getValueFromHash('segment', $window.location.href.split('#')[1])
};
// never append token_auth to url
if (getParamsToMixin.token_auth) {
getParamsToMixin.token_auth = null;
delete getParamsToMixin.token_auth;
}
for (var key in defaultParams) {
if (!getParamsToMixin[key] && !postParams[key] && defaultParams[key]) {
getParamsToMixin[key] = defaultParams[key];
}
}
// handle default date & period if not already set
if (!getParamsToMixin.date && !postParams.date) {
getParamsToMixin.date = piwik.currentDateString || piwik.broadcast.getValueFromUrl('date');
if (getParamsToMixin.period == 'range' && piwik.currentDateString) {
getParamsToMixin.date = piwik.startDateString + ',' + getParamsToMixin.date;
}
}
return getParamsToMixin;
}
piwikApi.abort = function () {
reset();
if (requestHandle) {
requestHandle.resolve();
requestHandle = null;
}
};
/**
* Perform a reading API request.
* @param getParams
*/
piwikApi.fetch = function (getParams) {
getParams.module = 'API';
getParams.format = 'JSON';
addParams(getParams, 'GET');
var promise = send();
reset();
return promise;
};
piwikApi.post = function (getParams, _postParams_) {
if (_postParams_) {
postParams = _postParams_;
}
return this.fetch(getParams);
};
return piwikApi;
});
})();

View file

@ -0,0 +1,273 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
describe('piwikApiClient', function () {
var piwikApi,
$httpBackend;
if (!window.piwik) window.piwik = {};
if (!window.piwik.UI) window.piwik.UI = {};
if (!window.piwik.UI.Notification) {
window.piwik.UI.Notification = function () {
this.show = function () {};
this.scrollToNotification = function () {};
return this;
};
}
beforeEach(module('piwikApp.service'));
beforeEach(inject(function($injector) {
piwikApi = $injector.get('piwikApi');
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('POST', /.*getBulkRequest.*/, /.*errorAction.*/).respond(function (method, url, data, headers) {
url = url.replace(/date=[^&]+/, "date=");
var errorResponse = {result: 'error', message: "error message"},
successResponse= "Response #2: " + url + " - " + data;
return [200, [errorResponse, successResponse]];
});
$httpBackend.when('POST', /.*getBulkRequest.*/).respond(function (method, url, data, headers) {
url = url.replace(/date=[^&]+/, "date=");
var responses = [
"Response #1: " + url + " - " + data,
"Response #2: " + url + " - " + data
];
return [200, JSON.stringify(responses)];
});
$httpBackend.when('POST', /.*/).respond(function (method, url, data, headers) {
url = url.replace(/date=[^&]+/, "date=");
return [200, "Request url: " + url];
});
}));
it("should successfully send a request to Piwik when fetch is called", function (done) {
piwikApi.fetch({
method: "SomePlugin.action"
}).then(function (response) {
expect(response).to.equal("Request url: index.php?date=&format=JSON2&idSite=1&method=SomePlugin.action&module=API&period=day");
done();
}).catch(function (ex) {
done(ex);
});
$httpBackend.flush();
});
it("should chain multiple then callbacks correctly when a fetch succeeds", function (done) {
var firstThenDone = false;
piwikApi.fetch({
method: "SomePlugin.action"
}).then(function (response) {
firstThenDone = true;
return "newval";
}).then(function (response) {
expect(firstThenDone).to.equal(true);
expect(response).to.equal("newval");
done();
}).catch(function (ex) {
done(ex);
});
$httpBackend.flush();
});
it("should fail when multiple aborts are issued", function (done) {
var request = piwikApi.fetch({
method: "SomePlugin.action"
}).then(function (response) {
done(new Error("Aborted request succeeded but should fail!"));
}).catch(function (ex) {
done();
});
request.abort();
request.abort();
$httpBackend.flush();
request.abort();
});
it("should send multiple requests concurrently when fetch is called more than once", function (done) {
var request1Done, request2Done;
function finishIfBothDone() {
if (request1Done && request2Done) {
done();
}
}
piwikApi.fetch({
method: "SomePlugin.action"
}).then(function (response) {
expect(response).to.equal("Request url: index.php?date=&format=JSON2&idSite=1&method=SomePlugin.action&module=API&period=day");
request1Done = true;
finishIfBothDone();
}).catch(function (ex) {
done(ex);
});
piwikApi.fetch({
method: "SomeOtherPlugin.action"
}).then(function (response) {
expect(response).to.equal("Request url: index.php?date=&format=JSON2&idSite=1&method=SomeOtherPlugin.action&module=API&period=day");
request2Done = true;
finishIfBothDone();
}).catch(function (ex) {
done(ex);
});
$httpBackend.flush();
});
it("should abort individual requests when abort() is called on a promise", function (done) {
var request1Done, request2Done;
function finishIfBothDone() {
if (request1Done && request2Done) {
done();
}
}
var request = piwikApi.fetch({
method: "SomePlugin.waitAction"
}).then(function (response) {
done(new Error("Aborted request finished!"));
}).catch(function (ex) {
request1Done = true;
finishIfBothDone();
});
piwikApi.fetch({
method: "SomeOtherPlugin.action"
}).then(function (response) {
expect(response).to.equal("Request url: index.php?date=&format=JSON2&idSite=1&method=SomeOtherPlugin.action&module=API&period=day");
request2Done = true;
finishIfBothDone();
}).catch(function (ex) {
done(ex);
});
request.abort();
$httpBackend.flush();
});
it("should abort all requests when abortAll() is called on the piwikApi", function (done) {
var request1Done, request2Done;
function finishIfBothDone() {
if (request1Done && request2Done) {
done();
}
}
piwikApi.fetch({
method: "SomePlugin.waitAction"
}).then(function (response) {
done(new Error("Aborted request finished (request 1)!"));
}).catch(function (ex) {
request1Done = true;
finishIfBothDone();
});
piwikApi.fetch({
method: "SomePlugin.waitAction"
}).then(function (response) {
done(new Error("Aborted request finished (request 2)!"));
}).catch(function (ex) {
request2Done = true;
finishIfBothDone();
});
piwikApi.abortAll();
$httpBackend.flush();
});
it("should perform a bulk request correctly when bulkFetch is called on the piwikApi", function (done) {
piwikApi.bulkFetch([
{
method: "SomePlugin.action",
param: "value"
},
{
method: "SomeOtherPlugin.action"
}
]).then(function (response) {
var restOfExpected = "index.php?date=&format=JSON2&idSite=1&method=API.getBulkRequest&" +
"module=API&period=day - urls%5B%5D=%3Fmethod%3DSomePlugin.action%26param%3D" +
"value&urls%5B%5D=%3Fmethod%3DSomeOtherPlugin.action&token_auth=100bf5eeeed1468f3f9d93750044d3dd";
expect(response.length).to.equal(2);
expect(response[0]).to.equal("Response #1: " + restOfExpected);
expect(response[1]).to.equal("Response #2: " + restOfExpected);
done();
}).catch(function (ex) {
done(ex);
});
$httpBackend.flush();
});
it("should correctly handle errors in a bulk request response", function (done) {
piwikApi.bulkFetch([
{
method: "SomePlugin.errorAction"
},
{
method: "SomeOtherPlugin.whatever"
}
]).then(function (response) {
done(new Error("promise resolved after bulkFetch request returned an error (response = " + JSON.stringify(response) + ")"));
}).catch(function (error) {
expect(error).to.equal("error message");
done();
});
$httpBackend.flush();
});
it("shuld correctly handle errors in a bulk request response, regardless of error location", function (done) {
piwikApi.bulkFetch([
{
method: "SomeOtherPlugin.whatever"
},
{
method: "SomePlugin.errorAction"
}
]).then(function (response) {
done(new Error("promise resolved after bulkFetch request returned an error (response = " + JSON.stringify(response) + ")"));
}).catch(function (error) {
expect(error).to.equal("error message");
done();
});
$httpBackend.flush();
});
});
})();

View file

@ -1,13 +1,16 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.service').service('piwik', piwikService);
angular.module('piwikApp.service').service('piwik', function () {
function piwikService() {
piwik.helper = piwikHelper;
piwik.broadcast = broadcast;
return piwik;
});
piwik.helper = piwikHelper;
piwik.broadcast = broadcast;
return piwik;
}
})();

View file

@ -0,0 +1,38 @@
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
describe('piwikService', function() {
var piwikService;
beforeEach(module('piwikApp.service'));
beforeEach(inject(function($injector) {
piwikService = $injector.get('piwik');
}));
describe('#piwikService', function() {
it('should be the same as piwik global var', function() {
piwik.should.equal(piwikService);
});
it('should mixin broadcast', function() {
expect(piwikService.broadcast).to.be.an('object');
});
it('should mixin piwikHelper', function() {
expect(piwikService.helper).to.be.an('object');
});
});
describe('#piwik_url', function() {
it('should contain the piwik url', function() {
expect(piwikService.piwik_url).to.eql('http://localhost/');
});
});
});
})();

View file

@ -1,37 +0,0 @@
/*!
* Piwik - Web Analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
describe('piwikService', function() {
var piwikService;
beforeEach(module('piwikApp.service'));
beforeEach(inject(function($injector) {
piwikService = $injector.get('piwik');
}));
describe('#piwikService', function() {
it('should be the same as piwik global var', function() {
piwik.should.equal(piwikService);
});
it('should mixin broadcast', function() {
expect(piwikService.broadcast).to.be.an('object');
});
it('should mixin piwikHelper', function() {
expect(piwikService.helper).to.be.an('object');
});
});
describe('#piwik_url', function() {
it('should contain the piwik url', function() {
expect(piwikService.piwik_url).to.eql('http://localhost/');
});
});
});

View file

@ -1,8 +1,9 @@
/*!
* Piwik - Web Analytics
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
angular.module('piwikApp.directive', []);
(function () {
angular.module('piwikApp.service', []);
})();