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