141888cda6e2a241de1791caee6275826696a347
[lhc/web/wiklou.git] / includes / deferred / LinksUpdate.php
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 use Wikimedia\Rdbms\IDatabase;
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
26
27 /**
28 * Class the manages updates of *_link tables as well as similar extension-managed tables
29 *
30 * @note: LinksUpdate is managed by DeferredUpdates::execute(). Do not run this in a transaction.
31 *
32 * See docs/deferred.txt
33 */
34 class LinksUpdate extends DataUpdate implements EnqueueableDataUpdate {
35 // @todo make members protected, but make sure extensions don't break
36
37 /** @var int Page ID of the article linked from */
38 public $mId;
39
40 /** @var Title Title object of the article linked from */
41 public $mTitle;
42
43 /** @var ParserOutput */
44 public $mParserOutput;
45
46 /** @var array Map of title strings to IDs for the links in the document */
47 public $mLinks;
48
49 /** @var array DB keys of the images used, in the array key only */
50 public $mImages;
51
52 /** @var array Map of title strings to IDs for the template references, including broken ones */
53 public $mTemplates;
54
55 /** @var array URLs of external links, array key only */
56 public $mExternals;
57
58 /** @var array Map of category names to sort keys */
59 public $mCategories;
60
61 /** @var array Map of language codes to titles */
62 public $mInterlangs;
63
64 /** @var array 2-D map of (prefix => DBK => 1) */
65 public $mInterwikis;
66
67 /** @var array Map of arbitrary name to value */
68 public $mProperties;
69
70 /** @var bool Whether to queue jobs for recursive updates */
71 public $mRecursive;
72
73 /** @var Revision Revision for which this update has been triggered */
74 private $mRevision;
75
76 /**
77 * @var null|array Added links if calculated.
78 */
79 private $linkInsertions = null;
80
81 /**
82 * @var null|array Deleted links if calculated.
83 */
84 private $linkDeletions = null;
85
86 /**
87 * @var null|array Added properties if calculated.
88 */
89 private $propertyInsertions = null;
90
91 /**
92 * @var null|array Deleted properties if calculated.
93 */
94 private $propertyDeletions = null;
95
96 /**
97 * @var User|null
98 */
99 private $user;
100
101 /** @var IDatabase */
102 private $db;
103
104 /**
105 * @param Title $title Title of the page we're updating
106 * @param ParserOutput $parserOutput Output from a full parse of this page
107 * @param bool $recursive Queue jobs for recursive updates?
108 * @throws MWException
109 */
110 function __construct( Title $title, ParserOutput $parserOutput, $recursive = true ) {
111 parent::__construct();
112
113 $this->mTitle = $title;
114 $this->mId = $title->getArticleID( Title::GAID_FOR_UPDATE );
115
116 if ( !$this->mId ) {
117 throw new InvalidArgumentException(
118 "The Title object yields no ID. Perhaps the page doesn't exist?"
119 );
120 }
121
122 $this->mParserOutput = $parserOutput;
123
124 $this->mLinks = $parserOutput->getLinks();
125 $this->mImages = $parserOutput->getImages();
126 $this->mTemplates = $parserOutput->getTemplates();
127 $this->mExternals = $parserOutput->getExternalLinks();
128 $this->mCategories = $parserOutput->getCategories();
129 $this->mProperties = $parserOutput->getProperties();
130 $this->mInterwikis = $parserOutput->getInterwikiLinks();
131
132 # Convert the format of the interlanguage links
133 # I didn't want to change it in the ParserOutput, because that array is passed all
134 # the way back to the skin, so either a skin API break would be required, or an
135 # inefficient back-conversion.
136 $ill = $parserOutput->getLanguageLinks();
137 $this->mInterlangs = [];
138 foreach ( $ill as $link ) {
139 list( $key, $title ) = explode( ':', $link, 2 );
140 $this->mInterlangs[$key] = $title;
141 }
142
143 foreach ( $this->mCategories as &$sortkey ) {
144 # If the sortkey is longer then 255 bytes, it is truncated by DB, and then doesn't match
145 # when comparing existing vs current categories, causing T27254.
146 $sortkey = mb_strcut( $sortkey, 0, 255 );
147 }
148
149 $this->mRecursive = $recursive;
150
151 // Avoid PHP 7.1 warning from passing $this by reference
152 $linksUpdate = $this;
153 Hooks::run( 'LinksUpdateConstructed', [ &$linksUpdate ] );
154 }
155
156 /**
157 * Update link tables with outgoing links from an updated article
158 *
159 * @note this is managed by DeferredUpdates::execute(). Do not run this in a transaction.
160 */
161 public function doUpdate() {
162 if ( $this->ticket ) {
163 // Make sure all links update threads see the changes of each other.
164 // This handles the case when updates have to batched into several COMMITs.
165 $scopedLock = self::acquirePageLock( $this->getDB(), $this->mId );
166 }
167
168 // Avoid PHP 7.1 warning from passing $this by reference
169 $linksUpdate = $this;
170 Hooks::run( 'LinksUpdate', [ &$linksUpdate ] );
171 $this->doIncrementalUpdate();
172
173 // Commit and release the lock (if set)
174 ScopedCallback::consume( $scopedLock );
175 // Run post-commit hook handlers without DBO_TRX
176 DeferredUpdates::addUpdate( new AutoCommitUpdate(
177 $this->getDB(),
178 __METHOD__,
179 function () {
180 // Avoid PHP 7.1 warning from passing $this by reference
181 $linksUpdate = $this;
182 Hooks::run( 'LinksUpdateComplete', [ &$linksUpdate, $this->ticket ] );
183 }
184 ) );
185 }
186
187 /**
188 * Acquire a lock for performing link table updates for a page on a DB
189 *
190 * @param IDatabase $dbw
191 * @param int $pageId
192 * @param string $why One of (job, atomicity)
193 * @return ScopedCallback
194 * @throws RuntimeException
195 * @since 1.27
196 */
197 public static function acquirePageLock( IDatabase $dbw, $pageId, $why = 'atomicity' ) {
198 $key = "LinksUpdate:$why:pageid:$pageId";
199 $scopedLock = $dbw->getScopedLockAndFlush( $key, __METHOD__, 15 );
200 if ( !$scopedLock ) {
201 throw new RuntimeException( "Could not acquire lock '$key'." );
202 }
203
204 return $scopedLock;
205 }
206
207 protected function doIncrementalUpdate() {
208 # Page links
209 $existingPL = $this->getExistingLinks();
210 $this->linkDeletions = $this->getLinkDeletions( $existingPL );
211 $this->linkInsertions = $this->getLinkInsertions( $existingPL );
212 $this->incrTableUpdate( 'pagelinks', 'pl', $this->linkDeletions, $this->linkInsertions );
213
214 # Image links
215 $existingIL = $this->getExistingImages();
216 $imageDeletes = $this->getImageDeletions( $existingIL );
217 $this->incrTableUpdate(
218 'imagelinks',
219 'il',
220 $imageDeletes,
221 $this->getImageInsertions( $existingIL ) );
222
223 # Invalidate all image description pages which had links added or removed
224 $imageUpdates = $imageDeletes + array_diff_key( $this->mImages, $existingIL );
225 $this->invalidateImageDescriptions( $imageUpdates );
226
227 # External links
228 $existingEL = $this->getExistingExternals();
229 $this->incrTableUpdate(
230 'externallinks',
231 'el',
232 $this->getExternalDeletions( $existingEL ),
233 $this->getExternalInsertions( $existingEL ) );
234
235 # Language links
236 $existingLL = $this->getExistingInterlangs();
237 $this->incrTableUpdate(
238 'langlinks',
239 'll',
240 $this->getInterlangDeletions( $existingLL ),
241 $this->getInterlangInsertions( $existingLL ) );
242
243 # Inline interwiki links
244 $existingIW = $this->getExistingInterwikis();
245 $this->incrTableUpdate(
246 'iwlinks',
247 'iwl',
248 $this->getInterwikiDeletions( $existingIW ),
249 $this->getInterwikiInsertions( $existingIW ) );
250
251 # Template links
252 $existingTL = $this->getExistingTemplates();
253 $this->incrTableUpdate(
254 'templatelinks',
255 'tl',
256 $this->getTemplateDeletions( $existingTL ),
257 $this->getTemplateInsertions( $existingTL ) );
258
259 # Category links
260 $existingCL = $this->getExistingCategories();
261 $categoryDeletes = $this->getCategoryDeletions( $existingCL );
262 $this->incrTableUpdate(
263 'categorylinks',
264 'cl',
265 $categoryDeletes,
266 $this->getCategoryInsertions( $existingCL ) );
267 $categoryInserts = array_diff_assoc( $this->mCategories, $existingCL );
268 $categoryUpdates = $categoryInserts + $categoryDeletes;
269
270 # Page properties
271 $existingPP = $this->getExistingProperties();
272 $this->propertyDeletions = $this->getPropertyDeletions( $existingPP );
273 $this->incrTableUpdate(
274 'page_props',
275 'pp',
276 $this->propertyDeletions,
277 $this->getPropertyInsertions( $existingPP ) );
278
279 # Invalidate the necessary pages
280 $this->propertyInsertions = array_diff_assoc( $this->mProperties, $existingPP );
281 $changed = $this->propertyDeletions + $this->propertyInsertions;
282 $this->invalidateProperties( $changed );
283
284 # Invalidate all categories which were added, deleted or changed (set symmetric difference)
285 $this->invalidateCategories( $categoryUpdates );
286 $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
287
288 # Refresh links of all pages including this page
289 # This will be in a separate transaction
290 if ( $this->mRecursive ) {
291 $this->queueRecursiveJobs();
292 }
293
294 # Update the links table freshness for this title
295 $this->updateLinksTimestamp();
296 }
297
298 /**
299 * Queue recursive jobs for this page
300 *
301 * Which means do LinksUpdate on all pages that include the current page,
302 * using the job queue.
303 */
304 protected function queueRecursiveJobs() {
305 $action = $this->getCauseAction();
306 $agent = $this->getCauseAgent();
307
308 self::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks', $action, $agent );
309 if ( $this->mTitle->getNamespace() == NS_FILE ) {
310 // Process imagelinks in case the title is or was a redirect
311 self::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks', $action, $agent );
312 }
313
314 $bc = $this->mTitle->getBacklinkCache();
315 // Get jobs for cascade-protected backlinks for a high priority queue.
316 // If meta-templates change to using a new template, the new template
317 // should be implicitly protected as soon as possible, if applicable.
318 // These jobs duplicate a subset of the above ones, but can run sooner.
319 // Which ever runs first generally no-ops the other one.
320 $jobs = [];
321 foreach ( $bc->getCascadeProtectedLinks() as $title ) {
322 $jobs[] = RefreshLinksJob::newPrioritized(
323 $title,
324 [
325 'causeAction' => $action,
326 'causeAgent' => $agent
327 ]
328 );
329 }
330 JobQueueGroup::singleton()->push( $jobs );
331 }
332
333 /**
334 * Queue a RefreshLinks job for any table.
335 *
336 * @param Title $title Title to do job for
337 * @param string $table Table to use (e.g. 'templatelinks')
338 * @param string $action Triggering action
339 * @param string $userName Triggering user name
340 */
341 public static function queueRecursiveJobsForTable(
342 Title $title, $table, $action = 'unknown', $userName = 'unknown'
343 ) {
344 if ( $title->getBacklinkCache()->hasLinks( $table ) ) {
345 $job = new RefreshLinksJob(
346 $title,
347 [
348 'table' => $table,
349 'recursive' => true,
350 ] + Job::newRootJobParams( // "overall" refresh links job info
351 "refreshlinks:{$table}:{$title->getPrefixedText()}"
352 ) + [ 'causeAction' => $action, 'causeAgent' => $userName ]
353 );
354
355 JobQueueGroup::singleton()->push( $job );
356 }
357 }
358
359 /**
360 * @param array $cats
361 */
362 private function invalidateCategories( $cats ) {
363 PurgeJobUtils::invalidatePages( $this->getDB(), NS_CATEGORY, array_keys( $cats ) );
364 }
365
366 /**
367 * Update all the appropriate counts in the category table.
368 * @param array $added Associative array of category name => sort key
369 * @param array $deleted Associative array of category name => sort key
370 */
371 private function updateCategoryCounts( array $added, array $deleted ) {
372 global $wgUpdateRowsPerQuery;
373
374 if ( !$added && !$deleted ) {
375 return;
376 }
377
378 $domainId = $this->getDB()->getDomainID();
379 $wp = WikiPage::factory( $this->mTitle );
380 $lbf = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
381 // T163801: try to release any row locks to reduce contention
382 $lbf->commitAndWaitForReplication( __METHOD__, $this->ticket, [ 'domain' => $domainId ] );
383
384 foreach ( array_chunk( array_keys( $added ), $wgUpdateRowsPerQuery ) as $addBatch ) {
385 $wp->updateCategoryCounts( $addBatch, [], $this->mId );
386 $lbf->commitAndWaitForReplication(
387 __METHOD__, $this->ticket, [ 'domain' => $domainId ] );
388 }
389
390 foreach ( array_chunk( array_keys( $deleted ), $wgUpdateRowsPerQuery ) as $deleteBatch ) {
391 $wp->updateCategoryCounts( [], $deleteBatch, $this->mId );
392 $lbf->commitAndWaitForReplication(
393 __METHOD__, $this->ticket, [ 'domain' => $domainId ] );
394 }
395 }
396
397 /**
398 * @param array $images
399 */
400 private function invalidateImageDescriptions( $images ) {
401 PurgeJobUtils::invalidatePages( $this->getDB(), NS_FILE, array_keys( $images ) );
402 }
403
404 /**
405 * Update a table by doing a delete query then an insert query
406 * @param string $table Table name
407 * @param string $prefix Field name prefix
408 * @param array $deletions
409 * @param array $insertions Rows to insert
410 */
411 private function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
412 $services = MediaWikiServices::getInstance();
413 $bSize = $services->getMainConfig()->get( 'UpdateRowsPerQuery' );
414 $lbf = $services->getDBLoadBalancerFactory();
415
416 if ( $table === 'page_props' ) {
417 $fromField = 'pp_page';
418 } else {
419 $fromField = "{$prefix}_from";
420 }
421
422 $deleteWheres = []; // list of WHERE clause arrays for each DB delete() call
423 if ( $table === 'pagelinks' || $table === 'templatelinks' || $table === 'iwlinks' ) {
424 $baseKey = ( $table === 'iwlinks' ) ? 'iwl_prefix' : "{$prefix}_namespace";
425
426 $curBatchSize = 0;
427 $curDeletionBatch = [];
428 $deletionBatches = [];
429 foreach ( $deletions as $ns => $dbKeys ) {
430 foreach ( $dbKeys as $dbKey => $unused ) {
431 $curDeletionBatch[$ns][$dbKey] = 1;
432 if ( ++$curBatchSize >= $bSize ) {
433 $deletionBatches[] = $curDeletionBatch;
434 $curDeletionBatch = [];
435 $curBatchSize = 0;
436 }
437 }
438 }
439 if ( $curDeletionBatch ) {
440 $deletionBatches[] = $curDeletionBatch;
441 }
442
443 foreach ( $deletionBatches as $deletionBatch ) {
444 $deleteWheres[] = [
445 $fromField => $this->mId,
446 $this->getDB()->makeWhereFrom2d( $deletionBatch, $baseKey, "{$prefix}_title" )
447 ];
448 }
449 } else {
450 if ( $table === 'langlinks' ) {
451 $toField = 'll_lang';
452 } elseif ( $table === 'page_props' ) {
453 $toField = 'pp_propname';
454 } else {
455 $toField = $prefix . '_to';
456 }
457
458 $deletionBatches = array_chunk( array_keys( $deletions ), $bSize );
459 foreach ( $deletionBatches as $deletionBatch ) {
460 $deleteWheres[] = [ $fromField => $this->mId, $toField => $deletionBatch ];
461 }
462 }
463
464 $domainId = $this->getDB()->getDomainID();
465
466 foreach ( $deleteWheres as $deleteWhere ) {
467 $this->getDB()->delete( $table, $deleteWhere, __METHOD__ );
468 $lbf->commitAndWaitForReplication(
469 __METHOD__, $this->ticket, [ 'domain' => $domainId ]
470 );
471 }
472
473 $insertBatches = array_chunk( $insertions, $bSize );
474 foreach ( $insertBatches as $insertBatch ) {
475 $this->getDB()->insert( $table, $insertBatch, __METHOD__, 'IGNORE' );
476 $lbf->commitAndWaitForReplication(
477 __METHOD__, $this->ticket, [ 'domain' => $domainId ]
478 );
479 }
480
481 if ( count( $insertions ) ) {
482 Hooks::run( 'LinksUpdateAfterInsert', [ $this, $table, $insertions ] );
483 }
484 }
485
486 /**
487 * Get an array of pagelinks insertions for passing to the DB
488 * Skips the titles specified by the 2-D array $existing
489 * @param array $existing
490 * @return array
491 */
492 private function getLinkInsertions( $existing = [] ) {
493 $arr = [];
494 foreach ( $this->mLinks as $ns => $dbkeys ) {
495 $diffs = isset( $existing[$ns] )
496 ? array_diff_key( $dbkeys, $existing[$ns] )
497 : $dbkeys;
498 foreach ( $diffs as $dbk => $id ) {
499 $arr[] = [
500 'pl_from' => $this->mId,
501 'pl_from_namespace' => $this->mTitle->getNamespace(),
502 'pl_namespace' => $ns,
503 'pl_title' => $dbk
504 ];
505 }
506 }
507
508 return $arr;
509 }
510
511 /**
512 * Get an array of template insertions. Like getLinkInsertions()
513 * @param array $existing
514 * @return array
515 */
516 private function getTemplateInsertions( $existing = [] ) {
517 $arr = [];
518 foreach ( $this->mTemplates as $ns => $dbkeys ) {
519 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
520 foreach ( $diffs as $dbk => $id ) {
521 $arr[] = [
522 'tl_from' => $this->mId,
523 'tl_from_namespace' => $this->mTitle->getNamespace(),
524 'tl_namespace' => $ns,
525 'tl_title' => $dbk
526 ];
527 }
528 }
529
530 return $arr;
531 }
532
533 /**
534 * Get an array of image insertions
535 * Skips the names specified in $existing
536 * @param array $existing
537 * @return array
538 */
539 private function getImageInsertions( $existing = [] ) {
540 $arr = [];
541 $diffs = array_diff_key( $this->mImages, $existing );
542 foreach ( $diffs as $iname => $dummy ) {
543 $arr[] = [
544 'il_from' => $this->mId,
545 'il_from_namespace' => $this->mTitle->getNamespace(),
546 'il_to' => $iname
547 ];
548 }
549
550 return $arr;
551 }
552
553 /**
554 * Get an array of externallinks insertions. Skips the names specified in $existing
555 * @param array $existing
556 * @return array
557 */
558 private function getExternalInsertions( $existing = [] ) {
559 $arr = [];
560 $diffs = array_diff_key( $this->mExternals, $existing );
561 foreach ( $diffs as $url => $dummy ) {
562 foreach ( wfMakeUrlIndexes( $url ) as $index ) {
563 $arr[] = [
564 'el_from' => $this->mId,
565 'el_to' => $url,
566 'el_index' => $index,
567 'el_index_60' => substr( $index, 0, 60 ),
568 ];
569 }
570 }
571
572 return $arr;
573 }
574
575 /**
576 * Get an array of category insertions
577 *
578 * @param array $existing Mapping existing category names to sort keys. If both
579 * match a link in $this, the link will be omitted from the output
580 *
581 * @return array
582 */
583 private function getCategoryInsertions( $existing = [] ) {
584 global $wgContLang, $wgCategoryCollation;
585 $diffs = array_diff_assoc( $this->mCategories, $existing );
586 $arr = [];
587 foreach ( $diffs as $name => $prefix ) {
588 $nt = Title::makeTitleSafe( NS_CATEGORY, $name );
589 $wgContLang->findVariantLink( $name, $nt, true );
590
591 $type = MWNamespace::getCategoryLinkType( $this->mTitle->getNamespace() );
592
593 # Treat custom sortkeys as a prefix, so that if multiple
594 # things are forced to sort as '*' or something, they'll
595 # sort properly in the category rather than in page_id
596 # order or such.
597 $sortkey = Collation::singleton()->getSortKey(
598 $this->mTitle->getCategorySortkey( $prefix ) );
599
600 $arr[] = [
601 'cl_from' => $this->mId,
602 'cl_to' => $name,
603 'cl_sortkey' => $sortkey,
604 'cl_timestamp' => $this->getDB()->timestamp(),
605 'cl_sortkey_prefix' => $prefix,
606 'cl_collation' => $wgCategoryCollation,
607 'cl_type' => $type,
608 ];
609 }
610
611 return $arr;
612 }
613
614 /**
615 * Get an array of interlanguage link insertions
616 *
617 * @param array $existing Mapping existing language codes to titles
618 *
619 * @return array
620 */
621 private function getInterlangInsertions( $existing = [] ) {
622 $diffs = array_diff_assoc( $this->mInterlangs, $existing );
623 $arr = [];
624 foreach ( $diffs as $lang => $title ) {
625 $arr[] = [
626 'll_from' => $this->mId,
627 'll_lang' => $lang,
628 'll_title' => $title
629 ];
630 }
631
632 return $arr;
633 }
634
635 /**
636 * Get an array of page property insertions
637 * @param array $existing
638 * @return array
639 */
640 function getPropertyInsertions( $existing = [] ) {
641 $diffs = array_diff_assoc( $this->mProperties, $existing );
642
643 $arr = [];
644 foreach ( array_keys( $diffs ) as $name ) {
645 $arr[] = $this->getPagePropRowData( $name );
646 }
647
648 return $arr;
649 }
650
651 /**
652 * Returns an associative array to be used for inserting a row into
653 * the page_props table. Besides the given property name, this will
654 * include the page id from $this->mId and any property value from
655 * $this->mProperties.
656 *
657 * The array returned will include the pp_sortkey field if this
658 * is present in the database (as indicated by $wgPagePropsHaveSortkey).
659 * The sortkey value is currently determined by getPropertySortKeyValue().
660 *
661 * @note this assumes that $this->mProperties[$prop] is defined.
662 *
663 * @param string $prop The name of the property.
664 *
665 * @return array
666 */
667 private function getPagePropRowData( $prop ) {
668 global $wgPagePropsHaveSortkey;
669
670 $value = $this->mProperties[$prop];
671
672 $row = [
673 'pp_page' => $this->mId,
674 'pp_propname' => $prop,
675 'pp_value' => $value,
676 ];
677
678 if ( $wgPagePropsHaveSortkey ) {
679 $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
680 }
681
682 return $row;
683 }
684
685 /**
686 * Determines the sort key for the given property value.
687 * This will return $value if it is a float or int,
688 * 1 or resp. 0 if it is a bool, and null otherwise.
689 *
690 * @note In the future, we may allow the sortkey to be specified explicitly
691 * in ParserOutput::setProperty.
692 *
693 * @param mixed $value
694 *
695 * @return float|null
696 */
697 private function getPropertySortKeyValue( $value ) {
698 if ( is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
699 return floatval( $value );
700 }
701
702 return null;
703 }
704
705 /**
706 * Get an array of interwiki insertions for passing to the DB
707 * Skips the titles specified by the 2-D array $existing
708 * @param array $existing
709 * @return array
710 */
711 private function getInterwikiInsertions( $existing = [] ) {
712 $arr = [];
713 foreach ( $this->mInterwikis as $prefix => $dbkeys ) {
714 $diffs = isset( $existing[$prefix] )
715 ? array_diff_key( $dbkeys, $existing[$prefix] )
716 : $dbkeys;
717
718 foreach ( $diffs as $dbk => $id ) {
719 $arr[] = [
720 'iwl_from' => $this->mId,
721 'iwl_prefix' => $prefix,
722 'iwl_title' => $dbk
723 ];
724 }
725 }
726
727 return $arr;
728 }
729
730 /**
731 * Given an array of existing links, returns those links which are not in $this
732 * and thus should be deleted.
733 * @param array $existing
734 * @return array
735 */
736 private function getLinkDeletions( $existing ) {
737 $del = [];
738 foreach ( $existing as $ns => $dbkeys ) {
739 if ( isset( $this->mLinks[$ns] ) ) {
740 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
741 } else {
742 $del[$ns] = $existing[$ns];
743 }
744 }
745
746 return $del;
747 }
748
749 /**
750 * Given an array of existing templates, returns those templates which are not in $this
751 * and thus should be deleted.
752 * @param array $existing
753 * @return array
754 */
755 private function getTemplateDeletions( $existing ) {
756 $del = [];
757 foreach ( $existing as $ns => $dbkeys ) {
758 if ( isset( $this->mTemplates[$ns] ) ) {
759 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
760 } else {
761 $del[$ns] = $existing[$ns];
762 }
763 }
764
765 return $del;
766 }
767
768 /**
769 * Given an array of existing images, returns those images which are not in $this
770 * and thus should be deleted.
771 * @param array $existing
772 * @return array
773 */
774 private function getImageDeletions( $existing ) {
775 return array_diff_key( $existing, $this->mImages );
776 }
777
778 /**
779 * Given an array of existing external links, returns those links which are not
780 * in $this and thus should be deleted.
781 * @param array $existing
782 * @return array
783 */
784 private function getExternalDeletions( $existing ) {
785 return array_diff_key( $existing, $this->mExternals );
786 }
787
788 /**
789 * Given an array of existing categories, returns those categories which are not in $this
790 * and thus should be deleted.
791 * @param array $existing
792 * @return array
793 */
794 private function getCategoryDeletions( $existing ) {
795 return array_diff_assoc( $existing, $this->mCategories );
796 }
797
798 /**
799 * Given an array of existing interlanguage links, returns those links which are not
800 * in $this and thus should be deleted.
801 * @param array $existing
802 * @return array
803 */
804 private function getInterlangDeletions( $existing ) {
805 return array_diff_assoc( $existing, $this->mInterlangs );
806 }
807
808 /**
809 * Get array of properties which should be deleted.
810 * @param array $existing
811 * @return array
812 */
813 function getPropertyDeletions( $existing ) {
814 return array_diff_assoc( $existing, $this->mProperties );
815 }
816
817 /**
818 * Given an array of existing interwiki links, returns those links which are not in $this
819 * and thus should be deleted.
820 * @param array $existing
821 * @return array
822 */
823 private function getInterwikiDeletions( $existing ) {
824 $del = [];
825 foreach ( $existing as $prefix => $dbkeys ) {
826 if ( isset( $this->mInterwikis[$prefix] ) ) {
827 $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis[$prefix] );
828 } else {
829 $del[$prefix] = $existing[$prefix];
830 }
831 }
832
833 return $del;
834 }
835
836 /**
837 * Get an array of existing links, as a 2-D array
838 *
839 * @return array
840 */
841 private function getExistingLinks() {
842 $res = $this->getDB()->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
843 [ 'pl_from' => $this->mId ], __METHOD__ );
844 $arr = [];
845 foreach ( $res as $row ) {
846 if ( !isset( $arr[$row->pl_namespace] ) ) {
847 $arr[$row->pl_namespace] = [];
848 }
849 $arr[$row->pl_namespace][$row->pl_title] = 1;
850 }
851
852 return $arr;
853 }
854
855 /**
856 * Get an array of existing templates, as a 2-D array
857 *
858 * @return array
859 */
860 private function getExistingTemplates() {
861 $res = $this->getDB()->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
862 [ 'tl_from' => $this->mId ], __METHOD__ );
863 $arr = [];
864 foreach ( $res as $row ) {
865 if ( !isset( $arr[$row->tl_namespace] ) ) {
866 $arr[$row->tl_namespace] = [];
867 }
868 $arr[$row->tl_namespace][$row->tl_title] = 1;
869 }
870
871 return $arr;
872 }
873
874 /**
875 * Get an array of existing images, image names in the keys
876 *
877 * @return array
878 */
879 private function getExistingImages() {
880 $res = $this->getDB()->select( 'imagelinks', [ 'il_to' ],
881 [ 'il_from' => $this->mId ], __METHOD__ );
882 $arr = [];
883 foreach ( $res as $row ) {
884 $arr[$row->il_to] = 1;
885 }
886
887 return $arr;
888 }
889
890 /**
891 * Get an array of existing external links, URLs in the keys
892 *
893 * @return array
894 */
895 private function getExistingExternals() {
896 $res = $this->getDB()->select( 'externallinks', [ 'el_to' ],
897 [ 'el_from' => $this->mId ], __METHOD__ );
898 $arr = [];
899 foreach ( $res as $row ) {
900 $arr[$row->el_to] = 1;
901 }
902
903 return $arr;
904 }
905
906 /**
907 * Get an array of existing categories, with the name in the key and sort key in the value.
908 *
909 * @return array
910 */
911 private function getExistingCategories() {
912 $res = $this->getDB()->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
913 [ 'cl_from' => $this->mId ], __METHOD__ );
914 $arr = [];
915 foreach ( $res as $row ) {
916 $arr[$row->cl_to] = $row->cl_sortkey_prefix;
917 }
918
919 return $arr;
920 }
921
922 /**
923 * Get an array of existing interlanguage links, with the language code in the key and the
924 * title in the value.
925 *
926 * @return array
927 */
928 private function getExistingInterlangs() {
929 $res = $this->getDB()->select( 'langlinks', [ 'll_lang', 'll_title' ],
930 [ 'll_from' => $this->mId ], __METHOD__ );
931 $arr = [];
932 foreach ( $res as $row ) {
933 $arr[$row->ll_lang] = $row->ll_title;
934 }
935
936 return $arr;
937 }
938
939 /**
940 * Get an array of existing inline interwiki links, as a 2-D array
941 * @return array (prefix => array(dbkey => 1))
942 */
943 private function getExistingInterwikis() {
944 $res = $this->getDB()->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
945 [ 'iwl_from' => $this->mId ], __METHOD__ );
946 $arr = [];
947 foreach ( $res as $row ) {
948 if ( !isset( $arr[$row->iwl_prefix] ) ) {
949 $arr[$row->iwl_prefix] = [];
950 }
951 $arr[$row->iwl_prefix][$row->iwl_title] = 1;
952 }
953
954 return $arr;
955 }
956
957 /**
958 * Get an array of existing categories, with the name in the key and sort key in the value.
959 *
960 * @return array Array of property names and values
961 */
962 private function getExistingProperties() {
963 $res = $this->getDB()->select( 'page_props', [ 'pp_propname', 'pp_value' ],
964 [ 'pp_page' => $this->mId ], __METHOD__ );
965 $arr = [];
966 foreach ( $res as $row ) {
967 $arr[$row->pp_propname] = $row->pp_value;
968 }
969
970 return $arr;
971 }
972
973 /**
974 * Return the title object of the page being updated
975 * @return Title
976 */
977 public function getTitle() {
978 return $this->mTitle;
979 }
980
981 /**
982 * Returns parser output
983 * @since 1.19
984 * @return ParserOutput
985 */
986 public function getParserOutput() {
987 return $this->mParserOutput;
988 }
989
990 /**
991 * Return the list of images used as generated by the parser
992 * @return array
993 */
994 public function getImages() {
995 return $this->mImages;
996 }
997
998 /**
999 * Set the revision corresponding to this LinksUpdate
1000 *
1001 * @since 1.27
1002 *
1003 * @param Revision $revision
1004 */
1005 public function setRevision( Revision $revision ) {
1006 $this->mRevision = $revision;
1007 }
1008
1009 /**
1010 * @since 1.28
1011 * @return null|Revision
1012 */
1013 public function getRevision() {
1014 return $this->mRevision;
1015 }
1016
1017 /**
1018 * Set the User who triggered this LinksUpdate
1019 *
1020 * @since 1.27
1021 * @param User $user
1022 */
1023 public function setTriggeringUser( User $user ) {
1024 $this->user = $user;
1025 }
1026
1027 /**
1028 * @since 1.27
1029 * @return null|User
1030 */
1031 public function getTriggeringUser() {
1032 return $this->user;
1033 }
1034
1035 /**
1036 * Invalidate any necessary link lists related to page property changes
1037 * @param array $changed
1038 */
1039 private function invalidateProperties( $changed ) {
1040 global $wgPagePropLinkInvalidations;
1041
1042 foreach ( $changed as $name => $value ) {
1043 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
1044 $inv = $wgPagePropLinkInvalidations[$name];
1045 if ( !is_array( $inv ) ) {
1046 $inv = [ $inv ];
1047 }
1048 foreach ( $inv as $table ) {
1049 DeferredUpdates::addUpdate(
1050 new HTMLCacheUpdate( $this->mTitle, $table, 'page-props' )
1051 );
1052 }
1053 }
1054 }
1055 }
1056
1057 /**
1058 * Fetch page links added by this LinksUpdate. Only available after the update is complete.
1059 * @since 1.22
1060 * @return null|array Array of Titles
1061 */
1062 public function getAddedLinks() {
1063 if ( $this->linkInsertions === null ) {
1064 return null;
1065 }
1066 $result = [];
1067 foreach ( $this->linkInsertions as $insertion ) {
1068 $result[] = Title::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
1069 }
1070
1071 return $result;
1072 }
1073
1074 /**
1075 * Fetch page links removed by this LinksUpdate. Only available after the update is complete.
1076 * @since 1.22
1077 * @return null|array Array of Titles
1078 */
1079 public function getRemovedLinks() {
1080 if ( $this->linkDeletions === null ) {
1081 return null;
1082 }
1083 $result = [];
1084 foreach ( $this->linkDeletions as $ns => $titles ) {
1085 foreach ( $titles as $title => $unused ) {
1086 $result[] = Title::makeTitle( $ns, $title );
1087 }
1088 }
1089
1090 return $result;
1091 }
1092
1093 /**
1094 * Fetch page properties added by this LinksUpdate.
1095 * Only available after the update is complete.
1096 * @since 1.28
1097 * @return null|array
1098 */
1099 public function getAddedProperties() {
1100 return $this->propertyInsertions;
1101 }
1102
1103 /**
1104 * Fetch page properties removed by this LinksUpdate.
1105 * Only available after the update is complete.
1106 * @since 1.28
1107 * @return null|array
1108 */
1109 public function getRemovedProperties() {
1110 return $this->propertyDeletions;
1111 }
1112
1113 /**
1114 * Update links table freshness
1115 */
1116 private function updateLinksTimestamp() {
1117 if ( $this->mId ) {
1118 // The link updates made here only reflect the freshness of the parser output
1119 $timestamp = $this->mParserOutput->getCacheTime();
1120 $this->getDB()->update( 'page',
1121 [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ],
1122 [ 'page_id' => $this->mId ],
1123 __METHOD__
1124 );
1125 }
1126 }
1127
1128 /**
1129 * @return IDatabase
1130 */
1131 private function getDB() {
1132 if ( !$this->db ) {
1133 $this->db = wfGetDB( DB_MASTER );
1134 }
1135
1136 return $this->db;
1137 }
1138
1139 public function getAsJobSpecification() {
1140 if ( $this->user ) {
1141 $userInfo = [
1142 'userId' => $this->user->getId(),
1143 'userName' => $this->user->getName(),
1144 ];
1145 } else {
1146 $userInfo = false;
1147 }
1148
1149 if ( $this->mRevision ) {
1150 $triggeringRevisionId = $this->mRevision->getId();
1151 } else {
1152 $triggeringRevisionId = false;
1153 }
1154
1155 return [
1156 'wiki' => WikiMap::getWikiIdFromDomain( $this->getDB()->getDomainID() ),
1157 'job' => new JobSpecification(
1158 'refreshLinksPrioritized',
1159 [
1160 // Reuse the parser cache if it was saved
1161 'rootJobTimestamp' => $this->mParserOutput->getCacheTime(),
1162 'useRecursiveLinksUpdate' => $this->mRecursive,
1163 'triggeringUser' => $userInfo,
1164 'triggeringRevisionId' => $triggeringRevisionId,
1165 'causeAction' => $this->getCauseAction(),
1166 'causeAgent' => $this->getCauseAgent()
1167 ],
1168 [ 'removeDuplicates' => true ],
1169 $this->getTitle()
1170 )
1171 ];
1172 }
1173 }