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