MediaWiki REL1_29
LinksUpdate.php
Go to the documentation of this file.
1<?php
25use Wikimedia\ScopedCallback;
26
35 // @todo make members protected, but make sure extensions don't break
36
38 public $mId;
39
41 public $mTitle;
42
45
47 public $mLinks;
48
50 public $mImages;
51
54
57
60
63
66
69
72
74 private $mRevision;
75
79 private $linkInsertions = null;
80
84 private $linkDeletions = null;
85
89 private $propertyInsertions = null;
90
94 private $propertyDeletions = null;
95
99 private $user;
100
102 private $db;
103
112 function __construct( Title $title, ParserOutput $parserOutput, $recursive = true ) {
113 parent::__construct();
114
115 $this->mTitle = $title;
116 $this->mId = $title->getArticleID( Title::GAID_FOR_UPDATE );
117
118 if ( !$this->mId ) {
119 throw new InvalidArgumentException(
120 "The Title object yields no ID. Perhaps the page doesn't exist?"
121 );
122 }
123
124 $this->mParserOutput = $parserOutput;
125
126 $this->mLinks = $parserOutput->getLinks();
127 $this->mImages = $parserOutput->getImages();
128 $this->mTemplates = $parserOutput->getTemplates();
129 $this->mExternals = $parserOutput->getExternalLinks();
130 $this->mCategories = $parserOutput->getCategories();
131 $this->mProperties = $parserOutput->getProperties();
132 $this->mInterwikis = $parserOutput->getInterwikiLinks();
133
134 # Convert the format of the interlanguage links
135 # I didn't want to change it in the ParserOutput, because that array is passed all
136 # the way back to the skin, so either a skin API break would be required, or an
137 # inefficient back-conversion.
138 $ill = $parserOutput->getLanguageLinks();
139 $this->mInterlangs = [];
140 foreach ( $ill as $link ) {
141 list( $key, $title ) = explode( ':', $link, 2 );
142 $this->mInterlangs[$key] = $title;
143 }
144
145 foreach ( $this->mCategories as &$sortkey ) {
146 # If the sortkey is longer then 255 bytes,
147 # it truncated by DB, and then doesn't get
148 # matched when comparing existing vs current
149 # categories, causing T27254.
150 # Also. substr behaves weird when given "".
151 if ( $sortkey !== '' ) {
152 $sortkey = substr( $sortkey, 0, 255 );
153 }
154 }
155
156 $this->mRecursive = $recursive;
157
158 // Avoid PHP 7.1 warning from passing $this by reference
159 $linksUpdate = $this;
160 Hooks::run( 'LinksUpdateConstructed', [ &$linksUpdate ] );
161 }
162
168 public function doUpdate() {
169 if ( $this->ticket ) {
170 // Make sure all links update threads see the changes of each other.
171 // This handles the case when updates have to batched into several COMMITs.
172 $scopedLock = self::acquirePageLock( $this->getDB(), $this->mId );
173 }
174
175 // Avoid PHP 7.1 warning from passing $this by reference
176 $linksUpdate = $this;
177 Hooks::run( 'LinksUpdate', [ &$linksUpdate ] );
178 $this->doIncrementalUpdate();
179
180 // Commit and release the lock (if set)
181 ScopedCallback::consume( $scopedLock );
182 // Run post-commit hooks without DBO_TRX
183 $this->getDB()->onTransactionIdle(
184 function () {
185 // Avoid PHP 7.1 warning from passing $this by reference
186 $linksUpdate = $this;
187 Hooks::run( 'LinksUpdateComplete', [ &$linksUpdate, $this->ticket ] );
188 },
189 __METHOD__
190 );
191 }
192
203 public static function acquirePageLock( IDatabase $dbw, $pageId, $why = 'atomicity' ) {
204 $key = "LinksUpdate:$why:pageid:$pageId";
205 $scopedLock = $dbw->getScopedLockAndFlush( $key, __METHOD__, 15 );
206 if ( !$scopedLock ) {
207 throw new RuntimeException( "Could not acquire lock '$key'." );
208 }
209
210 return $scopedLock;
211 }
212
213 protected function doIncrementalUpdate() {
214 # Page links
215 $existingPL = $this->getExistingLinks();
216 $this->linkDeletions = $this->getLinkDeletions( $existingPL );
217 $this->linkInsertions = $this->getLinkInsertions( $existingPL );
218 $this->incrTableUpdate( 'pagelinks', 'pl', $this->linkDeletions, $this->linkInsertions );
219
220 # Image links
221 $existingIL = $this->getExistingImages();
222 $imageDeletes = $this->getImageDeletions( $existingIL );
223 $this->incrTableUpdate(
224 'imagelinks',
225 'il',
226 $imageDeletes,
227 $this->getImageInsertions( $existingIL ) );
228
229 # Invalidate all image description pages which had links added or removed
230 $imageUpdates = $imageDeletes + array_diff_key( $this->mImages, $existingIL );
231 $this->invalidateImageDescriptions( $imageUpdates );
232
233 # External links
234 $existingEL = $this->getExistingExternals();
235 $this->incrTableUpdate(
236 'externallinks',
237 'el',
238 $this->getExternalDeletions( $existingEL ),
239 $this->getExternalInsertions( $existingEL ) );
240
241 # Language links
242 $existingLL = $this->getExistingInterlangs();
243 $this->incrTableUpdate(
244 'langlinks',
245 'll',
246 $this->getInterlangDeletions( $existingLL ),
247 $this->getInterlangInsertions( $existingLL ) );
248
249 # Inline interwiki links
250 $existingIW = $this->getExistingInterwikis();
251 $this->incrTableUpdate(
252 'iwlinks',
253 'iwl',
254 $this->getInterwikiDeletions( $existingIW ),
255 $this->getInterwikiInsertions( $existingIW ) );
256
257 # Template links
258 $existingTL = $this->getExistingTemplates();
259 $this->incrTableUpdate(
260 'templatelinks',
261 'tl',
262 $this->getTemplateDeletions( $existingTL ),
263 $this->getTemplateInsertions( $existingTL ) );
264
265 # Category links
266 $existingCL = $this->getExistingCategories();
267 $categoryDeletes = $this->getCategoryDeletions( $existingCL );
268 $this->incrTableUpdate(
269 'categorylinks',
270 'cl',
271 $categoryDeletes,
272 $this->getCategoryInsertions( $existingCL ) );
273 $categoryInserts = array_diff_assoc( $this->mCategories, $existingCL );
274 $categoryUpdates = $categoryInserts + $categoryDeletes;
275
276 # Page properties
277 $existingPP = $this->getExistingProperties();
278 $this->propertyDeletions = $this->getPropertyDeletions( $existingPP );
279 $this->incrTableUpdate(
280 'page_props',
281 'pp',
282 $this->propertyDeletions,
283 $this->getPropertyInsertions( $existingPP ) );
284
285 # Invalidate the necessary pages
286 $this->propertyInsertions = array_diff_assoc( $this->mProperties, $existingPP );
287 $changed = $this->propertyDeletions + $this->propertyInsertions;
288 $this->invalidateProperties( $changed );
289
290 # Invalidate all categories which were added, deleted or changed (set symmetric difference)
291 $this->invalidateCategories( $categoryUpdates );
292 $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
293
294 # Refresh links of all pages including this page
295 # This will be in a separate transaction
296 if ( $this->mRecursive ) {
297 $this->queueRecursiveJobs();
298 }
299
300 # Update the links table freshness for this title
301 $this->updateLinksTimestamp();
302 }
303
310 protected function queueRecursiveJobs() {
311 self::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
312 if ( $this->mTitle->getNamespace() == NS_FILE ) {
313 // Process imagelinks in case the title is or was a redirect
314 self::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
315 }
316
317 $bc = $this->mTitle->getBacklinkCache();
318 // Get jobs for cascade-protected backlinks for a high priority queue.
319 // If meta-templates change to using a new template, the new template
320 // should be implicitly protected as soon as possible, if applicable.
321 // These jobs duplicate a subset of the above ones, but can run sooner.
322 // Which ever runs first generally no-ops the other one.
323 $jobs = [];
324 foreach ( $bc->getCascadeProtectedLinks() as $title ) {
326 }
327 JobQueueGroup::singleton()->push( $jobs );
328 }
329
336 public static function queueRecursiveJobsForTable( Title $title, $table ) {
337 if ( $title->getBacklinkCache()->hasLinks( $table ) ) {
338 $job = new RefreshLinksJob(
339 $title,
340 [
341 'table' => $table,
342 'recursive' => true,
343 ] + Job::newRootJobParams( // "overall" refresh links job info
344 "refreshlinks:{$table}:{$title->getPrefixedText()}"
345 )
346 );
347
349 }
350 }
351
355 private function invalidateCategories( $cats ) {
356 PurgeJobUtils::invalidatePages( $this->getDB(), NS_CATEGORY, array_keys( $cats ) );
357 }
358
364 private function updateCategoryCounts( array $added, array $deleted ) {
366
367 $wp = WikiPage::factory( $this->mTitle );
368 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
369
370 foreach ( array_chunk( array_keys( $added ), $wgUpdateRowsPerQuery ) as $addBatch ) {
371 $wp->updateCategoryCounts( $addBatch, [], $this->mId );
372 $factory->commitAndWaitForReplication(
373 __METHOD__, $this->ticket, [ 'wiki' => $this->getDB()->getWikiID() ]
374 );
375 }
376
377 foreach ( array_chunk( array_keys( $deleted ), $wgUpdateRowsPerQuery ) as $deleteBatch ) {
378 $wp->updateCategoryCounts( [], $deleteBatch, $this->mId );
379 $factory->commitAndWaitForReplication(
380 __METHOD__, $this->ticket, [ 'wiki' => $this->getDB()->getWikiID() ]
381 );
382 }
383 }
384
388 private function invalidateImageDescriptions( $images ) {
389 PurgeJobUtils::invalidatePages( $this->getDB(), NS_FILE, array_keys( $images ) );
390 }
391
399 private function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
400 $services = MediaWikiServices::getInstance();
401 $bSize = $services->getMainConfig()->get( 'UpdateRowsPerQuery' );
402 $factory = $services->getDBLoadBalancerFactory();
403
404 if ( $table === 'page_props' ) {
405 $fromField = 'pp_page';
406 } else {
407 $fromField = "{$prefix}_from";
408 }
409
410 $deleteWheres = []; // list of WHERE clause arrays for each DB delete() call
411 if ( $table === 'pagelinks' || $table === 'templatelinks' || $table === 'iwlinks' ) {
412 $baseKey = ( $table === 'iwlinks' ) ? 'iwl_prefix' : "{$prefix}_namespace";
413
414 $curBatchSize = 0;
415 $curDeletionBatch = [];
416 $deletionBatches = [];
417 foreach ( $deletions as $ns => $dbKeys ) {
418 foreach ( $dbKeys as $dbKey => $unused ) {
419 $curDeletionBatch[$ns][$dbKey] = 1;
420 if ( ++$curBatchSize >= $bSize ) {
421 $deletionBatches[] = $curDeletionBatch;
422 $curDeletionBatch = [];
423 $curBatchSize = 0;
424 }
425 }
426 }
427 if ( $curDeletionBatch ) {
428 $deletionBatches[] = $curDeletionBatch;
429 }
430
431 foreach ( $deletionBatches as $deletionBatch ) {
432 $deleteWheres[] = [
433 $fromField => $this->mId,
434 $this->getDB()->makeWhereFrom2d( $deletionBatch, $baseKey, "{$prefix}_title" )
435 ];
436 }
437 } else {
438 if ( $table === 'langlinks' ) {
439 $toField = 'll_lang';
440 } elseif ( $table === 'page_props' ) {
441 $toField = 'pp_propname';
442 } else {
443 $toField = $prefix . '_to';
444 }
445
446 $deletionBatches = array_chunk( array_keys( $deletions ), $bSize );
447 foreach ( $deletionBatches as $deletionBatch ) {
448 $deleteWheres[] = [ $fromField => $this->mId, $toField => $deletionBatch ];
449 }
450 }
451
452 foreach ( $deleteWheres as $deleteWhere ) {
453 $this->getDB()->delete( $table, $deleteWhere, __METHOD__ );
454 $factory->commitAndWaitForReplication(
455 __METHOD__, $this->ticket, [ 'wiki' => $this->getDB()->getWikiID() ]
456 );
457 }
458
459 $insertBatches = array_chunk( $insertions, $bSize );
460 foreach ( $insertBatches as $insertBatch ) {
461 $this->getDB()->insert( $table, $insertBatch, __METHOD__, 'IGNORE' );
462 $factory->commitAndWaitForReplication(
463 __METHOD__, $this->ticket, [ 'wiki' => $this->getDB()->getWikiID() ]
464 );
465 }
466
467 if ( count( $insertions ) ) {
468 Hooks::run( 'LinksUpdateAfterInsert', [ $this, $table, $insertions ] );
469 }
470 }
471
478 private function getLinkInsertions( $existing = [] ) {
479 $arr = [];
480 foreach ( $this->mLinks as $ns => $dbkeys ) {
481 $diffs = isset( $existing[$ns] )
482 ? array_diff_key( $dbkeys, $existing[$ns] )
483 : $dbkeys;
484 foreach ( $diffs as $dbk => $id ) {
485 $arr[] = [
486 'pl_from' => $this->mId,
487 'pl_from_namespace' => $this->mTitle->getNamespace(),
488 'pl_namespace' => $ns,
489 'pl_title' => $dbk
490 ];
491 }
492 }
493
494 return $arr;
495 }
496
502 private function getTemplateInsertions( $existing = [] ) {
503 $arr = [];
504 foreach ( $this->mTemplates as $ns => $dbkeys ) {
505 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
506 foreach ( $diffs as $dbk => $id ) {
507 $arr[] = [
508 'tl_from' => $this->mId,
509 'tl_from_namespace' => $this->mTitle->getNamespace(),
510 'tl_namespace' => $ns,
511 'tl_title' => $dbk
512 ];
513 }
514 }
515
516 return $arr;
517 }
518
525 private function getImageInsertions( $existing = [] ) {
526 $arr = [];
527 $diffs = array_diff_key( $this->mImages, $existing );
528 foreach ( $diffs as $iname => $dummy ) {
529 $arr[] = [
530 'il_from' => $this->mId,
531 'il_from_namespace' => $this->mTitle->getNamespace(),
532 'il_to' => $iname
533 ];
534 }
535
536 return $arr;
537 }
538
544 private function getExternalInsertions( $existing = [] ) {
545 $arr = [];
546 $diffs = array_diff_key( $this->mExternals, $existing );
547 foreach ( $diffs as $url => $dummy ) {
548 foreach ( wfMakeUrlIndexes( $url ) as $index ) {
549 $arr[] = [
550 'el_id' => $this->getDB()->nextSequenceValue( 'externallinks_el_id_seq' ),
551 'el_from' => $this->mId,
552 'el_to' => $url,
553 'el_index' => $index,
554 ];
555 }
556 }
557
558 return $arr;
559 }
560
569 private function getCategoryInsertions( $existing = [] ) {
571 $diffs = array_diff_assoc( $this->mCategories, $existing );
572 $arr = [];
573 foreach ( $diffs as $name => $prefix ) {
574 $nt = Title::makeTitleSafe( NS_CATEGORY, $name );
575 $wgContLang->findVariantLink( $name, $nt, true );
576
577 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
578 $type = 'subcat';
579 } elseif ( $this->mTitle->getNamespace() == NS_FILE ) {
580 $type = 'file';
581 } else {
582 $type = 'page';
583 }
584
585 # Treat custom sortkeys as a prefix, so that if multiple
586 # things are forced to sort as '*' or something, they'll
587 # sort properly in the category rather than in page_id
588 # order or such.
589 $sortkey = Collation::singleton()->getSortKey(
590 $this->mTitle->getCategorySortkey( $prefix ) );
591
592 $arr[] = [
593 'cl_from' => $this->mId,
594 'cl_to' => $name,
595 'cl_sortkey' => $sortkey,
596 'cl_timestamp' => $this->getDB()->timestamp(),
597 'cl_sortkey_prefix' => $prefix,
598 'cl_collation' => $wgCategoryCollation,
599 'cl_type' => $type,
600 ];
601 }
602
603 return $arr;
604 }
605
613 private function getInterlangInsertions( $existing = [] ) {
614 $diffs = array_diff_assoc( $this->mInterlangs, $existing );
615 $arr = [];
616 foreach ( $diffs as $lang => $title ) {
617 $arr[] = [
618 'll_from' => $this->mId,
619 'll_lang' => $lang,
620 'll_title' => $title
621 ];
622 }
623
624 return $arr;
625 }
626
632 function getPropertyInsertions( $existing = [] ) {
633 $diffs = array_diff_assoc( $this->mProperties, $existing );
634
635 $arr = [];
636 foreach ( array_keys( $diffs ) as $name ) {
637 $arr[] = $this->getPagePropRowData( $name );
638 }
639
640 return $arr;
641 }
642
659 private function getPagePropRowData( $prop ) {
661
662 $value = $this->mProperties[$prop];
663
664 $row = [
665 'pp_page' => $this->mId,
666 'pp_propname' => $prop,
667 'pp_value' => $value,
668 ];
669
671 $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
672 }
673
674 return $row;
675 }
676
689 private function getPropertySortKeyValue( $value ) {
690 if ( is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
691 return floatval( $value );
692 }
693
694 return null;
695 }
696
703 private function getInterwikiInsertions( $existing = [] ) {
704 $arr = [];
705 foreach ( $this->mInterwikis as $prefix => $dbkeys ) {
706 $diffs = isset( $existing[$prefix] )
707 ? array_diff_key( $dbkeys, $existing[$prefix] )
708 : $dbkeys;
709
710 foreach ( $diffs as $dbk => $id ) {
711 $arr[] = [
712 'iwl_from' => $this->mId,
713 'iwl_prefix' => $prefix,
714 'iwl_title' => $dbk
715 ];
716 }
717 }
718
719 return $arr;
720 }
721
728 private function getLinkDeletions( $existing ) {
729 $del = [];
730 foreach ( $existing as $ns => $dbkeys ) {
731 if ( isset( $this->mLinks[$ns] ) ) {
732 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
733 } else {
734 $del[$ns] = $existing[$ns];
735 }
736 }
737
738 return $del;
739 }
740
747 private function getTemplateDeletions( $existing ) {
748 $del = [];
749 foreach ( $existing as $ns => $dbkeys ) {
750 if ( isset( $this->mTemplates[$ns] ) ) {
751 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
752 } else {
753 $del[$ns] = $existing[$ns];
754 }
755 }
756
757 return $del;
758 }
759
766 private function getImageDeletions( $existing ) {
767 return array_diff_key( $existing, $this->mImages );
768 }
769
776 private function getExternalDeletions( $existing ) {
777 return array_diff_key( $existing, $this->mExternals );
778 }
779
786 private function getCategoryDeletions( $existing ) {
787 return array_diff_assoc( $existing, $this->mCategories );
788 }
789
796 private function getInterlangDeletions( $existing ) {
797 return array_diff_assoc( $existing, $this->mInterlangs );
798 }
799
805 function getPropertyDeletions( $existing ) {
806 return array_diff_assoc( $existing, $this->mProperties );
807 }
808
815 private function getInterwikiDeletions( $existing ) {
816 $del = [];
817 foreach ( $existing as $prefix => $dbkeys ) {
818 if ( isset( $this->mInterwikis[$prefix] ) ) {
819 $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis[$prefix] );
820 } else {
821 $del[$prefix] = $existing[$prefix];
822 }
823 }
824
825 return $del;
826 }
827
833 private function getExistingLinks() {
834 $res = $this->getDB()->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
835 [ 'pl_from' => $this->mId ], __METHOD__ );
836 $arr = [];
837 foreach ( $res as $row ) {
838 if ( !isset( $arr[$row->pl_namespace] ) ) {
839 $arr[$row->pl_namespace] = [];
840 }
841 $arr[$row->pl_namespace][$row->pl_title] = 1;
842 }
843
844 return $arr;
845 }
846
852 private function getExistingTemplates() {
853 $res = $this->getDB()->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
854 [ 'tl_from' => $this->mId ], __METHOD__ );
855 $arr = [];
856 foreach ( $res as $row ) {
857 if ( !isset( $arr[$row->tl_namespace] ) ) {
858 $arr[$row->tl_namespace] = [];
859 }
860 $arr[$row->tl_namespace][$row->tl_title] = 1;
861 }
862
863 return $arr;
864 }
865
871 private function getExistingImages() {
872 $res = $this->getDB()->select( 'imagelinks', [ 'il_to' ],
873 [ 'il_from' => $this->mId ], __METHOD__ );
874 $arr = [];
875 foreach ( $res as $row ) {
876 $arr[$row->il_to] = 1;
877 }
878
879 return $arr;
880 }
881
887 private function getExistingExternals() {
888 $res = $this->getDB()->select( 'externallinks', [ 'el_to' ],
889 [ 'el_from' => $this->mId ], __METHOD__ );
890 $arr = [];
891 foreach ( $res as $row ) {
892 $arr[$row->el_to] = 1;
893 }
894
895 return $arr;
896 }
897
903 private function getExistingCategories() {
904 $res = $this->getDB()->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
905 [ 'cl_from' => $this->mId ], __METHOD__ );
906 $arr = [];
907 foreach ( $res as $row ) {
908 $arr[$row->cl_to] = $row->cl_sortkey_prefix;
909 }
910
911 return $arr;
912 }
913
920 private function getExistingInterlangs() {
921 $res = $this->getDB()->select( 'langlinks', [ 'll_lang', 'll_title' ],
922 [ 'll_from' => $this->mId ], __METHOD__ );
923 $arr = [];
924 foreach ( $res as $row ) {
925 $arr[$row->ll_lang] = $row->ll_title;
926 }
927
928 return $arr;
929 }
930
935 private function getExistingInterwikis() {
936 $res = $this->getDB()->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
937 [ 'iwl_from' => $this->mId ], __METHOD__ );
938 $arr = [];
939 foreach ( $res as $row ) {
940 if ( !isset( $arr[$row->iwl_prefix] ) ) {
941 $arr[$row->iwl_prefix] = [];
942 }
943 $arr[$row->iwl_prefix][$row->iwl_title] = 1;
944 }
945
946 return $arr;
947 }
948
954 private function getExistingProperties() {
955 $res = $this->getDB()->select( 'page_props', [ 'pp_propname', 'pp_value' ],
956 [ 'pp_page' => $this->mId ], __METHOD__ );
957 $arr = [];
958 foreach ( $res as $row ) {
959 $arr[$row->pp_propname] = $row->pp_value;
960 }
961
962 return $arr;
963 }
964
969 public function getTitle() {
970 return $this->mTitle;
971 }
972
978 public function getParserOutput() {
980 }
981
986 public function getImages() {
987 return $this->mImages;
988 }
989
997 public function setRevision( Revision $revision ) {
998 $this->mRevision = $revision;
999 }
1000
1005 public function getRevision() {
1006 return $this->mRevision;
1007 }
1008
1015 public function setTriggeringUser( User $user ) {
1016 $this->user = $user;
1017 }
1018
1023 public function getTriggeringUser() {
1024 return $this->user;
1025 }
1026
1031 private function invalidateProperties( $changed ) {
1033
1034 foreach ( $changed as $name => $value ) {
1035 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
1037 if ( !is_array( $inv ) ) {
1038 $inv = [ $inv ];
1039 }
1040 foreach ( $inv as $table ) {
1041 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->mTitle, $table ) );
1042 }
1043 }
1044 }
1045 }
1046
1052 public function getAddedLinks() {
1053 if ( $this->linkInsertions === null ) {
1054 return null;
1055 }
1056 $result = [];
1057 foreach ( $this->linkInsertions as $insertion ) {
1058 $result[] = Title::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
1059 }
1060
1061 return $result;
1062 }
1063
1069 public function getRemovedLinks() {
1070 if ( $this->linkDeletions === null ) {
1071 return null;
1072 }
1073 $result = [];
1074 foreach ( $this->linkDeletions as $ns => $titles ) {
1075 foreach ( $titles as $title => $unused ) {
1076 $result[] = Title::makeTitle( $ns, $title );
1077 }
1078 }
1079
1080 return $result;
1081 }
1082
1089 public function getAddedProperties() {
1091 }
1092
1099 public function getRemovedProperties() {
1101 }
1102
1106 private function updateLinksTimestamp() {
1107 if ( $this->mId ) {
1108 // The link updates made here only reflect the freshness of the parser output
1109 $timestamp = $this->mParserOutput->getCacheTime();
1110 $this->getDB()->update( 'page',
1111 [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ],
1112 [ 'page_id' => $this->mId ],
1113 __METHOD__
1114 );
1115 }
1116 }
1117
1121 private function getDB() {
1122 if ( !$this->db ) {
1123 $this->db = wfGetDB( DB_MASTER );
1124 }
1125
1126 return $this->db;
1127 }
1128
1129 public function getAsJobSpecification() {
1130 if ( $this->user ) {
1131 $userInfo = [
1132 'userId' => $this->user->getId(),
1133 'userName' => $this->user->getName(),
1134 ];
1135 } else {
1136 $userInfo = false;
1137 }
1138
1139 if ( $this->mRevision ) {
1140 $triggeringRevisionId = $this->mRevision->getId();
1141 } else {
1142 $triggeringRevisionId = false;
1143 }
1144
1145 return [
1146 'wiki' => $this->getDB()->getWikiID(),
1147 'job' => new JobSpecification(
1148 'refreshLinksPrioritized',
1149 [
1150 // Reuse the parser cache if it was saved
1151 'rootJobTimestamp' => $this->mParserOutput->getCacheTime(),
1152 'useRecursiveLinksUpdate' => $this->mRecursive,
1153 'triggeringUser' => $userInfo,
1154 'triggeringRevisionId' => $triggeringRevisionId,
1155 ],
1156 [ 'removeDuplicates' => true ],
1157 $this->getTitle()
1158 )
1159 ];
1160 }
1161}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgPagePropLinkInvalidations
Page property link table invalidation lists.
$wgCategoryCollation
Specify how category names should be sorted, when listed on a category page.
$wgUpdateRowsPerQuery
Number of rows to update per query.
$wgPagePropsHaveSortkey
Whether the page_props table has a pp_sortkey column.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfMakeUrlIndexes( $url)
Make URL indexes, appropriate for the el_index field of externallinks.
static singleton()
Definition Collation.php:34
Abstract base class for update jobs that do something with some secondary data extracted from article...
Class to invalidate the HTML cache of all the pages linking to a given title.
static singleton( $wiki=false)
Job queue task description base code.
static newRootJobParams( $key)
Get "root job" parameters for a task.
Definition Job.php:261
Class the manages updates of *_link tables as well as similar extension-managed tables.
updateCategoryCounts(array $added, array $deleted)
Update all the appropriate counts in the category table.
array $mTemplates
Map of title strings to IDs for the template references, including broken ones.
updateLinksTimestamp()
Update links table freshness.
getTitle()
Return the title object of the page being updated.
User null $user
getExistingLinks()
Get an array of existing links, as a 2-D array.
getExistingProperties()
Get an array of existing categories, with the name in the key and sort key in the value.
getImageInsertions( $existing=[])
Get an array of image insertions Skips the names specified in $existing.
getInterlangInsertions( $existing=[])
Get an array of interlanguage link insertions.
getExternalInsertions( $existing=[])
Get an array of externallinks insertions.
__construct(Title $title, ParserOutput $parserOutput, $recursive=true)
Constructor.
getPropertyInsertions( $existing=[])
Get an array of page property insertions.
array $mLinks
Map of title strings to IDs for the links in the document.
array $mInterwikis
2-D map of (prefix => DBK => 1)
setTriggeringUser(User $user)
Set the User who triggered this LinksUpdate.
getTemplateDeletions( $existing)
Given an array of existing templates, returns those templates which are not in $this and thus should ...
invalidateCategories( $cats)
null array $propertyInsertions
Added properties if calculated.
doUpdate()
Update link tables with outgoing links from an updated article.
Title $mTitle
Title object of the article linked from.
getPropertySortKeyValue( $value)
Determines the sort key for the given property value.
int $mId
Page ID of the article linked from.
getAddedProperties()
Fetch page properties added by this LinksUpdate.
getLinkInsertions( $existing=[])
Get an array of pagelinks insertions for passing to the DB Skips the titles specified by the 2-D arra...
getExistingImages()
Get an array of existing images, image names in the keys.
getRemovedLinks()
Fetch page links removed by this LinksUpdate.
Revision $mRevision
Revision for which this update has been triggered.
setRevision(Revision $revision)
Set the revision corresponding to this LinksUpdate.
getTemplateInsertions( $existing=[])
Get an array of template insertions.
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
getCategoryDeletions( $existing)
Given an array of existing categories, returns those categories which are not in $this and thus shoul...
getInterwikiInsertions( $existing=[])
Get an array of interwiki insertions for passing to the DB Skips the titles specified by the 2-D arra...
ParserOutput $mParserOutput
null array $linkInsertions
Added links if calculated.
getImages()
Return the list of images used as generated by the parser.
array $mProperties
Map of arbitrary name to value.
getExistingInterlangs()
Get an array of existing interlanguage links, with the language code in the key and the title in the ...
getExistingExternals()
Get an array of existing external links, URLs in the keys.
getParserOutput()
Returns parser output.
getPropertyDeletions( $existing)
Get array of properties which should be deleted.
invalidateProperties( $changed)
Invalidate any necessary link lists related to page property changes.
null array $linkDeletions
Deleted links if calculated.
null array $propertyDeletions
Deleted properties if calculated.
getInterlangDeletions( $existing)
Given an array of existing interlanguage links, returns those links which are not in $this and thus s...
getPagePropRowData( $prop)
Returns an associative array to be used for inserting a row into the page_props table.
getExistingCategories()
Get an array of existing categories, with the name in the key and sort key in the value.
invalidateImageDescriptions( $images)
getAddedLinks()
Fetch page links added by this LinksUpdate.
queueRecursiveJobs()
Queue recursive jobs for this page.
array $mImages
DB keys of the images used, in the array key only.
getImageDeletions( $existing)
Given an array of existing images, returns those images which are not in $this and thus should be del...
array $mInterlangs
Map of language codes to titles.
getLinkDeletions( $existing)
Given an array of existing links, returns those links which are not in $this and thus should be delet...
array $mCategories
Map of category names to sort keys.
bool $mRecursive
Whether to queue jobs for recursive updates.
getCategoryInsertions( $existing=[])
Get an array of category insertions.
getRemovedProperties()
Fetch page properties removed by this LinksUpdate.
getExistingTemplates()
Get an array of existing templates, as a 2-D array.
getExternalDeletions( $existing)
Given an array of existing external links, returns those links which are not in $this and thus should...
static acquirePageLock(IDatabase $dbw, $pageId, $why='atomicity')
Acquire a lock for performing link table updates for a page on a DB.
getInterwikiDeletions( $existing)
Given an array of existing interwiki links, returns those links which are not in $this and thus shoul...
array $mExternals
URLs of external links, array key only.
incrTableUpdate( $table, $prefix, $deletions, $insertions)
Update a table by doing a delete query then an insert query.
IDatabase $db
getExistingInterwikis()
Get an array of existing inline interwiki links, as a 2-D array.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static invalidatePages(IDatabase $dbw, $namespace, array $dbkeys)
Invalidate the cache of a list of pages from a single namespace.
Job to update link tables for pages.
static newPrioritized(Title $title, array $params)
Represents a title within MediaWiki.
Definition Title.php:39
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:50
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition WikiPage.php:120
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
const NS_FILE
Definition Defines.php:68
const NS_CATEGORY
Definition Defines.php:76
the array() calling protocol came about after MediaWiki 1.4rc1.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context $parserOutput
Definition hooks.txt:1096
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1954
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:964
either a unescaped string or a HtmlArmor object after in associative array form externallinks $linksUpdate
Definition hooks.txt:2041
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition hooks.txt:2604
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition hooks.txt:2224
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:2937
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Interface that marks a DataUpdate as enqueuable via the JobQueue.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:40
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition linkcache.txt:17
const DB_MASTER
Definition defines.php:26
if(count( $args)< 1) $job
if(!isset( $args[0])) $lang