MediaWiki master
refreshLinks.php
Go to the documentation of this file.
1<?php
23
24// @codeCoverageIgnoreStart
25require_once __DIR__ . '/Maintenance.php';
26// @codeCoverageIgnoreEnd
27
34 private const REPORTING_INTERVAL = 100;
35
36 public function __construct() {
37 parent::__construct();
38 $this->addDescription( 'Refresh link tables' );
39 $this->addOption( 'verbose', 'Output information about link refresh progress', false, false, 'v' );
40 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
41 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
42 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
43 $this->addOption( 'touched-only', 'Only fix pages that have been touched after last update' );
44 $this->addOption( 'e', 'Last page id to refresh', false, true );
45 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
46 'query, default 100,000', false, true );
47 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
48 $this->addOption( 'category', 'Only fix pages in this category', false, true );
49 $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
50 $this->addOption( 'before-timestamp', 'Only fix pages that were last updated before this timestamp',
51 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', 100_000 );
64
65 if ( $this->hasOption( 'dfn-only' ) ) {
66 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
67 return;
68 }
69
70 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
71 $builder = $dbr->newSelectQueryBuilder()
72 ->from( 'page' )
73 ->where( self::intervalCond( $dbr, 'page_id', $start, $end ) )
74 ->limit( $this->getBatchSize() );
75
76 if ( $this->hasOption( 'namespace' ) ) {
77 $builder->andWhere( [ 'page_namespace' => (int)$this->getOption( 'namespace' ) ] );
78 }
79
80 if ( $this->hasOption( 'before-timestamp' ) ) {
81 $builder->andWhere(
82 $dbr->expr( 'page_links_updated', '<', $this->getOption( 'before-timestamp' ) )
83 ->or( 'page_links_updated', '=', null )
84 );
85 }
86
87 if ( $this->hasOption( 'category' ) ) {
88 $category = $this->getOption( 'category' );
89 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
90 if ( !$title ) {
91 $this->fatalError( "'$category' is an invalid category name!\n" );
92 }
93 $this->refreshCategory( $builder, $title );
94 } elseif ( $this->hasOption( 'tracking-category' ) ) {
95 // See TrackingCategories::CORE_TRACKING_CATEGORIES for tracking category keys defined by core
96 $this->refreshTrackingCategory( $builder, $this->getOption( 'tracking-category' ) );
97 } else {
98 $new = $this->hasOption( 'new-only' );
99 $redir = $this->hasOption( 'redirects-only' );
100 $touched = $this->hasOption( 'touched-only' );
101 $what = $redir ? 'redirects' : 'links';
102 if ( $new ) {
103 $builder->andWhere( [ 'page_is_new' => 1 ] );
104 $this->output( "Refreshing $what from new pages...\n" );
105 } else {
106 if ( $touched ) {
107 $builder->andWhere( [
108 $dbr->expr( 'page_links_updated', '=', null )
109 ->orExpr( new RawSQLExpression( 'page_touched > page_links_updated' ) ),
110 ] );
111 }
112 $this->output( "Refreshing $what from pages...\n" );
113 }
114 $this->doRefreshLinks( $builder, $redir );
115 if ( !$this->hasOption( 'namespace' ) ) {
116 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
117 }
118 }
119 }
120
127 private function doRefreshLinks(
128 SelectQueryBuilder $builder,
129 bool $redirectsOnly = false,
130 array $indexFields = [ 'page_id' ]
131 ) {
132 // Give extensions a chance to optimize settings
133 $this->getHookRunner()->onMaintenanceRefreshLinksInit( $this );
134
135 $estimateCount = $builder->caller( __METHOD__ )->estimateRowCount();
136 $this->output( "Estimated page count: $estimateCount\n" );
137
138 $i = 0;
139 $lastIndexes = array_fill_keys( $indexFields, 0 );
140 $selectFields = in_array( 'page_id', $indexFields )
141 ? $indexFields : [ 'page_id', ...$indexFields ];
142 $verbose = $this->hasOption( 'verbose' );
143 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
144 do {
145 $batchCond = $dbr->buildComparison( '>', $lastIndexes );
146 $res = ( clone $builder )->select( $selectFields )
147 ->andWhere( [ $batchCond ] )
148 ->orderBy( $indexFields )
149 ->caller( __METHOD__ )->fetchResultSet();
150
151 if ( $verbose ) {
152 $this->output( "Refreshing links for {$res->numRows()} pages\n" );
153 }
154
155 foreach ( $res as $row ) {
156 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
157 $this->output( "$i\n" );
158 $this->waitForReplication();
159 }
160 if ( $verbose ) {
161 $this->output( "Refreshing links for page ID {$row->page_id}\n" );
162 }
163 self::fixRedirect( $this, $row->page_id );
164 if ( !$redirectsOnly ) {
165 self::fixLinksFromArticle( $row->page_id );
166 }
167 }
168 if ( $res->numRows() ) {
169 $res->seek( $res->numRows() - 1 );
170 foreach ( $indexFields as $field ) {
171 $lastIndexes[$field] = $res->current()->$field;
172 }
173 }
174
175 } while ( $res->numRows() == $this->getBatchSize() );
176 }
177
192 public static function fixRedirect( Maintenance $maint, $id ) {
193 $page = $maint->getServiceContainer()->getWikiPageFactory()->newFromID( $id );
194
195 // In case the page just got deleted.
196 if ( $page === null ) {
197 return;
198 }
199
200 $rt = null;
201 $content = $page->getContent( RevisionRecord::RAW );
202 if ( $content !== null ) {
203 $rt = $content->getRedirectTarget();
204 }
205
206 $dbw = $maint->getDB( DB_PRIMARY );
207 if ( $rt === null ) {
208 // The page is not a redirect
209 // Delete any redirect table entry for it
210 $dbw->newDeleteQueryBuilder()
211 ->deleteFrom( 'redirect' )
212 ->where( [ 'rd_from' => $id ] )
213 ->caller( __METHOD__ )->execute();
214 $fieldValue = 0;
215 } else {
216 $page->insertRedirectEntry( $rt );
217 $fieldValue = 1;
218 }
219
220 // Update the page table to be sure it is an a consistent state
221 $dbw->newUpdateQueryBuilder()
222 ->update( 'page' )
223 ->set( [ 'page_is_redirect' => $fieldValue ] )
224 ->where( [ 'page_id' => $id ] )
225 ->caller( __METHOD__ )
226 ->execute();
227 }
228
233 public static function fixLinksFromArticle( $id ) {
234 $services = MediaWikiServices::getInstance();
235 $page = $services->getWikiPageFactory()->newFromID( $id );
236
237 // In case the page just got deleted.
238 if ( $page === null ) {
239 return;
240 }
241
242 // Defer updates to post-send but then immediately execute deferred updates;
243 // this is the simplest way to run all updates immediately (including updates
244 // scheduled by other updates).
245 $page->doSecondaryDataUpdates( [
246 'defer' => DeferredUpdates::POSTSEND,
247 'causeAction' => 'refresh-links-maintenance',
248 'recursive' => false,
249 ] );
250 DeferredUpdates::doUpdates();
251 }
252
264 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
265 $chunkSize = 100_000
266 ) {
267 $this->waitForReplication();
268 $this->output( "Deleting illegal entries from the links tables...\n" );
269 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
270 do {
271 // Find the start of the next chunk. This is based only
272 // on existent page_ids.
273 $nextStart = $dbr->newSelectQueryBuilder()
274 ->select( 'page_id' )
275 ->from( 'page' )
276 ->where( [ self::intervalCond( $dbr, 'page_id', $start, $end ) ] )
277 ->orderBy( 'page_id' )
278 ->offset( $chunkSize )
279 ->caller( __METHOD__ )->fetchField();
280
281 if ( $nextStart !== false ) {
282 // To find the end of the current chunk, subtract one.
283 // This will serve to limit the number of rows scanned in
284 // dfnCheckInterval(), per query, to at most the sum of
285 // the chunk size and deletion batch size.
286 $chunkEnd = $nextStart - 1;
287 } else {
288 // This is the last chunk. Check all page_ids up to $end.
289 $chunkEnd = $end;
290 }
291
292 $fmtStart = $start !== null ? "[$start" : '(-INF';
293 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
294 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
295 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
296
297 $start = $nextStart;
298
299 } while ( $nextStart !== false );
300 }
301
308 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
309 $linksTables = [
310 // table name => page_id field
311 'pagelinks' => 'pl_from',
312 'imagelinks' => 'il_from',
313 'categorylinks' => 'cl_from',
314 'templatelinks' => 'tl_from',
315 'externallinks' => 'el_from',
316 'iwlinks' => 'iwl_from',
317 'langlinks' => 'll_from',
318 'redirect' => 'rd_from',
319 'page_props' => 'pp_page',
320 ];
321
322 $domains = [
323 'categorylinks' => CategoryLinksTable::VIRTUAL_DOMAIN,
324 'externallinks' => ExternalLinksTable::VIRTUAL_DOMAIN,
325 'imagelinks' => ImageLinksTable::VIRTUAL_DOMAIN,
326 'iwlinks' => InterwikiLinksTable::VIRTUAL_DOMAIN,
327 'pagelinks' => PageLinksTable::VIRTUAL_DOMAIN,
328 'templatelinks' => TemplateLinksTable::VIRTUAL_DOMAIN,
329 ];
330
331 foreach ( $linksTables as $table => $field ) {
332 $domain = $domains[$table] ?? false;
333 $dbw = $this->getServiceContainer()->getConnectionProvider()->getPrimaryDatabase( $domain );
334 $dbr = $this->getServiceContainer()->getConnectionProvider()->getReplicaDatabase( $domain, 'vslow' );
335
336 $this->output( " $table: 0" );
337 $tableStart = $start;
338 $counter = 0;
339 do {
340 $ids = $dbr->newSelectQueryBuilder()
341 ->select( $field )
342 ->distinct()
343 ->from( $table )
344 ->leftJoin( 'page', null, "$field = page_id" )
345 ->where( self::intervalCond( $dbr, $field, $tableStart, $end ) )
346 ->andWhere( [ 'page_id' => null ] )
347 ->orderBy( $field )
348 ->limit( $batchSize )
349 ->caller( __METHOD__ )->fetchFieldValues();
350
351 $numIds = count( $ids );
352 if ( $numIds ) {
353 $counter += $numIds;
354 $dbw->newDeleteQueryBuilder()
355 ->deleteFrom( $table )
356 ->where( [ $field => $ids ] )
357 ->caller( __METHOD__ )->execute();
358 $this->output( ", $counter" );
359 $tableStart = $ids[$numIds - 1] + 1;
360 $this->waitForReplication();
361 }
362
363 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
364
365 $this->output( " deleted.\n" );
366 }
367 }
368
381 private static function intervalCond( IReadableDatabase $db, $var, $start, $end ) {
382 if ( $start === null && $end === null ) {
383 return $db->expr( $var, '!=', null );
384 } elseif ( $end === null ) {
385 return $db->expr( $var, '>=', $start );
386 } elseif ( $start === null ) {
387 return $db->expr( $var, '<=', $end );
388 } else {
389 return $db->expr( $var, '>=', $start )->and( $var, '<=', $end );
390 }
391 }
392
399 private function refreshTrackingCategory( SelectQueryBuilder $builder, $category ) {
400 $cats = $this->getPossibleCategories( $category );
401
402 if ( !$cats ) {
403 $this->error( "Tracking category '$category' is disabled\n" );
404 // Output to stderr but don't bail out.
405 }
406
407 foreach ( $cats as $cat ) {
408 $this->refreshCategory( clone $builder, $cat );
409 }
410 }
411
418 private function refreshCategory( SelectQueryBuilder $builder, LinkTarget $category ) {
419 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
420
421 $builder->join( 'categorylinks', null, 'page_id=cl_from' )
422 ->join( 'linktarget', null, 'lt_id=cl_target_id' )
423 ->andWhere( [ 'lt_title' => $category->getDBkey(), 'lt_namespace' => NS_CATEGORY ] );
424 $this->doRefreshLinks( $builder, false, [ 'cl_timestamp', 'cl_from' ] );
425 }
426
433 private function getPossibleCategories( $categoryKey ) {
434 $cats = $this->getServiceContainer()->getTrackingCategories()->getTrackingCategories();
435 if ( isset( $cats[$categoryKey] ) ) {
436 return $cats[$categoryKey]['cats'];
437 }
438 $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
439 }
440}
441
442// @codeCoverageIgnoreStart
443$maintClass = RefreshLinks::class;
444require_once RUN_MAINTENANCE_IF_MAIN;
445// @codeCoverageIgnoreEnd
const NS_CATEGORY
Definition Defines.php:65
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
Defer callable updates to run later in the PHP process.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
getArg( $argId=0, $default=null)
Get an argument.
getBatchSize()
Returns batch size.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
waitForReplication()
Wait for replica DB servers to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
error( $err, $die=0)
Throw an error to the user.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Service locator for MediaWiki core services.
Page revision base class.
Represents a title within MediaWiki.
Definition Title.php:69
join( $table, $alias=null, $conds=[])
Inner join a table or group of tables.
Raw SQL expression to be used in query builders.
Build SELECT queries with a fluent interface.
andWhere( $conds)
Add conditions to the query.
caller( $fname)
Set the method name to be included in an SQL comment.
from( $table, $alias=null)
Add a single table to the SELECT query.
Represents the target of a wiki link.
getDBkey()
Get the main part of the link target, in canonical database form.
A database connection without write operations.
expr(string $field, string $op, $value)
See Expression::__construct()