Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.21% covered (warning)
59.21%
135 / 228
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
PagePostSaveHandler
59.21% covered (warning)
59.21%
135 / 228
66.67% covered (warning)
66.67%
2 / 3
155.08
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 onRecentChange_save
58.67% covered (warning)
58.67%
132 / 225
0.00% covered (danger)
0.00%
0 / 1
146.41
 roundTripJson
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * WikiLambda handler for hooks which react to page editing
5 *
6 * @file
7 * @ingroup Extensions
8 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
9 * @license MIT
10 */
11
12namespace MediaWiki\Extension\WikiLambda\HookHandler;
13
14use MediaWiki\Extension\WikiLambda\Diff\ZObjectDiffer;
15use MediaWiki\Extension\WikiLambda\Jobs\WikifunctionsClientFanOutQueueJob;
16use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
17use MediaWiki\Extension\WikiLambda\WikiLambdaMode;
18use MediaWiki\Extension\WikiLambda\ZErrorException;
19use MediaWiki\Extension\WikiLambda\ZObjectContent\ZObjectContent;
20use MediaWiki\Extension\WikiLambda\ZObjectStore;
21use MediaWiki\JobQueue\JobQueueGroup;
22use MediaWiki\Logger\LoggerFactory;
23use MediaWiki\RecentChanges\RecentChange;
24use MediaWiki\Title\Title;
25use MediaWiki\User\CentralId\CentralIdLookupFactory;
26use Psr\Log\LoggerInterface;
27use Wikimedia\Rdbms\IConnectionProvider;
28use Wikimedia\Rdbms\IReadableDatabase;
29
30class PagePostSaveHandler implements
31    \MediaWiki\RecentChanges\Hook\RecentChange_saveHook
32{
33    private IReadableDatabase $dbr;
34    private LoggerInterface $logger;
35
36    public function __construct(
37        IConnectionProvider $dbProvider,
38        private readonly WikiLambdaMode $mode,
39        private readonly ZObjectStore $zObjectStore,
40        private readonly JobQueueGroup $jobQueueGroup,
41        private readonly CentralIdLookupFactory $centralIdLookupFactory
42    ) {
43        // Non-injected items
44        $this->dbr = $dbProvider->getReplicaDatabase();
45        $this->logger = LoggerFactory::getInstance( 'WikiLambda' );
46    }
47
48    /**
49     * @see https://www.mediawiki.org/wiki/Manual:Hooks/RecentChange_save
50     *
51     * @param RecentChange $recentChange
52     * @return bool|void
53     */
54    public function onRecentChange_save( $recentChange ) {
55        // We use this on the repo-mode wiki to create a job that *might* trigger updates to client wikis
56
57        $targetPage = $recentChange->getPage();
58        if (
59            // We're not in repo-mode
60            !$this->mode->isRepo() ||
61            // We're on a page that's not in the main namespace
62            $targetPage->getNamespace() !== NS_MAIN
63        ) {
64            // Nothing for us to do.
65            return;
66        }
67
68        // Start collecting the structured data about the edit that we'll send to client wikis
69        $changeData = [];
70
71        $changeComment = $recentChange->getAttribute( 'rc_comment_text' );
72
73        // If this is a logged action, we only care the edge case of deletions; other kinds, like moves, are irrelevant
74        $logType = $recentChange->getAttribute( 'rc_log_type' );
75        if ( $logType !== null ) {
76            if ( $logType === 'delete' ) {
77                // … and specifically, full page deletions and restorations; revision deletions don't matter, as they
78                // won't ever affect the current revision (so a previous RC entry for the creation of the newer rev will
79                // have been sent to the client wikis).
80                $logAction = $recentChange->getAttribute( 'rc_log_action' );
81                if ( $logAction !== 'restore' && $logAction !== 'delete' ) {
82                    return;
83                }
84                $changeData['action'] = $logAction;
85
86                // We need to look up the comment made for the log entry in this case.
87                $changeId = $recentChange->getAttribute( 'rc_logid' );
88
89                // Ideally we'd get this from the LogFormatterFactory's method, but it appears broken for RC entries:
90                // $changeComment = $this->logFormatterFactory->newFromRow( $recentChange )->getComment();
91
92                // This walks rc_logid => log_id; log_comment_id => comment_id; then returns comment_text
93                $changeComment = $this->dbr->newSelectQueryBuilder()
94                    ->select( [ 'comment_text' ] )
95                    ->from( 'recentchanges' )
96                    ->where( [ 'log_id' => $changeId ] )
97                    ->join( 'logging', null, [ 'rc_logid = log_id' ] )
98                    ->join( 'comment', null, [ 'log_comment_id = comment_id' ] )
99                    ->caller( __METHOD__ )
100                    ->fetchField();
101            }
102        }
103
104        $targetTitle = Title::castFromPageReference( $targetPage );
105        if ( $targetTitle === null ) {
106            // This isn't a valid title, so we don't care.
107            return;
108        }
109
110        $newId = $recentChange->getAttribute( 'rc_this_oldid' );
111        $changeData['newId'] = $newId;
112        $newTargetZObject = $this->zObjectStore->fetchZObjectByTitle( $targetTitle, $newId );
113        if ( !$newTargetZObject || !( $newTargetZObject instanceof ZObjectContent ) ) {
114            // This isn't a ZObject, so we don't care.
115            // var_dump( $newTargetZObject );
116            return;
117        }
118
119        try {
120            $changedObject = $newTargetZObject->getZid();
121            $changeData['target'] = $changedObject;
122            $changeData['type'] = $newTargetZObject->getZType();
123        } catch ( ZErrorException $ze ) {
124            // (T406708): Something's gone wrong; log and exit.
125            $this->logger->error(
126                __METHOD__ . ': Failed to get ZID/Type for {obj} revision {rev}: {message}',
127                [
128                    'obj' => $targetTitle->getDBkey(),
129                    'rev' => $newId,
130                    'exception' => $ze,
131                    'message' => $ze->getMessage(),
132                    'errortype' => $ze->getZErrorType()
133                ]
134            );
135            return;
136        }
137
138        // (T383156): Only act if this is (a) a change to a Function or a linked Imp/Test & (b) the kind we care about.
139        switch ( $changeData['type'] ) {
140            case ZTypeRegistry::Z_FUNCTION:
141                // For consistency, we'll include this even when it's the Function itself that changed
142                $changeData['function'] = $changedObject;
143                $this->logger->debug(
144                    __METHOD__ . ': Handling edit to a Function {obj} revision {rev}',
145                    [
146                        'obj' => $changedObject,
147                        'rev' => $newId
148                    ]
149                );
150                break;
151
152            case ZTypeRegistry::Z_IMPLEMENTATION:
153                $targetFunctionZid = $newTargetZObject->getInnerZObject()->getValueByKey(
154                    ZTypeRegistry::Z_IMPLEMENTATION_FUNCTION
155                )->getZValue();
156
157                $targetContent = $this->zObjectStore->fetchZObjectByTitle( Title::newFromDBkey( $targetFunctionZid ) );
158                if ( !( $targetContent instanceof ZObjectContent ) ) {
159                    // Something has gone wrong; let's exit.
160                    return;
161                }
162                $targetFunction = $targetContent->getInnerZObject();
163                '@phan-var \MediaWiki\Extension\WikiLambda\ZObjects\ZFunction $targetFunction';
164                $approvedImplementations = $targetFunction->getImplementationZids();
165                if ( !in_array( $changedObject, $approvedImplementations ) ) {
166                    // This isn't an approved Implementation, so we don't care.
167                    return;
168                }
169
170                $this->logger->debug(
171                    __METHOD__ . ': Handling edit to a connected Implementation {obj} revision {rev} of Function {fun}',
172                    [
173                        'obj' => $changedObject,
174                        'rev' => $newId,
175                        'fun' => $targetFunctionZid
176                    ]
177                );
178
179                $changeData['function'] = $targetFunctionZid;
180                break;
181
182            case ZTypeRegistry::Z_TESTER:
183                $targetFunctionZid = $newTargetZObject->getInnerZObject()->getValueByKey(
184                    ZTypeRegistry::Z_TESTER_FUNCTION
185                )->getZValue();
186
187                $targetContent = $this->zObjectStore->fetchZObjectByTitle( Title::newFromDBkey( $targetFunctionZid ) );
188                if ( !( $targetContent instanceof ZObjectContent ) ) {
189                    // Something has gone wrong; let's exit.
190                    return;
191                }
192                $targetFunction = $targetContent->getInnerZObject();
193                '@phan-var \MediaWiki\Extension\WikiLambda\ZObjects\ZFunction $targetFunction';
194                $approvedTesters = $targetFunction->getTesterZids();
195                if ( !in_array( $changedObject, $approvedTesters ) ) {
196                    // This isn't an approved Tester, so we don't care.
197                    return;
198                }
199
200                $this->logger->debug(
201                    __METHOD__ . ': Handling edit to a connected Tester {obj} revision {rev} of Function {fun}',
202                    [
203                        'obj' => $changedObject,
204                        'rev' => $newId,
205                        'fun' => $targetFunctionZid
206                    ]
207                );
208
209                $changeData['function'] = $targetFunctionZid;
210                break;
211
212            default:
213                // We only care about certain ZObjects
214                $this->logger->debug(
215                    __METHOD__ . ': Ignoring edit to an irrelevant Object {obj} revision {rev}',
216                    [
217                        'obj' => $changedObject,
218                        'rev' => $newId
219                    ]
220                );
221                return;
222        }
223
224        // Now, we construct the changes that were made in the edit we're being told about.
225        // If we've already decided above that this is a deletion/undeletion, do nothing else.
226        if ( $logType === null ) {
227            // If this has been created, short-circuit
228            if ( $recentChange->getAttribute( 'rc_source' ) === RecentChange::SRC_NEW ) {
229                $changeData['action'] = 'create';
230
231                $this->logger->debug(
232                    __METHOD__ . ': Handled creation of {obj} revision {rev}',
233                    [
234                        'obj' => $changedObject,
235                        'rev' => $newId
236                    ]
237                );
238            } else {
239                $changeData['action'] = 'edit';
240                $changeData['operations'] = [];
241
242                $oldId = $recentChange->getAttribute( 'rc_last_oldid' );
243                if ( !$oldId ) {
244                    // This is a new page, so there's nothing to diff against
245                    $fromContentObject = '';
246                } else {
247                    $fromContentObject = $this->roundTripJson(
248                        $this->zObjectStore->fetchZObjectByTitle( $targetTitle, $oldId )->getObject()
249                    );
250                }
251
252                $toContentObject = $this->roundTripJson( $newTargetZObject->getObject() );
253
254                // TODO (T389090): Consider refactoring the below to use the same code as in ZObjectAuthorization?
255                $differ = new ZObjectDiffer();
256                $diffOps = $differ->doDiff( $fromContentObject, $toContentObject );
257                $flattedDiffOps = ZObjectDiffer::flattenDiff( $diffOps );
258
259                // Filter out irrelevant changes (e.g. label changed)
260                foreach ( $flattedDiffOps as $index => $diffOp ) {
261
262                    $firstPathElement = ( $diffOp['path'] === [] )
263                        // If the edit is a creation, the 'path' will not be useful
264                        ? ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE
265                        : $diffOp['path'][0];
266
267                    $lastPathElement = ( is_numeric( end( $diffOp['path'] ) ) )
268                        // Bump up a layer if this is an array value change
269                        ? $diffOp['path'][count( $diffOp['path'] ) - 2]
270                        : end( $diffOp['path'] );
271
272                    // Discard irrelevant label/alias/etc. changes
273                    if (
274                        // Any changes not to the Z2K2 (e.g. label/alias/short description changes)
275                        ( $firstPathElement !== ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE ) ||
276                        // Any changes to a Z12K1 (i.e. addition/removal of a label or short description)
277                        ( $lastPathElement === ZTypeRegistry::Z_MULTILINGUALSTRING_VALUE ) ||
278                        // Any changes to a Z11K2 (i.e. change of a label or short description)
279                        ( $lastPathElement === ZTypeRegistry::Z_MONOLINGUALSTRING_VALUE ) ||
280                        // Any changes to a Z32K1 (i.e. addition/removal of an alias)
281                        ( $lastPathElement === ZTypeRegistry::Z_MULTILINGUALSTRINGSET_VALUE ) ||
282                        // Any changes to a Z31K2 (i.e. change of an alias)
283                        ( $lastPathElement === ZTypeRegistry::Z_MONOLINGUALSTRINGSET_VALUE )
284                    ) {
285                        // Given the above, we don't care about this change, so skip to the next (if any)
286                        $this->logger->debug(
287                            __METHOD__ . ': Ignoring label-only edit to Object {obj} revision {rev}',
288                            [
289                                'obj' => $changedObject,
290                                'rev' => $newId
291                            ]
292                        );
293
294                        unset( $flattedDiffOps[$index] );
295                        continue;
296                    }
297
298                    // (T383156): At this point we think this is a relevant change, so build structured data about what
299                    // changed (e.g. implementation approved, tester value edited) so it can be sent to client wikis.
300
301                    // Edits to a Function, mostly additions/removals of Implementations or Testers
302                    if ( $newTargetZObject->getZType() === ZTypeRegistry::Z_FUNCTION ) {
303
304                        $changeType = $diffOp['op']->getType();
305
306                        // Note: We don't handle 'copy' operations, as they're invalid in our model
307                        if ( !in_array( $changeType, [ 'add', 'remove', 'change' ] ) ) {
308                            $this->logger->error(
309                                __METHOD__ . ': Unhandled {type} diff operation on {obj} revision {rev}: {diffOp}',
310                                [
311                                    'type' => $changeType,
312                                    'obj' => $changedObject,
313                                    'rev' => $newId,
314                                    'diffOp' => var_export( $diffOp, true )
315                                ]
316                            );
317                            continue;
318                        }
319
320                        if ( $changeType === 'add' ) {
321                            $changeData['operations'][implode( '.', $diffOp['path'] )][$changeType][] =
322                                $diffOp['op']->getNewValue();
323                        }
324
325                        if ( $changeType === 'remove' ) {
326                            $changeData['operations'][implode( '.', $diffOp['path'] )][$changeType][] =
327                                $diffOp['op']->getOldValue();
328                        }
329
330                        if ( $changeType === 'change' ) {
331                            $changeData['operations'][implode( '.', $diffOp['path'] )][$changeType][] = [
332                                $diffOp['op']->getOldValue(),
333                                $diffOp['op']->getNewValue()
334                            ];
335                        }
336
337                        $this->logger->debug(
338                            __METHOD__ . ': Handled Imp/Test approval {type} diff on Function {obj} revision {rev}',
339                            [
340                                'type' => $diffOp['op']->getType(),
341                                'obj' => $changedObject,
342                                'rev' => $newId
343                            ]
344                        );
345
346                        // We've handled this change, so move on to the next
347                        continue;
348                    }
349
350                    if (
351                        // If we're covering a change to a connected Implementation/Tester, we just care that it changed
352                        $newTargetZObject->getZType() === ZTypeRegistry::Z_IMPLEMENTATION ||
353                        $newTargetZObject->getZType() === ZTypeRegistry::Z_TESTER
354                    ) {
355                        $changeData['operations'][$newTargetZObject->getZType()] = implode( '.', $diffOp['path'] );
356
357                        $this->logger->debug(
358                            __METHOD__ . ': Handled edit of approved Imp/Test on {type} {obj} revision {rev}',
359                            [
360                                'type' => $newTargetZObject->getZType(),
361                                'obj' => $changedObject,
362                                'rev' => $newId
363                            ]
364                        );
365
366                        // We've handled this change, so move on to the next
367                        continue;
368                    }
369
370                    $this->logger->error(
371                        __METHOD__ . ': Unhandled diff operation on {changedObject} revision {revision}: {diffOp}',
372                        [
373                            'changedObject' => $changedObject,
374                            'revision' => $newId,
375                            'diffOp' => var_export( $diffOp, true )
376                        ]
377                    );
378                    return;
379                }
380
381                if ( count( $flattedDiffOps ) === 0 ) {
382                    // No relevant changes left after filtering
383                    $this->logger->debug(
384                        __METHOD__ . ': No interesting diff operations on {changedObject} revision {revision}',
385                        [
386                            'changedObject' => $changedObject,
387                            'revision' => $newId
388                        ]
389                    );
390                    return;
391                }
392
393                // TODO (T383156): Add labels for this Function for the UX to render (? all languages)
394            }
395        }
396        $changeData['oldId'] = $oldId ?? 0;
397
398        $performer = $recentChange->getPerformerIdentity();
399        $centralIdLookup = $this->centralIdLookupFactory->getNonLocalLookup();
400        $centralUserId = $centralIdLookup ? $centralIdLookup->centralIdFromLocalUser( $performer ) : 0;
401
402        $generalUpdateJob = new WikifunctionsClientFanOutQueueJob( [
403            'target' => $targetPage->getDBkey(),
404            'timestamp' => $recentChange->getAttribute( 'rc_timestamp' ),
405            'summary' => $changeComment,
406            'data' => $changeData,
407            'centralUserId' => $centralUserId,
408            'bot' => $recentChange->getAttribute( 'rc_bot' ),
409        ] );
410
411        $this->jobQueueGroup->lazyPush( $generalUpdateJob );
412
413        // The return value isn't used, but we return something so we can show in tests that we reached this point
414        return true;
415    }
416
417    /**
418     * Utility function to round-trip data through JSON encoding/decoding
419     *
420     * @param mixed $data
421     * @return array
422     */
423    private function roundTripJson( $data ): array {
424        return json_decode( json_encode( $data ), true );
425    }
426
427}