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