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