MediaWiki  master
refreshLinks.php
Go to the documentation of this file.
1 <?php
27 
28 require_once __DIR__ . '/Maintenance.php';
29 
35 class RefreshLinks extends Maintenance {
36  private const REPORTING_INTERVAL = 100;
37 
39  protected $namespace = false;
40 
41  public function __construct() {
42  parent::__construct();
43  $this->addDescription( 'Refresh link tables' );
44  $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
45  $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
46  $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
47  $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
48  $this->addOption( 'e', 'Last page id to refresh', false, true );
49  $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
50  'query, default 100000', false, true );
51  $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
52  $this->addOption( 'category', 'Only fix pages in this category', false, true );
53  $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
54  $this->addArg( 'start', 'Page_id to start from, default 1', false );
55  $this->setBatchSize( 100 );
56  }
57 
58  public function execute() {
59  // Note that there is a difference between not specifying the start
60  // and end IDs and using the minimum and maximum values from the page
61  // table. In the latter case, deleteLinksFromNonexistent() will not
62  // delete entries for nonexistent IDs that fall outside the range.
63  $start = (int)$this->getArg( 0 ) ?: null;
64  $end = (int)$this->getOption( 'e' ) ?: null;
65  $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
66  $ns = $this->getOption( 'namespace' );
67  if ( $ns === null ) {
68  $this->namespace = false;
69  } else {
70  $this->namespace = (int)$ns;
71  }
72  if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
73  $title = Title::makeTitleSafe( NS_CATEGORY, $category );
74  if ( !$title ) {
75  $this->fatalError( "'$category' is an invalid category name!\n" );
76  }
77  $this->refreshCategory( $title );
78  } elseif ( ( $category = $this->getOption( 'tracking-category', false ) ) !== false ) {
79  $this->refreshTrackingCategory( $category );
80  } elseif ( !$this->hasOption( 'dfn-only' ) ) {
81  $new = $this->hasOption( 'new-only' );
82  $redir = $this->hasOption( 'redirects-only' );
83  $oldRedir = $this->hasOption( 'old-redirects-only' );
84  $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
85  $this->deleteLinksFromNonexistent( null, null, $this->getBatchSize(), $dfnChunkSize );
86  } else {
87  $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
88  }
89  }
90 
91  private function namespaceCond() {
92  return $this->namespace !== false
93  ? [ 'page_namespace' => $this->namespace ]
94  : [];
95  }
96 
105  private function doRefreshLinks( $start, $newOnly = false,
106  $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
107  ) {
108  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
109 
110  if ( $start === null ) {
111  $start = 1;
112  }
113 
114  // Give extensions a chance to optimize settings
115  $this->getHookRunner()->onMaintenanceRefreshLinksInit( $this );
116 
117  $what = $redirectsOnly ? "redirects" : "links";
118  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
119 
120  if ( $oldRedirectsOnly ) {
121  # This entire code path is cut-and-pasted from below. Hurrah.
122 
123  $conds = [
124  "page_is_redirect=1",
125  "rd_from IS NULL",
126  self::intervalCond( $dbr, 'page_id', $start, $end ),
127  ] + $this->namespaceCond();
128 
129  $res = $dbr->select(
130  [ 'page', 'redirect' ],
131  'page_id',
132  $conds,
133  __METHOD__,
134  [],
135  [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
136  );
137  $num = $res->numRows();
138  $this->output( "Refreshing $num old redirects from $start...\n" );
139 
140  $i = 0;
141 
142  foreach ( $res as $row ) {
143  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
144  $this->output( "$i\n" );
145  $lbFactory->waitForReplication();
146  }
147  $this->fixRedirect( $row->page_id );
148  }
149  } elseif ( $newOnly ) {
150  $this->output( "Refreshing $what from " );
151  $res = $dbr->select( 'page',
152  [ 'page_id' ],
153  [
154  'page_is_new' => 1,
155  self::intervalCond( $dbr, 'page_id', $start, $end ),
156  ] + $this->namespaceCond(),
157  __METHOD__
158  );
159  $num = $res->numRows();
160  $this->output( "$num new articles...\n" );
161 
162  $i = 0;
163  foreach ( $res as $row ) {
164  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
165  $this->output( "$i\n" );
166  $lbFactory->waitForReplication();
167  }
168  if ( $redirectsOnly ) {
169  $this->fixRedirect( $row->page_id );
170  } else {
171  self::fixLinksFromArticle( $row->page_id, $this->namespace );
172  }
173  }
174  } else {
175  if ( !$end ) {
176  $maxPage = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
177  $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', '', __METHOD__ );
178  $end = max( $maxPage, $maxRD );
179  }
180  $this->output( "Refreshing redirects table.\n" );
181  $this->output( "Starting from page_id $start of $end.\n" );
182 
183  for ( $id = $start; $id <= $end; $id++ ) {
184  if ( !( $id % self::REPORTING_INTERVAL ) ) {
185  $this->output( "$id\n" );
186  $lbFactory->waitForReplication();
187  }
188  $this->fixRedirect( $id );
189  }
190 
191  if ( !$redirectsOnly ) {
192  $this->output( "Refreshing links tables.\n" );
193  $this->output( "Starting from page_id $start of $end.\n" );
194 
195  for ( $id = $start; $id <= $end; $id++ ) {
196  if ( !( $id % self::REPORTING_INTERVAL ) ) {
197  $this->output( "$id\n" );
198  $lbFactory->waitForReplication();
199  }
200  self::fixLinksFromArticle( $id, $this->namespace );
201  }
202  }
203  }
204  }
205 
218  private function fixRedirect( $id ) {
219  $page = WikiPage::newFromID( $id );
220  $dbw = $this->getDB( DB_MASTER );
221 
222  if ( $page === null ) {
223  // This page doesn't exist (any more)
224  // Delete any redirect table entry for it
225  $dbw->delete( 'redirect', [ 'rd_from' => $id ],
226  __METHOD__ );
227 
228  return;
229  } elseif ( $this->namespace !== false
230  && !$page->getTitle()->inNamespace( $this->namespace )
231  ) {
232  return;
233  }
234 
235  $rt = null;
236  $content = $page->getContent( RevisionRecord::RAW );
237  if ( $content !== null ) {
238  $rt = $content->getUltimateRedirectTarget();
239  }
240 
241  if ( $rt === null ) {
242  // The page is not a redirect
243  // Delete any redirect table entry for it
244  $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
245  $fieldValue = 0;
246  } else {
247  $page->insertRedirectEntry( $rt );
248  $fieldValue = 1;
249  }
250 
251  // Update the page table to be sure it is an a consistent state
252  $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
253  [ 'page_id' => $id ], __METHOD__ );
254  }
255 
261  public static function fixLinksFromArticle( $id, $ns = false ) {
262  $page = WikiPage::newFromID( $id );
263 
264  MediaWikiServices::getInstance()->getLinkCache()->clear();
265 
266  if ( $page === null ) {
267  return;
268  } elseif ( $ns !== false
269  && !$page->getTitle()->inNamespace( $ns ) ) {
270  return;
271  }
272 
273  // Defer updates to post-send but then immediately execute deferred updates;
274  // this is the simplest way to run all updates immediately (including updates
275  // scheduled by other updates).
276  $page->doSecondaryDataUpdates( [
277  'defer' => DeferredUpdates::POSTSEND,
278  'recursive' => false,
279  ] );
281  }
282 
294  private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
295  $chunkSize = 100000
296  ) {
297  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
298  $this->output( "Deleting illegal entries from the links tables...\n" );
299  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
300  do {
301  // Find the start of the next chunk. This is based only
302  // on existent page_ids.
303  $nextStart = $dbr->selectField(
304  'page',
305  'page_id',
306  [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
307  + $this->namespaceCond(),
308  __METHOD__,
309  [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
310  );
311 
312  if ( $nextStart !== false ) {
313  // To find the end of the current chunk, subtract one.
314  // This will serve to limit the number of rows scanned in
315  // dfnCheckInterval(), per query, to at most the sum of
316  // the chunk size and deletion batch size.
317  $chunkEnd = $nextStart - 1;
318  } else {
319  // This is the last chunk. Check all page_ids up to $end.
320  $chunkEnd = $end;
321  }
322 
323  $fmtStart = $start !== null ? "[$start" : '(-INF';
324  $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
325  $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
326  $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
327 
328  $start = $nextStart;
329 
330  } while ( $nextStart !== false );
331  }
332 
339  private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
340  $dbw = $this->getDB( DB_MASTER );
341  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
342 
343  $linksTables = [
344  // table name => page_id field
345  'pagelinks' => 'pl_from',
346  'imagelinks' => 'il_from',
347  'categorylinks' => 'cl_from',
348  'templatelinks' => 'tl_from',
349  'externallinks' => 'el_from',
350  'iwlinks' => 'iwl_from',
351  'langlinks' => 'll_from',
352  'redirect' => 'rd_from',
353  'page_props' => 'pp_page',
354  ];
355 
356  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
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', [], __METHOD__ )})",
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  $lbFactory->waitForReplication();
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  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
451  do {
452  $finalConds = $conds;
453  $timestamp = $dbr->addQuotes( $timestamp );
454  $finalConds [] =
455  "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
456  $res = $dbr->select( [ 'page', 'categorylinks' ],
457  [ 'page_id', 'cl_timestamp' ],
458  $finalConds,
459  __METHOD__,
460  [
461  'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
462  'LIMIT' => $this->getBatchSize(),
463  ]
464  );
465 
466  foreach ( $res as $row ) {
467  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
468  $this->output( "$i\n" );
469  $lbFactory->waitForReplication();
470  }
471  $lastId = $row->page_id;
472  $timestamp = $row->cl_timestamp;
473  self::fixLinksFromArticle( $row->page_id );
474  }
475 
476  } while ( $res->numRows() == $this->getBatchSize() );
477  }
478 
485  private function getPossibleCategories( $categoryKey ) {
486  $trackingCategories = new TrackingCategories( $this->getConfig() );
487  $cats = $trackingCategories->getTrackingCategories();
488  if ( isset( $cats[$categoryKey] ) ) {
489  return $cats[$categoryKey]['cats'];
490  }
491  $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
492  }
493 }
494 
495 $maintClass = RefreshLinks::class;
496 require_once RUN_MAINTENANCE_IF_MAIN;
RUN_MAINTENANCE_IF_MAIN
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:38
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:46
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:152
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:480
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:323
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:53
$res
$res
Definition: testCompression.php:57
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
$dbr
$dbr
Definition: testCompression.php:54
REPORTING_INTERVAL
const REPORTING_INTERVAL
Definition: moveToExternal.php:26
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:1023
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:587
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:241
DeferredUpdates\POSTSEND
const POSTSEND
Definition: DeferredUpdates.php:85
$title
$title
Definition: testCompression.php:38
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:83
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:618
$content
$content
Definition: router.php:76
WikiPage\newFromID
static newFromID( $id, $from='fromdb')
Constructor from a page id.
Definition: WikiPage.php:192
Maintenance\getHookRunner
getHookRunner()
Get a HookRunner for running core hooks.
Definition: Maintenance.php:1689
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1350
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Consume the list of deferred updates and execute them.
Definition: DeferredUpdates.php:171
TrackingCategories
This class performs some operations related to tracking categories, such as creating a list of all su...
Definition: TrackingCategories.php:29
Title
Represents a title within MediaWiki.
Definition: Title.php:42
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:277
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:294
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:362
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:457
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:429
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:262
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:347
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:370