Debian Codegraph @

includes/deferred/LinksUpdate/LinksUpdate.php

raw symbols SCIP
1 <?php
2 /**
3 * Updater for link tracking tables after a page edit.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Deferred\LinksUpdate;
24
25 use InvalidArgumentException;
26 use Job;
27 use MediaWiki\Cache\BacklinkCache;
28 use MediaWiki\Deferred\AutoCommitUpdate;
29 use MediaWiki\Deferred\DataUpdate;
30 use MediaWiki\Deferred\DeferredUpdates;
31 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
32 use MediaWiki\Logger\LoggerFactory;
33 use MediaWiki\MainConfigNames;
34 use MediaWiki\MediaWikiServices;
35 use MediaWiki\Page\PageIdentity;
36 use MediaWiki\Page\PageReference;
37 use MediaWiki\Page\PageReferenceValue;
38 use MediaWiki\Parser\ParserOutput;
39 use MediaWiki\Revision\RevisionRecord;
40 use MediaWiki\Title\Title;
41 use MediaWiki\User\UserIdentity;
42 use RefreshLinksJob;
43 use RuntimeException;
44 use Wikimedia\Rdbms\IConnectionProvider;
45 use Wikimedia\Rdbms\IDatabase;
46 use Wikimedia\Rdbms\IDBAccessObject;
47 use Wikimedia\ScopedCallback;
48
49 /**
50 * Class the manages updates of *_link tables as well as similar extension-managed tables
51 *
52 * @note: LinksUpdate is managed by DeferredUpdates::execute(). Do not run this in a transaction.
53 *
54 * See docs/deferred.txt
55 */
56 class LinksUpdate extends DataUpdate {
57 use ProtectedHookAccessorTrait;
58
59 /** @var int Page ID of the article linked from */
60 protected $mId;
61
62 /** @var Title Title object of the article linked from */
63 protected $mTitle;
64
65 /** @var ParserOutput */
66 protected $mParserOutput;
67
68 /** @var bool Whether to queue jobs for recursive updates */
69 protected $mRecursive;
70
71 /** @var bool Whether the page's redirect target may have changed in the latest revision */
72 protected $mMaybeRedirectChanged;
73
74 /** @var RevisionRecord Revision for which this update has been triggered */
75 private $mRevisionRecord;
76
77 /**
78 * @var UserIdentity|null
79 */
80 private $user;
81
82 /** @var IDatabase */
83 private $db;
84
85 /** @var LinksTableGroup */
86 private $tableFactory;
87
88 private IConnectionProvider $connectionProvider;
89
90 /**
91 * @param PageIdentity $page The page we're updating
92 * @param ParserOutput $parserOutput Output from a full parse of this page
93 * @param bool $recursive Queue jobs for recursive updates?
94 * @param bool $maybeRedirectChanged True if the page's redirect target may have changed in the
95 * latest revision. If false, this is used as a hint to skip some unnecessary updates.
96 */
97 public function __construct(
98 PageIdentity $page,
99 ParserOutput $parserOutput,
100 $recursive = true,
101 $maybeRedirectChanged = true
102 ) {
103 parent::__construct();
104
105 $this->mTitle = Title::newFromPageIdentity( $page );
106 $this->mParserOutput = $parserOutput;
107 $this->mRecursive = $recursive;
108 $this->mMaybeRedirectChanged = $maybeRedirectChanged;
109
110 $services = MediaWikiServices::getInstance();
111 $config = $services->getMainConfig();
112 $this->tableFactory = new LinksTableGroup(
113 $services->getObjectFactory(),
114 $services->getDBLoadBalancerFactory(),
115 $services->getCollationFactory(),
116 $page,
117 $services->getLinkTargetLookup(),
118 $config->get( MainConfigNames::UpdateRowsPerQuery ),
119 $config->get( MainConfigNames::TempCategoryCollations )
120 );
121 // TODO: this does not have to be called in LinksDeletionUpdate
122 $this->tableFactory->setParserOutput( $parserOutput );
123 $this->connectionProvider = $services->getDBLoadBalancerFactory();
124 }
125
126 public function setTransactionTicket( $ticket ) {
127 parent::setTransactionTicket( $ticket );
128 $this->tableFactory->setTransactionTicket( $ticket );
129 }
130
131 /**
132 * Notify LinksUpdate that a move has just been completed and set the
133 * original title
134 *
135 * @param PageReference $oldPage
136 */
137 public function setMoveDetails( PageReference $oldPage ) {
138 $this->tableFactory->setMoveDetails( $oldPage );
139 }
140
141 /**
142 * Update link tables with outgoing links from an updated article
143 *
144 * @note this is managed by DeferredUpdates::execute(). Do not run this in a transaction.
145 */
146 public function doUpdate() {
147 if ( !$this->mId ) {
148 // NOTE: subclasses may initialize mId directly!
149 $this->mId = $this->mTitle->getArticleID( IDBAccessObject::READ_LATEST );
150 }
151
152 if ( !$this->mId ) {
153 // Probably due to concurrent deletion or renaming of the page
154 $logger = LoggerFactory::getInstance( 'SecondaryDataUpdate' );
155 $logger->warning(
156 'LinksUpdate: The Title object yields no ID. Perhaps the page was deleted?',
157 [
158 'page_title' => $this->mTitle->getPrefixedDBkey(),
159 'cause_action' => $this->getCauseAction(),
160 'cause_agent' => $this->getCauseAgent()
161 ]
162 );
163
164 // nothing to do
165 return;
166 }
167
168 // Do any setup that needs to be done prior to acquiring the lock
169 // Calling getAll() here has the side-effect of calling
170 // LinksUpdateBatch::setParserOutput() on all subclasses, allowing
171 // those methods to also do pre-lock operations.
172 foreach ( $this->tableFactory->getAll() as $table ) {
173 $table->beforeLock();
174 }
175
176 if ( $this->ticket ) {
177 // Make sure all links update threads see the changes of each other.
178 // This handles the case when updates have to batched into several COMMITs.
179 $scopedLock = self::acquirePageLock( $this->getDB(), $this->mId );
180 if ( !$scopedLock ) {
181 throw new RuntimeException( "Could not acquire lock for page ID '{$this->mId}'." );
182 }
183 }
184
185 $this->getHookRunner()->onLinksUpdate( $this );
186 $this->doIncrementalUpdate();
187
188 // Commit and release the lock (if set)
189 ScopedCallback::consume( $scopedLock );
190 // Run post-commit hook handlers without DBO_TRX
191 DeferredUpdates::addUpdate( new AutoCommitUpdate(
192 $this->getDB(),
193 __METHOD__,
194 function () {
195 $this->getHookRunner()->onLinksUpdateComplete( $this, $this->ticket );
196 }
197 ) );
198 }
199
200 /**
201 * Acquire a session-level lock for performing link table updates for a page on a DB
202 *
203 * @param IDatabase $dbw
204 * @param int $pageId
205 * @param string $why One of (job, atomicity)
206 * @return ScopedCallback|null
207 * @since 1.27
208 */
209 public static function acquirePageLock( IDatabase $dbw, $pageId, $why = 'atomicity' ) {
210 $key = "{$dbw->getDomainID()}:LinksUpdate:$why:pageid:$pageId"; // per-wiki
211 $scopedLock = $dbw->getScopedLockAndFlush( $key, __METHOD__, 15 );
212 if ( !$scopedLock ) {
213 $logger = LoggerFactory::getInstance( 'SecondaryDataUpdate' );
214 $logger->info( "Could not acquire lock '{key}' for page ID '{page_id}'.", [
215 'key' => $key,
216 'page_id' => $pageId,
217 ] );
218 return null;
219 }
220
221 return $scopedLock;
222 }
223
224 protected function doIncrementalUpdate() {
225 foreach ( $this->tableFactory->getAll() as $table ) {
226 $table->update();
227 }
228
229 # Refresh links of all pages including this page
230 # This will be in a separate transaction
231 if ( $this->mRecursive ) {
232 $this->queueRecursiveJobs();
233 }
234
235 # Update the links table freshness for this title
236 $this->updateLinksTimestamp();
237 }
238
239 /**
240 * Queue recursive jobs for this page
241 *
242 * Which means do LinksUpdate on all pages that include the current page,
243 * using the job queue.
244 */
245 protected function queueRecursiveJobs() {
246 $services = MediaWikiServices::getInstance();
247 $backlinkCache = $services->getBacklinkCacheFactory()
248 ->getBacklinkCache( $this->mTitle );
249 $action = $this->getCauseAction();
250 $agent = $this->getCauseAgent();
251
252 self::queueRecursiveJobsForTable(
253 $this->mTitle, 'templatelinks', $action, $agent, $backlinkCache
254 );
255 if ( $this->mMaybeRedirectChanged && $this->mTitle->getNamespace() === NS_FILE ) {
256 // Process imagelinks in case the redirect target has changed
257 self::queueRecursiveJobsForTable(
258 $this->mTitle, 'imagelinks', $action, $agent, $backlinkCache
259 );
260 }
261
262 // Get jobs for cascade-protected backlinks for a high priority queue.
263 // If meta-templates change to using a new template, the new template
264 // should be implicitly protected as soon as possible, if applicable.
265 // These jobs duplicate a subset of the above ones, but can run sooner.
266 // Which ever runs first generally no-ops the other one.
267 $jobs = [];
268 foreach ( $backlinkCache->getCascadeProtectedLinkPages() as $page ) {
269 $jobs[] = RefreshLinksJob::newPrioritized(
270 $page,
271 [
272 'causeAction' => $action,
273 'causeAgent' => $agent
274 ]
275 );
276 }
277 $services->getJobQueueGroup()->push( $jobs );
278 }
279
280 /**
281 * Queue a RefreshLinks job for any table.
282 *
283 * @param PageIdentity $page Page to do job for
284 * @param string $table Table to use (e.g. 'templatelinks')
285 * @param string $action Triggering action
286 * @param string $userName Triggering user name
287 * @param BacklinkCache|null $backlinkCache
288 */
289 public static function queueRecursiveJobsForTable(
290 PageIdentity $page, $table, $action = 'LinksUpdate', $userName = 'unknown', ?BacklinkCache $backlinkCache = null
291 ) {
292 $title = Title::newFromPageIdentity( $page );
293 if ( !$backlinkCache ) {
294 wfDeprecatedMsg( __METHOD__ . " needs a BacklinkCache object, null passed", '1.37' );
295 $backlinkCache = MediaWikiServices::getInstance()->getBacklinkCacheFactory()
296 ->getBacklinkCache( $title );
297 }
298 if ( $backlinkCache->hasLinks( $table ) ) {
299 $job = new RefreshLinksJob(
300 $title,
301 [
302 'table' => $table,
303 'recursive' => true,
304 ] + Job::newRootJobParams( // "overall" refresh links job info
305 "refreshlinks:{$table}:{$title->getPrefixedText()}"
306 ) + [ 'causeAction' => $action, 'causeAgent' => $userName ]
307 );
308
309 MediaWikiServices::getInstance()->getJobQueueGroup()->push( $job );
310 }
311 }
312
313 /**
314 * Omit conflict resolution options from the insert query so that testing
315 * can confirm that the incremental update logic was correct.
316 *
317 * @param bool $mode
318 */
319 public function setStrictTestMode( $mode = true ) {
320 $this->tableFactory->setStrictTestMode( $mode );
321 }
322
323 /**
324 * Return the title object of the page being updated
325 * @return Title
326 */
327 public function getTitle() {
328 return $this->mTitle;
329 }
330
331 /**
332 * Get the page_id of the page being updated
333 *
334 * @since 1.38
335 * @return int
336 */
337 public function getPageId() {
338 if ( $this->mId ) {
339 return $this->mId;
340 } else {
341 return $this->mTitle->getArticleID();
342 }
343 }
344
345 /**
346 * Returns parser output
347 * @since 1.19
348 * @return ParserOutput
349 */
350 public function getParserOutput() {
351 return $this->mParserOutput;
352 }
353
354 /**
355 * Return the list of images used as generated by the parser
356 * @return array
357 */
358 public function getImages() {
359 return $this->getParserOutput()->getImages();
360 }
361
362 /**
363 * Set the RevisionRecord corresponding to this LinksUpdate
364 *
365 * @since 1.35
366 * @param RevisionRecord $revisionRecord
367 */
368 public function setRevisionRecord( RevisionRecord $revisionRecord ) {
369 $this->mRevisionRecord = $revisionRecord;
370 $this->tableFactory->setRevision( $revisionRecord );
371 }
372
373 /**
374 * @since 1.35
375 * @return RevisionRecord|null
376 */
377 public function getRevisionRecord() {
378 return $this->mRevisionRecord;
379 }
380
381 /**
382 * Set the user who triggered this LinksUpdate
383 *
384 * @since 1.27
385 * @param UserIdentity $user
386 */
387 public function setTriggeringUser( UserIdentity $user ) {
388 $this->user = $user;
389 }
390
391 /**
392 * Get the user who triggered this LinksUpdate
393 *
394 * @since 1.27
395 * @return UserIdentity|null
396 */
397 public function getTriggeringUser(): ?UserIdentity {
398 return $this->user;
399 }
400
401 /**
402 * @return PageLinksTable
403 */
404 protected function getPageLinksTable(): PageLinksTable {
405 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
406 return $this->tableFactory->get( 'pagelinks' );
407 }
408
409 /**
410 * @return ExternalLinksTable
411 */
412 protected function getExternalLinksTable(): ExternalLinksTable {
413 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
414 return $this->tableFactory->get( 'externallinks' );
415 }
416
417 /**
418 * @return PagePropsTable
419 */
420 protected function getPagePropsTable(): PagePropsTable {
421 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
422 return $this->tableFactory->get( 'page_props' );
423 }
424
425 /**
426 * Fetch page links added by this LinksUpdate. Only available after the update is complete.
427 *
428 * @since 1.22
429 * @deprecated since 1.38 use getPageReferenceIterator() or getPageReferenceArray(), hard-deprecated since 1.43
430 * @return Title[] Array of Titles
431 */
432 public function getAddedLinks() {
433 wfDeprecated( __METHOD__, '1.43' );
434 return $this->getPageLinksTable()->getTitleArray( LinksTable::INSERTED );
435 }
436
437 /**
438 * Fetch page links removed by this LinksUpdate. Only available after the update is complete.
439 *
440 * @since 1.22
441 * @deprecated since 1.38 use getPageReferenceIterator() or getPageReferenceArray(), hard-deprecated since 1.43
442 * @return Title[] Array of Titles
443 */
444 public function getRemovedLinks() {
445 wfDeprecated( __METHOD__, '1.43' );
446 return $this->getPageLinksTable()->getTitleArray( LinksTable::DELETED );
447 }
448
449 /**
450 * Fetch external links added by this LinksUpdate. Only available after
451 * the update is complete.
452 * @since 1.33
453 * @return null|array Array of Strings
454 */
455 public function getAddedExternalLinks() {
456 return $this->getExternalLinksTable()->getStringArray( LinksTable::INSERTED );
457 }
458
459 /**
460 * Fetch external links removed by this LinksUpdate. Only available after
461 * the update is complete.
462 * @since 1.33
463 * @return null|string[]
464 */
465 public function getRemovedExternalLinks() {
466 return $this->getExternalLinksTable()->getStringArray( LinksTable::DELETED );
467 }
468
469 /**
470 * Fetch page properties added by this LinksUpdate.
471 * Only available after the update is complete.
472 * @since 1.28
473 * @return null|array
474 */
475 public function getAddedProperties() {
476 return $this->getPagePropsTable()->getAssocArray( LinksTable::INSERTED );
477 }
478
479 /**
480 * Fetch page properties removed by this LinksUpdate.
481 * Only available after the update is complete.
482 * @since 1.28
483 * @return null|array
484 */
485 public function getRemovedProperties() {
486 return $this->getPagePropsTable()->getAssocArray( LinksTable::DELETED );
487 }
488
489 /**
490 * Get an iterator over PageReferenceValue objects corresponding to a given set
491 * type in a given table.
492 *
493 * @since 1.38
494 * @param string $tableName The name of any table that links to local titles
495 * @param int $setType One of:
496 * - LinksTable::INSERTED: The inserted links
497 * - LinksTable::DELETED: The deleted links
498 * - LinksTable::CHANGED: Both the inserted and deleted links
499 * - LinksTable::OLD: The old set of links, loaded before the update
500 * - LinksTable::NEW: The new set of links from the ParserOutput
501 * @return iterable<PageReferenceValue>
502 * @phan-return \Traversable
503 */
504 public function getPageReferenceIterator( $tableName, $setType ) {
505 $table = $this->tableFactory->get( $tableName );
506 if ( $table instanceof TitleLinksTable ) {
507 return $table->getPageReferenceIterator( $setType );
508 } else {
509 throw new InvalidArgumentException(
510 __METHOD__ . ": $tableName does not have a list of titles" );
511 }
512 }
513
514 /**
515 * Same as getPageReferenceIterator() but converted to an array for convenience
516 * (at the expense of additional time and memory usage)
517 *
518 * @since 1.38
519 * @param string $tableName
520 * @param int $setType
521 * @return PageReferenceValue[]
522 */
523 public function getPageReferenceArray( $tableName, $setType ) {
524 return iterator_to_array( $this->getPageReferenceIterator( $tableName, $setType ) );
525 }
526
527 /**
528 * Update links table freshness
529 */
530 protected function updateLinksTimestamp() {
531 if ( $this->mId ) {
532 // The link updates made here only reflect the freshness of the parser output
533 $timestamp = $this->mParserOutput->getCacheTime();
534 $this->getDB()->newUpdateQueryBuilder()
535 ->update( 'page' )
536 ->set( [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ] )
537 ->where( [ 'page_id' => $this->mId ] )
538 ->caller( __METHOD__ )->execute();
539 }
540 }
541
542 /**
543 * @return IDatabase
544 */
545 protected function getDB() {
546 if ( !$this->db ) {
547 $this->db = $this->connectionProvider->getPrimaryDatabase();
548 }
549
550 return $this->db;
551 }
552
553 /**
554 * Whether or not this LinksUpdate will also update pages which transclude the
555 * current page or otherwise depend on it.
556 *
557 * @return bool
558 */
559 public function isRecursive() {
560 return $this->mRecursive;
561 }
562 }