3 * Updater for link tracking tables after a page edit.
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.
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.
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
23 use Wikimedia\Rdbms\IDatabase
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use Wikimedia\ScopedCallback
;
29 * Class the manages updates of *_link tables as well as similar extension-managed tables
31 * @note: LinksUpdate is managed by DeferredUpdates::execute(). Do not run this in a transaction.
33 * See docs/deferred.txt
35 class LinksUpdate
extends DataUpdate
implements EnqueueableDataUpdate
{
36 // @todo make members protected, but make sure extensions don't break
38 /** @var int Page ID of the article linked from */
41 /** @var Title Title object of the article linked from */
44 /** @var ParserOutput */
45 public $mParserOutput;
47 /** @var array Map of title strings to IDs for the links in the document */
50 /** @var array DB keys of the images used, in the array key only */
53 /** @var array Map of title strings to IDs for the template references, including broken ones */
56 /** @var array URLs of external links, array key only */
59 /** @var array Map of category names to sort keys */
62 /** @var array Map of language codes to titles */
65 /** @var array 2-D map of (prefix => DBK => 1) */
68 /** @var array Map of arbitrary name to value */
71 /** @var bool Whether to queue jobs for recursive updates */
74 /** @var Revision Revision for which this update has been triggered */
78 * @var null|array Added links if calculated.
80 private $linkInsertions = null;
83 * @var null|array Deleted links if calculated.
85 private $linkDeletions = null;
88 * @var null|array Added external links if calculated.
90 private $externalLinkInsertions = null;
93 * @var null|array Deleted external links if calculated.
95 private $externalLinkDeletions = null;
98 * @var null|array Added properties if calculated.
100 private $propertyInsertions = null;
103 * @var null|array Deleted properties if calculated.
105 private $propertyDeletions = null;
112 /** @var IDatabase */
116 * @param Title $title Title of the page we're updating
117 * @param ParserOutput $parserOutput Output from a full parse of this page
118 * @param bool $recursive Queue jobs for recursive updates?
119 * @throws MWException
121 function __construct( Title
$title, ParserOutput
$parserOutput, $recursive = true ) {
122 parent
::__construct();
124 $this->mTitle
= $title;
127 // NOTE: subclasses may initialize mId before calling this constructor!
128 $this->mId
= $title->getArticleID( Title
::GAID_FOR_UPDATE
);
132 throw new InvalidArgumentException(
133 "The Title object yields no ID. Perhaps the page doesn't exist?"
137 $this->mParserOutput
= $parserOutput;
139 $this->mLinks
= $parserOutput->getLinks();
140 $this->mImages
= $parserOutput->getImages();
141 $this->mTemplates
= $parserOutput->getTemplates();
142 $this->mExternals
= $parserOutput->getExternalLinks();
143 $this->mCategories
= $parserOutput->getCategories();
144 $this->mProperties
= $parserOutput->getProperties();
145 $this->mInterwikis
= $parserOutput->getInterwikiLinks();
147 # Convert the format of the interlanguage links
148 # I didn't want to change it in the ParserOutput, because that array is passed all
149 # the way back to the skin, so either a skin API break would be required, or an
150 # inefficient back-conversion.
151 $ill = $parserOutput->getLanguageLinks();
152 $this->mInterlangs
= [];
153 foreach ( $ill as $link ) {
154 list( $key, $title ) = explode( ':', $link, 2 );
155 $this->mInterlangs
[$key] = $title;
158 foreach ( $this->mCategories
as &$sortkey ) {
159 # If the sortkey is longer then 255 bytes, it is truncated by DB, and then doesn't match
160 # when comparing existing vs current categories, causing T27254.
161 $sortkey = mb_strcut( $sortkey, 0, 255 );
164 $this->mRecursive
= $recursive;
166 // Avoid PHP 7.1 warning from passing $this by reference
167 $linksUpdate = $this;
168 Hooks
::run( 'LinksUpdateConstructed', [ &$linksUpdate ] );
172 * Update link tables with outgoing links from an updated article
174 * @note this is managed by DeferredUpdates::execute(). Do not run this in a transaction.
176 public function doUpdate() {
177 if ( $this->ticket
) {
178 // Make sure all links update threads see the changes of each other.
179 // This handles the case when updates have to batched into several COMMITs.
180 $scopedLock = self
::acquirePageLock( $this->getDB(), $this->mId
);
181 if ( !$scopedLock ) {
182 throw new RuntimeException( "Could not acquire lock for page ID '{$this->mId}'." );
186 // Avoid PHP 7.1 warning from passing $this by reference
187 $linksUpdate = $this;
188 Hooks
::run( 'LinksUpdate', [ &$linksUpdate ] );
189 $this->doIncrementalUpdate();
191 // Commit and release the lock (if set)
192 ScopedCallback
::consume( $scopedLock );
193 // Run post-commit hook handlers without DBO_TRX
194 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
198 // Avoid PHP 7.1 warning from passing $this by reference
199 $linksUpdate = $this;
200 Hooks
::run( 'LinksUpdateComplete', [ &$linksUpdate, $this->ticket
] );
206 * Acquire a lock for performing link table updates for a page on a DB
208 * @param IDatabase $dbw
210 * @param string $why One of (job, atomicity)
211 * @return ScopedCallback|null
214 public static function acquirePageLock( IDatabase
$dbw, $pageId, $why = 'atomicity' ) {
215 $key = "LinksUpdate:$why:pageid:$pageId";
216 $scopedLock = $dbw->getScopedLockAndFlush( $key, __METHOD__
, 15 );
217 if ( !$scopedLock ) {
218 $logger = LoggerFactory
::getInstance( 'SecondaryDataUpdate' );
219 $logger->info( "Could not acquire lock '{key}' for page ID '{page_id}'.", [
221 'page_id' => $pageId,
229 protected function doIncrementalUpdate() {
231 $existingPL = $this->getExistingLinks();
232 $this->linkDeletions
= $this->getLinkDeletions( $existingPL );
233 $this->linkInsertions
= $this->getLinkInsertions( $existingPL );
234 $this->incrTableUpdate( 'pagelinks', 'pl', $this->linkDeletions
, $this->linkInsertions
);
237 $existingIL = $this->getExistingImages();
238 $imageDeletes = $this->getImageDeletions( $existingIL );
239 $this->incrTableUpdate(
243 $this->getImageInsertions( $existingIL ) );
245 # Invalidate all image description pages which had links added or removed
246 $imageUpdates = $imageDeletes +
array_diff_key( $this->mImages
, $existingIL );
247 $this->invalidateImageDescriptions( $imageUpdates );
250 $existingEL = $this->getExistingExternals();
251 $this->externalLinkDeletions
= $this->getExternalDeletions( $existingEL );
252 $this->externalLinkInsertions
= $this->getExternalInsertions(
254 $this->incrTableUpdate(
257 $this->externalLinkDeletions
,
258 $this->externalLinkInsertions
);
261 $existingLL = $this->getExistingInterlangs();
262 $this->incrTableUpdate(
265 $this->getInterlangDeletions( $existingLL ),
266 $this->getInterlangInsertions( $existingLL ) );
268 # Inline interwiki links
269 $existingIW = $this->getExistingInterwikis();
270 $this->incrTableUpdate(
273 $this->getInterwikiDeletions( $existingIW ),
274 $this->getInterwikiInsertions( $existingIW ) );
277 $existingTL = $this->getExistingTemplates();
278 $this->incrTableUpdate(
281 $this->getTemplateDeletions( $existingTL ),
282 $this->getTemplateInsertions( $existingTL ) );
285 $existingCL = $this->getExistingCategories();
286 $categoryDeletes = $this->getCategoryDeletions( $existingCL );
287 $this->incrTableUpdate(
291 $this->getCategoryInsertions( $existingCL ) );
292 $categoryInserts = array_diff_assoc( $this->mCategories
, $existingCL );
293 $categoryUpdates = $categoryInserts +
$categoryDeletes;
296 $existingPP = $this->getExistingProperties();
297 $this->propertyDeletions
= $this->getPropertyDeletions( $existingPP );
298 $this->incrTableUpdate(
301 $this->propertyDeletions
,
302 $this->getPropertyInsertions( $existingPP ) );
304 # Invalidate the necessary pages
305 $this->propertyInsertions
= array_diff_assoc( $this->mProperties
, $existingPP );
306 $changed = $this->propertyDeletions +
$this->propertyInsertions
;
307 $this->invalidateProperties( $changed );
309 # Invalidate all categories which were added, deleted or changed (set symmetric difference)
310 $this->invalidateCategories( $categoryUpdates );
311 $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
313 # Refresh links of all pages including this page
314 # This will be in a separate transaction
315 if ( $this->mRecursive
) {
316 $this->queueRecursiveJobs();
319 # Update the links table freshness for this title
320 $this->updateLinksTimestamp();
324 * Queue recursive jobs for this page
326 * Which means do LinksUpdate on all pages that include the current page,
327 * using the job queue.
329 protected function queueRecursiveJobs() {
330 $action = $this->getCauseAction();
331 $agent = $this->getCauseAgent();
333 self
::queueRecursiveJobsForTable( $this->mTitle
, 'templatelinks', $action, $agent );
334 if ( $this->mTitle
->getNamespace() == NS_FILE
) {
335 // Process imagelinks in case the title is or was a redirect
336 self
::queueRecursiveJobsForTable( $this->mTitle
, 'imagelinks', $action, $agent );
339 $bc = $this->mTitle
->getBacklinkCache();
340 // Get jobs for cascade-protected backlinks for a high priority queue.
341 // If meta-templates change to using a new template, the new template
342 // should be implicitly protected as soon as possible, if applicable.
343 // These jobs duplicate a subset of the above ones, but can run sooner.
344 // Which ever runs first generally no-ops the other one.
346 foreach ( $bc->getCascadeProtectedLinks() as $title ) {
347 $jobs[] = RefreshLinksJob
::newPrioritized(
350 'causeAction' => $action,
351 'causeAgent' => $agent
355 JobQueueGroup
::singleton()->push( $jobs );
359 * Queue a RefreshLinks job for any table.
361 * @param Title $title Title to do job for
362 * @param string $table Table to use (e.g. 'templatelinks')
363 * @param string $action Triggering action
364 * @param string $userName Triggering user name
366 public static function queueRecursiveJobsForTable(
367 Title
$title, $table, $action = 'unknown', $userName = 'unknown'
369 if ( $title->getBacklinkCache()->hasLinks( $table ) ) {
370 $job = new RefreshLinksJob(
375 ] + Job
::newRootJobParams( // "overall" refresh links job info
376 "refreshlinks:{$table}:{$title->getPrefixedText()}"
377 ) +
[ 'causeAction' => $action, 'causeAgent' => $userName ]
380 JobQueueGroup
::singleton()->push( $job );
387 private function invalidateCategories( $cats ) {
388 PurgeJobUtils
::invalidatePages( $this->getDB(), NS_CATEGORY
, array_keys( $cats ) );
392 * Update all the appropriate counts in the category table.
393 * @param array $added Associative array of category name => sort key
394 * @param array $deleted Associative array of category name => sort key
396 private function updateCategoryCounts( array $added, array $deleted ) {
397 global $wgUpdateRowsPerQuery;
399 if ( !$added && !$deleted ) {
403 $domainId = $this->getDB()->getDomainID();
404 $wp = WikiPage
::factory( $this->mTitle
);
405 $lbf = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
406 // T163801: try to release any row locks to reduce contention
407 $lbf->commitAndWaitForReplication( __METHOD__
, $this->ticket
, [ 'domain' => $domainId ] );
409 foreach ( array_chunk( array_keys( $added ), $wgUpdateRowsPerQuery ) as $addBatch ) {
410 $wp->updateCategoryCounts( $addBatch, [], $this->mId
);
411 $lbf->commitAndWaitForReplication(
412 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ] );
415 foreach ( array_chunk( array_keys( $deleted ), $wgUpdateRowsPerQuery ) as $deleteBatch ) {
416 $wp->updateCategoryCounts( [], $deleteBatch, $this->mId
);
417 $lbf->commitAndWaitForReplication(
418 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ] );
423 * @param array $images
425 private function invalidateImageDescriptions( array $images ) {
426 PurgeJobUtils
::invalidatePages( $this->getDB(), NS_FILE
, array_keys( $images ) );
430 * Update a table by doing a delete query then an insert query
431 * @param string $table Table name
432 * @param string $prefix Field name prefix
433 * @param array $deletions
434 * @param array $insertions Rows to insert
436 private function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
437 $services = MediaWikiServices
::getInstance();
438 $bSize = $services->getMainConfig()->get( 'UpdateRowsPerQuery' );
439 $lbf = $services->getDBLoadBalancerFactory();
441 if ( $table === 'page_props' ) {
442 $fromField = 'pp_page';
444 $fromField = "{$prefix}_from";
447 $deleteWheres = []; // list of WHERE clause arrays for each DB delete() call
448 if ( $table === 'pagelinks' ||
$table === 'templatelinks' ||
$table === 'iwlinks' ) {
449 $baseKey = ( $table === 'iwlinks' ) ?
'iwl_prefix' : "{$prefix}_namespace";
452 $curDeletionBatch = [];
453 $deletionBatches = [];
454 foreach ( $deletions as $ns => $dbKeys ) {
455 foreach ( $dbKeys as $dbKey => $unused ) {
456 $curDeletionBatch[$ns][$dbKey] = 1;
457 if ( ++
$curBatchSize >= $bSize ) {
458 $deletionBatches[] = $curDeletionBatch;
459 $curDeletionBatch = [];
464 if ( $curDeletionBatch ) {
465 $deletionBatches[] = $curDeletionBatch;
468 foreach ( $deletionBatches as $deletionBatch ) {
470 $fromField => $this->mId
,
471 $this->getDB()->makeWhereFrom2d( $deletionBatch, $baseKey, "{$prefix}_title" )
475 if ( $table === 'langlinks' ) {
476 $toField = 'll_lang';
477 } elseif ( $table === 'page_props' ) {
478 $toField = 'pp_propname';
480 $toField = $prefix . '_to';
483 $deletionBatches = array_chunk( array_keys( $deletions ), $bSize );
484 foreach ( $deletionBatches as $deletionBatch ) {
485 $deleteWheres[] = [ $fromField => $this->mId
, $toField => $deletionBatch ];
489 $domainId = $this->getDB()->getDomainID();
491 foreach ( $deleteWheres as $deleteWhere ) {
492 $this->getDB()->delete( $table, $deleteWhere, __METHOD__
);
493 $lbf->commitAndWaitForReplication(
494 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ]
498 $insertBatches = array_chunk( $insertions, $bSize );
499 foreach ( $insertBatches as $insertBatch ) {
500 $this->getDB()->insert( $table, $insertBatch, __METHOD__
, 'IGNORE' );
501 $lbf->commitAndWaitForReplication(
502 __METHOD__
, $this->ticket
, [ 'domain' => $domainId ]
506 if ( count( $insertions ) ) {
507 Hooks
::run( 'LinksUpdateAfterInsert', [ $this, $table, $insertions ] );
512 * Get an array of pagelinks insertions for passing to the DB
513 * Skips the titles specified by the 2-D array $existing
514 * @param array $existing
517 private function getLinkInsertions( $existing = [] ) {
519 foreach ( $this->mLinks
as $ns => $dbkeys ) {
520 $diffs = isset( $existing[$ns] )
521 ?
array_diff_key( $dbkeys, $existing[$ns] )
523 foreach ( $diffs as $dbk => $id ) {
525 'pl_from' => $this->mId
,
526 'pl_from_namespace' => $this->mTitle
->getNamespace(),
527 'pl_namespace' => $ns,
537 * Get an array of template insertions. Like getLinkInsertions()
538 * @param array $existing
541 private function getTemplateInsertions( $existing = [] ) {
543 foreach ( $this->mTemplates
as $ns => $dbkeys ) {
544 $diffs = isset( $existing[$ns] ) ?
array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
545 foreach ( $diffs as $dbk => $id ) {
547 'tl_from' => $this->mId
,
548 'tl_from_namespace' => $this->mTitle
->getNamespace(),
549 'tl_namespace' => $ns,
559 * Get an array of image insertions
560 * Skips the names specified in $existing
561 * @param array $existing
564 private function getImageInsertions( $existing = [] ) {
566 $diffs = array_diff_key( $this->mImages
, $existing );
567 foreach ( $diffs as $iname => $dummy ) {
569 'il_from' => $this->mId
,
570 'il_from_namespace' => $this->mTitle
->getNamespace(),
579 * Get an array of externallinks insertions. Skips the names specified in $existing
580 * @param array $existing
583 private function getExternalInsertions( $existing = [] ) {
585 $diffs = array_diff_key( $this->mExternals
, $existing );
586 foreach ( $diffs as $url => $dummy ) {
587 foreach ( LinkFilter
::makeIndexes( $url ) as $index ) {
589 'el_from' => $this->mId
,
591 'el_index' => $index,
592 'el_index_60' => substr( $index, 0, 60 ),
601 * Get an array of category insertions
603 * @param array $existing Mapping existing category names to sort keys. If both
604 * match a link in $this, the link will be omitted from the output
608 private function getCategoryInsertions( $existing = [] ) {
609 global $wgCategoryCollation;
610 $diffs = array_diff_assoc( $this->mCategories
, $existing );
612 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
613 $collation = Collation
::singleton();
614 foreach ( $diffs as $name => $prefix ) {
615 $nt = Title
::makeTitleSafe( NS_CATEGORY
, $name );
616 $contLang->findVariantLink( $name, $nt, true );
618 $type = MediaWikiServices
::getInstance()->getNamespaceInfo()->
619 getCategoryLinkType( $this->mTitle
->getNamespace() );
621 # Treat custom sortkeys as a prefix, so that if multiple
622 # things are forced to sort as '*' or something, they'll
623 # sort properly in the category rather than in page_id
625 $sortkey = $collation->getSortKey( $this->mTitle
->getCategorySortkey( $prefix ) );
628 'cl_from' => $this->mId
,
630 'cl_sortkey' => $sortkey,
631 'cl_timestamp' => $this->getDB()->timestamp(),
632 'cl_sortkey_prefix' => $prefix,
633 'cl_collation' => $wgCategoryCollation,
642 * Get an array of interlanguage link insertions
644 * @param array $existing Mapping existing language codes to titles
648 private function getInterlangInsertions( $existing = [] ) {
649 $diffs = array_diff_assoc( $this->mInterlangs
, $existing );
651 foreach ( $diffs as $lang => $title ) {
653 'll_from' => $this->mId
,
663 * Get an array of page property insertions
664 * @param array $existing
667 function getPropertyInsertions( $existing = [] ) {
668 $diffs = array_diff_assoc( $this->mProperties
, $existing );
671 foreach ( array_keys( $diffs ) as $name ) {
672 $arr[] = $this->getPagePropRowData( $name );
679 * Returns an associative array to be used for inserting a row into
680 * the page_props table. Besides the given property name, this will
681 * include the page id from $this->mId and any property value from
682 * $this->mProperties.
684 * The array returned will include the pp_sortkey field if this
685 * is present in the database (as indicated by $wgPagePropsHaveSortkey).
686 * The sortkey value is currently determined by getPropertySortKeyValue().
688 * @note this assumes that $this->mProperties[$prop] is defined.
690 * @param string $prop The name of the property.
694 private function getPagePropRowData( $prop ) {
695 global $wgPagePropsHaveSortkey;
697 $value = $this->mProperties
[$prop];
700 'pp_page' => $this->mId
,
701 'pp_propname' => $prop,
702 'pp_value' => $value,
705 if ( $wgPagePropsHaveSortkey ) {
706 $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
713 * Determines the sort key for the given property value.
714 * This will return $value if it is a float or int,
715 * 1 or resp. 0 if it is a bool, and null otherwise.
717 * @note In the future, we may allow the sortkey to be specified explicitly
718 * in ParserOutput::setProperty.
720 * @param mixed $value
724 private function getPropertySortKeyValue( $value ) {
725 if ( is_int( $value ) ||
is_float( $value ) ||
is_bool( $value ) ) {
726 return floatval( $value );
733 * Get an array of interwiki insertions for passing to the DB
734 * Skips the titles specified by the 2-D array $existing
735 * @param array $existing
738 private function getInterwikiInsertions( $existing = [] ) {
740 foreach ( $this->mInterwikis
as $prefix => $dbkeys ) {
741 $diffs = isset( $existing[$prefix] )
742 ?
array_diff_key( $dbkeys, $existing[$prefix] )
745 foreach ( $diffs as $dbk => $id ) {
747 'iwl_from' => $this->mId
,
748 'iwl_prefix' => $prefix,
758 * Given an array of existing links, returns those links which are not in $this
759 * and thus should be deleted.
760 * @param array $existing
763 private function getLinkDeletions( $existing ) {
765 foreach ( $existing as $ns => $dbkeys ) {
766 if ( isset( $this->mLinks
[$ns] ) ) {
767 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks
[$ns] );
769 $del[$ns] = $existing[$ns];
777 * Given an array of existing templates, returns those templates which are not in $this
778 * and thus should be deleted.
779 * @param array $existing
782 private function getTemplateDeletions( $existing ) {
784 foreach ( $existing as $ns => $dbkeys ) {
785 if ( isset( $this->mTemplates
[$ns] ) ) {
786 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates
[$ns] );
788 $del[$ns] = $existing[$ns];
796 * Given an array of existing images, returns those images which are not in $this
797 * and thus should be deleted.
798 * @param array $existing
801 private function getImageDeletions( $existing ) {
802 return array_diff_key( $existing, $this->mImages
);
806 * Given an array of existing external links, returns those links which are not
807 * in $this and thus should be deleted.
808 * @param array $existing
811 private function getExternalDeletions( $existing ) {
812 return array_diff_key( $existing, $this->mExternals
);
816 * Given an array of existing categories, returns those categories which are not in $this
817 * and thus should be deleted.
818 * @param array $existing
821 private function getCategoryDeletions( $existing ) {
822 return array_diff_assoc( $existing, $this->mCategories
);
826 * Given an array of existing interlanguage links, returns those links which are not
827 * in $this and thus should be deleted.
828 * @param array $existing
831 private function getInterlangDeletions( $existing ) {
832 return array_diff_assoc( $existing, $this->mInterlangs
);
836 * Get array of properties which should be deleted.
837 * @param array $existing
840 private function getPropertyDeletions( $existing ) {
841 return array_diff_assoc( $existing, $this->mProperties
);
845 * Given an array of existing interwiki links, returns those links which are not in $this
846 * and thus should be deleted.
847 * @param array $existing
850 private function getInterwikiDeletions( $existing ) {
852 foreach ( $existing as $prefix => $dbkeys ) {
853 if ( isset( $this->mInterwikis
[$prefix] ) ) {
854 $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis
[$prefix] );
856 $del[$prefix] = $existing[$prefix];
864 * Get an array of existing links, as a 2-D array
868 private function getExistingLinks() {
869 $res = $this->getDB()->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
870 [ 'pl_from' => $this->mId
], __METHOD__
);
872 foreach ( $res as $row ) {
873 if ( !isset( $arr[$row->pl_namespace
] ) ) {
874 $arr[$row->pl_namespace
] = [];
876 $arr[$row->pl_namespace
][$row->pl_title
] = 1;
883 * Get an array of existing templates, as a 2-D array
887 private function getExistingTemplates() {
888 $res = $this->getDB()->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
889 [ 'tl_from' => $this->mId
], __METHOD__
);
891 foreach ( $res as $row ) {
892 if ( !isset( $arr[$row->tl_namespace
] ) ) {
893 $arr[$row->tl_namespace
] = [];
895 $arr[$row->tl_namespace
][$row->tl_title
] = 1;
902 * Get an array of existing images, image names in the keys
906 private function getExistingImages() {
907 $res = $this->getDB()->select( 'imagelinks', [ 'il_to' ],
908 [ 'il_from' => $this->mId
], __METHOD__
);
910 foreach ( $res as $row ) {
911 $arr[$row->il_to
] = 1;
918 * Get an array of existing external links, URLs in the keys
922 private function getExistingExternals() {
923 $res = $this->getDB()->select( 'externallinks', [ 'el_to' ],
924 [ 'el_from' => $this->mId
], __METHOD__
);
926 foreach ( $res as $row ) {
927 $arr[$row->el_to
] = 1;
934 * Get an array of existing categories, with the name in the key and sort key in the value.
938 private function getExistingCategories() {
939 $res = $this->getDB()->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
940 [ 'cl_from' => $this->mId
], __METHOD__
);
942 foreach ( $res as $row ) {
943 $arr[$row->cl_to
] = $row->cl_sortkey_prefix
;
950 * Get an array of existing interlanguage links, with the language code in the key and the
951 * title in the value.
955 private function getExistingInterlangs() {
956 $res = $this->getDB()->select( 'langlinks', [ 'll_lang', 'll_title' ],
957 [ 'll_from' => $this->mId
], __METHOD__
);
959 foreach ( $res as $row ) {
960 $arr[$row->ll_lang
] = $row->ll_title
;
967 * Get an array of existing inline interwiki links, as a 2-D array
968 * @return array (prefix => array(dbkey => 1))
970 private function getExistingInterwikis() {
971 $res = $this->getDB()->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
972 [ 'iwl_from' => $this->mId
], __METHOD__
);
974 foreach ( $res as $row ) {
975 if ( !isset( $arr[$row->iwl_prefix
] ) ) {
976 $arr[$row->iwl_prefix
] = [];
978 $arr[$row->iwl_prefix
][$row->iwl_title
] = 1;
985 * Get an array of existing categories, with the name in the key and sort key in the value.
987 * @return array Array of property names and values
989 private function getExistingProperties() {
990 $res = $this->getDB()->select( 'page_props', [ 'pp_propname', 'pp_value' ],
991 [ 'pp_page' => $this->mId
], __METHOD__
);
993 foreach ( $res as $row ) {
994 $arr[$row->pp_propname
] = $row->pp_value
;
1001 * Return the title object of the page being updated
1004 public function getTitle() {
1005 return $this->mTitle
;
1009 * Returns parser output
1011 * @return ParserOutput
1013 public function getParserOutput() {
1014 return $this->mParserOutput
;
1018 * Return the list of images used as generated by the parser
1021 public function getImages() {
1022 return $this->mImages
;
1026 * Set the revision corresponding to this LinksUpdate
1030 * @param Revision $revision
1032 public function setRevision( Revision
$revision ) {
1033 $this->mRevision
= $revision;
1038 * @return null|Revision
1040 public function getRevision() {
1041 return $this->mRevision
;
1045 * Set the User who triggered this LinksUpdate
1050 public function setTriggeringUser( User
$user ) {
1051 $this->user
= $user;
1058 public function getTriggeringUser() {
1063 * Invalidate any necessary link lists related to page property changes
1064 * @param array $changed
1066 private function invalidateProperties( $changed ) {
1067 global $wgPagePropLinkInvalidations;
1069 foreach ( $changed as $name => $value ) {
1070 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
1071 $inv = $wgPagePropLinkInvalidations[$name];
1072 if ( !is_array( $inv ) ) {
1075 foreach ( $inv as $table ) {
1076 DeferredUpdates
::addUpdate(
1077 new HTMLCacheUpdate( $this->mTitle
, $table, 'page-props' )
1085 * Fetch page links added by this LinksUpdate. Only available after the update is complete.
1087 * @return null|array Array of Titles
1089 public function getAddedLinks() {
1090 if ( $this->linkInsertions
=== null ) {
1094 foreach ( $this->linkInsertions
as $insertion ) {
1095 $result[] = Title
::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
1102 * Fetch page links removed by this LinksUpdate. Only available after the update is complete.
1104 * @return null|array Array of Titles
1106 public function getRemovedLinks() {
1107 if ( $this->linkDeletions
=== null ) {
1111 foreach ( $this->linkDeletions
as $ns => $titles ) {
1112 foreach ( $titles as $title => $unused ) {
1113 $result[] = Title
::makeTitle( $ns, $title );
1121 * Fetch external links added by this LinksUpdate. Only available after
1122 * the update is complete.
1124 * @return null|array Array of Strings
1126 public function getAddedExternalLinks() {
1127 if ( $this->externalLinkInsertions
=== null ) {
1131 foreach ( $this->externalLinkInsertions
as $key => $value ) {
1132 $result[] = $value['el_to'];
1138 * Fetch external links removed by this LinksUpdate. Only available after
1139 * the update is complete.
1141 * @return null|array Array of Strings
1143 public function getRemovedExternalLinks() {
1144 if ( $this->externalLinkDeletions
=== null ) {
1147 return array_keys( $this->externalLinkDeletions
);
1151 * Fetch page properties added by this LinksUpdate.
1152 * Only available after the update is complete.
1154 * @return null|array
1156 public function getAddedProperties() {
1157 return $this->propertyInsertions
;
1161 * Fetch page properties removed by this LinksUpdate.
1162 * Only available after the update is complete.
1164 * @return null|array
1166 public function getRemovedProperties() {
1167 return $this->propertyDeletions
;
1171 * Update links table freshness
1173 private function updateLinksTimestamp() {
1175 // The link updates made here only reflect the freshness of the parser output
1176 $timestamp = $this->mParserOutput
->getCacheTime();
1177 $this->getDB()->update( 'page',
1178 [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ],
1179 [ 'page_id' => $this->mId
],
1188 protected function getDB() {
1190 $this->db
= wfGetDB( DB_MASTER
);
1196 public function getAsJobSpecification() {
1197 if ( $this->user
) {
1199 'userId' => $this->user
->getId(),
1200 'userName' => $this->user
->getName(),
1206 if ( $this->mRevision
) {
1207 $triggeringRevisionId = $this->mRevision
->getId();
1209 $triggeringRevisionId = false;
1213 'domain' => $this->getDB()->getDomainID(),
1214 'job' => new JobSpecification(
1215 'refreshLinksPrioritized',
1217 // Reuse the parser cache if it was saved
1218 'rootJobTimestamp' => $this->mParserOutput
->getCacheTime(),
1219 'useRecursiveLinksUpdate' => $this->mRecursive
,
1220 'triggeringUser' => $userInfo,
1221 'triggeringRevisionId' => $triggeringRevisionId,
1222 'causeAction' => $this->getCauseAction(),
1223 'causeAgent' => $this->getCauseAgent()
1225 [ 'removeDuplicates' => true ],