Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.68% covered (success)
93.68%
178 / 190
57.89% covered (warning)
57.89%
11 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
GoogleAnalyticsPageViewService
93.68% covered (success)
93.68%
178 / 190
57.89% covered (warning)
57.89%
11 / 19
53.71
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 setLogger
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 supports
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 getPageData
88.24% covered (warning)
88.24%
15 / 17
0.00% covered (danger)
0.00%
0 / 1
4.03
 getChunkData
100.00% covered (success)
100.00%
45 / 45
100.00% covered (success)
100.00%
1 / 1
8
 getSiteData
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 getTopPages
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
6
 getCacheExpiry
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 runReport
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
5
 describe
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 getGAMetric
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 getTitleDimension
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getDbKeysByPageIdOfTitles
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 getDbKeysByPageId
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 fetchDbKeysByPageId
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getPageTitleRegex
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 stripSiteName
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 formatDate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getDates
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace MediaWiki\Extension\PageViewInfoGA;
4
5use InvalidArgumentException;
6use MediaWiki\Extension\PageViewInfo\PageViewService;
7use MediaWiki\Http\HttpRequestFactory;
8use MediaWiki\Json\FormatJson;
9use MediaWiki\Page\PageReference;
10use MediaWiki\Page\PageSelectQueryBuilder;
11use MediaWiki\Page\PageStore;
12use MediaWiki\Title\TitleFormatter;
13use Psr\Log\LoggerAwareInterface;
14use Psr\Log\LoggerInterface;
15use Psr\Log\NullLogger;
16use StatusValue;
17use Wikimedia\Message\MessageParam;
18
19/**
20 * PageViewService implementation for wikis using Google Analytics 4, through the Google Analytics Data API
21 *
22 * GA4 counts days in the time zone of the property, which should be the wiki's $wgLocaltimezone.
23 * Like PageViewInfo's Wikimedia backend, the data ends with yesterday, whose counts can still
24 * grow while GA4 processes late events.
25 *
26 * @see https://developers.google.com/analytics/devguides/reporting/data/v1
27 */
28class GoogleAnalyticsPageViewService implements PageViewService, LoggerAwareInterface {
29
30    public const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
31    private const ENDPOINT = 'https://analyticsdata.googleapis.com/v1beta';
32
33    /** Separators of the "pagetitle" message across languages: hyphen, en dash, em dash, middle dot */
34    private const SITE_NAME_SEPARATOR = '[-–—·]';
35
36    /** The most rows one report returns */
37    private const ROW_LIMIT = 250000;
38    /** Pages per report, to keep each request and its filter small */
39    private const PAGES_PER_REPORT = 50;
40    /** Seconds to wait for a report */
41    private const TIMEOUT = 10;
42
43    private LoggerInterface $logger;
44
45    /** @var string GA4 property ID, digits only */
46    private string $propertyId;
47
48    private string $siteName;
49
50    private bool $readCustomDimensions;
51
52    /**
53     * @param HttpRequestFactory $httpRequestFactory
54     * @param TitleFormatter $titleFormatter
55     * @param PageStore $pageStore
56     * @param CredentialsFileTokenProvider $tokenProvider
57     * @param array $options
58     *   - propertyId: (string|int) GA4 property ID, like 123456789 or "properties/123456789"
59     *   - siteName: (string) $wgSitename, which events from before the Google tag sent page_title
60     *     carry in the document title
61     *   - readCustomDimensions: (bool, default false) Match pages by the mw_page_id event
62     *     parameter, registered as an event-scoped custom dimension, instead of by the page title.
63     *     Page IDs follow a page when it is moved.
64     * @phan-param array{propertyId:string|int,siteName:string,readCustomDimensions?:bool} $options
65     * @throws InvalidArgumentException When propertyId is not a GA4 property ID
66     */
67    public function __construct(
68        private readonly HttpRequestFactory $httpRequestFactory,
69        private readonly TitleFormatter $titleFormatter,
70        private readonly PageStore $pageStore,
71        private readonly CredentialsFileTokenProvider $tokenProvider,
72        array $options
73    ) {
74        // Accept "properties/123" as the API shows it
75        $propertyId = preg_replace( '/^properties\//', '', (string)( $options['propertyId'] ?? '' ) );
76        if ( !ctype_digit( $propertyId ) ) {
77            throw new InvalidArgumentException( "'propertyId' must be a GA4 property ID" );
78        }
79        $this->propertyId = $propertyId;
80        $this->siteName = (string)( $options['siteName'] ?? '' );
81        $this->readCustomDimensions = (bool)( $options['readCustomDimensions'] ?? false );
82        $this->logger = new NullLogger();
83    }
84
85    /** @inheritDoc */
86    public function setLogger( LoggerInterface $logger ): void {
87        $this->logger = $logger;
88    }
89
90    /** @inheritDoc */
91    public function supports( $metric, $scope ) {
92        return in_array( $metric, [ self::METRIC_VIEW, self::METRIC_UNIQUE ] ) &&
93            in_array( $scope, [ self::SCOPE_ARTICLE, self::SCOPE_TOP, self::SCOPE_SITE ] );
94    }
95
96    /**
97     * @inheritDoc
98     *
99     * For METRIC_UNIQUE, the users of a page under page_title and under its document title are
100     * added up, so a user counted under both counts twice.
101     */
102    public function getPageData( array $titles, $days, $metric = self::METRIC_VIEW ) {
103        $gaMetric = self::getGAMetric( $metric );
104        if ( $days <= 0 ) {
105            throw new InvalidArgumentException( 'Invalid days: ' . $days );
106        }
107        if ( !$titles ) {
108            return StatusValue::newGood( [] );
109        }
110
111        $dates = $this->getDates( $days );
112        $status = StatusValue::newGood();
113        $result = [];
114        foreach ( array_chunk( $titles, self::PAGES_PER_REPORT ) as $chunk ) {
115            $chunkStatus = $this->getChunkData( $chunk, $dates, $gaMetric );
116            $status->merge( $chunkStatus );
117            $status->success += $chunkStatus->success;
118            $result += $chunkStatus->getValue();
119        }
120        $status->successCount = count( array_filter( $status->success ) );
121        $status->failCount = count( $status->success ) - $status->successCount;
122        $status->setResult( (bool)$status->successCount, $result );
123        return $status;
124    }
125
126    /**
127     * @param PageReference[] $titles
128     * @param string[] $dates YYYY-MM-DD, oldest first
129     * @param string $gaMetric
130     * @return StatusValue With per-title success, and the data of getPageData() as its value
131     */
132    private function getChunkData( array $titles, array $dates, string $gaMetric ): StatusValue {
133        $dbKeys = array_map( [ $this->titleFormatter, 'getPrefixedDBkey' ], $titles );
134        $titleDimension = $this->getTitleDimension();
135        // The page as the report names it => prefixed DB key
136        if ( $this->readCustomDimensions ) {
137            $dbKeysByGATitle = $this->getDbKeysByPageIdOfTitles( $titles );
138            $filter = [ 'filter' => [
139                'fieldName' => $titleDimension,
140                'inListFilter' => [ 'values' => array_map( 'strval', array_keys( $dbKeysByGATitle ) ) ],
141            ] ];
142        } else {
143            $dbKeysByGATitle = array_combine(
144                array_map( [ $this->titleFormatter, 'getPrefixedText' ], $titles ),
145                $dbKeys
146            );
147            $filter = [ 'orGroup' => [ 'expressions' => array_map( fn ( $text ) => [
148                'filter' => [
149                    'fieldName' => $titleDimension,
150                    'stringFilter' => [
151                        'matchType' => 'FULL_REGEXP',
152                        'value' => $this->getPageTitleRegex( (string)$text ),
153                        'caseSensitive' => true,
154                    ],
155                ],
156            ], array_keys( $dbKeysByGATitle ) ) ] ];
157        }
158
159        // A page with no row on a day had no views that day
160        $counts = array_fill_keys( $dbKeys, array_fill_keys( $dates, 0 ) );
161        if ( $dbKeysByGATitle ) {
162            $status = $this->runReport( [
163                'dateRanges' => [ [ 'startDate' => reset( $dates ), 'endDate' => end( $dates ) ] ],
164                'dimensions' => [ [ 'name' => 'date' ], [ 'name' => $titleDimension ] ],
165                'metrics' => [ [ 'name' => $gaMetric ] ],
166                'dimensionFilter' => $filter,
167                'limit' => self::ROW_LIMIT,
168            ] );
169            if ( !$status->isOK() ) {
170                $status->success = array_fill_keys( $dbKeys, false );
171                $status->setResult( false, array_fill_keys( $dbKeys, array_fill_keys( $dates, null ) ) );
172                return $status;
173            }
174            foreach ( $status->getValue() as [ $date, $gaTitle, $count ] ) {
175                // Since the Google tag sends page_title, it is the page alone, as asked for. Older
176                // events carry the document title with the site name.
177                $dbKey = $dbKeysByGATitle[$gaTitle] ?? (
178                    $this->readCustomDimensions ? null : $dbKeysByGATitle[$this->stripSiteName( $gaTitle )] ?? null
179                );
180                $day = self::formatDate( $date );
181                if ( $dbKey !== null && isset( $counts[$dbKey][$day] ) ) {
182                    $counts[$dbKey][$day] += $count;
183                }
184            }
185        }
186
187        $status = StatusValue::newGood();
188        $status->success = array_fill_keys( $dbKeys, true );
189        $status->setResult( true, $counts );
190        return $status;
191    }
192
193    /** @inheritDoc */
194    public function getSiteData( $days, $metric = self::METRIC_VIEW ) {
195        $gaMetric = self::getGAMetric( $metric );
196        if ( $days <= 0 ) {
197            throw new InvalidArgumentException( 'Invalid days: ' . $days );
198        }
199
200        $dates = $this->getDates( $days );
201        $status = $this->runReport( [
202            'dateRanges' => [ [ 'startDate' => reset( $dates ), 'endDate' => end( $dates ) ] ],
203            'dimensions' => [ [ 'name' => 'date' ] ],
204            'metrics' => [ [ 'name' => $gaMetric ] ],
205        ] );
206        if ( !$status->isOK() ) {
207            return $status;
208        }
209
210        $result = array_fill_keys( $dates, 0 );
211        foreach ( $status->getValue() as [ $date, $count ] ) {
212            $day = self::formatDate( $date );
213            if ( isset( $result[$day] ) ) {
214                $result[$day] = $count;
215            }
216        }
217        $status->setResult( true, $result );
218        return $status;
219    }
220
221    /** @inheritDoc */
222    public function getTopPages( $metric = self::METRIC_VIEW ) {
223        $gaMetric = self::getGAMetric( $metric );
224        $yesterday = $this->getDates( 1 )[0];
225
226        $status = $this->runReport( [
227            'dateRanges' => [ [ 'startDate' => $yesterday, 'endDate' => $yesterday ] ],
228            'dimensions' => [ [ 'name' => $this->getTitleDimension() ] ],
229            'metrics' => [ [ 'name' => $gaMetric ] ],
230            'orderBys' => [ [ 'metric' => [ 'metricName' => $gaMetric ], 'desc' => true ] ],
231        ] );
232        if ( !$status->isOK() ) {
233            return $status;
234        }
235
236        $rows = array_filter( $status->getValue(),
237            // GA4 names events without the dimension "(not set)", and the rows past its cardinality
238            // limits "(other)"
239            static fn ( $row ) => !in_array( $row[0], [ '', '(not set)', '(other)' ], true )
240        );
241        $dbKeysByPageId = [];
242        if ( $this->readCustomDimensions ) {
243            // Pages by their current title, which follows moves. Deleted pages drop out.
244            $dbKeysByPageId = $this->getDbKeysByPageId( array_column( $rows, 0 ) );
245        }
246        $result = [];
247        foreach ( $rows as [ $gaTitle, $count ] ) {
248            // Any page can be on top, so turn the title back into a DB key
249            $dbKey = $this->readCustomDimensions ?
250                $dbKeysByPageId[$gaTitle] ?? null :
251                str_replace( ' ', '_', $this->stripSiteName( $gaTitle ) );
252            if ( $dbKey !== null ) {
253                $result[$dbKey] = ( $result[$dbKey] ?? 0 ) + $count;
254            }
255        }
256        arsort( $result );
257        $status->setResult( true, $result );
258        return $status;
259    }
260
261    /** @inheritDoc */
262    public function getCacheExpiry( $metric, $scope ) {
263        // data is valid until the end of the day
264        $endOfDay = strtotime( '0:0 next day' );
265        return $endOfDay - time();
266    }
267
268    /**
269     * Run one report
270     * @param array $request RunReportRequest
271     * @return StatusValue With a list of rows as its value when OK; each row is the dimension values
272     *   followed by the first metric value as an integer
273     */
274    private function runReport( array $request ): StatusValue {
275        $tokenStatus = $this->tokenProvider->getAccessToken();
276        if ( !$tokenStatus->isOK() ) {
277            $this->logger->error( 'Failed getting an access token for Google Analytics: {error}', [
278                'error' => self::describe( $tokenStatus ),
279            ] );
280            return $tokenStatus;
281        }
282
283        $url = self::ENDPOINT . "/properties/{$this->propertyId}:runReport";
284        $httpRequest = $this->httpRequestFactory->create( $url, [
285            'method' => 'POST',
286            'postData' => FormatJson::encode( $request ),
287            'timeout' => self::TIMEOUT,
288        ], __METHOD__ );
289        $httpRequest->setHeader( 'Content-Type', 'application/json' );
290        $httpRequest->setHeader( 'Authorization', 'Bearer ' . $tokenStatus->getValue() );
291        $httpStatus = $httpRequest->execute();
292        $data = FormatJson::decode( $httpRequest->getContent(), true );
293        if ( !$httpStatus->isOK() || !is_array( $data ) ) {
294            $this->logger->error( 'Failed fetching {requesturl}: {error}', [
295                'requesturl' => $url,
296                'error' => $data['error']['message'] ?? self::describe( $httpStatus ),
297            ] );
298            $status = StatusValue::newFatal( 'pvi-invalidresponse' );
299            $status->merge( $httpStatus );
300            return $status;
301        }
302
303        $rows = [];
304        foreach ( $data['rows'] ?? [] as $row ) {
305            $values = array_column( $row['dimensionValues'] ?? [], 'value' );
306            $values[] = (int)( $row['metricValues'][0]['value'] ?? 0 );
307            $rows[] = $values;
308        }
309        return StatusValue::newGood( $rows );
310    }
311
312    /**
313     * Message keys and parameters of a status for the log, which needs no message lookup
314     * @param StatusValue $status
315     * @return string
316     */
317    private static function describe( StatusValue $status ): string {
318        return implode( '; ', array_map(
319            static fn ( $message ) => $message->getKey() . ' ' . FormatJson::encode( array_map(
320                static fn ( $param ) => $param instanceof MessageParam ? $param->getValue() : $param,
321                $message->getParams()
322            ) ),
323            $status->getMessages()
324        ) );
325    }
326
327    /**
328     * @param string $metric One of the METRIC_* constants
329     * @return string GA4 metric name
330     * @throws InvalidArgumentException
331     */
332    private static function getGAMetric( $metric ): string {
333        if ( $metric === self::METRIC_VIEW ) {
334            return 'screenPageViews';
335        } elseif ( $metric === self::METRIC_UNIQUE ) {
336            return 'totalUsers';
337        }
338        throw new InvalidArgumentException( 'Invalid metric: ' . $metric );
339    }
340
341    private function getTitleDimension(): string {
342        return $this->readCustomDimensions ?
343            'customEvent:' . Constants::EVENT_PARAM_PAGE_ID :
344            'pageTitle';
345    }
346
347    /**
348     * @param PageReference[] $titles
349     * @return string[] Prefixed DB key by page ID, for the pages that exist
350     */
351    private function getDbKeysByPageIdOfTitles( array $titles ): array {
352        $byNamespace = [];
353        foreach ( $titles as $title ) {
354            $byNamespace[$title->getNamespace()][] = $title->getDBkey();
355        }
356        $dbKeys = [];
357        foreach ( $byNamespace as $namespace => $namespaceDbKeys ) {
358            $dbKeys += $this->fetchDbKeysByPageId(
359                $this->pageStore->newSelectQueryBuilder()->whereTitles( $namespace, $namespaceDbKeys )
360            );
361        }
362        return $dbKeys;
363    }
364
365    /**
366     * @param string[] $pageIds Page IDs as GA4 reports them
367     * @return string[] Current prefixed DB key by page ID, for the pages that still exist
368     */
369    private function getDbKeysByPageId( array $pageIds ): array {
370        $pageIds = array_map( 'intval', array_filter( $pageIds, 'ctype_digit' ) );
371        if ( !$pageIds ) {
372            return [];
373        }
374        return $this->fetchDbKeysByPageId( $this->pageStore->newSelectQueryBuilder()->wherePageIds( $pageIds ) );
375    }
376
377    /**
378     * @param PageSelectQueryBuilder $query
379     * @return string[]
380     */
381    private function fetchDbKeysByPageId( PageSelectQueryBuilder $query ): array {
382        $dbKeys = [];
383        foreach ( $query->fetchPageRecords() as $record ) {
384            $dbKeys[$record->getId()] = $this->titleFormatter->getPrefixedDBkey( $record );
385        }
386        return $dbKeys;
387    }
388
389    /**
390     * Match the page title as the Google tag sends it in page_title, or as GA4 took it from the
391     * document title, "<page> - <site name>", before the tag sent page_title. The separator
392     * depends on the interface language. This does not match a document title from a page with
393     * {{DISPLAYTITLE:}}, from the main page or from a customized MediaWiki:Pagetitle.
394     *
395     * @param string $prefixedText The page as TitleFormatter::getPrefixedText() gives it
396     * @return string A regular expression in the RE2 syntax GA4 uses
397     */
398    private function getPageTitleRegex( string $prefixedText ): string {
399        return preg_quote( $prefixedText ) .
400            '( ' . self::SITE_NAME_SEPARATOR . ' ' . preg_quote( $this->siteName ) . ')?';
401    }
402
403    /**
404     * @param string $title A page title, or a document title "<page> - <site name>"
405     * @return string The page part
406     */
407    private function stripSiteName( string $title ): string {
408        return preg_replace(
409            '/ ' . self::SITE_NAME_SEPARATOR . ' ' . preg_quote( $this->siteName, '/' ) . '$/u', '', $title
410        ) ?? $title;
411    }
412
413    /**
414     * @param string $date YYYYMMDD
415     * @return string YYYY-MM-DD
416     */
417    private static function formatDate( string $date ): string {
418        return substr( $date, 0, 4 ) . '-' . substr( $date, 4, 2 ) . '-' . substr( $date, 6, 2 );
419    }
420
421    /**
422     * The days to report, in the wiki's time zone. The current day is left out, as only partial
423     * information is available for it.
424     *
425     * @param int $days
426     * @return string[] YYYY-MM-DD, oldest first, ending with yesterday
427     */
428    private function getDates( int $days ): array {
429        $dates = [];
430        for ( $i = $days; $i >= 1; $i-- ) {
431            $dates[] = date( 'Y-m-d', strtotime( "today -$i days" ) );
432        }
433        return $dates;
434    }
435}