Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.53% covered (success)
91.53%
54 / 59
70.00% covered (warning)
70.00%
7 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
EventLogging
93.10% covered (success)
93.10%
54 / 58
70.00% covered (warning)
70.00%
7 / 10
17.09
0.00% covered (danger)
0.00%
0 / 1
 getLogger
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getEventSubmitter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 submit
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sendBeacon
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 logEvent
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
3.00
 serializeEvent
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 schemaValidate
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 sessionInSample
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 encapsulate
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 getLegacyStreamName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * PHP API for logging events.
4 *
5 * @file
6 * @ingroup Extensions
7 * @ingroup EventLogging
8 *
9 * @author Ori Livneh <ori@wikimedia.org>
10 */
11
12namespace MediaWiki\Extension\EventLogging;
13
14use MediaWiki\Deferred\DeferredUpdates;
15use MediaWiki\Extension\EventLogging\EventSubmitter\EventSubmitter;
16use MediaWiki\Extension\EventLogging\Libs\JsonSchemaValidation\JsonSchemaException;
17use MediaWiki\Extension\EventLogging\Libs\JsonSchemaValidation\JsonTreeRef;
18use MediaWiki\Json\FormatJson;
19use MediaWiki\Logger\LoggerFactory;
20use MediaWiki\MediaWikiServices;
21use Psr\Log\LoggerInterface;
22
23class EventLogging {
24
25    /**
26     * Default logger.
27     *
28     * @internal
29     */
30    public static function getLogger(): LoggerInterface {
31        return LoggerFactory::getInstance( 'EventLogging' );
32    }
33
34    private static function getEventSubmitter(): EventSubmitter {
35        return MediaWikiServices::getInstance()->get( 'EventLogging.EventSubmitter' );
36    }
37
38    /**
39     * Submit an event according to the given stream's configuration.
40     *
41     * @param string $streamName
42     * @param array $event
43     * @deprecated since 1.48 Use the Test Kitchen PHP SDK instead, via the
44     * TestKitchen.InstrumentManager service and Instrument::send().
45     * @see https://wikitech.wikimedia.org/wiki/Test_Kitchen/SDK/PHP_SDK
46     */
47    public static function submit(
48        string $streamName,
49        array $event
50    ): void {
51        self::getEventSubmitter()->submit( $streamName, $event );
52    }
53
54    /**
55     * Transfer small data asynchronously using an HTTP POST.
56     * This is meant to match the Navigator.sendBeacon() API.
57     *
58     * @see https://w3c.github.io/beacon/#sec-sendBeacon-method
59     * @param string $url
60     * @param array $data
61     * @return bool
62     * @deprecated use submit with new Event Platform based schemas.
63     */
64    public static function sendBeacon( $url, array $data = [] ) {
65        $fname = __METHOD__;
66        $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
67        $url = $urlUtils->expand( $url, PROTO_INTERNAL ) ?? '';
68        DeferredUpdates::addCallableUpdate( static function () use ( $url, $data, $fname ) {
69            $options = $data ? [ 'postData' => $data ] : [];
70            return MediaWikiServices::getInstance()->getHttpRequestFactory()
71                ->post( $url, $options, $fname );
72        } );
73
74        return true;
75    }
76
77    /**
78     * Legacy EventLogging entrypoint.
79     *
80     * NOTE: For forwards compatibility with Event Platform schemas,
81     * we hijack the wgEventLoggingSchemas revision to encode the
82     * $schema URI. If the value for a schema defined in
83     * EventLoggingSchemas is a string, it is assumed
84     * to be an Event Platform $schema URI, not a MW revision id.
85     * In this case, the event will be POSTed to EventGate.
86     *
87     * @param string $schemaName Schema name.
88     * @param int $revId
89     *        revision ID of schema.  $schemasInfo[$schemaName] will override this.
90     * @param array $eventData
91     *        Map of event keys/vals.
92     *        This is the 'event' field, as provided by the caller,
93     *        not an encapsulated real event.
94     * @param int $options This parameter is deprecated and no longer used.
95     * @return bool Whether the event was logged.
96     * @deprecated use EventLogging::submit() with new Event Platform based schemas.
97     * @see https://wikitech.wikimedia.org/wiki/Event_Platform/Instrumentation_How_To#In_PHP
98     */
99    public static function logEvent( $schemaName, $revId, $eventData, $options = 0 ) {
100        $config = MediaWikiServices::getInstance()->getMainConfig();
101
102        $eventLoggingConfig = Hooks::getEventLoggingConfig( $config );
103        $schemasInfo = $eventLoggingConfig['schemasInfo'];
104        $eventLoggingBaseUri = $eventLoggingConfig['baseUrl'];
105
106        // Get the configured revision id or $schema URI
107        // to use with events of a particular (legacy metawiki) EventLogging schema.
108        // $schemasInfo[$schemaName] overrides passed in $revId.
109        $revisionOrSchemaUri = $schemasInfo[$schemaName] ?? $revId ?? -1;
110
111        // Encapsulate and other event meta data to eventData.
112        $event = self::encapsulate(
113            $schemaName,
114            $revisionOrSchemaUri,
115            $eventData
116        );
117
118        if ( isset( $event['$schema'] ) ) {
119            // Assume that if $schema was set by self::encapsulate(), this
120            // event should be POSTed to EventGate via EventServiceClient submit()
121            self::submit( self::getLegacyStreamName( $schemaName ), $event );
122            return true;
123        } else {
124            // Else this will be sent to the legacy eventlogging backend
125            // via 'sendBeacon' by url encoding the json data into a query parameter.
126            if ( !$eventLoggingBaseUri ) {
127                return false;
128            }
129
130            $json = self::serializeEvent( $event );
131            $url = $eventLoggingBaseUri . '?' . rawurlencode( $json ) . ';';
132
133            return self::sendBeacon( $url );
134        }
135    }
136
137    /**
138     * Converts the encapsulated event from an object to a string.
139     *
140     * @param array $event Encapsulated event
141     * @return string $json
142     */
143    public static function serializeEvent( $event ) {
144        $eventData = $event['event'];
145
146        if ( count( $eventData ) === 0 ) {
147            // Ensure empty events are serialized as '{}' and not '[]'.
148            $eventData = (object)$eventData;
149        }
150        $event['event'] = $eventData;
151
152        // To make the resultant JSON easily extracted from a row of
153        // space-separated values, we replace literal spaces with unicode
154        // escapes. This is permitted by the JSON specs.
155        return str_replace( ' ', '\u0020', FormatJson::encode( $event ) );
156    }
157
158    /**
159     * Validates object against JSON Schema.
160     *
161     * @throws JsonSchemaException If the object fails to validate.
162     * @param array $object Object to be validated.
163     * @param array|null $schema Schema to validate against (default: JSON Schema).
164     * @return bool True.
165     */
166    public static function schemaValidate( $object, $schema = null ) {
167        if ( $schema === null ) {
168            // Default to JSON Schema
169            $json = file_get_contents( dirname( __DIR__ ) . '/schemas/schemaschema.json' );
170            $schema = FormatJson::decode( $json, true );
171        }
172
173        // We depart from the JSON Schema specification in disallowing by default
174        // additional event fields not mentioned in the schema.
175        // See <https://bugzilla.wikimedia.org/show_bug.cgi?id=44454> and
176        // <https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4>.
177        $schema['additionalProperties'] ??= false;
178
179        $root = new JsonTreeRef( $object );
180        $root->attachSchema( $schema );
181        return $root->validate();
182    }
183
184    /**
185     * Randomise inclusion based on population size and a session ID.
186     * @param int $populationSize Return true one in this many times. This is 1/samplingRate.
187     * @param string $sessionId Hexadecimal value, only the first 8 characters are used
188     * @return bool True if the event should be included (sampled in), false if not (sampled out)
189     */
190    public static function sessionInSample( $populationSize, $sessionId ) {
191        $decimal = (int)base_convert( substr( $sessionId, 0, 8 ), 16, 10 );
192        return $decimal % $populationSize === 0;
193    }
194
195    /**
196     * This encapsulates the event data in a wrapper object with
197     * the default metadata for the current request.
198     *
199     * NOTE: for forwards compatibility with Event Platform schemas,
200     * we hijack the wgEventLoggingSchemas revision to encode the
201     * $schema URI. If the value for a schema defined in
202     * EventLoggingSchemas is a string, it is assumed
203     * to be an Event Platform $schema URI, not a MW revision id.
204     * In this case, the event will be prepared to be POSTed to EventGate.
205     *
206     * @param string $schemaName
207     * @param int|string $revisionOrSchemaUri
208     *        The revision id or a string $schema URI for use with Event Platform.
209     * @param array $eventData un-encapsulated event data
210     * @return array encapsulated event
211     */
212    private static function encapsulate( $schemaName, $revisionOrSchemaUri, $eventData ) {
213        global $wgDBname;
214
215        $event = [
216            'event'            => $eventData,
217            'schema'           => $schemaName,
218            'wiki'             => $wgDBname,
219        ];
220
221        if ( isset( $_SERVER[ 'HTTP_HOST' ] ) ) {
222            $event['webHost'] = $_SERVER['HTTP_HOST'];
223        }
224
225        if ( is_string( $revisionOrSchemaUri ) ) {
226            $event['$schema'] = $revisionOrSchemaUri;
227            // NOTE: `client_dt` is 'legacy' event time.  `dt` is the preferred event time field
228            // and is set in EventServiceClient.
229            $event['client_dt'] = wfTimestamp( TS_ISO_8601 );
230
231            // Note: some fields will have defaults set by eventgate-wikimedia.
232            // See:
233            // - https://gerrit.wikimedia.org/r/plugins/gitiles/eventgate-wikimedia/+/refs/heads/master/eventgate-wikimedia.js#358
234            // - https://wikitech.wikimedia.org/wiki/Event_Platform/Schemas/Guidelines#Automatically_populated_fields
235        } else {
236            $event['revision'] = $revisionOrSchemaUri;
237            $event['userAgent'] = $_SERVER[ 'HTTP_USER_AGENT' ] ?? '';
238        }
239
240        return $event;
241    }
242
243    /**
244     * Prepend "eventlogging_" to the schema name to create a stream name for a migrated legacy
245     * schema.
246     *
247     * @param string $schemaName
248     * @return string
249     */
250    private static function getLegacyStreamName( string $schemaName ): string {
251        return "eventlogging_$schemaName";
252    }
253
254}
255
256class_alias( EventLogging::class, 'EventLogging' );