diff --git a/src/app/shared/cookies/klaro-configuration.ts b/src/app/shared/cookies/klaro-configuration.ts index bd569175014..156ced5dc57 100644 --- a/src/app/shared/cookies/klaro-configuration.ts +++ b/src/app/shared/cookies/klaro-configuration.ts @@ -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 @@ -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 @@ -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'], diff --git a/src/app/statistics/matomo-consent-tracker.spec.ts b/src/app/statistics/matomo-consent-tracker.spec.ts new file mode 100644 index 00000000000..7df8b794b88 --- /dev/null +++ b/src/app/statistics/matomo-consent-tracker.spec.ts @@ -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); + }); + }); +}); diff --git a/src/app/statistics/matomo-consent-tracker.ts b/src/app/statistics/matomo-consent-tracker.ts new file mode 100644 index 00000000000..d1cbfb3cd53 --- /dev/null +++ b/src/app/statistics/matomo-consent-tracker.ts @@ -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); + } +} diff --git a/src/assets/i18n/cs.json5 b/src/assets/i18n/cs.json5 index 9c1a82c6506..d554944e675 100644 --- a/src/assets/i18n/cs.json5 +++ b/src/assets/i18n/cs.json5 @@ -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", diff --git a/src/assets/i18n/en.json5 b/src/assets/i18n/en.json5 index 6f1ec59821f..bcfa2767aab 100644 --- a/src/assets/i18n/en.json5 +++ b/src/assets/i18n/en.json5 @@ -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", diff --git a/src/main.browser.ts b/src/main.browser.ts index d17101d07a6..93e830d8127 100644 --- a/src/main.browser.ts +++ b/src/main.browser.ts @@ -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(); @@ -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(); diff --git a/src/modules/app/browser-init.service.spec.ts b/src/modules/app/browser-init.service.spec.ts new file mode 100644 index 00000000000..5e48b4f75c9 --- /dev/null +++ b/src/modules/app/browser-init.service.spec.ts @@ -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([]); + }); +}); diff --git a/src/modules/app/browser-init.service.ts b/src/modules/app/browser-init.service.ts index 905485637d6..44d96de5a6a 100644 --- a/src/modules/app/browser-init.service.ts +++ b/src/modules/app/browser-init.service.ts @@ -37,6 +37,7 @@ import { ServerCheckGuard } from '../../app/core/server-check/server-check.guard import { HALEndpointService } from '../../app/core/shared/hal-endpoint.service'; import { BuildConfig } from '../../config/build-config.interface'; import { Angulartics2Matomo } from 'angulartics2'; +import { MatomoConsentTracker } from '../../app/statistics/matomo-consent-tracker'; /** * Performs client-side initialization. @@ -107,21 +108,10 @@ export class BrowserInitService extends InitService { this.initRouteListeners(); this.themeService.listenForThemeChanges(true); this.trackAuthTokenExpiration(); - // ideally we'd add the custom dimension to the 'trackPageView' action only, but don't have that information - // in pageTrack context. So we add it to page_view events, and remove it after the page view. - // page_view events are fired via view-track.component, and exposes dc.identifier.uri via properties - this.angulartics2Matomo.eventTrack = function (action: string, properties?: any) { - if (action === 'page_view') { - if (properties.dc_identifier) { - (window as any)._paq.push(['setCustomDimension', environment.matomo.dimensionId, properties.dc_identifier]); - } - } - }; - let pageTrack = this.angulartics2Matomo.pageTrack; - this.angulartics2Matomo.pageTrack = function (path: string) { - pageTrack.call(this, path); - (window as any)._paq.push(['deleteCustomDimension', environment.matomo.dimensionId]); - }; + const matomo = new MatomoConsentTracker(window, document, environment.matomo, + this.angulartics2Matomo.pageTrack.bind(this.angulartics2Matomo), environment.info?.enableCookieConsentPopup !== false); + this.angulartics2Matomo.eventTrack = (action: string, properties?: any) => matomo.eventTrack(action, properties); + this.angulartics2Matomo.pageTrack = (path: string) => matomo.trackPage(path); this.angulartics2Matomo.startTracking(); this.initKlaro();