Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[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 ];
573 }
574 }
575
576 return $arr;
577 }
578
579 /**
580 * Get an array of category insertions
581 *
582 * @param array $existing Mapping existing category names to sort keys. If both
583 * match a link in $this, the link will be omitted from the output
584 *
585 * @return array
586 */
587 private function getCategoryInsertions( $existing = [] ) {
588 global $wgContLang, $wgCategoryCollation;
589 $diffs = array_diff_assoc( $this->mCategories, $existing );
590 $arr = [];
591 foreach ( $diffs as $name => $prefix ) {
592 $nt = Title::makeTitleSafe( NS_CATEGORY, $name );
593 $wgContLang->findVariantLink( $name, $nt, true );
594
595 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
596 $type = 'subcat';
597 } elseif ( $this->mTitle->getNamespace() == NS_FILE ) {
598 $type = 'file';
599 } else {
600 $type = 'page';
601 }
602
603 # Treat custom sortkeys as a prefix, so that if multiple
604 # things are forced to sort as '*' or something, they'll
605 # sort properly in the category rather than in page_id
606 # order or such.
607 $sortkey = Collation::singleton()->getSortKey(
608 $this->mTitle->getCategorySortkey( $prefix ) );
609
610 $arr[] = [
611 'cl_from' => $this->mId,
612 'cl_to' => $name,
613 'cl_sortkey' => $sortkey,
614 'cl_timestamp' => $this->getDB()->timestamp(),
615 'cl_sortkey_prefix' => $prefix,
616 'cl_collation' => $wgCategoryCollation,
617 'cl_type' => $type,
618 ];
619 }
620
621 return $arr;
622 }
623
624 /**
625 * Get an array of interlanguage link insertions
626 *
627 * @param array $existing Mapping existing language codes to titles
628 *
629 * @return array
630 */
631 private function getInterlangInsertions( $existing = [] ) {
632 $diffs = array_diff_assoc( $this->mInterlangs, $existing );
633 $arr = [];
634 foreach ( $diffs as $lang => $title ) {
635 $arr[] = [
636 'll_from' => $this->mId,
637 'll_lang' => $lang,
638 'll_title' => $title
639 ];
640 }
641
642 return $arr;
643 }
644
645 /**
646 * Get an array of page property insertions
647 * @param array $existing
648 * @return array
649 */
650 function getPropertyInsertions( $existing = [] ) {
651 $diffs = array_diff_assoc( $this->mProperties, $existing );
652
653 $arr = [];
654 foreach ( array_keys( $diffs ) as $name ) {
655 $arr[] = $this->getPagePropRowData( $name );
656 }
657
658 return $arr;
659 }
660
661 /**
662 * Returns an associative array to be used for inserting a row into
663 * the page_props table. Besides the given property name, this will
664 * include the page id from $this->mId and any property value from
665 * $this->mProperties.
666 *
667 * The array returned will include the pp_sortkey field if this
668 * is present in the database (as indicated by $wgPagePropsHaveSortkey).
669 * The sortkey value is currently determined by getPropertySortKeyValue().
670 *
671 * @note this assumes that $this->mProperties[$prop] is defined.
672 *
673 * @param string $prop The name of the property.
674 *
675 * @return array
676 */
677 private function getPagePropRowData( $prop ) {
678 global $wgPagePropsHaveSortkey;
679
680 $value = $this->mProperties[$prop];
681
682 $row = [
683 'pp_page' => $this->mId,
684 'pp_propname' => $prop,
685 'pp_value' => $value,
686 ];
687
688 if ( $wgPagePropsHaveSortkey ) {
689 $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
690 }
691
692 return $row;
693 }
694
695 /**
696 * Determines the sort key for the given property value.
697 * This will return $value if it is a float or int,
698 * 1 or resp. 0 if it is a bool, and null otherwise.
699 *
700 * @note In the future, we may allow the sortkey to be specified explicitly
701 * in ParserOutput::setProperty.
702 *
703 * @param mixed $value
704 *
705 * @return float|null
706 */
707 private function getPropertySortKeyValue( $value ) {
708 if ( is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
709 return floatval( $value );
710 }
711
712 return null;
713 }
714
715 /**
716 * Get an array of interwiki insertions for passing to the DB
717 * Skips the titles specified by the 2-D array $existing
718 * @param array $existing
719 * @return array
720 */
721 private function getInterwikiInsertions( $existing = [] ) {
722 $arr = [];
723 foreach ( $this->mInterwikis as $prefix => $dbkeys ) {
724 $diffs = isset( $existing[$prefix] )
725 ? array_diff_key( $dbkeys, $existing[$prefix] )
726 : $dbkeys;
727
728 foreach ( $diffs as $dbk => $id ) {
729 $arr[] = [
730 'iwl_from' => $this->mId,
731 'iwl_prefix' => $prefix,
732 'iwl_title' => $dbk
733 ];
734 }
735 }
736
737 return $arr;
738 }
739
740 /**
741 * Given an array of existing links, returns those links which are not in $this
742 * and thus should be deleted.
743 * @param array $existing
744 * @return array
745 */
746 private function getLinkDeletions( $existing ) {
747 $del = [];
748 foreach ( $existing as $ns => $dbkeys ) {
749 if ( isset( $this->mLinks[$ns] ) ) {
750 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
751 } else {
752 $del[$ns] = $existing[$ns];
753 }
754 }
755
756 return $del;
757 }
758
759 /**
760 * Given an array of existing templates, returns those templates which are not in $this
761 * and thus should be deleted.
762 * @param array $existing
763 * @return array
764 */
765 private function getTemplateDeletions( $existing ) {
766 $del = [];
767 foreach ( $existing as $ns => $dbkeys ) {
768 if ( isset( $this->mTemplates[$ns] ) ) {
769 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
770 } else {
771 $del[$ns] = $existing[$ns];
772 }
773 }
774
775 return $del;
776 }
777
778 /**
779 * Given an array of existing images, returns those images which are not in $this
780 * and thus should be deleted.
781 * @param array $existing
782 * @return array
783 */
784 private function getImageDeletions( $existing ) {
785 return array_diff_key( $existing, $this->mImages );
786 }
787
788 /**
789 * Given an array of existing external links, returns those links which are not
790 * in $this and thus should be deleted.
791 * @param array $existing
792 * @return array
793 */
794 private function getExternalDeletions( $existing ) {
795 return array_diff_key( $existing, $this->mExternals );
796 }
797
798 /**
799 * Given an array of existing categories, returns those categories which are not in $this
800 * and thus should be deleted.
801 * @param array $existing
802 * @return array
803 */
804 private function getCategoryDeletions( $existing ) {
805 return array_diff_assoc( $existing, $this->mCategories );
806 }
807
808 /**
809 * Given an array of existing interlanguage links, returns those links which are not
810 * in $this and thus should be deleted.
811 * @param array $existing
812 * @return array
813 */
814 private function getInterlangDeletions( $existing ) {
815 return array_diff_assoc( $existing, $this->mInterlangs );
816 }
817
818 /**
819 * Get array of properties which should be deleted.
820 * @param array $existing
821 * @return array
822 */
823 function getPropertyDeletions( $existing ) {
824 return array_diff_assoc( $existing, $this->mProperties );
825 }
826
827 /**
828 * Given an array of existing interwiki links, returns those links which are not in $this
829 * and thus should be deleted.
830 * @param array $existing
831 * @return array
832 */
833 private function getInterwikiDeletions( $existing ) {
834 $del = [];
835 foreach ( $existing as $prefix => $dbkeys ) {
836 if ( isset( $this->mInterwikis[$prefix] ) ) {
837 $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis[$prefix] );
838 } else {
839 $del[$prefix] = $existing[$prefix];
840 }
841 }
842
843 return $del;
844 }
845
846 /**
847 * Get an array of existing links, as a 2-D array
848 *
849 * @return array
850 */
851 private function getExistingLinks() {
852 $res = $this->getDB()->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
853 [ 'pl_from' => $this->mId ], __METHOD__ );
854 $arr = [];
855 foreach ( $res as $row ) {
856 if ( !isset( $arr[$row->pl_namespace] ) ) {
857 $arr[$row->pl_namespace] = [];
858 }
859 $arr[$row->pl_namespace][$row->pl_title] = 1;
860 }
861
862 return $arr;
863 }
864
865 /**
866 * Get an array of existing templates, as a 2-D array
867 *
868 * @return array
869 */
870 private function getExistingTemplates() {
871 $res = $this->getDB()->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
872 [ 'tl_from' => $this->mId ], __METHOD__ );
873 $arr = [];
874 foreach ( $res as $row ) {
875 if ( !isset( $arr[$row->tl_namespace] ) ) {
876 $arr[$row->tl_namespace] = [];
877 }
878 $arr[$row->tl_namespace][$row->tl_title] = 1;
879 }
880
881 return $arr;
882 }
883
884 /**
885 * Get an array of existing images, image names in the keys
886 *
887 * @return array
888 */
889 private function getExistingImages() {
890 $res = $this->getDB()->select( 'imagelinks', [ 'il_to' ],
891 [ 'il_from' => $this->mId ], __METHOD__ );
892 $arr = [];
893 foreach ( $res as $row ) {
894 $arr[$row->il_to] = 1;
895 }
896
897 return $arr;
898 }
899
900 /**
901 * Get an array of existing external links, URLs in the keys
902 *
903 * @return array
904 */
905 private function getExistingExternals() {
906 $res = $this->getDB()->select( 'externallinks', [ 'el_to' ],
907 [ 'el_from' => $this->mId ], __METHOD__ );
908 $arr = [];
909 foreach ( $res as $row ) {
910 $arr[$row->el_to] = 1;
911 }
912
913 return $arr;
914 }
915
916 /**
917 * Get an array of existing categories, with the name in the key and sort key in the value.
918 *
919 * @return array
920 */
921 private function getExistingCategories() {
922 $res = $this->getDB()->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
923 [ 'cl_from' => $this->mId ], __METHOD__ );
924 $arr = [];
925 foreach ( $res as $row ) {
926 $arr[$row->cl_to] = $row->cl_sortkey_prefix;
927 }
928
929 return $arr;
930 }
931
932 /**
933 * Get an array of existing interlanguage links, with the language code in the key and the
934 * title in the value.
935 *
936 * @return array
937 */
938 private function getExistingInterlangs() {
939 $res = $this->getDB()->select( 'langlinks', [ 'll_lang', 'll_title' ],
940 [ 'll_from' => $this->mId ], __METHOD__ );
941 $arr = [];
942 foreach ( $res as $row ) {
943 $arr[$row->ll_lang] = $row->ll_title;
944 }
945
946 return $arr;
947 }
948
949 /**
950 * Get an array of existing inline interwiki links, as a 2-D array
951 * @return array (prefix => array(dbkey => 1))
952 */
953 private function getExistingInterwikis() {
954 $res = $this->getDB()->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
955 [ 'iwl_from' => $this->mId ], __METHOD__ );
956 $arr = [];
957 foreach ( $res as $row ) {
958 if ( !isset( $arr[$row->iwl_prefix] ) ) {
959 $arr[$row->iwl_prefix] = [];
960 }
961 $arr[$row->iwl_prefix][$row->iwl_title] = 1;
962 }
963
964 return $arr;
965 }
966
967 /**
968 * Get an array of existing categories, with the name in the key and sort key in the value.
969 *
970 * @return array Array of property names and values
971 */
972 private function getExistingProperties() {
973 $res = $this->getDB()->select( 'page_props', [ 'pp_propname', 'pp_value' ],
974 [ 'pp_page' => $this->mId ], __METHOD__ );
975 $arr = [];
976 foreach ( $res as $row ) {
977 $arr[$row->pp_propname] = $row->pp_value;
978 }
979
980 return $arr;
981 }
982
983 /**
984 * Return the title object of the page being updated
985 * @return Title
986 */
987 public function getTitle() {
988 return $this->mTitle;
989 }
990
991 /**
992 * Returns parser output
993 * @since 1.19
994 * @return ParserOutput
995 */
996 public function getParserOutput() {
997 return $this->mParserOutput;
998 }
999
1000 /**
1001 * Return the list of images used as generated by the parser
1002 * @return array
1003 */
1004 public function getImages() {
1005 return $this->mImages;
1006 }
1007
1008 /**
1009 * Set the revision corresponding to this LinksUpdate
1010 *
1011 * @since 1.27
1012 *
1013 * @param Revision $revision
1014 */
1015 public function setRevision( Revision $revision ) {
1016 $this->mRevision = $revision;
1017 }
1018
1019 /**
1020 * @since 1.28
1021 * @return null|Revision
1022 */
1023 public function getRevision() {
1024 return $this->mRevision;
1025 }
1026
1027 /**
1028 * Set the User who triggered this LinksUpdate
1029 *
1030 * @since 1.27
1031 * @param User $user
1032 */
1033 public function setTriggeringUser( User $user ) {
1034 $this->user = $user;
1035 }
1036
1037 /**
1038 * @since 1.27
1039 * @return null|User
1040 */
1041 public function getTriggeringUser() {
1042 return $this->user;
1043 }
1044
1045 /**
1046 * Invalidate any necessary link lists related to page property changes
1047 * @param array $changed
1048 */
1049 private function invalidateProperties( $changed ) {
1050 global $wgPagePropLinkInvalidations;
1051
1052 foreach ( $changed as $name => $value ) {
1053 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
1054 $inv = $wgPagePropLinkInvalidations[$name];
1055 if ( !is_array( $inv ) ) {
1056 $inv = [ $inv ];
1057 }
1058 foreach ( $inv as $table ) {
1059 DeferredUpdates::addUpdate(
1060 new HTMLCacheUpdate( $this->mTitle, $table, 'page-props' )
1061 );
1062 }
1063 }
1064 }
1065 }
1066
1067 /**
1068 * Fetch page links added by this LinksUpdate. Only available after the update is complete.
1069 * @since 1.22
1070 * @return null|array Array of Titles
1071 */
1072 public function getAddedLinks() {
1073 if ( $this->linkInsertions === null ) {
1074 return null;
1075 }
1076 $result = [];
1077 foreach ( $this->linkInsertions as $insertion ) {
1078 $result[] = Title::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
1079 }
1080
1081 return $result;
1082 }
1083
1084 /**
1085 * Fetch page links removed by this LinksUpdate. Only available after the update is complete.
1086 * @since 1.22
1087 * @return null|array Array of Titles
1088 */
1089 public function getRemovedLinks() {
1090 if ( $this->linkDeletions === null ) {
1091 return null;
1092 }
1093 $result = [];
1094 foreach ( $this->linkDeletions as $ns => $titles ) {
1095 foreach ( $titles as $title => $unused ) {
1096 $result[] = Title::makeTitle( $ns, $title );
1097 }
1098 }
1099
1100 return $result;
1101 }
1102
1103 /**
1104 * Fetch page properties added by this LinksUpdate.
1105 * Only available after the update is complete.
1106 * @since 1.28
1107 * @return null|array
1108 */
1109 public function getAddedProperties() {
1110 return $this->propertyInsertions;
1111 }
1112
1113 /**
1114 * Fetch page properties removed by this LinksUpdate.
1115 * Only available after the update is complete.
1116 * @since 1.28
1117 * @return null|array
1118 */
1119 public function getRemovedProperties() {
1120 return $this->propertyDeletions;
1121 }
1122
1123 /**
1124 * Update links table freshness
1125 */
1126 private function updateLinksTimestamp() {
1127 if ( $this->mId ) {
1128 // The link updates made here only reflect the freshness of the parser output
1129 $timestamp = $this->mParserOutput->getCacheTime();
1130 $this->getDB()->update( 'page',
1131 [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ],
1132 [ 'page_id' => $this->mId ],
1133 __METHOD__
1134 );
1135 }
1136 }
1137
1138 /**
1139 * @return IDatabase
1140 */
1141 private function getDB() {
1142 if ( !$this->db ) {
1143 $this->db = wfGetDB( DB_MASTER );
1144 }
1145
1146 return $this->db;
1147 }
1148
1149 public function getAsJobSpecification() {
1150 if ( $this->user ) {
1151 $userInfo = [
1152 'userId' => $this->user->getId(),
1153 'userName' => $this->user->getName(),
1154 ];
1155 } else {
1156 $userInfo = false;
1157 }
1158
1159 if ( $this->mRevision ) {
1160 $triggeringRevisionId = $this->mRevision->getId();
1161 } else {
1162 $triggeringRevisionId = false;
1163 }
1164
1165 return [
1166 'wiki' => WikiMap::getWikiIdFromDomain( $this->getDB()->getDomainID() ),
1167 'job' => new JobSpecification(
1168 'refreshLinksPrioritized',
1169 [
1170 // Reuse the parser cache if it was saved
1171 'rootJobTimestamp' => $this->mParserOutput->getCacheTime(),
1172 'useRecursiveLinksUpdate' => $this->mRecursive,
1173 'triggeringUser' => $userInfo,
1174 'triggeringRevisionId' => $triggeringRevisionId,
1175 'causeAction' => $this->getCauseAction(),
1176 'causeAgent' => $this->getCauseAgent()
1177 ],
1178 [ 'removeDuplicates' => true ],
1179 $this->getTitle()
1180 )
1181 ];
1182 }
1183 }