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