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 = MediaWikiServices::getInstance()->getWikiPageFactory()->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  $services = MediaWikiServices::getInstance();
263  $page = $services->getWikiPageFactory()->newFromID( $id );
264 
265  $services->getLinkCache()->clear();
266 
267  if ( $page === null ) {
268  return;
269  } elseif ( $ns !== false
270  && !$page->getTitle()->inNamespace( $ns ) ) {
271  return;
272  }
273 
274  // Defer updates to post-send but then immediately execute deferred updates;
275  // this is the simplest way to run all updates immediately (including updates
276  // scheduled by other updates).
277  $page->doSecondaryDataUpdates( [
278  'defer' => DeferredUpdates::POSTSEND,
279  'recursive' => false,
280  ] );
282  }
283 
295  private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
296  $chunkSize = 100000
297  ) {
298  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
299  $this->output( "Deleting illegal entries from the links tables...\n" );
300  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
301  do {
302  // Find the start of the next chunk. This is based only
303  // on existent page_ids.
304  $nextStart = $dbr->selectField(
305  'page',
306  'page_id',
307  [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
308  + $this->namespaceCond(),
309  __METHOD__,
310  [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
311  );
312 
313  if ( $nextStart !== false ) {
314  // To find the end of the current chunk, subtract one.
315  // This will serve to limit the number of rows scanned in
316  // dfnCheckInterval(), per query, to at most the sum of
317  // the chunk size and deletion batch size.
318  $chunkEnd = $nextStart - 1;
319  } else {
320  // This is the last chunk. Check all page_ids up to $end.
321  $chunkEnd = $end;
322  }
323 
324  $fmtStart = $start !== null ? "[$start" : '(-INF';
325  $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
326  $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
327  $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
328 
329  $start = $nextStart;
330 
331  } while ( $nextStart !== false );
332  }
333 
340  private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
341  $dbw = $this->getDB( DB_MASTER );
342  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
343 
344  $linksTables = [
345  // 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  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
358  foreach ( $linksTables as $table => $field ) {
359  $this->output( " $table: 0" );
360  $tableStart = $start;
361  $counter = 0;
362  do {
363  $ids = $dbr->selectFieldValues(
364  $table,
365  $field,
366  [
367  self::intervalCond( $dbr, $field, $tableStart, $end ),
368  "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id', [], __METHOD__ )})",
369  ],
370  __METHOD__,
371  [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
372  );
373 
374  $numIds = count( $ids );
375  if ( $numIds ) {
376  $counter += $numIds;
377  $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
378  $this->output( ", $counter" );
379  $tableStart = $ids[$numIds - 1] + 1;
380  $lbFactory->waitForReplication();
381  }
382 
383  } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
384 
385  $this->output( " deleted.\n" );
386  }
387  }
388 
401  private static function intervalCond( IDatabase $db, $var, $start, $end ) {
402  if ( $start === null && $end === null ) {
403  return "$var IS NOT NULL";
404  } elseif ( $end === null ) {
405  return "$var >= {$db->addQuotes( $start )}";
406  } elseif ( $start === null ) {
407  return "$var <= {$db->addQuotes( $end )}";
408  } else {
409  return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
410  }
411  }
412 
418  private function refreshTrackingCategory( $category ) {
419  $cats = $this->getPossibleCategories( $category );
420 
421  if ( !$cats ) {
422  $this->error( "Tracking category '$category' is disabled\n" );
423  // Output to stderr but don't bail out,
424  }
425 
426  foreach ( $cats as $cat ) {
427  $this->refreshCategory( $cat );
428  }
429  }
430 
436  private function refreshCategory( Title $category ) {
437  $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
438 
439  $dbr = $this->getDB( DB_REPLICA );
440  $conds = [
441  'page_id=cl_from',
442  'cl_to' => $category->getDBkey(),
443  ];
444  if ( $this->namespace !== false ) {
445  $conds['page_namespace'] = $this->namespace;
446  }
447 
448  $i = 0;
449  $timestamp = '';
450  $lastId = 0;
451  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
452  do {
453  $finalConds = $conds;
454  $timestamp = $dbr->addQuotes( $timestamp );
455  $finalConds [] =
456  "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
457  $res = $dbr->select( [ 'page', 'categorylinks' ],
458  [ 'page_id', 'cl_timestamp' ],
459  $finalConds,
460  __METHOD__,
461  [
462  'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
463  'LIMIT' => $this->getBatchSize(),
464  ]
465  );
466 
467  foreach ( $res as $row ) {
468  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
469  $this->output( "$i\n" );
470  $lbFactory->waitForReplication();
471  }
472  $lastId = $row->page_id;
473  $timestamp = $row->cl_timestamp;
474  self::fixLinksFromArticle( $row->page_id );
475  }
476 
477  } while ( $res->numRows() == $this->getBatchSize() );
478  }
479 
486  private function getPossibleCategories( $categoryKey ) {
487  $trackingCategories = new TrackingCategories( $this->getConfig() );
488  $cats = $trackingCategories->getTrackingCategories();
489  if ( isset( $cats[$categoryKey] ) ) {
490  return $cats[$categoryKey]['cats'];
491  }
492  $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
493  }
494 }
495 
496 $maintClass = RefreshLinks::class;
497 require_once RUN_MAINTENANCE_IF_MAIN;
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:486
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:327
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:55
$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:28
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:1057
Maintenance\getConfig
getConfig()
Definition: Maintenance.php:595
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:245
$title
$title
Definition: testCompression.php:38
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
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:650
$content
$content
Definition: router.php:76
Maintenance\getHookRunner
getHookRunner()
Get a HookRunner for running core hooks.
Definition: Maintenance.php:1734
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1393
DeferredUpdates\doUpdates
static doUpdates( $mode='run', $stage=self::ALL)
Consume and execute all pending updates.
Definition: DeferredUpdates.php:173
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:46
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:281
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:298
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:366
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:77
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:462
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:433
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:266
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:351
Maintenance\setBatchSize
setBatchSize( $s=0)
Definition: Maintenance.php:373