MediaWiki REL1_40
refreshLinks.php
Go to the documentation of this file.
1<?php
26
27require_once __DIR__ . '/Maintenance.php';
28
35 private const REPORTING_INTERVAL = 100;
36
38 protected $namespace = false;
39
41 protected $beforeTimestamp = false;
42
43 public function __construct() {
44 parent::__construct();
45 $this->addDescription( 'Refresh link tables' );
46 $this->addOption( 'verbose', 'Output information about link refresh progress', false, false, 'v' );
47 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
48 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
49 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
50 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
51 $this->addOption( 'e', 'Last page id to refresh', false, true );
52 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
53 'query, default 100000', false, true );
54 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
55 $this->addOption( 'category', 'Only fix pages in this category', false, true );
56 $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
57 $this->addOption( 'before-timestamp', 'Only fix pages that were last updated before this timestamp',
58 false, true );
59 $this->addArg( 'start', 'Page_id to start from, default 1', false );
60 $this->setBatchSize( 100 );
61 }
62
63 public function execute() {
64 // Note that there is a difference between not specifying the start
65 // and end IDs and using the minimum and maximum values from the page
66 // table. In the latter case, deleteLinksFromNonexistent() will not
67 // delete entries for nonexistent IDs that fall outside the range.
68 $start = (int)$this->getArg( 0 ) ?: null;
69 $end = (int)$this->getOption( 'e' ) ?: null;
70 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
71
72 $ns = $this->getOption( 'namespace' );
73 if ( $ns === null ) {
74 $this->namespace = false;
75 } else {
76 $this->namespace = (int)$ns;
77 }
78 $this->beforeTimestamp = $this->getOption( 'before-timestamp', false );
79
80 if ( $this->hasOption( 'category' ) ) {
81 $category = $this->getOption( 'category' );
82 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
83 if ( !$title ) {
84 $this->fatalError( "'$category' is an invalid category name!\n" );
85 }
86 $this->refreshCategory( $title );
87 } elseif ( $this->hasOption( 'tracking-category' ) ) {
88 $category = $this->getOption( 'tracking-category' );
89 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
90 if ( !$title ) {
91 $this->fatalError( "'$category' is an invalid category name!\n" );
92 }
93 $this->refreshTrackingCategory( $this->getOption( 'tracking-category' ) );
94 } elseif ( !$this->hasOption( 'dfn-only' ) ) {
95 $new = $this->hasOption( 'new-only' );
96 $redir = $this->hasOption( 'redirects-only' );
97 $oldRedir = $this->hasOption( 'old-redirects-only' );
98 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
99 $this->deleteLinksFromNonexistent( null, null, $this->getBatchSize(), $dfnChunkSize );
100 } else {
101 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
102 }
103 }
104
105 private function namespaceCond() {
106 return $this->namespace !== false
107 ? [ 'page_namespace' => $this->namespace ]
108 : [];
109 }
110
119 private function doRefreshLinks( $start, $newOnly = false,
120 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
121 ) {
122 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
123
124 if ( $start === null ) {
125 $start = 1;
126 }
127
128 // Give extensions a chance to optimize settings
129 $this->getHookRunner()->onMaintenanceRefreshLinksInit( $this );
130
131 $what = $redirectsOnly ? "redirects" : "links";
132
133 if ( $oldRedirectsOnly ) {
134 # This entire code path is cut-and-pasted from below. Hurrah.
135
136 $conds = [
137 "page_is_redirect=1",
138 "rd_from IS NULL",
139 self::intervalCond( $dbr, 'page_id', $start, $end ),
140 ] + $this->namespaceCond();
141
142 $res = $dbr->select(
143 [ 'page', 'redirect' ],
144 'page_id',
145 $conds,
146 __METHOD__,
147 [],
148 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
149 );
150 $num = $res->numRows();
151 $this->output( "Refreshing $num old redirects from $start...\n" );
152
153 $i = 0;
154
155 foreach ( $res as $row ) {
156 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
157 $this->output( "$i\n" );
158 $this->waitForReplication();
159 }
160 $this->fixRedirect( $row->page_id );
161 }
162 } elseif ( $newOnly ) {
163 $this->output( "Refreshing $what from " );
164 $res = $dbr->select( 'page',
165 [ 'page_id' ],
166 [
167 'page_is_new' => 1,
168 self::intervalCond( $dbr, 'page_id', $start, $end ),
169 ] + $this->namespaceCond(),
170 __METHOD__
171 );
172 $num = $res->numRows();
173 $this->output( "$num new articles...\n" );
174
175 $i = 0;
176 foreach ( $res as $row ) {
177 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
178 $this->output( "$i\n" );
179 $this->waitForReplication();
180 }
181 if ( $redirectsOnly ) {
182 $this->fixRedirect( $row->page_id );
183 } else {
184 self::fixLinksFromArticle( $row->page_id, $this->namespace, $this->beforeTimestamp );
185 }
186 }
187 } else {
188 if ( !$end ) {
189 $maxPage = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
190 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', '', __METHOD__ );
191 $end = max( $maxPage, $maxRD );
192 }
193 $this->output( "Refreshing redirects table.\n" );
194 $this->output( "Starting from page_id $start of $end.\n" );
195
196 for ( $id = $start; $id <= $end; $id++ ) {
197 if ( !( $id % self::REPORTING_INTERVAL ) ) {
198 $this->output( "$id\n" );
199 $this->waitForReplication();
200 }
201 $this->fixRedirect( $id );
202 }
203
204 if ( !$redirectsOnly ) {
205 $this->output( "Refreshing links tables.\n" );
206 $this->output( "Starting from page_id $start of $end.\n" );
207
208 for ( $id = $start; $id <= $end; $id++ ) {
209 if ( !( $id % self::REPORTING_INTERVAL ) ) {
210 $this->output( "$id\n" );
211 $this->waitForReplication();
212 }
213 self::fixLinksFromArticle( $id, $this->namespace, $this->beforeTimestamp );
214 }
215 }
216 }
217 }
218
231 private function fixRedirect( $id ) {
232 $page = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromID( $id );
233 $dbw = $this->getDB( DB_PRIMARY );
234
235 if ( $page === null ) {
236 // This page doesn't exist (any more)
237 // Delete any redirect table entry for it
238 $dbw->delete( 'redirect', [ 'rd_from' => $id ],
239 __METHOD__ );
240
241 return;
242 } elseif ( $this->namespace !== false
243 && !$page->getTitle()->inNamespace( $this->namespace )
244 ) {
245 return;
246 } elseif ( $this->beforeTimestamp !== false
247 && $page->getLinksTimestamp() >= $this->beforeTimestamp
248 ) {
249 return;
250 }
251
252 $rt = null;
253 $content = $page->getContent( RevisionRecord::RAW );
254 if ( $content !== null ) {
255 $rt = $content->getRedirectTarget();
256 }
257
258 if ( $rt === null ) {
259 // The page is not a redirect
260 // Delete any redirect table entry for it
261 $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
262 $fieldValue = 0;
263 } else {
264 $page->insertRedirectEntry( $rt );
265 $fieldValue = 1;
266 }
267
268 // Update the page table to be sure it is an a consistent state
269 $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
270 [ 'page_id' => $id ], __METHOD__ );
271 }
272
279 public static function fixLinksFromArticle( $id, $ns = false, $beforeTimestamp = false ) {
280 $services = MediaWikiServices::getInstance();
281 $page = $services->getWikiPageFactory()->newFromID( $id );
282
283 $services->getLinkCache()->clear();
284
285 if ( $page === null ) {
286 return;
287 } elseif ( $ns !== false
288 && !$page->getTitle()->inNamespace( $ns )
289 ) {
290 return;
291 } elseif ( $beforeTimestamp !== false
292 && $page->getLinksTimestamp() >= $beforeTimestamp
293 ) {
294 return;
295 }
296
297 // Defer updates to post-send but then immediately execute deferred updates;
298 // this is the simplest way to run all updates immediately (including updates
299 // scheduled by other updates).
300 $page->doSecondaryDataUpdates( [
301 'defer' => DeferredUpdates::POSTSEND,
302 'recursive' => false,
303 ] );
304 DeferredUpdates::doUpdates();
305 }
306
318 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
319 $chunkSize = 100000
320 ) {
321 $this->waitForReplication();
322 $this->output( "Deleting illegal entries from the links tables...\n" );
323 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
324 do {
325 // Find the start of the next chunk. This is based only
326 // on existent page_ids.
327 $nextStart = $dbr->selectField(
328 'page',
329 'page_id',
330 [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
331 + $this->namespaceCond(),
332 __METHOD__,
333 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
334 );
335
336 if ( $nextStart !== false ) {
337 // To find the end of the current chunk, subtract one.
338 // This will serve to limit the number of rows scanned in
339 // dfnCheckInterval(), per query, to at most the sum of
340 // the chunk size and deletion batch size.
341 $chunkEnd = $nextStart - 1;
342 } else {
343 // This is the last chunk. Check all page_ids up to $end.
344 $chunkEnd = $end;
345 }
346
347 $fmtStart = $start !== null ? "[$start" : '(-INF';
348 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
349 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
350 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
351
352 $start = $nextStart;
353
354 } while ( $nextStart !== false );
355 }
356
363 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
364 $dbw = $this->getDB( DB_PRIMARY );
365 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
366
367 $linksTables = [
368 // table name => page_id field
369 'pagelinks' => 'pl_from',
370 'imagelinks' => 'il_from',
371 'categorylinks' => 'cl_from',
372 'templatelinks' => 'tl_from',
373 'externallinks' => 'el_from',
374 'iwlinks' => 'iwl_from',
375 'langlinks' => 'll_from',
376 'redirect' => 'rd_from',
377 'page_props' => 'pp_page',
378 ];
379
380 foreach ( $linksTables as $table => $field ) {
381 $this->output( " $table: 0" );
382 $tableStart = $start;
383 $counter = 0;
384 do {
385 $ids = $dbr->selectFieldValues(
386 $table,
387 $field,
388 [
389 self::intervalCond( $dbr, $field, $tableStart, $end ),
390 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id', [], __METHOD__ )})",
391 ],
392 __METHOD__,
393 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
394 );
395
396 $numIds = count( $ids );
397 if ( $numIds ) {
398 $counter += $numIds;
399 $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
400 $this->output( ", $counter" );
401 $tableStart = $ids[$numIds - 1] + 1;
402 $this->waitForReplication();
403 }
404
405 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
406
407 $this->output( " deleted.\n" );
408 }
409 }
410
423 private static function intervalCond( IReadableDatabase $db, $var, $start, $end ) {
424 if ( $start === null && $end === null ) {
425 return "$var IS NOT NULL";
426 } elseif ( $end === null ) {
427 return "$var >= " . $db->addQuotes( $start );
428 } elseif ( $start === null ) {
429 return "$var <= " . $db->addQuotes( $end );
430 } else {
431 return "$var BETWEEN " . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
432 }
433 }
434
440 private function refreshTrackingCategory( $category ) {
441 $cats = $this->getPossibleCategories( $category );
442
443 if ( !$cats ) {
444 $this->error( "Tracking category '$category' is disabled\n" );
445 // Output to stderr but don't bail out,
446 }
447
448 foreach ( $cats as $cat ) {
449 $this->refreshCategory( Title::newFromLinkTarget( $cat ) );
450 }
451 }
452
458 private function refreshCategory( Title $category ) {
459 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
460
461 $dbr = $this->getDB( DB_REPLICA );
462 $conds = [
463 'page_id=cl_from',
464 'cl_to' => $category->getDBkey(),
465 ] + $this->namespaceCond();
466
467 $i = 0;
468 $timestamp = '';
469 $lastId = 0;
470 do {
471 $finalConds = $conds;
472 $finalConds[] = $dbr->buildComparison( '>', [
473 'cl_timestamp' => $timestamp,
474 'cl_from' => $lastId,
475 ] );
476 $res = $dbr->select( [ 'page', 'categorylinks' ],
477 [ 'page_id', 'cl_timestamp' ],
478 $finalConds,
479 __METHOD__,
480 [
481 'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
482 'LIMIT' => $this->getBatchSize(),
483 ]
484 );
485
486 if ( $this->hasOption( 'verbose' ) ) {
487 $this->output( "Refreshing links for {$res->numRows()} pages\n" );
488 }
489
490 foreach ( $res as $row ) {
491 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
492 $this->output( "$i\n" );
493 $this->waitForReplication();
494 }
495 $lastId = $row->page_id;
496 $timestamp = $row->cl_timestamp;
497 if ( $this->hasOption( 'verbose' ) ) {
498 $this->output( "Refreshing links for page ID {$row->page_id}\n" );
499 }
500 self::fixLinksFromArticle( $row->page_id, false, $this->beforeTimestamp );
501 }
502
503 } while ( $res->numRows() == $this->getBatchSize() );
504 }
505
512 private function getPossibleCategories( $categoryKey ) {
513 $cats = MediaWikiServices::getInstance()->getTrackingCategories()->getTrackingCategories();
514 if ( isset( $cats[$categoryKey] ) ) {
515 return $cats[$categoryKey]['cats'];
516 }
517 $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
518 }
519}
520
521$maintClass = RefreshLinks::class;
522require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
const NS_CATEGORY
Definition Defines.php:78
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
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.
getHookRunner()
Get a HookRunner for running core hooks.
waitForReplication()
Wait for replica DBs to catch up.
hasOption( $name)
Checks to see if a particular option was set.
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.
Service locator for MediaWiki core services.
Page revision base class.
Represents a title within MediaWiki.
Definition Title.php:82
getDBkey()
Get the main part with underscores.
Definition Title.php:1090
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
A database connection without write operations.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
$content
Definition router.php:76