MediaWiki  1.28.3
LinksUpdate.php
Go to the documentation of this file.
1 <?php
25 
33 class LinksUpdate extends DataUpdate implements EnqueueableDataUpdate {
34  // @todo make members protected, but make sure extensions don't break
35 
37  public $mId;
38 
40  public $mTitle;
41 
44 
46  public $mLinks;
47 
49  public $mImages;
50 
52  public $mTemplates;
53 
55  public $mExternals;
56 
58  public $mCategories;
59 
61  public $mInterlangs;
62 
64  public $mInterwikis;
65 
67  public $mProperties;
68 
70  public $mRecursive;
71 
73  private $mRevision;
74 
78  private $linkInsertions = null;
79 
83  private $linkDeletions = null;
84 
88  private $propertyInsertions = null;
89 
93  private $propertyDeletions = null;
94 
98  private $user;
99 
101  private $db;
102 
111  function __construct( Title $title, ParserOutput $parserOutput, $recursive = true ) {
112  parent::__construct();
113 
114  $this->mTitle = $title;
115  $this->mId = $title->getArticleID( Title::GAID_FOR_UPDATE );
116 
117  if ( !$this->mId ) {
118  throw new InvalidArgumentException(
119  "The Title object yields no ID. Perhaps the page doesn't exist?"
120  );
121  }
122 
123  $this->mParserOutput = $parserOutput;
124 
125  $this->mLinks = $parserOutput->getLinks();
126  $this->mImages = $parserOutput->getImages();
127  $this->mTemplates = $parserOutput->getTemplates();
128  $this->mExternals = $parserOutput->getExternalLinks();
129  $this->mCategories = $parserOutput->getCategories();
130  $this->mProperties = $parserOutput->getProperties();
131  $this->mInterwikis = $parserOutput->getInterwikiLinks();
132 
133  # Convert the format of the interlanguage links
134  # I didn't want to change it in the ParserOutput, because that array is passed all
135  # the way back to the skin, so either a skin API break would be required, or an
136  # inefficient back-conversion.
137  $ill = $parserOutput->getLanguageLinks();
138  $this->mInterlangs = [];
139  foreach ( $ill as $link ) {
140  list( $key, $title ) = explode( ':', $link, 2 );
141  $this->mInterlangs[$key] = $title;
142  }
143 
144  foreach ( $this->mCategories as &$sortkey ) {
145  # If the sortkey is longer then 255 bytes,
146  # it truncated by DB, and then doesn't get
147  # matched when comparing existing vs current
148  # categories, causing bug 25254.
149  # Also. substr behaves weird when given "".
150  if ( $sortkey !== '' ) {
151  $sortkey = substr( $sortkey, 0, 255 );
152  }
153  }
154 
155  $this->mRecursive = $recursive;
156 
157  // Avoid PHP 7.1 warning from passing $this by reference
158  $linksUpdate = $this;
159  Hooks::run( 'LinksUpdateConstructed', [ &$linksUpdate ] );
160  }
161 
167  public function doUpdate() {
168  if ( $this->ticket ) {
169  // Make sure all links update threads see the changes of each other.
170  // This handles the case when updates have to batched into several COMMITs.
171  $scopedLock = self::acquirePageLock( $this->getDB(), $this->mId );
172  }
173 
174  // Avoid PHP 7.1 warning from passing $this by reference
175  $linksUpdate = $this;
176  Hooks::run( 'LinksUpdate', [ &$linksUpdate ] );
177  $this->doIncrementalUpdate();
178 
179  // Commit and release the lock (if set)
180  ScopedCallback::consume( $scopedLock );
181  // Run post-commit hooks without DBO_TRX
182  $this->getDB()->onTransactionIdle(
183  function () {
184  // Avoid PHP 7.1 warning from passing $this by reference
185  $linksUpdate = $this;
186  Hooks::run( 'LinksUpdateComplete', [ &$linksUpdate, $this->ticket ] );
187  },
188  __METHOD__
189  );
190  }
191 
202  public static function acquirePageLock( IDatabase $dbw, $pageId, $why = 'atomicity' ) {
203  $key = "LinksUpdate:$why:pageid:$pageId";
204  $scopedLock = $dbw->getScopedLockAndFlush( $key, __METHOD__, 15 );
205  if ( !$scopedLock ) {
206  throw new RuntimeException( "Could not acquire lock '$key'." );
207  }
208 
209  return $scopedLock;
210  }
211 
212  protected function doIncrementalUpdate() {
213  # Page links
214  $existing = $this->getExistingLinks();
215  $this->linkDeletions = $this->getLinkDeletions( $existing );
216  $this->linkInsertions = $this->getLinkInsertions( $existing );
217  $this->incrTableUpdate( 'pagelinks', 'pl', $this->linkDeletions, $this->linkInsertions );
218 
219  # Image links
220  $existing = $this->getExistingImages();
221  $imageDeletes = $this->getImageDeletions( $existing );
222  $this->incrTableUpdate( 'imagelinks', 'il', $imageDeletes,
223  $this->getImageInsertions( $existing ) );
224 
225  # Invalidate all image description pages which had links added or removed
226  $imageUpdates = $imageDeletes + array_diff_key( $this->mImages, $existing );
227  $this->invalidateImageDescriptions( $imageUpdates );
228 
229  # External links
230  $existing = $this->getExistingExternals();
231  $this->incrTableUpdate( 'externallinks', 'el', $this->getExternalDeletions( $existing ),
232  $this->getExternalInsertions( $existing ) );
233 
234  # Language links
235  $existing = $this->getExistingInterlangs();
236  $this->incrTableUpdate( 'langlinks', 'll', $this->getInterlangDeletions( $existing ),
237  $this->getInterlangInsertions( $existing ) );
238 
239  # Inline interwiki links
240  $existing = $this->getExistingInterwikis();
241  $this->incrTableUpdate( 'iwlinks', 'iwl', $this->getInterwikiDeletions( $existing ),
242  $this->getInterwikiInsertions( $existing ) );
243 
244  # Template links
245  $existing = $this->getExistingTemplates();
246  $this->incrTableUpdate( 'templatelinks', 'tl', $this->getTemplateDeletions( $existing ),
247  $this->getTemplateInsertions( $existing ) );
248 
249  # Category links
250  $existing = $this->getExistingCategories();
251  $categoryDeletes = $this->getCategoryDeletions( $existing );
252  $this->incrTableUpdate( 'categorylinks', 'cl', $categoryDeletes,
253  $this->getCategoryInsertions( $existing ) );
254 
255  # Invalidate all categories which were added, deleted or changed (set symmetric difference)
256  $categoryInserts = array_diff_assoc( $this->mCategories, $existing );
257  $categoryUpdates = $categoryInserts + $categoryDeletes;
258  $this->invalidateCategories( $categoryUpdates );
259  $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
260 
261  # Page properties
262  $existing = $this->getExistingProperties();
263  $this->propertyDeletions = $this->getPropertyDeletions( $existing );
264  $this->incrTableUpdate( 'page_props', 'pp', $this->propertyDeletions,
265  $this->getPropertyInsertions( $existing ) );
266 
267  # Invalidate the necessary pages
268  $this->propertyInsertions = array_diff_assoc( $this->mProperties, $existing );
269  $changed = $this->propertyDeletions + $this->propertyInsertions;
270  $this->invalidateProperties( $changed );
271 
272  # Refresh links of all pages including this page
273  # This will be in a separate transaction
274  if ( $this->mRecursive ) {
275  $this->queueRecursiveJobs();
276  }
277 
278  # Update the links table freshness for this title
279  $this->updateLinksTimestamp();
280  }
281 
288  protected function queueRecursiveJobs() {
289  self::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
290  if ( $this->mTitle->getNamespace() == NS_FILE ) {
291  // Process imagelinks in case the title is or was a redirect
292  self::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
293  }
294 
295  $bc = $this->mTitle->getBacklinkCache();
296  // Get jobs for cascade-protected backlinks for a high priority queue.
297  // If meta-templates change to using a new template, the new template
298  // should be implicitly protected as soon as possible, if applicable.
299  // These jobs duplicate a subset of the above ones, but can run sooner.
300  // Which ever runs first generally no-ops the other one.
301  $jobs = [];
302  foreach ( $bc->getCascadeProtectedLinks() as $title ) {
303  $jobs[] = RefreshLinksJob::newPrioritized( $title, [] );
304  }
305  JobQueueGroup::singleton()->push( $jobs );
306  }
307 
314  public static function queueRecursiveJobsForTable( Title $title, $table ) {
315  if ( $title->getBacklinkCache()->hasLinks( $table ) ) {
316  $job = new RefreshLinksJob(
317  $title,
318  [
319  'table' => $table,
320  'recursive' => true,
321  ] + Job::newRootJobParams( // "overall" refresh links job info
322  "refreshlinks:{$table}:{$title->getPrefixedText()}"
323  )
324  );
325 
326  JobQueueGroup::singleton()->push( $job );
327  }
328  }
329 
333  function invalidateCategories( $cats ) {
334  PurgeJobUtils::invalidatePages( $this->getDB(), NS_CATEGORY, array_keys( $cats ) );
335  }
336 
342  function updateCategoryCounts( $added, $deleted ) {
343  $a = WikiPage::factory( $this->mTitle );
344  $a->updateCategoryCounts(
345  array_keys( $added ), array_keys( $deleted )
346  );
347  }
348 
352  function invalidateImageDescriptions( $images ) {
353  PurgeJobUtils::invalidatePages( $this->getDB(), NS_FILE, array_keys( $images ) );
354  }
355 
363  private function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
364  $services = MediaWikiServices::getInstance();
365  $bSize = $services->getMainConfig()->get( 'UpdateRowsPerQuery' );
366  $factory = $services->getDBLoadBalancerFactory();
367 
368  if ( $table === 'page_props' ) {
369  $fromField = 'pp_page';
370  } else {
371  $fromField = "{$prefix}_from";
372  }
373 
374  $deleteWheres = []; // list of WHERE clause arrays for each DB delete() call
375  if ( $table === 'pagelinks' || $table === 'templatelinks' || $table === 'iwlinks' ) {
376  $baseKey = ( $table === 'iwlinks' ) ? 'iwl_prefix' : "{$prefix}_namespace";
377 
378  $curBatchSize = 0;
379  $curDeletionBatch = [];
380  $deletionBatches = [];
381  foreach ( $deletions as $ns => $dbKeys ) {
382  foreach ( $dbKeys as $dbKey => $unused ) {
383  $curDeletionBatch[$ns][$dbKey] = 1;
384  if ( ++$curBatchSize >= $bSize ) {
385  $deletionBatches[] = $curDeletionBatch;
386  $curDeletionBatch = [];
387  $curBatchSize = 0;
388  }
389  }
390  }
391  if ( $curDeletionBatch ) {
392  $deletionBatches[] = $curDeletionBatch;
393  }
394 
395  foreach ( $deletionBatches as $deletionBatch ) {
396  $deleteWheres[] = [
397  $fromField => $this->mId,
398  $this->getDB()->makeWhereFrom2d( $deletionBatch, $baseKey, "{$prefix}_title" )
399  ];
400  }
401  } else {
402  if ( $table === 'langlinks' ) {
403  $toField = 'll_lang';
404  } elseif ( $table === 'page_props' ) {
405  $toField = 'pp_propname';
406  } else {
407  $toField = $prefix . '_to';
408  }
409 
410  $deletionBatches = array_chunk( array_keys( $deletions ), $bSize );
411  foreach ( $deletionBatches as $deletionBatch ) {
412  $deleteWheres[] = [ $fromField => $this->mId, $toField => $deletionBatch ];
413  }
414  }
415 
416  foreach ( $deleteWheres as $deleteWhere ) {
417  $this->getDB()->delete( $table, $deleteWhere, __METHOD__ );
418  $factory->commitAndWaitForReplication(
419  __METHOD__, $this->ticket, [ 'wiki' => $this->getDB()->getWikiID() ]
420  );
421  }
422 
423  $insertBatches = array_chunk( $insertions, $bSize );
424  foreach ( $insertBatches as $insertBatch ) {
425  $this->getDB()->insert( $table, $insertBatch, __METHOD__, 'IGNORE' );
426  $factory->commitAndWaitForReplication(
427  __METHOD__, $this->ticket, [ 'wiki' => $this->getDB()->getWikiID() ]
428  );
429  }
430 
431  if ( count( $insertions ) ) {
432  Hooks::run( 'LinksUpdateAfterInsert', [ $this, $table, $insertions ] );
433  }
434  }
435 
442  private function getLinkInsertions( $existing = [] ) {
443  $arr = [];
444  foreach ( $this->mLinks as $ns => $dbkeys ) {
445  $diffs = isset( $existing[$ns] )
446  ? array_diff_key( $dbkeys, $existing[$ns] )
447  : $dbkeys;
448  foreach ( $diffs as $dbk => $id ) {
449  $arr[] = [
450  'pl_from' => $this->mId,
451  'pl_from_namespace' => $this->mTitle->getNamespace(),
452  'pl_namespace' => $ns,
453  'pl_title' => $dbk
454  ];
455  }
456  }
457 
458  return $arr;
459  }
460 
466  private function getTemplateInsertions( $existing = [] ) {
467  $arr = [];
468  foreach ( $this->mTemplates as $ns => $dbkeys ) {
469  $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
470  foreach ( $diffs as $dbk => $id ) {
471  $arr[] = [
472  'tl_from' => $this->mId,
473  'tl_from_namespace' => $this->mTitle->getNamespace(),
474  'tl_namespace' => $ns,
475  'tl_title' => $dbk
476  ];
477  }
478  }
479 
480  return $arr;
481  }
482 
489  private function getImageInsertions( $existing = [] ) {
490  $arr = [];
491  $diffs = array_diff_key( $this->mImages, $existing );
492  foreach ( $diffs as $iname => $dummy ) {
493  $arr[] = [
494  'il_from' => $this->mId,
495  'il_from_namespace' => $this->mTitle->getNamespace(),
496  'il_to' => $iname
497  ];
498  }
499 
500  return $arr;
501  }
502 
508  private function getExternalInsertions( $existing = [] ) {
509  $arr = [];
510  $diffs = array_diff_key( $this->mExternals, $existing );
511  foreach ( $diffs as $url => $dummy ) {
512  foreach ( wfMakeUrlIndexes( $url ) as $index ) {
513  $arr[] = [
514  'el_id' => $this->getDB()->nextSequenceValue( 'externallinks_el_id_seq' ),
515  'el_from' => $this->mId,
516  'el_to' => $url,
517  'el_index' => $index,
518  ];
519  }
520  }
521 
522  return $arr;
523  }
524 
533  private function getCategoryInsertions( $existing = [] ) {
534  global $wgContLang, $wgCategoryCollation;
535  $diffs = array_diff_assoc( $this->mCategories, $existing );
536  $arr = [];
537  foreach ( $diffs as $name => $prefix ) {
539  $wgContLang->findVariantLink( $name, $nt, true );
540 
541  if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
542  $type = 'subcat';
543  } elseif ( $this->mTitle->getNamespace() == NS_FILE ) {
544  $type = 'file';
545  } else {
546  $type = 'page';
547  }
548 
549  # Treat custom sortkeys as a prefix, so that if multiple
550  # things are forced to sort as '*' or something, they'll
551  # sort properly in the category rather than in page_id
552  # order or such.
553  $sortkey = Collation::singleton()->getSortKey(
554  $this->mTitle->getCategorySortkey( $prefix ) );
555 
556  $arr[] = [
557  'cl_from' => $this->mId,
558  'cl_to' => $name,
559  'cl_sortkey' => $sortkey,
560  'cl_timestamp' => $this->getDB()->timestamp(),
561  'cl_sortkey_prefix' => $prefix,
562  'cl_collation' => $wgCategoryCollation,
563  'cl_type' => $type,
564  ];
565  }
566 
567  return $arr;
568  }
569 
577  private function getInterlangInsertions( $existing = [] ) {
578  $diffs = array_diff_assoc( $this->mInterlangs, $existing );
579  $arr = [];
580  foreach ( $diffs as $lang => $title ) {
581  $arr[] = [
582  'll_from' => $this->mId,
583  'll_lang' => $lang,
584  'll_title' => $title
585  ];
586  }
587 
588  return $arr;
589  }
590 
596  function getPropertyInsertions( $existing = [] ) {
597  $diffs = array_diff_assoc( $this->mProperties, $existing );
598 
599  $arr = [];
600  foreach ( array_keys( $diffs ) as $name ) {
601  $arr[] = $this->getPagePropRowData( $name );
602  }
603 
604  return $arr;
605  }
606 
623  private function getPagePropRowData( $prop ) {
624  global $wgPagePropsHaveSortkey;
625 
626  $value = $this->mProperties[$prop];
627 
628  $row = [
629  'pp_page' => $this->mId,
630  'pp_propname' => $prop,
631  'pp_value' => $value,
632  ];
633 
634  if ( $wgPagePropsHaveSortkey ) {
635  $row['pp_sortkey'] = $this->getPropertySortKeyValue( $value );
636  }
637 
638  return $row;
639  }
640 
653  private function getPropertySortKeyValue( $value ) {
654  if ( is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
655  return floatval( $value );
656  }
657 
658  return null;
659  }
660 
667  private function getInterwikiInsertions( $existing = [] ) {
668  $arr = [];
669  foreach ( $this->mInterwikis as $prefix => $dbkeys ) {
670  $diffs = isset( $existing[$prefix] )
671  ? array_diff_key( $dbkeys, $existing[$prefix] )
672  : $dbkeys;
673 
674  foreach ( $diffs as $dbk => $id ) {
675  $arr[] = [
676  'iwl_from' => $this->mId,
677  'iwl_prefix' => $prefix,
678  'iwl_title' => $dbk
679  ];
680  }
681  }
682 
683  return $arr;
684  }
685 
692  private function getLinkDeletions( $existing ) {
693  $del = [];
694  foreach ( $existing as $ns => $dbkeys ) {
695  if ( isset( $this->mLinks[$ns] ) ) {
696  $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
697  } else {
698  $del[$ns] = $existing[$ns];
699  }
700  }
701 
702  return $del;
703  }
704 
711  private function getTemplateDeletions( $existing ) {
712  $del = [];
713  foreach ( $existing as $ns => $dbkeys ) {
714  if ( isset( $this->mTemplates[$ns] ) ) {
715  $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
716  } else {
717  $del[$ns] = $existing[$ns];
718  }
719  }
720 
721  return $del;
722  }
723 
730  private function getImageDeletions( $existing ) {
731  return array_diff_key( $existing, $this->mImages );
732  }
733 
740  private function getExternalDeletions( $existing ) {
741  return array_diff_key( $existing, $this->mExternals );
742  }
743 
750  private function getCategoryDeletions( $existing ) {
751  return array_diff_assoc( $existing, $this->mCategories );
752  }
753 
760  private function getInterlangDeletions( $existing ) {
761  return array_diff_assoc( $existing, $this->mInterlangs );
762  }
763 
769  function getPropertyDeletions( $existing ) {
770  return array_diff_assoc( $existing, $this->mProperties );
771  }
772 
779  private function getInterwikiDeletions( $existing ) {
780  $del = [];
781  foreach ( $existing as $prefix => $dbkeys ) {
782  if ( isset( $this->mInterwikis[$prefix] ) ) {
783  $del[$prefix] = array_diff_key( $existing[$prefix], $this->mInterwikis[$prefix] );
784  } else {
785  $del[$prefix] = $existing[$prefix];
786  }
787  }
788 
789  return $del;
790  }
791 
797  private function getExistingLinks() {
798  $res = $this->getDB()->select( 'pagelinks', [ 'pl_namespace', 'pl_title' ],
799  [ 'pl_from' => $this->mId ], __METHOD__ );
800  $arr = [];
801  foreach ( $res as $row ) {
802  if ( !isset( $arr[$row->pl_namespace] ) ) {
803  $arr[$row->pl_namespace] = [];
804  }
805  $arr[$row->pl_namespace][$row->pl_title] = 1;
806  }
807 
808  return $arr;
809  }
810 
816  private function getExistingTemplates() {
817  $res = $this->getDB()->select( 'templatelinks', [ 'tl_namespace', 'tl_title' ],
818  [ 'tl_from' => $this->mId ], __METHOD__ );
819  $arr = [];
820  foreach ( $res as $row ) {
821  if ( !isset( $arr[$row->tl_namespace] ) ) {
822  $arr[$row->tl_namespace] = [];
823  }
824  $arr[$row->tl_namespace][$row->tl_title] = 1;
825  }
826 
827  return $arr;
828  }
829 
835  private function getExistingImages() {
836  $res = $this->getDB()->select( 'imagelinks', [ 'il_to' ],
837  [ 'il_from' => $this->mId ], __METHOD__ );
838  $arr = [];
839  foreach ( $res as $row ) {
840  $arr[$row->il_to] = 1;
841  }
842 
843  return $arr;
844  }
845 
851  private function getExistingExternals() {
852  $res = $this->getDB()->select( 'externallinks', [ 'el_to' ],
853  [ 'el_from' => $this->mId ], __METHOD__ );
854  $arr = [];
855  foreach ( $res as $row ) {
856  $arr[$row->el_to] = 1;
857  }
858 
859  return $arr;
860  }
861 
867  private function getExistingCategories() {
868  $res = $this->getDB()->select( 'categorylinks', [ 'cl_to', 'cl_sortkey_prefix' ],
869  [ 'cl_from' => $this->mId ], __METHOD__ );
870  $arr = [];
871  foreach ( $res as $row ) {
872  $arr[$row->cl_to] = $row->cl_sortkey_prefix;
873  }
874 
875  return $arr;
876  }
877 
884  private function getExistingInterlangs() {
885  $res = $this->getDB()->select( 'langlinks', [ 'll_lang', 'll_title' ],
886  [ 'll_from' => $this->mId ], __METHOD__ );
887  $arr = [];
888  foreach ( $res as $row ) {
889  $arr[$row->ll_lang] = $row->ll_title;
890  }
891 
892  return $arr;
893  }
894 
899  private function getExistingInterwikis() {
900  $res = $this->getDB()->select( 'iwlinks', [ 'iwl_prefix', 'iwl_title' ],
901  [ 'iwl_from' => $this->mId ], __METHOD__ );
902  $arr = [];
903  foreach ( $res as $row ) {
904  if ( !isset( $arr[$row->iwl_prefix] ) ) {
905  $arr[$row->iwl_prefix] = [];
906  }
907  $arr[$row->iwl_prefix][$row->iwl_title] = 1;
908  }
909 
910  return $arr;
911  }
912 
918  private function getExistingProperties() {
919  $res = $this->getDB()->select( 'page_props', [ 'pp_propname', 'pp_value' ],
920  [ 'pp_page' => $this->mId ], __METHOD__ );
921  $arr = [];
922  foreach ( $res as $row ) {
923  $arr[$row->pp_propname] = $row->pp_value;
924  }
925 
926  return $arr;
927  }
928 
933  public function getTitle() {
934  return $this->mTitle;
935  }
936 
942  public function getParserOutput() {
943  return $this->mParserOutput;
944  }
945 
950  public function getImages() {
951  return $this->mImages;
952  }
953 
961  public function setRevision( Revision $revision ) {
962  $this->mRevision = $revision;
963  }
964 
969  public function getRevision() {
970  return $this->mRevision;
971  }
972 
979  public function setTriggeringUser( User $user ) {
980  $this->user = $user;
981  }
982 
987  public function getTriggeringUser() {
988  return $this->user;
989  }
990 
995  private function invalidateProperties( $changed ) {
996  global $wgPagePropLinkInvalidations;
997 
998  foreach ( $changed as $name => $value ) {
999  if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
1000  $inv = $wgPagePropLinkInvalidations[$name];
1001  if ( !is_array( $inv ) ) {
1002  $inv = [ $inv ];
1003  }
1004  foreach ( $inv as $table ) {
1005  DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->mTitle, $table ) );
1006  }
1007  }
1008  }
1009  }
1010 
1016  public function getAddedLinks() {
1017  if ( $this->linkInsertions === null ) {
1018  return null;
1019  }
1020  $result = [];
1021  foreach ( $this->linkInsertions as $insertion ) {
1022  $result[] = Title::makeTitle( $insertion['pl_namespace'], $insertion['pl_title'] );
1023  }
1024 
1025  return $result;
1026  }
1027 
1033  public function getRemovedLinks() {
1034  if ( $this->linkDeletions === null ) {
1035  return null;
1036  }
1037  $result = [];
1038  foreach ( $this->linkDeletions as $ns => $titles ) {
1039  foreach ( $titles as $title => $unused ) {
1040  $result[] = Title::makeTitle( $ns, $title );
1041  }
1042  }
1043 
1044  return $result;
1045  }
1046 
1053  public function getAddedProperties() {
1055  }
1056 
1063  public function getRemovedProperties() {
1064  return $this->propertyDeletions;
1065  }
1066 
1070  private function updateLinksTimestamp() {
1071  if ( $this->mId ) {
1072  // The link updates made here only reflect the freshness of the parser output
1073  $timestamp = $this->mParserOutput->getCacheTime();
1074  $this->getDB()->update( 'page',
1075  [ 'page_links_updated' => $this->getDB()->timestamp( $timestamp ) ],
1076  [ 'page_id' => $this->mId ],
1077  __METHOD__
1078  );
1079  }
1080  }
1081 
1085  private function getDB() {
1086  if ( !$this->db ) {
1087  $this->db = wfGetDB( DB_MASTER );
1088  }
1089 
1090  return $this->db;
1091  }
1092 
1093  public function getAsJobSpecification() {
1094  if ( $this->user ) {
1095  $userInfo = [
1096  'userId' => $this->user->getId(),
1097  'userName' => $this->user->getName(),
1098  ];
1099  } else {
1100  $userInfo = false;
1101  }
1102 
1103  if ( $this->mRevision ) {
1104  $triggeringRevisionId = $this->mRevision->getId();
1105  } else {
1106  $triggeringRevisionId = false;
1107  }
1108 
1109  return [
1110  'wiki' => $this->getDB()->getWikiID(),
1111  'job' => new JobSpecification(
1112  'refreshLinksPrioritized',
1113  [
1114  // Reuse the parser cache if it was saved
1115  'rootJobTimestamp' => $this->mParserOutput->getCacheTime(),
1116  'useRecursiveLinksUpdate' => $this->mRecursive,
1117  'triggeringUser' => $userInfo,
1118  'triggeringRevisionId' => $triggeringRevisionId,
1119  ],
1120  [ 'removeDuplicates' => true ],
1121  $this->getTitle()
1122  )
1123  ];
1124  }
1125 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
setRevision(Revision $revision)
Set the revision corresponding to this LinksUpdate.
invalidateProperties($changed)
Invalidate any necessary link lists related to page property changes.
updateLinksTimestamp()
Update links table freshness.
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
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
queueRecursiveJobs()
Queue recursive jobs for this page.
getImageDeletions($existing)
Given an array of existing images, returns those images which are not in $this and thus should be del...
bool $mRecursive
Whether to queue jobs for recursive updates.
Definition: LinksUpdate.php:70
getArticleID($flags=0)
Get the article ID for this Title from the link cache, adding it if necessary.
Definition: Title.php:3209
static invalidatePages(IDatabase $dbw, $namespace, array $dbkeys)
Invalidate the cache of a list of pages from a single namespace.
getPropertySortKeyValue($value)
Determines the sort key for the given property value.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Class the manages updates of *_link tables as well as similar extension-managed tables.
Definition: LinksUpdate.php:33
getCategoryInsertions($existing=[])
Get an array of category insertions.
getExistingInterwikis()
Get an array of existing inline interwiki links, as a 2-D array.
array $mProperties
Map of arbitrary name to value.
Definition: LinksUpdate.php:67
static singleton()
Definition: Collation.php:34
if(!isset($args[0])) $lang
Interface that marks a DataUpdate as enqueuable via the JobQueue.
$value
static newRootJobParams($key)
Get "root job" parameters for a task.
Definition: Job.php:261
wfMakeUrlIndexes($url)
Make URL indexes, appropriate for the el_index field of externallinks.
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 MediaWikiServices
Definition: injection.txt:23
Revision $mRevision
Revision for which this update has been triggered.
Definition: LinksUpdate.php:73
null array $linkInsertions
Added links if calculated.
Definition: LinksUpdate.php:78
updateCategoryCounts($added, $deleted)
Update all the appropriate counts in the category table.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getExistingProperties()
Get an array of existing categories, with the name in the key and sort key in the value...
Title $mTitle
Title object of the article linked from.
Definition: LinksUpdate.php:40
getBacklinkCache()
Get a backlink cache object.
Definition: Title.php:4624
const DB_MASTER
Definition: defines.php:23
__construct(Title $title, ParserOutput $parserOutput, $recursive=true)
Constructor.
getPagePropRowData($prop)
Returns an associative array to be used for inserting a row into the page_props table.
getExistingInterlangs()
Get an array of existing interlanguage links, with the language code in the key and the title in the ...
either a unescaped string or a HtmlArmor object after in associative array form externallinks $linksUpdate
Definition: hooks.txt:2009
static queueRecursiveJobsForTable(Title $title, $table)
Queue a RefreshLinks job for any table.
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1938
ParserOutput $mParserOutput
Definition: LinksUpdate.php:43
getTemplateDeletions($existing)
Given an array of existing templates, returns those templates which are not in $this and thus should ...
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2893
getLinkInsertions($existing=[])
Get an array of pagelinks insertions for passing to the DB Skips the titles specified by the 2-D arra...
getInterlangDeletions($existing)
Given an array of existing interlanguage links, returns those links which are not in $this and thus s...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1940
getPropertyInsertions($existing=[])
Get an array of page property insertions.
getRemovedProperties()
Fetch page properties removed by this LinksUpdate.
getTitle()
Return the title object of the page being updated.
getExistingCategories()
Get an array of existing categories, with the name in the key and sort key in the value...
array $mImages
DB keys of the images used, in the array key only.
Definition: LinksUpdate.php:49
getExistingExternals()
Get an array of existing external links, URLs in the keys.
getParserOutput()
Returns parser output.
getCategoryDeletions($existing)
Given an array of existing categories, returns those categories which are not in $this and thus shoul...
Class to invalidate the HTML cache of all the pages linking to a given title.
getAddedLinks()
Fetch page links added by this LinksUpdate.
if($limit) $timestamp
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1050
null array $propertyInsertions
Added properties if calculated.
Definition: LinksUpdate.php:88
$res
Definition: database.txt:21
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
Definition: Title.php:51
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.
Definition: distributors.txt:9
setTriggeringUser(User $user)
Set the User who triggered this LinksUpdate.
getRemovedLinks()
Fetch page links removed by this LinksUpdate.
const NS_CATEGORY
Definition: Defines.php:70
incrTableUpdate($table, $prefix, $deletions, $insertions)
Update a table by doing a delete query then an insert query.
array $mExternals
URLs of external links, array key only.
Definition: LinksUpdate.php:55
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:535
array $mTemplates
Map of title strings to IDs for the template references, including broken ones.
Definition: LinksUpdate.php:52
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:957
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
invalidateCategories($cats)
getExistingImages()
Get an array of existing images, image names in the keys.
const NS_FILE
Definition: Defines.php:62
getInterlangInsertions($existing=[])
Get an array of interlanguage link insertions.
getTemplateInsertions($existing=[])
Get an array of template insertions.
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:2163
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
Definition: distributors.txt:9
getExistingTemplates()
Get an array of existing templates, as a 2-D array.
getExternalInsertions($existing=[])
Get an array of externallinks insertions.
getExistingLinks()
Get an array of existing links, as a 2-D array.
invalidateImageDescriptions($images)
static singleton($wiki=false)
Job to update link tables for pages.
User null $user
Definition: LinksUpdate.php:98
null array $propertyDeletions
Deleted properties if calculated.
Definition: LinksUpdate.php:93
array $mLinks
Map of title strings to IDs for the links in the document.
Definition: LinksUpdate.php:46
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:35
getExternalDeletions($existing)
Given an array of existing external links, returns those links which are not in $this and thus should...
getInterwikiDeletions($existing)
Given an array of existing interwiki links, returns those links which are not in $this and thus shoul...
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
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
Abstract base class for update jobs that do something with some secondary data extracted from article...
Definition: DataUpdate.php:28
getAddedProperties()
Fetch page properties added by this LinksUpdate.
if(count($args)< 1) $job
static newPrioritized(Title $title, array $params)
getPropertyDeletions($existing)
Get array of properties which should be deleted.
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:56
getInterwikiInsertions($existing=[])
Get an array of interwiki insertions for passing to the DB Skips the titles specified by the 2-D arra...
getLinkDeletions($existing)
Given an array of existing links, returns those links which are not in $this and thus should be delet...
doUpdate()
Update link tables with outgoing links from an updated article.
null array $linkDeletions
Deleted links if calculated.
Definition: LinksUpdate.php:83
getImages()
Return the list of images used as generated by the parser.
array $mInterlangs
Map of language codes to titles.
Definition: LinksUpdate.php:61
static acquirePageLock(IDatabase $dbw, $pageId, $why= 'atomicity')
Acquire a lock for performing link table updates for a page on a DB.
int $mId
Page ID of the article linked from.
Definition: LinksUpdate.php:37
getImageInsertions($existing=[])
Get an array of image insertions Skips the names specified in $existing.
array $mCategories
Map of category names to sort keys.
Definition: LinksUpdate.php:58
Job queue task description base code.
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 one of or reset 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:2495
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:511
getScopedLockAndFlush($lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:34
array $mInterwikis
2-D map of (prefix => DBK => 1)
Definition: LinksUpdate.php:64
IDatabase $db
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304