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