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 Wikimedia\Rdbms\IDatabase
;
26 require_once __DIR__
. '/Maintenance.php';
29 * Maintenance script to refresh link tables.
31 * @ingroup Maintenance
33 class RefreshLinks
extends Maintenance
{
34 const REPORTING_INTERVAL
= 100;
37 protected $namespace = false;
39 public function __construct() {
40 parent
::__construct();
41 $this->addDescription( 'Refresh link tables' );
42 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
43 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
44 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
45 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
46 $this->addOption( 'e', 'Last page id to refresh', false, true );
47 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
48 'query, default 100000', false, true );
49 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
50 $this->addOption( 'category', 'Only fix pages in this category', false, true );
51 $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
52 $this->addArg( 'start', 'Page_id to start from, default 1', false );
53 $this->setBatchSize( 100 );
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', 100000 );
64 $ns = $this->getOption( 'namespace' );
66 $this->namespace = false;
68 $this->namespace = (int)$ns;
70 if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
71 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
73 $this->error( "'$category' is an invalid category name!\n", true );
75 $this->refreshCategory( $category );
76 } elseif ( ( $category = $this->getOption( 'tracking-category', false ) ) !== false ) {
77 $this->refreshTrackingCategory( $category );
78 } elseif ( !$this->hasOption( 'dfn-only' ) ) {
79 $new = $this->getOption( 'new-only', false );
80 $redir = $this->getOption( 'redirects-only', false );
81 $oldRedir = $this->getOption( 'old-redirects-only', false );
82 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
83 $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize
, $dfnChunkSize );
85 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize
, $dfnChunkSize );
89 private function namespaceCond() {
90 return $this->namespace !== false
91 ?
[ 'page_namespace' => $this->namespace ]
96 * Do the actual link refreshing.
97 * @param int|null $start Page_id to start from
98 * @param bool $newOnly Only do pages with 1 edit
99 * @param int|null $end Page_id to stop at
100 * @param bool $redirectsOnly Only fix redirects
101 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
103 private function doRefreshLinks( $start, $newOnly = false,
104 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
106 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
108 if ( $start === null ) {
112 // Give extensions a chance to optimize settings
113 Hooks
::run( 'MaintenanceRefreshLinksInit', [ $this ] );
115 $what = $redirectsOnly ?
"redirects" : "links";
117 if ( $oldRedirectsOnly ) {
118 # This entire code path is cut-and-pasted from below. Hurrah.
121 "page_is_redirect=1",
123 self
::intervalCond( $dbr, 'page_id', $start, $end ),
124 ] +
$this->namespaceCond();
127 [ 'page', 'redirect' ],
132 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
134 $num = $res->numRows();
135 $this->output( "Refreshing $num old redirects from $start...\n" );
139 foreach ( $res as $row ) {
140 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
141 $this->output( "$i\n" );
144 $this->fixRedirect( $row->page_id
);
146 } elseif ( $newOnly ) {
147 $this->output( "Refreshing $what from " );
148 $res = $dbr->select( 'page',
152 self
::intervalCond( $dbr, 'page_id', $start, $end ),
153 ] +
$this->namespaceCond(),
156 $num = $res->numRows();
157 $this->output( "$num new articles...\n" );
160 foreach ( $res as $row ) {
161 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
162 $this->output( "$i\n" );
165 if ( $redirectsOnly ) {
166 $this->fixRedirect( $row->page_id
);
168 self
::fixLinksFromArticle( $row->page_id
, $this->namespace );
173 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
174 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
175 $end = max( $maxPage, $maxRD );
177 $this->output( "Refreshing redirects table.\n" );
178 $this->output( "Starting from page_id $start of $end.\n" );
180 for ( $id = $start; $id <= $end; $id++
) {
182 if ( !( $id % self
::REPORTING_INTERVAL
) ) {
183 $this->output( "$id\n" );
186 $this->fixRedirect( $id );
189 if ( !$redirectsOnly ) {
190 $this->output( "Refreshing links tables.\n" );
191 $this->output( "Starting from page_id $start of $end.\n" );
193 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( Revision
::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 LinkCache
::singleton()->clear();
265 if ( $page === null ) {
267 } elseif ( $ns !== false
268 && !$page->getTitle()->inNamespace( $ns ) ) {
272 $content = $page->getContent( Revision
::RAW
);
273 if ( $content === null ) {
277 $updates = $content->getSecondaryDataUpdates(
278 $page->getTitle(), /* $old = */ null, /* $recursive = */ false );
279 foreach ( $updates as $update ) {
280 DeferredUpdates
::addUpdate( $update );
285 * Removes non-existing links from pages from pagelinks, imagelinks,
286 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
288 * @param int|null $start Page_id to start from
289 * @param int|null $end Page_id to stop at
290 * @param int $batchSize The size of deletion batches
291 * @param int $chunkSize Maximum number of existent IDs to check per query
293 * @author Merlijn van Deen <valhallasw@arctus.nl>
295 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
299 $this->output( "Deleting illegal entries from the links tables...\n" );
300 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
302 // Find the start of the next chunk. This is based only
303 // on existent page_ids.
304 $nextStart = $dbr->selectField(
307 [ self
::intervalCond( $dbr, 'page_id', $start, $end ) ]
308 +
$this->namespaceCond(),
310 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
313 if ( $nextStart !== false ) {
314 // To find the end of the current chunk, subtract one.
315 // This will serve to limit the number of rows scanned in
316 // dfnCheckInterval(), per query, to at most the sum of
317 // the chunk size and deletion batch size.
318 $chunkEnd = $nextStart - 1;
320 // This is the last chunk. Check all page_ids up to $end.
324 $fmtStart = $start !== null ?
"[$start" : '(-INF';
325 $fmtChunkEnd = $chunkEnd !== null ?
"$chunkEnd]" : 'INF)';
326 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
327 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
331 } while ( $nextStart !== false );
335 * @see RefreshLinks::deleteLinksFromNonexistent()
336 * @param int|null $start Page_id to start from
337 * @param int|null $end Page_id to stop at
338 * @param int $batchSize The size of deletion batches
340 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
341 $dbw = $this->getDB( DB_MASTER
);
342 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
344 $linksTables = [ // table name => page_id field
345 'pagelinks' => 'pl_from',
346 'imagelinks' => 'il_from',
347 'categorylinks' => 'cl_from',
348 'templatelinks' => 'tl_from',
349 'externallinks' => 'el_from',
350 'iwlinks' => 'iwl_from',
351 'langlinks' => 'll_from',
352 'redirect' => 'rd_from',
353 'page_props' => 'pp_page',
356 foreach ( $linksTables as $table => $field ) {
357 $this->output( " $table: 0" );
358 $tableStart = $start;
361 $ids = $dbr->selectFieldValues(
365 self
::intervalCond( $dbr, $field, $tableStart, $end ),
366 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
369 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
372 $numIds = count( $ids );
375 $dbw->delete( $table, [ $field => $ids ], __METHOD__
);
376 $this->output( ", $counter" );
377 $tableStart = $ids[$numIds - 1] +
1;
381 } while ( $numIds >= $batchSize && ( $end === null ||
$tableStart <= $end ) );
383 $this->output( " deleted.\n" );
388 * Build a SQL expression for a closed interval (i.e. BETWEEN).
390 * By specifying a null $start or $end, it is also possible to create
391 * half-bounded or unbounded intervals using this function.
393 * @param IDatabase $db
394 * @param string $var Field name
395 * @param mixed $start First value to include or null
396 * @param mixed $end Last value to include or null
399 private static function intervalCond( IDatabase
$db, $var, $start, $end ) {
400 if ( $start === null && $end === null ) {
401 return "$var IS NOT NULL";
402 } elseif ( $end === null ) {
403 return "$var >= {$db->addQuotes( $start )}";
404 } elseif ( $start === null ) {
405 return "$var <= {$db->addQuotes( $end )}";
407 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
412 * Refershes links for pages in a tracking category
414 * @param string $category Category key
416 private function refreshTrackingCategory( $category ) {
417 $cats = $this->getPossibleCategories( $category );
420 $this->error( "Tracking category '$category' is disabled\n" );
421 // Output to stderr but don't bail out,
424 foreach ( $cats as $cat ) {
425 $this->refreshCategory( $cat );
430 * Refreshes links to a category
432 * @param Title $category
434 private function refreshCategory( Title
$category ) {
435 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
437 $dbr = $this->getDB( DB_REPLICA
);
440 'cl_to' => $category->getDBkey(),
442 if ( $this->namespace !== false ) {
443 $conds['page_namespace'] = $this->namespace;
450 $finalConds = $conds;
451 $timestamp = $dbr->addQuotes( $timestamp );
453 "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
454 $res = $dbr->select( [ 'page', 'categorylinks' ],
455 [ 'page_id', 'cl_timestamp' ],
459 'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
460 'LIMIT' => $this->mBatchSize
,
464 foreach ( $res as $row ) {
465 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
466 $this->output( "$i\n" );
469 $lastId = $row->page_id
;
470 $timestamp = $row->cl_timestamp
;
471 self
::fixLinksFromArticle( $row->page_id
);
474 } while ( $res->numRows() == $this->mBatchSize
);
478 * Returns a list of possible categories for a given tracking category key
480 * @param string $categoryKey
483 private function getPossibleCategories( $categoryKey ) {
484 $trackingCategories = new TrackingCategories( $this->getConfig() );
485 $cats = $trackingCategories->getTrackingCategories();
486 if ( isset( $cats[$categoryKey] ) ) {
487 return $cats[$categoryKey]['cats'];
489 $this->error( "Unknown tracking category {$categoryKey}\n", true );
493 $maintClass = 'RefreshLinks';
494 require_once RUN_MAINTENANCE_IF_MAIN
;