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