MediaWiki  1.29.1
refreshLinks.php
Go to the documentation of this file.
1 <?php
25 
26 require_once __DIR__ . '/Maintenance.php';
27 
33 class RefreshLinks extends Maintenance {
34  const REPORTING_INTERVAL = 100;
35 
37  protected $namespace = false;
38 
39  public function __construct() {
40  parent::__construct();
41  $this->addDescription( 'Refresh link tables' );
42  $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
43  $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
44  $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
45  $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
46  $this->addOption( 'e', 'Last page id to refresh', false, true );
47  $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
48  'query, default 100000', false, true );
49  $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
50  $this->addOption( 'category', 'Only fix pages in this category', false, true );
51  $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
52  $this->addArg( 'start', 'Page_id to start from, default 1', false );
53  $this->setBatchSize( 100 );
54  }
55 
56  public function execute() {
57  // Note that there is a difference between not specifying the start
58  // and end IDs and using the minimum and maximum values from the page
59  // table. In the latter case, deleteLinksFromNonexistent() will not
60  // delete entries for nonexistent IDs that fall outside the range.
61  $start = (int)$this->getArg( 0 ) ?: null;
62  $end = (int)$this->getOption( 'e' ) ?: null;
63  $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
64  $ns = $this->getOption( 'namespace' );
65  if ( $ns === null ) {
66  $this->namespace = false;
67  } else {
68  $this->namespace = (int)$ns;
69  }
70  if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
71  $title = Title::makeTitleSafe( NS_CATEGORY, $category );
72  if ( !$title ) {
73  $this->error( "'$category' is an invalid category name!\n", true );
74  }
75  $this->refreshCategory( $title );
76  } elseif ( ( $category = $this->getOption( 'tracking-category', false ) ) !== false ) {
77  $this->refreshTrackingCategory( $category );
78  } elseif ( !$this->hasOption( 'dfn-only' ) ) {
79  $new = $this->getOption( 'new-only', false );
80  $redir = $this->getOption( 'redirects-only', false );
81  $oldRedir = $this->getOption( 'old-redirects-only', false );
82  $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
83  $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize, $dfnChunkSize );
84  } else {
85  $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize, $dfnChunkSize );
86  }
87  }
88 
89  private function namespaceCond() {
90  return $this->namespace !== false
91  ? [ 'page_namespace' => $this->namespace ]
92  : [];
93  }
94 
103  private function doRefreshLinks( $start, $newOnly = false,
104  $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
105  ) {
106  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
107 
108  if ( $start === null ) {
109  $start = 1;
110  }
111 
112  // Give extensions a chance to optimize settings
113  Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
114 
115  $what = $redirectsOnly ? "redirects" : "links";
116 
117  if ( $oldRedirectsOnly ) {
118  # This entire code path is cut-and-pasted from below. Hurrah.
119 
120  $conds = [
121  "page_is_redirect=1",
122  "rd_from IS NULL",
123  self::intervalCond( $dbr, 'page_id', $start, $end ),
124  ] + $this->namespaceCond();
125 
126  $res = $dbr->select(
127  [ 'page', 'redirect' ],
128  'page_id',
129  $conds,
130  __METHOD__,
131  [],
132  [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
133  );
134  $num = $res->numRows();
135  $this->output( "Refreshing $num old redirects from $start...\n" );
136 
137  $i = 0;
138 
139  foreach ( $res as $row ) {
140  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
141  $this->output( "$i\n" );
142  wfWaitForSlaves();
143  }
144  $this->fixRedirect( $row->page_id );
145  }
146  } elseif ( $newOnly ) {
147  $this->output( "Refreshing $what from " );
148  $res = $dbr->select( 'page',
149  [ 'page_id' ],
150  [
151  'page_is_new' => 1,
152  self::intervalCond( $dbr, 'page_id', $start, $end ),
153  ] + $this->namespaceCond(),
154  __METHOD__
155  );
156  $num = $res->numRows();
157  $this->output( "$num new articles...\n" );
158 
159  $i = 0;
160  foreach ( $res as $row ) {
161  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
162  $this->output( "$i\n" );
163  wfWaitForSlaves();
164  }
165  if ( $redirectsOnly ) {
166  $this->fixRedirect( $row->page_id );
167  } else {
168  self::fixLinksFromArticle( $row->page_id, $this->namespace );
169  }
170  }
171  } else {
172  if ( !$end ) {
173  $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
174  $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
175  $end = max( $maxPage, $maxRD );
176  }
177  $this->output( "Refreshing redirects table.\n" );
178  $this->output( "Starting from page_id $start of $end.\n" );
179 
180  for ( $id = $start; $id <= $end; $id++ ) {
181 
182  if ( !( $id % self::REPORTING_INTERVAL ) ) {
183  $this->output( "$id\n" );
184  wfWaitForSlaves();
185  }
186  $this->fixRedirect( $id );
187  }
188 
189  if ( !$redirectsOnly ) {
190  $this->output( "Refreshing links tables.\n" );
191  $this->output( "Starting from page_id $start of $end.\n" );
192 
193  for ( $id = $start; $id <= $end; $id++ ) {
194 
195  if ( !( $id % self::REPORTING_INTERVAL ) ) {
196  $this->output( "$id\n" );
197  wfWaitForSlaves();
198  }
199  self::fixLinksFromArticle( $id, $this->namespace );
200  }
201  }
202  }
203  }
204 
217  private function fixRedirect( $id ) {
218  $page = WikiPage::newFromID( $id );
219  $dbw = $this->getDB( DB_MASTER );
220 
221  if ( $page === null ) {
222  // This page doesn't exist (any more)
223  // Delete any redirect table entry for it
224  $dbw->delete( 'redirect', [ 'rd_from' => $id ],
225  __METHOD__ );
226 
227  return;
228  } elseif ( $this->namespace !== false
229  && !$page->getTitle()->inNamespace( $this->namespace )
230  ) {
231  return;
232  }
233 
234  $rt = null;
235  $content = $page->getContent( Revision::RAW );
236  if ( $content !== null ) {
237  $rt = $content->getUltimateRedirectTarget();
238  }
239 
240  if ( $rt === null ) {
241  // The page is not a redirect
242  // Delete any redirect table entry for it
243  $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
244  $fieldValue = 0;
245  } else {
246  $page->insertRedirectEntry( $rt );
247  $fieldValue = 1;
248  }
249 
250  // Update the page table to be sure it is an a consistent state
251  $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
252  [ 'page_id' => $id ], __METHOD__ );
253  }
254 
260  public static function fixLinksFromArticle( $id, $ns = false ) {
261  $page = WikiPage::newFromID( $id );
262 
263  LinkCache::singleton()->clear();
264 
265  if ( $page === null ) {
266  return;
267  } elseif ( $ns !== false
268  && !$page->getTitle()->inNamespace( $ns ) ) {
269  return;
270  }
271 
272  $content = $page->getContent( Revision::RAW );
273  if ( $content === null ) {
274  return;
275  }
276 
277  $updates = $content->getSecondaryDataUpdates(
278  $page->getTitle(), /* $old = */ null, /* $recursive = */ false );
279  foreach ( $updates as $update ) {
280  DeferredUpdates::addUpdate( $update );
282  }
283  }
284 
296  private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
297  $chunkSize = 100000
298  ) {
299  wfWaitForSlaves();
300  $this->output( "Deleting illegal entries from the links tables...\n" );
301  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
302  do {
303  // Find the start of the next chunk. This is based only
304  // on existent page_ids.
305  $nextStart = $dbr->selectField(
306  'page',
307  'page_id',
308  [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
309  + $this->namespaceCond(),
310  __METHOD__,
311  [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
312  );
313 
314  if ( $nextStart !== false ) {
315  // To find the end of the current chunk, subtract one.
316  // This will serve to limit the number of rows scanned in
317  // dfnCheckInterval(), per query, to at most the sum of
318  // the chunk size and deletion batch size.
319  $chunkEnd = $nextStart - 1;
320  } else {
321  // This is the last chunk. Check all page_ids up to $end.
322  $chunkEnd = $end;
323  }
324 
325  $fmtStart = $start !== null ? "[$start" : '(-INF';
326  $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
327  $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
328  $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
329 
330  $start = $nextStart;
331 
332  } while ( $nextStart !== false );
333  }
334 
341  private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
342  $dbw = $this->getDB( DB_MASTER );
343  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
344 
345  $linksTables = [ // table name => page_id field
346  'pagelinks' => 'pl_from',
347  'imagelinks' => 'il_from',
348  'categorylinks' => 'cl_from',
349  'templatelinks' => 'tl_from',
350  'externallinks' => 'el_from',
351  'iwlinks' => 'iwl_from',
352  'langlinks' => 'll_from',
353  'redirect' => 'rd_from',
354  'page_props' => 'pp_page',
355  ];
356 
357  foreach ( $linksTables as $table => $field ) {
358  $this->output( " $table: 0" );
359  $tableStart = $start;
360  $counter = 0;
361  do {
362  $ids = $dbr->selectFieldValues(
363  $table,
364  $field,
365  [
366  self::intervalCond( $dbr, $field, $tableStart, $end ),
367  "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
368  ],
369  __METHOD__,
370  [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
371  );
372 
373  $numIds = count( $ids );
374  if ( $numIds ) {
375  $counter += $numIds;
376  $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
377  $this->output( ", $counter" );
378  $tableStart = $ids[$numIds - 1] + 1;
379  wfWaitForSlaves();
380  }
381 
382  } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
383 
384  $this->output( " deleted.\n" );
385  }
386  }
387 
400  private static function intervalCond( IDatabase $db, $var, $start, $end ) {
401  if ( $start === null && $end === null ) {
402  return "$var IS NOT NULL";
403  } elseif ( $end === null ) {
404  return "$var >= {$db->addQuotes( $start )}";
405  } elseif ( $start === null ) {
406  return "$var <= {$db->addQuotes( $end )}";
407  } else {
408  return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
409  }
410  }
411 
417  private function refreshTrackingCategory( $category ) {
418  $cats = $this->getPossibleCategories( $category );
419 
420  if ( !$cats ) {
421  $this->error( "Tracking category '$category' is disabled\n" );
422  // Output to stderr but don't bail out,
423  }
424 
425  foreach ( $cats as $cat ) {
426  $this->refreshCategory( $cat );
427  }
428  }
429 
435  private function refreshCategory( Title $category ) {
436  $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
437 
438  $dbr = $this->getDB( DB_REPLICA );
439  $conds = [
440  'page_id=cl_from',
441  'cl_to' => $category->getDBkey(),
442  ];
443  if ( $this->namespace !== false ) {
444  $conds['page_namespace'] = $this->namespace;
445  }
446 
447  $i = 0;
448  $timestamp = '';
449  $lastId = 0;
450  do {
451  $finalConds = $conds;
452  $timestamp = $dbr->addQuotes( $timestamp );
453  $finalConds []=
454  "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
455  $res = $dbr->select( [ 'page', 'categorylinks' ],
456  [ 'page_id', 'cl_timestamp' ],
457  $finalConds,
458  __METHOD__,
459  [
460  'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
461  'LIMIT' => $this->mBatchSize,
462  ]
463  );
464 
465  foreach ( $res as $row ) {
466  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
467  $this->output( "$i\n" );
468  wfWaitForSlaves();
469  }
470  $lastId = $row->page_id;
471  $timestamp = $row->cl_timestamp;
472  self::fixLinksFromArticle( $row->page_id );
473  }
474 
475  } while ( $res->numRows() == $this->mBatchSize );
476  }
477 
484  private function getPossibleCategories( $categoryKey ) {
485  $trackingCategories = new TrackingCategories( $this->getConfig() );
486  $cats = $trackingCategories->getTrackingCategories();
487  if ( isset( $cats[$categoryKey] ) ) {
488  return $cats[$categoryKey]['cats'];
489  }
490  $this->error( "Unknown tracking category {$categoryKey}\n", true );
491  }
492 }
493 
494 $maintClass = 'RefreshLinks';
495 require_once RUN_MAINTENANCE_IF_MAIN;
Maintenance\$mBatchSize
int $mBatchSize
Batch size.
Definition: Maintenance.php:103
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
captcha-old.count
count
Definition: captcha-old.py:225
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:287
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
Definition: DeferredUpdates.php:76
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
$res
$res
Definition: database.txt:21
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
wfWaitForSlaves
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
Definition: GlobalFunctions.php:3214
php
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
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
REPORTING_INTERVAL
const REPORTING_INTERVAL
Definition: moveToExternal.php:24
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:901
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:504
$content
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 called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1049
$page
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 $page
Definition: hooks.txt:2536
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:215
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:76
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:538
WikiPage\newFromID
static newFromID( $id, $from='fromdb')
Constructor from a page id.
Definition: WikiPage.php:158
Revision\RAW
const RAW
Definition: Revision.php:100
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Do any deferred updates and clear the list.
Definition: DeferredUpdates.php:123
TrackingCategories
This class performs some operations related to tracking categories, such as creating a list of all su...
Definition: TrackingCategories.php:26
Title
Represents a title within MediaWiki.
Definition: Title.php:39
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:250
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
LinkCache\singleton
static singleton()
Get an instance of this class.
Definition: LinkCache.php:67
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:267
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 as
Definition: distributors.txt:9
Maintenance\getDB
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1251
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:392
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:373
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:236
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:306
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:314