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