5e02c5cc6cf14eeb7cadb78baf808caae1dca32a
[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 PurgeJobUtils::invalidatePages( $this->mDb, 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 PurgeJobUtils::invalidatePages( $this->mDb, 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->commitAndWaitForReplication(
391 __METHOD__, $this->ticket, [ 'wiki' => $this->mDb->getWikiID() ]
392 );
393 }
394
395 $insertBatches = array_chunk( $insertions, $bSize );
396 foreach ( $insertBatches as $insertBatch ) {
397 $this->mDb->insert( $table, $insertBatch, __METHOD__, 'IGNORE' );
398 $factory->commitAndWaitForReplication(
399 __METHOD__, $this->ticket, [ 'wiki' => $this->mDb->getWikiID() ]
400 );
401 }
402
403 if ( count( $insertions ) ) {
404 Hooks::run( 'LinksUpdateAfterInsert', [ $this, $table, $insertions ] );
405 }
406 }
407
408 /**
409 * Get an array of pagelinks insertions for passing to the DB
410 * Skips the titles specified by the 2-D array $existing
411 * @param array $existing
412 * @return array
413 */
414 private function getLinkInsertions( $existing = [] ) {
415 $arr = [];
416 foreach ( $this->mLinks as $ns => $dbkeys ) {
417 $diffs = isset( $existing[$ns] )
418 ? array_diff_key( $dbkeys, $existing[$ns] )
419 : $dbkeys;
420 foreach ( $diffs as $dbk => $id ) {
421 $arr[] = [
422 'pl_from' => $this->mId,
423 'pl_from_namespace' => $this->mTitle->getNamespace(),
424 'pl_namespace' => $ns,
425 'pl_title' => $dbk
426 ];
427 }
428 }
429
430 return $arr;
431 }
432
433 /**
434 * Get an array of template insertions. Like getLinkInsertions()
435 * @param array $existing
436 * @return array
437 */
438 private function getTemplateInsertions( $existing = [] ) {
439 $arr = [];
440 foreach ( $this->mTemplates as $ns => $dbkeys ) {
441 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
442 foreach ( $diffs as $dbk => $id ) {
443 $arr[] = [
444 'tl_from' => $this->mId,
445 'tl_from_namespace' => $this->mTitle->getNamespace(),
446 'tl_namespace' => $ns,
447 'tl_title' => $dbk
448 ];
449 }
450 }
451
452 return $arr;
453 }
454
455 /**
456 * Get an array of image insertions
457 * Skips the names specified in $existing
458 * @param array $existing
459 * @return array
460 */
461 private function getImageInsertions( $existing = [] ) {
462 $arr = [];
463 $diffs = array_diff_key( $this->mImages, $existing );
464 foreach ( $diffs as $iname => $dummy ) {
465 $arr[] = [
466 'il_from' => $this->mId,
467 'il_from_namespace' => $this->mTitle->getNamespace(),
468 'il_to' => $iname
469 ];
470 }
471
472 return $arr;
473 }
474
475 /**
476 * Get an array of externallinks insertions. Skips the names specified in $existing
477 * @param array $existing
478 * @return array
479 */
480 private function getExternalInsertions( $existing = [] ) {
481 $arr = [];
482 $diffs = array_diff_key( $this->mExternals, $existing );
483 foreach ( $diffs as $url => $dummy ) {
484 foreach ( wfMakeUrlIndexes( $url ) as $index ) {
485 $arr[] = [
486 'el_id' => $this->mDb->nextSequenceValue( 'externallinks_el_id_seq' ),
487 'el_from' => $this->mId,
488 'el_to' => $url,
489 'el_index' => $index,
490 ];
491 }
492 }
493
494 return $arr;
495 }
496
497 /**
498 * Get an array of category insertions
499 *
500 * @param array $existing Mapping existing category names to sort keys. If both
501 * match a link in $this, the link will be omitted from the output
502 *
503 * @return array
504 */
505 private function getCategoryInsertions( $existing = [] ) {
506 global $wgContLang, $wgCategoryCollation;
507 $diffs = array_diff_assoc( $this->mCategories, $existing );
508 $arr = [];
509 foreach ( $diffs as $name => $prefix ) {
510 $nt = Title::makeTitleSafe( NS_CATEGORY, $name );
511 $wgContLang->findVariantLink( $name, $nt, true );
512
513 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
514 $type = 'subcat';
515 } elseif ( $this->mTitle->getNamespace() == NS_FILE ) {
516 $type = 'file';
517 } else {
518 $type = 'page';
519 }
520
521 # Treat custom sortkeys as a prefix, so that if multiple
522 # things are forced to sort as '*' or something, they'll
523 # sort properly in the category rather than in page_id
524 # order or such.
525 $sortkey = Collation::singleton()->getSortKey(
526 $this->mTitle->getCategorySortkey( $prefix ) );
527
528 $arr[] = [
529 'cl_from' => $this->mId,
530 'cl_to' => $name,
531 'cl_sortkey' => $sortkey,
532 'cl_timestamp' => $this->mDb->timestamp(),
533 'cl_sortkey_prefix' => $prefix,
534 'cl_collation' => $wgCategoryCollation,
535 'cl_type' => $type,
536 ];
537 }
538
539 return $arr;
540 }
541
542 /**
543 * Get an array of interlanguage link insertions
544 *
545 * @param array $existing Mapping existing language codes to titles
546 *
547 * @return array
548 */
549 private function getInterlangInsertions( $existing = [] ) {
550 $diffs = array_diff_assoc( $this->mInterlangs, $existing );
551 $arr = [];
552 foreach ( $diffs as $lang => $title ) {
553 $arr[] = [
554 'll_from' => $this->mId,
555 'll_lang' => $lang,
556 'll_title' => $title
557 ];
558 }
559
560 return $arr;
561 }
562
563 /**
564 * Get an array of page property insertions
565 * @param array $existing
566 * @return array
567 */
568 function getPropertyInsertions( $existing = [] ) {
569 $diffs = array_diff_assoc( $this->mProperties, $existing );
570
571 $arr = [];
572 foreach ( array_keys( $diffs ) as $name ) {
573 $arr[] = $this->getPagePropRowData( $name );
574 }
575
576 return $arr;
577 }
578
579 /**
580 * Returns an associative array to be used for inserting a row into
581 * the page_props table. Besides the given property name, this will
582 * include the page id from $this->mId and any property value from
583 * $this->mProperties.
584 *
585 * The array returned will include the pp_sortkey field if this
586 * is present in the database (as indicated by $wgPagePropsHaveSortkey).
587 * The sortkey value is currently determined by getPropertySortKeyValue().
588 *
589 * @note this assumes that $this->mProperties[$prop] is defined.
590 *
591 * @param string $prop The name of the property.
592 *
593 * @return array
594 */
595 private function getPagePropRowData( $prop ) {
596 global $wgPagePropsHaveSortkey;
597
598 $value = $this->mProperties[$prop];
599
600 $row = [
601 'pp_page' => $this->mId,
602 'pp_propname' => $prop,
603 'pp_value' => $value,
604 ];
605
606 if ( $wgPagePropsHaveSortkey ) {
607 $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
608 }
609
610 return $row;
611 }
612
613 /**
614 * Determines the sort key for the given property value.
615 * This will return $value if it is a float or int,
616 * 1 or resp. 0 if it is a bool, and null otherwise.
617 *
618 * @note In the future, we may allow the sortkey to be specified explicitly
619 * in ParserOutput::setProperty.
620 *
621 * @param mixed $value
622 *
623 * @return float|null
624 */
625 private function getPropertySortKeyValue( $value ) {
626 if ( is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
627 return floatval( $value );
628 }
629
630 return null;
631 }
632
633 /**
634 * Get an array of interwiki insertions for passing to the DB
635 * Skips the titles specified by the 2-D array $existing
636 * @param array $existing
637 * @return array
638 */
639 private function getInterwikiInsertions( $existing = [] ) {
640 $arr = [];
641 foreach ( $this->mInterwikis as $prefix => $dbkeys ) {
642 $diffs = isset( $existing[$prefix] )
643 ? array_diff_key( $dbkeys, $existing[$prefix] )
644 : $dbkeys;
645
646 foreach ( $diffs as $dbk => $id ) {
647 $arr[] = [
648 'iwl_from' => $this->mId,
649 'iwl_prefix' => $prefix,
650 'iwl_title' => $dbk
651 ];
652 }
653 }
654
655 return $arr;
656 }
657
658 /**
659 * Given an array of existing links, returns those links which are not in $this
660 * and thus should be deleted.
661 * @param array $existing
662 * @return array
663 */
664 private function getLinkDeletions( $existing ) {
665 $del = [];
666 foreach ( $existing as $ns => $dbkeys ) {
667 if ( isset( $this->mLinks[$ns] ) ) {
668 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
669 } else {
670 $del[$ns] = $existing[$ns];
671 }
672 }
673
674 return $del;
675 }
676
677 /**
678 * Given an array of existing templates, returns those templates which are not in $this
679 * and thus should be deleted.
680 * @param array $existing
681 * @return array
682 */
683 private function getTemplateDeletions( $existing ) {
684 $del = [];
685 foreach ( $existing as $ns => $dbkeys ) {
686 if ( isset( $this->mTemplates[$ns] ) ) {
687 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
688 } else {
689 $del[$ns] = $existing[$ns];
690 }
691 }
692
693 return $del;
694 }
695
696 /**
697 * Given an array of existing images, returns those images which are not in $this
698 * and thus should be deleted.
699 * @param array $existing
700 * @return array
701 */
702 private function getImageDeletions( $existing ) {
703 return array_diff_key( $existing, $this->mImages );
704 }
705
706 /**
707 * Given an array of existing external links, returns those links which are not
708 * in $this and thus should be deleted.
709 * @param array $existing
710 * @return array
711 */
712 private function getExternalDeletions( $existing ) {
713 return array_diff_key( $existing, $this->mExternals );
714 }
715
716 /**
717 * Given an array of existing categories, returns those categories which are not in $this
718 * and thus should be deleted.
719 * @param array $existing
720 * @return array
721 */
722 private function getCategoryDeletions( $existing ) {
723 return array_diff_assoc( $existing, $this->mCategories );
724 }
725
726 /**
727 * Given an array of existing interlanguage links, returns those links which are not
728 * in $this and thus should be deleted.
729 * @param array $existing
730 * @return array
731 */
732 private function getInterlangDeletions( $existing ) {
733 return array_diff_assoc( $existing, $this->mInterlangs );
734 }
735
736 /**
737 * Get array of properties which should be deleted.
738 * @param array $existing
739 * @return array
740 */
741 function getPropertyDeletions( $existing ) {
742 return array_diff_assoc( $existing, $this->mProperties );
743 }
744
745 /**
746 * Given an array of existing interwiki links, returns those links which are not in $this
747 * and thus should be deleted.
748 * @param array $existing
749 * @return array
750 */
751 private function getInterwikiDeletions( $existing ) {
752 $del = [];
753 foreach ( $existing as $prefix => $dbkeys ) {
754 if ( isset( $this->mInterwikis[$prefix] ) ) {
755 $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis[$prefix] );
756 } else {
757 $del[$prefix] = $existing[$prefix];
758 }
759 }
760
761 return $del;
762 }
763
764 /**
765 * Get an array of existing links, as a 2-D array
766 *
767 * @return array
768 */
769 private function getExistingLinks() {
770 $res = $this->mDb->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
771 [ 'pl_from' => $this->mId ], __METHOD__, $this->mOptions );
772 $arr = [];
773 foreach ( $res as $row ) {
774 if ( !isset( $arr[$row->pl_namespace] ) ) {
775 $arr[$row->pl_namespace] = [];
776 }
777 $arr[$row->pl_namespace][$row->pl_title] = 1;
778 }
779
780 return $arr;
781 }
782
783 /**
784 * Get an array of existing templates, as a 2-D array
785 *
786 * @return array
787 */
788 private function getExistingTemplates() {
789 $res = $this->mDb->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
790 [ 'tl_from' => $this->mId ], __METHOD__, $this->mOptions );
791 $arr = [];
792 foreach ( $res as $row ) {
793 if ( !isset( $arr[$row->tl_namespace] ) ) {
794 $arr[$row->tl_namespace] = [];
795 }
796 $arr[$row->tl_namespace][$row->tl_title] = 1;
797 }
798
799 return $arr;
800 }
801
802 /**
803 * Get an array of existing images, image names in the keys
804 *
805 * @return array
806 */
807 private function getExistingImages() {
808 $res = $this->mDb->select( 'imagelinks', [ 'il_to' ],
809 [ 'il_from' => $this->mId ], __METHOD__, $this->mOptions );
810 $arr = [];
811 foreach ( $res as $row ) {
812 $arr[$row->il_to] = 1;
813 }
814
815 return $arr;
816 }
817
818 /**
819 * Get an array of existing external links, URLs in the keys
820 *
821 * @return array
822 */
823 private function getExistingExternals() {
824 $res = $this->mDb->select( 'externallinks', [ 'el_to' ],
825 [ 'el_from' => $this->mId ], __METHOD__, $this->mOptions );
826 $arr = [];
827 foreach ( $res as $row ) {
828 $arr[$row->el_to] = 1;
829 }
830
831 return $arr;
832 }
833
834 /**
835 * Get an array of existing categories, with the name in the key and sort key in the value.
836 *
837 * @return array
838 */
839 private function getExistingCategories() {
840 $res = $this->mDb->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
841 [ 'cl_from' => $this->mId ], __METHOD__, $this->mOptions );
842 $arr = [];
843 foreach ( $res as $row ) {
844 $arr[$row->cl_to] = $row->cl_sortkey_prefix;
845 }
846
847 return $arr;
848 }
849
850 /**
851 * Get an array of existing interlanguage links, with the language code in the key and the
852 * title in the value.
853 *
854 * @return array
855 */
856 private function getExistingInterlangs() {
857 $res = $this->mDb->select( 'langlinks', [ 'll_lang', 'll_title' ],
858 [ 'll_from' => $this->mId ], __METHOD__, $this->mOptions );
859 $arr = [];
860 foreach ( $res as $row ) {
861 $arr[$row->ll_lang] = $row->ll_title;
862 }
863
864 return $arr;
865 }
866
867 /**
868 * Get an array of existing inline interwiki links, as a 2-D array
869 * @return array (prefix => array(dbkey => 1))
870 */
871 protected function getExistingInterwikis() {
872 $res = $this->mDb->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
873 [ 'iwl_from' => $this->mId ], __METHOD__, $this->mOptions );
874 $arr = [];
875 foreach ( $res as $row ) {
876 if ( !isset( $arr[$row->iwl_prefix] ) ) {
877 $arr[$row->iwl_prefix] = [];
878 }
879 $arr[$row->iwl_prefix][$row->iwl_title] = 1;
880 }
881
882 return $arr;
883 }
884
885 /**
886 * Get an array of existing categories, with the name in the key and sort key in the value.
887 *
888 * @return array Array of property names and values
889 */
890 private function getExistingProperties() {
891 $res = $this->mDb->select( 'page_props', [ 'pp_propname', 'pp_value' ],
892 [ 'pp_page' => $this->mId ], __METHOD__, $this->mOptions );
893 $arr = [];
894 foreach ( $res as $row ) {
895 $arr[$row->pp_propname] = $row->pp_value;
896 }
897
898 return $arr;
899 }
900
901 /**
902 * Return the title object of the page being updated
903 * @return Title
904 */
905 public function getTitle() {
906 return $this->mTitle;
907 }
908
909 /**
910 * Returns parser output
911 * @since 1.19
912 * @return ParserOutput
913 */
914 public function getParserOutput() {
915 return $this->mParserOutput;
916 }
917
918 /**
919 * Return the list of images used as generated by the parser
920 * @return array
921 */
922 public function getImages() {
923 return $this->mImages;
924 }
925
926 /**
927 * Set the revision corresponding to this LinksUpdate
928 *
929 * @since 1.27
930 *
931 * @param Revision $revision
932 */
933 public function setRevision( Revision $revision ) {
934 $this->mRevision = $revision;
935 }
936
937 /**
938 * @since 1.28
939 * @return null|Revision
940 */
941 public function getRevision() {
942 return $this->mRevision;
943 }
944
945 /**
946 * Set the User who triggered this LinksUpdate
947 *
948 * @since 1.27
949 * @param User $user
950 */
951 public function setTriggeringUser( User $user ) {
952 $this->user = $user;
953 }
954
955 /**
956 * @since 1.27
957 * @return null|User
958 */
959 public function getTriggeringUser() {
960 return $this->user;
961 }
962
963 /**
964 * Invalidate any necessary link lists related to page property changes
965 * @param array $changed
966 */
967 private function invalidateProperties( $changed ) {
968 global $wgPagePropLinkInvalidations;
969
970 foreach ( $changed as $name => $value ) {
971 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
972 $inv = $wgPagePropLinkInvalidations[$name];
973 if ( !is_array( $inv ) ) {
974 $inv = [ $inv ];
975 }
976 foreach ( $inv as $table ) {
977 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->mTitle, $table ) );
978 }
979 }
980 }
981 }
982
983 /**
984 * Fetch page links added by this LinksUpdate. Only available after the update is complete.
985 * @since 1.22
986 * @return null|array Array of Titles
987 */
988 public function getAddedLinks() {
989 if ( $this->linkInsertions === null ) {
990 return null;
991 }
992 $result = [];
993 foreach ( $this->linkInsertions as $insertion ) {
994 $result[] = Title::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
995 }
996
997 return $result;
998 }
999
1000 /**
1001 * Fetch page links removed by this LinksUpdate. Only available after the update is complete.
1002 * @since 1.22
1003 * @return null|array Array of Titles
1004 */
1005 public function getRemovedLinks() {
1006 if ( $this->linkDeletions === null ) {
1007 return null;
1008 }
1009 $result = [];
1010 foreach ( $this->linkDeletions as $ns => $titles ) {
1011 foreach ( $titles as $title => $unused ) {
1012 $result[] = Title::makeTitle( $ns, $title );
1013 }
1014 }
1015
1016 return $result;
1017 }
1018
1019 /**
1020 * Update links table freshness
1021 */
1022 protected function updateLinksTimestamp() {
1023 if ( $this->mId ) {
1024 // The link updates made here only reflect the freshness of the parser output
1025 $timestamp = $this->mParserOutput->getCacheTime();
1026 $this->mDb->update( 'page',
1027 [ 'page_links_updated' => $this->mDb->timestamp( $timestamp ) ],
1028 [ 'page_id' => $this->mId ],
1029 __METHOD__
1030 );
1031 }
1032 }
1033
1034 public function getAsJobSpecification() {
1035 if ( $this->user ) {
1036 $userInfo = [
1037 'userId' => $this->user->getId(),
1038 'userName' => $this->user->getName(),
1039 ];
1040 } else {
1041 $userInfo = false;
1042 }
1043
1044 if ( $this->mRevision ) {
1045 $triggeringRevisionId = $this->mRevision->getId();
1046 } else {
1047 $triggeringRevisionId = false;
1048 }
1049
1050 return [
1051 'wiki' => $this->mDb->getWikiID(),
1052 'job' => new JobSpecification(
1053 'refreshLinksPrioritized',
1054 [
1055 // Reuse the parser cache if it was saved
1056 'rootJobTimestamp' => $this->mParserOutput->getCacheTime(),
1057 'useRecursiveLinksUpdate' => $this->mRecursive,
1058 'triggeringUser' => $userInfo,
1059 'triggeringRevisionId' => $triggeringRevisionId,
1060 ],
1061 [ 'removeDuplicates' => true ],
1062 $this->getTitle()
1063 )
1064 ];
1065 }
1066 }