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