5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Maintenance
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Storage\RevisionRecord
;
26 use Wikimedia\Rdbms\IDatabase
;
28 require_once __DIR__
. '/Maintenance.php';
31 * Maintenance script to refresh link tables.
33 * @ingroup Maintenance
35 class RefreshLinks
extends Maintenance
{
36 const REPORTING_INTERVAL
= 100;
39 protected $namespace = false;
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 );
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' );
68 $this->namespace = false;
70 $this->namespace = (int)$ns;
72 if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
73 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
75 $this->fatalError( "'$category' is an invalid category name!\n" );
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 );
87 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
91 private function namespaceCond() {
92 return $this->namespace !== false
93 ?
[ 'page_namespace' => $this->namespace ]
98 * Do the actual link refreshing.
99 * @param int|null $start Page_id to start from
100 * @param bool $newOnly Only do pages with 1 edit
101 * @param int|null $end Page_id to stop at
102 * @param bool $redirectsOnly Only fix redirects
103 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
105 private function doRefreshLinks( $start, $newOnly = false,
106 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
108 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
110 if ( $start === null ) {
114 // Give extensions a chance to optimize settings
115 Hooks
::run( 'MaintenanceRefreshLinksInit', [ $this ] );
117 $what = $redirectsOnly ?
"redirects" : "links";
119 if ( $oldRedirectsOnly ) {
120 # This entire code path is cut-and-pasted from below. Hurrah.
123 "page_is_redirect=1",
125 self
::intervalCond( $dbr, 'page_id', $start, $end ),
126 ] +
$this->namespaceCond();
129 [ 'page', 'redirect' ],
134 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
136 $num = $res->numRows();
137 $this->output( "Refreshing $num old redirects from $start...\n" );
141 foreach ( $res as $row ) {
142 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
143 $this->output( "$i\n" );
146 $this->fixRedirect( $row->page_id
);
148 } elseif ( $newOnly ) {
149 $this->output( "Refreshing $what from " );
150 $res = $dbr->select( 'page',
154 self
::intervalCond( $dbr, 'page_id', $start, $end ),
155 ] +
$this->namespaceCond(),
158 $num = $res->numRows();
159 $this->output( "$num new articles...\n" );
162 foreach ( $res as $row ) {
163 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
164 $this->output( "$i\n" );
167 if ( $redirectsOnly ) {
168 $this->fixRedirect( $row->page_id
);
170 self
::fixLinksFromArticle( $row->page_id
, $this->namespace );
175 $maxPage = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__
);
176 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', '', __METHOD__
);
177 $end = max( $maxPage, $maxRD );
179 $this->output( "Refreshing redirects table.\n" );
180 $this->output( "Starting from page_id $start of $end.\n" );
182 for ( $id = $start; $id <= $end; $id++
) {
183 if ( !( $id % self
::REPORTING_INTERVAL
) ) {
184 $this->output( "$id\n" );
187 $this->fixRedirect( $id );
190 if ( !$redirectsOnly ) {
191 $this->output( "Refreshing links tables.\n" );
192 $this->output( "Starting from page_id $start of $end.\n" );
194 for ( $id = $start; $id <= $end; $id++
) {
195 if ( !( $id % self
::REPORTING_INTERVAL
) ) {
196 $this->output( "$id\n" );
199 self
::fixLinksFromArticle( $id, $this->namespace );
206 * Update the redirect entry for a given page.
208 * This methods bypasses the "redirect" table to get the redirect target,
209 * and parses the page's content to fetch it. This allows to be sure that
210 * the redirect target is up to date and valid.
211 * This is particularly useful when modifying namespaces to be sure the
212 * entry in the "redirect" table points to the correct page and not to an
215 * @param int $id The page ID to check
217 private function fixRedirect( $id ) {
218 $page = WikiPage
::newFromID( $id );
219 $dbw = $this->getDB( DB_MASTER
);
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 ],
228 } elseif ( $this->namespace !== false
229 && !$page->getTitle()->inNamespace( $this->namespace )
235 $content = $page->getContent( RevisionRecord
::RAW
);
236 if ( $content !== null ) {
237 $rt = $content->getUltimateRedirectTarget();
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__
);
246 $page->insertRedirectEntry( $rt );
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__
);
256 * Run LinksUpdate for all links on a given page_id
257 * @param int $id The page_id
258 * @param int|bool $ns Only fix links if it is in this namespace
260 public static function fixLinksFromArticle( $id, $ns = false ) {
261 $page = WikiPage
::newFromID( $id );
263 MediaWikiServices
::getInstance()->getLinkCache()->clear();
265 if ( $page === null ) {
267 } elseif ( $ns !== false
268 && !$page->getTitle()->inNamespace( $ns ) ) {
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,
279 DeferredUpdates
::doUpdates();
283 * Removes non-existing links from pages from pagelinks, imagelinks,
284 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
286 * @param int|null $start Page_id to start from
287 * @param int|null $end Page_id to stop at
288 * @param int $batchSize The size of deletion batches
289 * @param int $chunkSize Maximum number of existent IDs to check per query
291 * @author Merlijn van Deen <valhallasw@arctus.nl>
293 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
297 $this->output( "Deleting illegal entries from the links tables...\n" );
298 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
300 // Find the start of the next chunk. This is based only
301 // on existent page_ids.
302 $nextStart = $dbr->selectField(
305 [ self
::intervalCond( $dbr, 'page_id', $start, $end ) ]
306 +
$this->namespaceCond(),
308 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
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;
318 // This is the last chunk. Check all page_ids up to $end.
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 );
329 } while ( $nextStart !== false );
333 * @see RefreshLinks::deleteLinksFromNonexistent()
334 * @param int|null $start Page_id to start from
335 * @param int|null $end Page_id to stop at
336 * @param int $batchSize The size of deletion batches
338 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
339 $dbw = $this->getDB( DB_MASTER
);
340 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
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',
354 foreach ( $linksTables as $table => $field ) {
355 $this->output( " $table: 0" );
356 $tableStart = $start;
359 $ids = $dbr->selectFieldValues(
363 self
::intervalCond( $dbr, $field, $tableStart, $end ),
364 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
367 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
370 $numIds = count( $ids );
373 $dbw->delete( $table, [ $field => $ids ], __METHOD__
);
374 $this->output( ", $counter" );
375 $tableStart = $ids[$numIds - 1] +
1;
379 } while ( $numIds >= $batchSize && ( $end === null ||
$tableStart <= $end ) );
381 $this->output( " deleted.\n" );
386 * Build a SQL expression for a closed interval (i.e. BETWEEN).
388 * By specifying a null $start or $end, it is also possible to create
389 * half-bounded or unbounded intervals using this function.
391 * @param IDatabase $db
392 * @param string $var Field name
393 * @param mixed $start First value to include or null
394 * @param mixed $end Last value to include or null
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 )}";
405 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
410 * Refershes links for pages in a tracking category
412 * @param string $category Category key
414 private function refreshTrackingCategory( $category ) {
415 $cats = $this->getPossibleCategories( $category );
418 $this->error( "Tracking category '$category' is disabled\n" );
419 // Output to stderr but don't bail out,
422 foreach ( $cats as $cat ) {
423 $this->refreshCategory( $cat );
428 * Refreshes links to a category
430 * @param Title $category
432 private function refreshCategory( Title
$category ) {
433 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
435 $dbr = $this->getDB( DB_REPLICA
);
438 'cl_to' => $category->getDBkey(),
440 if ( $this->namespace !== false ) {
441 $conds['page_namespace'] = $this->namespace;
448 $finalConds = $conds;
449 $timestamp = $dbr->addQuotes( $timestamp );
451 "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
452 $res = $dbr->select( [ 'page', 'categorylinks' ],
453 [ 'page_id', 'cl_timestamp' ],
457 'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
458 'LIMIT' => $this->getBatchSize(),
462 foreach ( $res as $row ) {
463 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
464 $this->output( "$i\n" );
467 $lastId = $row->page_id
;
468 $timestamp = $row->cl_timestamp
;
469 self
::fixLinksFromArticle( $row->page_id
);
472 } while ( $res->numRows() == $this->getBatchSize() );
476 * Returns a list of possible categories for a given tracking category key
478 * @param string $categoryKey
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'];
487 $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
491 $maintClass = RefreshLinks
::class;
492 require_once RUN_MAINTENANCE_IF_MAIN
;