Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/app/shared/cookies/klaro-configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { IMPERSONATING_COOKIE, REDIRECT_COOKIE } from '../../core/auth/auth.serv
import { LANG_COOKIE } from '../../core/locale/locale.service';
import { CAPTCHA_COOKIE, CAPTCHA_NAME } from '../../core/google-recaptcha/google-recaptcha.service';
import { ACCESSIBILITY_COOKIE } from '../../accessibility/accessibility-settings.service';
import { MATOMO_CONSENT_CALLBACK } from '../../statistics/matomo-consent-tracker';

/**
* Cookie for has_agreed_end_user
Expand All @@ -16,6 +17,8 @@ export const ANONYMOUS_STORAGE_NAME_KLARO = 'klaro-anonymous';

export const GOOGLE_ANALYTICS_KLARO_KEY = 'google-analytics';

export const MATOMO_KLARO_KEY = 'matomo';

/**
* Klaro configuration
* For more information see https://klaro.org/docs/integration/annotated-configuration
Expand Down Expand Up @@ -193,6 +196,12 @@ export const klaroConfiguration: any = {
*/
onlyOnce: true,
},
{
name: MATOMO_KLARO_KEY,
purposes: ['statistical'],
required: false,
callback: (consent: boolean) => (window as any)[MATOMO_CONSENT_CALLBACK]?.(consent),
},
{
name: CAPTCHA_NAME,
purposes: ['registration-password-recovery'],
Expand Down
94 changes: 94 additions & 0 deletions src/app/statistics/matomo-consent-tracker.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { MatomoConfig } from '../../config/matomo-config';
import { klaroConfiguration, MATOMO_KLARO_KEY } from '../shared/cookies/klaro-configuration';
import { MATOMO_CONSENT_CALLBACK, MatomoConsentTracker } from './matomo-consent-tracker';

describe('MatomoConsentTracker', () => {
const config: MatomoConfig = { hostUrl: 'https://matomo.example.org/', siteId: '7', dimensionId: 3 };
let browser: any;
let page: Document;

const createTracker = (matomoConfig: MatomoConfig, consentRequired = true) => new MatomoConsentTracker(
browser, page, matomoConfig, (path: string) => browser._paq.push(['trackPageView', path]), consentRequired);
const applyKlaroConsent = (consent: boolean) => browser[MATOMO_CONSENT_CALLBACK]?.(consent);
const loadedScripts = () => page.querySelectorAll('script').length;
const trackedPages = () => browser._paq.filter(([name]) => name === 'trackPageView').map(([, path]) => path);
const requestProcessor = () => browser._paq.find(([name]) => name === 'setCustomRequestProcessing')?.[1];

beforeEach(() => {
browser = { _paq: [] };
page = document.implementation.createHTMLDocument('matomo');
});

it('should load Matomo and track the current page only once the visitor consents', () => {
const tracker = createTracker(config);
tracker.eventTrack('page_view', { dc_identifier: 'current-item' });
tracker.trackPage('/items/current');
applyKlaroConsent(false);

expect(loadedScripts()).toBe(0);
expect(browser._paq).toEqual([]);

applyKlaroConsent(true);

expect(loadedScripts()).toBe(1);
expect(trackedPages()).toEqual(['/items/current']);
expect(browser._paq).toContain(['setCustomDimension', config.dimensionId, 'current-item']);
});

it('should stop tracking on revocation and never send activity from the declined period', () => {
const tracker = createTracker(config);
applyKlaroConsent(true);
tracker.trackPage('/accepted');

applyKlaroConsent(false);
tracker.eventTrack('page_view', { dc_identifier: 'declined-item' });
tracker.trackPage('/declined');
tracker.trackPage('/current');
tracker.eventTrack('page_view', { dc_identifier: 'declined-unfinished-navigation' });

expect(browser._paq).toContain(['forgetConsentGiven']);
expect(trackedPages()).toEqual(['/accepted']);
expect(requestProcessor()?.('link=declined')).toBe('');

applyKlaroConsent(true);
tracker.trackPage('/next');

expect(trackedPages()).toEqual(['/accepted', '/current', '/next']);
expect(JSON.stringify(browser._paq)).not.toContain('declined');
expect(requestProcessor()?.('link=accepted')).toBe('link=accepted');
expect(loadedScripts()).toBe(1);
});

it('should not load Matomo without a tracker URL and site ID', () => {
[undefined, { ...config, hostUrl: '' }, { ...config, siteId: '' }, { ...config, siteId: ' ' }].forEach((matomoConfig) => {
const tracker = createTracker(matomoConfig);
applyKlaroConsent(true);
tracker.trackPage('/items/current');
});

expect(loadedScripts()).toBe(0);
expect(browser._paq).toEqual([]);
});

it('should track without Klaro consent when the consent popup is explicitly disabled', () => {
createTracker(config, false).trackPage('/items/current');

expect(loadedScripts()).toBe(1);
expect(trackedPages()).toEqual(['/items/current']);
});

describe('Klaro service', () => {
afterEach(() => delete (window as any)[MATOMO_CONSENT_CALLBACK]);

it('should ask for individual opt-in consent and forward it to the tracker', () => {
const changeConsent = jasmine.createSpy(MATOMO_CONSENT_CALLBACK);
(window as any)[MATOMO_CONSENT_CALLBACK] = changeConsent;
const matomo = klaroConfiguration.services.find((service) => service.name === MATOMO_KLARO_KEY);

expect(matomo?.required).toBeFalse();
expect(matomo?.default).toBeFalsy();
matomo?.callback?.(true);
expect(changeConsent).toHaveBeenCalledWith(true);
});
});
});
144 changes: 144 additions & 0 deletions src/app/statistics/matomo-consent-tracker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { MatomoConfig } from '../../config/matomo-config';
import { hasValue, isNotEmpty } from '../shared/empty.util';

/**
* Window function through which the Klaro Matomo service reports the visitor's consent
*/
export const MATOMO_CONSENT_CALLBACK = 'changeMatomoConsent';

const MATOMO_SCRIPT = 'matomo.js';
const MATOMO_TRACKER_ENDPOINT = 'matomo.php';
const PAGE_VIEW_ACTION = 'page_view';
const DISCARDED_REQUEST = '';

/**
* A page view and the item identifier of its page, if any
*/
interface PageView {
path: string;
dimension?: string;
}

/**
* Forwards Angulartics page tracking to Matomo only while the visitor consents to Matomo.
* The tracker is loaded on the first consent. Without consent nothing is queued except the current page,
* which is tracked once consent is given, so pages and clicks from a declined period are never sent.
*/
export class MatomoConsentTracker {

private consent = false;
private loaded = false;
private dimension: string;
private pendingPageView: PageView;

/**
* @param window the browser window holding the Matomo command queue
* @param document the document to add the Matomo script to
* @param config the Matomo configuration
* @param sendPageView sends a page view to Matomo (the original Angulartics2Matomo pageTrack)
* @param consentRequired false when the cookie consent popup is disabled, so tracking needs no consent
*/
constructor(private window: any,
private document: Document,
private config: MatomoConfig,
private sendPageView: (path: string) => void,
consentRequired: boolean) {
this.window[MATOMO_CONSENT_CALLBACK] = (consent: boolean) => this.setConsent(consent);
if (!consentRequired) {
this.setConsent(true);
}
}

/**
* Apply the visitor's Matomo consent. Revoking it stops tracking, and every request Matomo builds
* meanwhile is emptied, so Matomo's consent queue cannot send it after a later consent.
* @param consent whether the visitor consents to Matomo
*/
setConsent(consent: boolean): void {
if (consent === this.consent || !this.isConfigured()) {
return;
}
this.consent = consent;
this.dimension = undefined;
if (consent) {
this.load();
// A function keeps its queue position; a queued 'setConsentGiven' name would run before 'forgetConsentGiven'
this.push(function () {
this.setConsentGiven();
});
this.trackPendingPageView();
} else {
this.push('forgetConsentGiven');
}
}

/**
* Remember the item identifier of a page_view event, if any, for the next page view
* @param action the Angulartics event action
* @param properties the Angulartics event properties
*/
eventTrack(action: string, properties?: any): void {
if (action === PAGE_VIEW_ACTION) {
this.dimension = properties?.dc_identifier;
}
}

/**
* Track a page view, or keep it as the current page until the visitor consents
* @param path the path of the page
*/
trackPage(path: string): void {
const pageView: PageView = { path, dimension: this.dimension };
this.dimension = undefined;
if (this.consent) {
this.track(pageView);
} else {
this.pendingPageView = pageView;
}
}

private trackPendingPageView(): void {
if (hasValue(this.pendingPageView)) {
this.track(this.pendingPageView);
this.pendingPageView = undefined;
}
}

private track(pageView: PageView): void {
if (isNotEmpty(pageView.dimension)) {
this.push('setCustomDimension', this.config.dimensionId, pageView.dimension);
}
this.sendPageView(pageView.path);
this.push('deleteCustomDimension', this.config.dimensionId);
}

private load(): void {
if (this.loaded) {
return;
}
this.loaded = true;
this.push('setTrackerUrl', this.config.hostUrl + MATOMO_TRACKER_ENDPOINT);
this.push('setSiteId', this.config.siteId);
this.push('setCustomRequestProcessing', (request: string) => this.consent ? request : DISCARDED_REQUEST);
this.push('enableLinkTracking');
this.addScript();
}

private addScript(): void {
const script = this.document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = this.config.hostUrl + MATOMO_SCRIPT;
this.document.head.appendChild(script);
}

private isConfigured(): boolean {
return [this.config?.hostUrl, this.config?.siteId].every((value) => isNotEmpty(`${value ?? ''}`.trim()));
}

private push(...command: unknown[]): void {
this.window._paq = this.window._paq || [];
this.window._paq.push(command);
}
}
6 changes: 6 additions & 0 deletions src/assets/i18n/cs.json5
Original file line number Diff line number Diff line change
Expand Up @@ -2162,6 +2162,12 @@
// "cookies.consent.app.description.google-analytics": "Allows us to track statistical data",
"cookies.consent.app.description.google-analytics": "Umožňuje nám sledovat statistické údaje",

// "cookies.consent.app.title.matomo": "Matomo",
"cookies.consent.app.title.matomo": "Matomo",

// "cookies.consent.app.description.matomo": "Allows us to track statistical data",
"cookies.consent.app.description.matomo": "Umožňuje nám sledovat statistické údaje",

// "cookies.consent.app.title.google-recaptcha": "Google reCaptcha",
"cookies.consent.app.title.google-recaptcha": "Google reCaptcha",

Expand Down
4 changes: 4 additions & 0 deletions src/assets/i18n/en.json5
Original file line number Diff line number Diff line change
Expand Up @@ -1441,6 +1441,10 @@

"cookies.consent.app.description.google-analytics": "Allows us to track statistical data",

"cookies.consent.app.title.matomo": "Matomo",

"cookies.consent.app.description.matomo": "Allows us to track statistical data",

"cookies.consent.app.title.google-recaptcha": "Google reCaptcha",

"cookies.consent.app.description.google-recaptcha": "We use google reCAPTCHA service during registration and password recovery",
Expand Down
25 changes: 2 additions & 23 deletions src/main.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ const main = () => {
enableProdMode();
}

addMatomoStatistics();
// Angulartics2Matomo expects the Matomo command queue; MatomoConsentTracker fills it only after consent
(window as any)._paq = (window as any)._paq || [];
if (hasTransferState) {
// Configuration will be taken from transfer state during initialization
return bootstrap();
Expand All @@ -43,28 +44,6 @@ const main = () => {
}
};

function addMatomoStatistics() {
(window as any)._paq = (window as any)._paq || [];

void fetch('assets/config.json')
.then((response) => response.json())
.then((config) => {
const matomoConfig = config.matomo;

// Push all configuration commands first
(window as any)._paq.push(['setTrackerUrl', matomoConfig.hostUrl + 'matomo.php']);
(window as any)._paq.push(['setSiteId', matomoConfig.siteId]);
(window as any)._paq.push(['enableLinkTracking']);

const g = document.createElement('script');
g.type = 'text/javascript';
g.async = true;
g.defer = true;
g.src = matomoConfig.hostUrl + 'matomo.js';
document.getElementsByTagName('head')[0].appendChild(g);
});
}

// support async tag or hmr
if (document.readyState === 'complete' && !hasTransferState) {
main();
Expand Down
37 changes: 37 additions & 0 deletions src/modules/app/browser-init.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { of as observableOf } from 'rxjs';
import { MATOMO_CONSENT_CALLBACK } from '../../app/statistics/matomo-consent-tracker';
import { BrowserInitService } from './browser-init.service';

describe('BrowserInitService', () => {
const unrelatedInitSteps = ['checkAuthenticationToken', 'externalAuthCheck', 'initCorrelationId', 'checkEnvironment',
'initI18n', 'initAngulartics', 'initGoogleAnalytics', 'initRouteListeners', 'trackAuthTokenExpiration', 'initKlaro'];
let matomoQueue: any;

beforeEach(() => {
matomoQueue = (window as any)._paq;
(window as any)._paq = [];
});

afterEach(() => {
(window as any)._paq = matomoQueue;
delete (window as any)[MATOMO_CONSENT_CALLBACK];
});

it('should route Angulartics Matomo tracking through the consent gate', async () => {
const service = Object.create(BrowserInitService.prototype);
const sendPageView = jasmine.createSpy('pageTrack');
service.angulartics2Matomo = { pageTrack: sendPageView, eventTrack: undefined, startTracking: jasmine.createSpy() };
service.themeService = jasmine.createSpyObj('themeService', ['listenForThemeChanges']);
spyOn(service, 'loadAppState').and.resolveTo(true);
spyOn(service, 'authenticationReady$').and.returnValue(observableOf(true));
unrelatedInitSteps.forEach((step) => spyOn(service, step));

await service.init()();
service.angulartics2Matomo.eventTrack('page_view', { dc_identifier: 'item' });
service.angulartics2Matomo.pageTrack('/items/item');

expect(service.angulartics2Matomo.startTracking).toHaveBeenCalled();
expect(sendPageView).not.toHaveBeenCalled();
expect((window as any)._paq).toEqual([]);
});
});
Loading
Loading