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