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