MediaWiki master
refreshLinks.php
Go to the documentation of this file.
1<?php
29
30require_once __DIR__ . '/Maintenance.php';
31
38 private const REPORTING_INTERVAL = 100;
39
40 public function __construct() {
41 parent::__construct();
42 $this->addDescription( 'Refresh link tables' );
43 $this->addOption( 'verbose', 'Output information about link refresh progress', false, false, 'v' );
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( 'touched-only', 'Only fix pages that have been touched after last update' );
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 100,000', 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->addOption( 'before-timestamp', 'Only fix pages that were last updated before this timestamp',
55 false, true );
56 $this->addArg( 'start', 'Page_id to start from, default 1', false );
57 $this->setBatchSize( 100 );
58 }
59
60 public function execute() {
61 // Note that there is a difference between not specifying the start
62 // and end IDs and using the minimum and maximum values from the page
63 // table. In the latter case, deleteLinksFromNonexistent() will not
64 // delete entries for nonexistent IDs that fall outside the range.
65 $start = (int)$this->getArg( 0 ) ?: null;
66 $end = (int)$this->getOption( 'e' ) ?: null;
67 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100_000 );
68
69 if ( $this->hasOption( 'dfn-only' ) ) {
70 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
71 return;
72 }
73
74 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
75 $builder = $dbr->newSelectQueryBuilder()
76 ->from( 'page' )
77 ->where( self::intervalCond( $dbr, 'page_id', $start, $end ) )
78 ->limit( $this->getBatchSize() );
79
80 if ( $this->hasOption( 'namespace' ) ) {
81 $builder->andWhere( [ 'page_namespace' => (int)$this->getOption( 'namespace' ) ] );
82 }
83
84 if ( $this->hasOption( 'before-timestamp' ) ) {
85 $builder->andWhere(
86 $dbr->expr( 'page_links_updated', '<', $this->getOption( 'before-timestamp' ) )
87 ->or( 'page_links_updated', '=', null )
88 );
89 }
90
91 if ( $this->hasOption( 'category' ) ) {
92 $category = $this->getOption( 'category' );
93 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
94 if ( !$title ) {
95 $this->fatalError( "'$category' is an invalid category name!\n" );
96 }
97 $this->refreshCategory( $builder, $title );
98 } elseif ( $this->hasOption( 'tracking-category' ) ) {
99 // See TrackingCategories::CORE_TRACKING_CATEGORIES for tracking category keys defined by core
100 $this->refreshTrackingCategory( $builder, $this->getOption( 'tracking-category' ) );
101 } else {
102 $new = $this->hasOption( 'new-only' );
103 $redir = $this->hasOption( 'redirects-only' );
104 $touched = $this->hasOption( 'touched-only' );
105 $what = $redir ? 'redirects' : 'links';
106 if ( $new ) {
107 $builder->andWhere( [ 'page_is_new' => 1 ] );
108 $this->output( "Refreshing $what from new pages...\n" );
109 } else {
110 if ( $touched ) {
111 $builder->andWhere( [
112 $dbr->expr( 'page_touched', '>', 'page_links_updated' )
113 ->or( 'page_links_updated', '=', null ),
114 ] );
115 }
116 $this->output( "Refreshing $what from pages...\n" );
117 }
118 $this->doRefreshLinks( $builder, $redir );
119 if ( !$this->hasOption( 'namespace' ) ) {
120 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
121 }
122 }
123 }
124
131 private function doRefreshLinks(
132 SelectQueryBuilder $builder,
133 bool $redirectsOnly = false,
134 array $indexFields = [ 'page_id' ]
135 ) {
136 // Give extensions a chance to optimize settings
137 $this->getHookRunner()->onMaintenanceRefreshLinksInit( $this );
138
139 $estimateCount = $builder->estimateRowCount();
140 $this->output( "Estimated page count: $estimateCount\n" );
141
142 $i = 0;
143 $lastIndexes = array_fill_keys( $indexFields, 0 );
144 $selectFields = in_array( 'page_id', $indexFields )
145 ? $indexFields : [ 'page_id', ...$indexFields ];
146 $verbose = $this->hasOption( 'verbose' );
147 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
148 do {
149 $batchCond = $dbr->buildComparison( '>', $lastIndexes );
150 $res = ( clone $builder )->select( $selectFields )
151 ->andWhere( [ $batchCond ] )
152 ->orderBy( $indexFields )
153 ->caller( __METHOD__ )->fetchResultSet();
154
155 if ( $verbose ) {
156 $this->output( "Refreshing links for {$res->numRows()} pages\n" );
157 }
158
159 foreach ( $res as $row ) {
160 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
161 $this->output( "$i\n" );
162 $this->waitForReplication();
163 }
164 if ( $verbose ) {
165 $this->output( "Refreshing links for page ID {$row->page_id}\n" );
166 }
167 self::fixRedirect( $this, $row->page_id );
168 if ( !$redirectsOnly ) {
169 self::fixLinksFromArticle( $row->page_id );
170 }
171 }
172 if ( $res->numRows() ) {
173 $res->seek( $res->numRows() - 1 );
174 foreach ( $indexFields as $field ) {
175 $lastIndexes[$field] = $res->current()->$field;
176 }
177 }
178
179 } while ( $res->numRows() == $this->getBatchSize() );
180 }
181
196 public static function fixRedirect( Maintenance $maint, $id ) {
197 $page = $maint->getServiceContainer()->getWikiPageFactory()->newFromID( $id );
198
199 // In case the page just got deleted.
200 if ( $page === null ) {
201 return;
202 }
203
204 $rt = null;
205 $content = $page->getContent( RevisionRecord::RAW );
206 if ( $content !== null ) {
207 $rt = $content->getRedirectTarget();
208 }
209
210 $dbw = $maint->getDB( DB_PRIMARY );
211 if ( $rt === null ) {
212 // The page is not a redirect
213 // Delete any redirect table entry for it
214 $dbw->newDeleteQueryBuilder()
215 ->deleteFrom( 'redirect' )
216 ->where( [ 'rd_from' => $id ] )
217 ->caller( __METHOD__ )->execute();
218 $fieldValue = 0;
219 } else {
220 $page->insertRedirectEntry( $rt );
221 $fieldValue = 1;
222 }
223
224 // Update the page table to be sure it is an a consistent state
225 $dbw->newUpdateQueryBuilder()
226 ->update( 'page' )
227 ->set( [ 'page_is_redirect' => $fieldValue ] )
228 ->where( [ 'page_id' => $id ] )
229 ->caller( __METHOD__ )
230 ->execute();
231 }
232
237 public static function fixLinksFromArticle( $id ) {
238 $services = MediaWikiServices::getInstance();
239 $page = $services->getWikiPageFactory()->newFromID( $id );
240
241 // In case the page just got deleted.
242 if ( $page === null ) {
243 return;
244 }
245
246 // Defer updates to post-send but then immediately execute deferred updates;
247 // this is the simplest way to run all updates immediately (including updates
248 // scheduled by other updates).
249 $page->doSecondaryDataUpdates( [
250 'defer' => DeferredUpdates::POSTSEND,
251 'causeAction' => 'refresh-links-maintenance',
252 'recursive' => false,
253 ] );
254 DeferredUpdates::doUpdates();
255 }
256
268 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
269 $chunkSize = 100_000
270 ) {
271 $this->waitForReplication();
272 $this->output( "Deleting illegal entries from the links tables...\n" );
273 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
274 do {
275 // Find the start of the next chunk. This is based only
276 // on existent page_ids.
277 $nextStart = $dbr->newSelectQueryBuilder()
278 ->select( 'page_id' )
279 ->from( 'page' )
280 ->where( [ self::intervalCond( $dbr, 'page_id', $start, $end ) ] )
281 ->orderBy( 'page_id' )
282 ->offset( $chunkSize )
283 ->caller( __METHOD__ )->fetchField();
284
285 if ( $nextStart !== false ) {
286 // To find the end of the current chunk, subtract one.
287 // This will serve to limit the number of rows scanned in
288 // dfnCheckInterval(), per query, to at most the sum of
289 // the chunk size and deletion batch size.
290 $chunkEnd = $nextStart - 1;
291 } else {
292 // This is the last chunk. Check all page_ids up to $end.
293 $chunkEnd = $end;
294 }
295
296 $fmtStart = $start !== null ? "[$start" : '(-INF';
297 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
298 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
299 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
300
301 $start = $nextStart;
302
303 } while ( $nextStart !== false );
304 }
305
312 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
313 $dbw = $this->getPrimaryDB();
314 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
315
316 $linksTables = [
317 // table name => page_id field
318 'pagelinks' => 'pl_from',
319 'imagelinks' => 'il_from',
320 'categorylinks' => 'cl_from',
321 'templatelinks' => 'tl_from',
322 'externallinks' => 'el_from',
323 'iwlinks' => 'iwl_from',
324 'langlinks' => 'll_from',
325 'redirect' => 'rd_from',
326 'page_props' => 'pp_page',
327 ];
328
329 foreach ( $linksTables as $table => $field ) {
330 $this->output( " $table: 0" );
331 $tableStart = $start;
332 $counter = 0;
333 do {
334 $ids = $dbr->newSelectQueryBuilder()
335 ->select( $field )
336 ->distinct()
337 ->from( $table )
338 ->leftJoin( 'page', null, "$field = page_id" )
339 ->where( self::intervalCond( $dbr, $field, $tableStart, $end ) )
340 ->andWhere( [ 'page_id' => null ] )
341 ->orderBy( $field )
342 ->limit( $batchSize )
343 ->caller( __METHOD__ )->fetchFieldValues();
344
345 $numIds = count( $ids );
346 if ( $numIds ) {
347 $counter += $numIds;
348 $dbw->newDeleteQueryBuilder()
349 ->deleteFrom( $table )
350 ->where( [ $field => $ids ] )
351 ->caller( __METHOD__ )->execute();
352 $this->output( ", $counter" );
353 $tableStart = $ids[$numIds - 1] + 1;
354 $this->waitForReplication();
355 }
356
357 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
358
359 $this->output( " deleted.\n" );
360 }
361 }
362
375 private static function intervalCond( IReadableDatabase $db, $var, $start, $end ) {
376 if ( $start === null && $end === null ) {
377 return $db->expr( $var, '!=', null );
378 } elseif ( $end === null ) {
379 return $db->expr( $var, '>=', $start );
380 } elseif ( $start === null ) {
381 return $db->expr( $var, '<=', $end );
382 } else {
383 return $db->expr( $var, '>=', $start )->and( $var, '<=', $end );
384 }
385 }
386
393 private function refreshTrackingCategory( SelectQueryBuilder $builder, $category ) {
394 $cats = $this->getPossibleCategories( $category );
395
396 if ( !$cats ) {
397 $this->error( "Tracking category '$category' is disabled\n" );
398 // Output to stderr but don't bail out.
399 }
400
401 foreach ( $cats as $cat ) {
402 $this->refreshCategory( clone $builder, $cat );
403 }
404 }
405
412 private function refreshCategory( SelectQueryBuilder $builder, LinkTarget $category ) {
413 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
414
415 $builder->join( 'categorylinks', null, 'page_id=cl_from' )
416 ->andWhere( [ 'cl_to' => $category->getDBkey() ] );
417 $this->doRefreshLinks( $builder, false, [ 'cl_timestamp', 'cl_from' ] );
418 }
419
426 private function getPossibleCategories( $categoryKey ) {
427 $cats = $this->getServiceContainer()->getTrackingCategories()->getTrackingCategories();
428 if ( isset( $cats[$categoryKey] ) ) {
429 return $cats[$categoryKey]['cats'];
430 }
431 $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
432 }
433}
434
435$maintClass = RefreshLinks::class;
436require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
const NS_CATEGORY
Definition Defines.php:79
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
error( $err, $die=0)
Throw an error to the user.
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
output( $out, $channel=null)
Throw some output to the user.
waitForReplication()
Wait for replica DBs to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
getBatchSize()
Returns batch size.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Defer callable updates to run later in the PHP process.
Service locator for MediaWiki core services.
Page revision base class.
Represents a title within MediaWiki.
Definition Title.php:79
join( $table, $alias=null, $conds=[])
Inner join a table or group of tables.
Build SELECT queries with a fluent interface.
estimateRowCount()
Estimate the number of rows in dataset.
andWhere( $conds)
Add conditions to the query.
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()
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28