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  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  Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
116 
117  $what = $redirectsOnly ? "redirects" : "links";
118 
119  if ( $oldRedirectsOnly ) {
120  # This entire code path is cut-and-pasted from below. Hurrah.
121 
122  $conds = [
123  "page_is_redirect=1",
124  "rd_from IS NULL",
125  self::intervalCond( $dbr, 'page_id', $start, $end ),
126  ] + $this->namespaceCond();
127 
128  $res = $dbr->select(
129  [ 'page', 'redirect' ],
130  'page_id',
131  $conds,
132  __METHOD__,
133  [],
134  [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
135  );
136  $num = $res->numRows();
137  $this->output( "Refreshing $num old redirects from $start...\n" );
138 
139  $i = 0;
140 
141  foreach ( $res as $row ) {
142  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
143  $this->output( "$i\n" );
144  wfWaitForSlaves();
145  }
146  $this->fixRedirect( $row->page_id );
147  }
148  } elseif ( $newOnly ) {
149  $this->output( "Refreshing $what from " );
150  $res = $dbr->select( 'page',
151  [ 'page_id' ],
152  [
153  'page_is_new' => 1,
154  self::intervalCond( $dbr, 'page_id', $start, $end ),
155  ] + $this->namespaceCond(),
156  __METHOD__
157  );
158  $num = $res->numRows();
159  $this->output( "$num new articles...\n" );
160 
161  $i = 0;
162  foreach ( $res as $row ) {
163  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
164  $this->output( "$i\n" );
165  wfWaitForSlaves();
166  }
167  if ( $redirectsOnly ) {
168  $this->fixRedirect( $row->page_id );
169  } else {
170  self::fixLinksFromArticle( $row->page_id, $this->namespace );
171  }
172  }
173  } else {
174  if ( !$end ) {
175  $maxPage = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
176  $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', '', __METHOD__ );
177  $end = max( $maxPage, $maxRD );
178  }
179  $this->output( "Refreshing redirects table.\n" );
180  $this->output( "Starting from page_id $start of $end.\n" );
181 
182  for ( $id = $start; $id <= $end; $id++ ) {
183  if ( !( $id % self::REPORTING_INTERVAL ) ) {
184  $this->output( "$id\n" );
185  wfWaitForSlaves();
186  }
187  $this->fixRedirect( $id );
188  }
189 
190  if ( !$redirectsOnly ) {
191  $this->output( "Refreshing links tables.\n" );
192  $this->output( "Starting from page_id $start of $end.\n" );
193 
194  for ( $id = $start; $id <= $end; $id++ ) {
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( RevisionRecord::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  MediaWikiServices::getInstance()->getLinkCache()->clear();
264 
265  if ( $page === null ) {
266  return;
267  } elseif ( $ns !== false
268  && !$page->getTitle()->inNamespace( $ns ) ) {
269  return;
270  }
271 
272  // Defer updates to post-send but then immediately execute deferred updates;
273  // this is the simplest way to run all updates immediately (including updates
274  // scheduled by other updates).
275  $page->doSecondaryDataUpdates( [
276  'defer' => DeferredUpdates::POSTSEND,
277  'recursive' => false,
278  ] );
280  }
281 
293  private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
294  $chunkSize = 100000
295  ) {
296  wfWaitForSlaves();
297  $this->output( "Deleting illegal entries from the links tables...\n" );
298  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
299  do {
300  // Find the start of the next chunk. This is based only
301  // on existent page_ids.
302  $nextStart = $dbr->selectField(
303  'page',
304  'page_id',
305  [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
306  + $this->namespaceCond(),
307  __METHOD__,
308  [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
309  );
310 
311  if ( $nextStart !== false ) {
312  // To find the end of the current chunk, subtract one.
313  // This will serve to limit the number of rows scanned in
314  // dfnCheckInterval(), per query, to at most the sum of
315  // the chunk size and deletion batch size.
316  $chunkEnd = $nextStart - 1;
317  } else {
318  // This is the last chunk. Check all page_ids up to $end.
319  $chunkEnd = $end;
320  }
321 
322  $fmtStart = $start !== null ? "[$start" : '(-INF';
323  $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
324  $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
325  $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
326 
327  $start = $nextStart;
328 
329  } while ( $nextStart !== false );
330  }
331 
338  private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
339  $dbw = $this->getDB( DB_MASTER );
340  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
341 
342  $linksTables = [ // table name => page_id field
343  'pagelinks' => 'pl_from',
344  'imagelinks' => 'il_from',
345  'categorylinks' => 'cl_from',
346  'templatelinks' => 'tl_from',
347  'externallinks' => 'el_from',
348  'iwlinks' => 'iwl_from',
349  'langlinks' => 'll_from',
350  'redirect' => 'rd_from',
351  'page_props' => 'pp_page',
352  ];
353 
354  foreach ( $linksTables as $table => $field ) {
355  $this->output( " $table: 0" );
356  $tableStart = $start;
357  $counter = 0;
358  do {
359  $ids = $dbr->selectFieldValues(
360  $table,
361  $field,
362  [
363  self::intervalCond( $dbr, $field, $tableStart, $end ),
364  "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
365  ],
366  __METHOD__,
367  [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
368  );
369 
370  $numIds = count( $ids );
371  if ( $numIds ) {
372  $counter += $numIds;
373  $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
374  $this->output( ", $counter" );
375  $tableStart = $ids[$numIds - 1] + 1;
376  wfWaitForSlaves();
377  }
378 
379  } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
380 
381  $this->output( " deleted.\n" );
382  }
383  }
384 
397  private static function intervalCond( IDatabase $db, $var, $start, $end ) {
398  if ( $start === null && $end === null ) {
399  return "$var IS NOT NULL";
400  } elseif ( $end === null ) {
401  return "$var >= {$db->addQuotes( $start )}";
402  } elseif ( $start === null ) {
403  return "$var <= {$db->addQuotes( $end )}";
404  } else {
405  return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
406  }
407  }
408 
414  private function refreshTrackingCategory( $category ) {
415  $cats = $this->getPossibleCategories( $category );
416 
417  if ( !$cats ) {
418  $this->error( "Tracking category '$category' is disabled\n" );
419  // Output to stderr but don't bail out,
420  }
421 
422  foreach ( $cats as $cat ) {
423  $this->refreshCategory( $cat );
424  }
425  }
426 
432  private function refreshCategory( Title $category ) {
433  $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
434 
435  $dbr = $this->getDB( DB_REPLICA );
436  $conds = [
437  'page_id=cl_from',
438  'cl_to' => $category->getDBkey(),
439  ];
440  if ( $this->namespace !== false ) {
441  $conds['page_namespace'] = $this->namespace;
442  }
443 
444  $i = 0;
445  $timestamp = '';
446  $lastId = 0;
447  do {
448  $finalConds = $conds;
449  $timestamp = $dbr->addQuotes( $timestamp );
450  $finalConds [] =
451  "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
452  $res = $dbr->select( [ 'page', 'categorylinks' ],
453  [ 'page_id', 'cl_timestamp' ],
454  $finalConds,
455  __METHOD__,
456  [
457  'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
458  'LIMIT' => $this->getBatchSize(),
459  ]
460  );
461 
462  foreach ( $res as $row ) {
463  if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
464  $this->output( "$i\n" );
465  wfWaitForSlaves();
466  }
467  $lastId = $row->page_id;
468  $timestamp = $row->cl_timestamp;
469  self::fixLinksFromArticle( $row->page_id );
470  }
471 
472  } while ( $res->numRows() == $this->getBatchSize() );
473  }
474 
481  private function getPossibleCategories( $categoryKey ) {
482  $trackingCategories = new TrackingCategories( $this->getConfig() );
483  $cats = $trackingCategories->getTrackingCategories();
484  if ( isset( $cats[$categoryKey] ) ) {
485  return $cats[$categoryKey]['cats'];
486  }
487  $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
488  }
489 }
490 
491 $maintClass = RefreshLinks::class;
492 require_once RUN_MAINTENANCE_IF_MAIN;
getArg( $argId=0, $default=null)
Get an argument.
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:39
error( $err, $die=0)
Throw an error to the user.
getOption( $name, $default=null)
Get an option, or return the default.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:82
setBatchSize( $s=0)
Set the batch size.
hasOption( $name)
Checks to see if a particular option exists.
const DB_MASTER
Definition: defines.php:26
getDBkey()
Get the main part with underscores.
Definition: Title.php:1013
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
addDescription( $text)
Set the description text.
const NS_CATEGORY
Definition: Defines.php:74
const REPORTING_INTERVAL
addArg( $arg, $description, $required=true)
Add some args that are needed.
output( $out, $channel=null)
Throw some output to the user.
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:613
static newFromID( $id, $from='fromdb')
Constructor from a page id.
Definition: WikiPage.php:180
static doUpdates( $mode='run', $stage=self::ALL)
Do any deferred updates and clear the list.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
getBatchSize()
Returns batch size.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
const DB_REPLICA
Definition: defines.php:25
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
This class performs some operations related to tracking categories, such as creating a list of all su...
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200