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 require_once __DIR__
. '/Maintenance.php';
27 * Maintenance script to refresh link tables.
29 * @ingroup Maintenance
31 class RefreshLinks
extends Maintenance
{
32 const REPORTING_INTERVAL
= 100;
35 protected $namespace = false;
37 public function __construct() {
38 parent
::__construct();
39 $this->addDescription( 'Refresh link tables' );
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( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
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 100000', 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->addArg( 'start', 'Page_id to start from, default 1', false );
51 $this->setBatchSize( 100 );
54 public function execute() {
55 // Note that there is a difference between not specifying the start
56 // and end IDs and using the minimum and maximum values from the page
57 // table. In the latter case, deleteLinksFromNonexistent() will not
58 // delete entries for nonexistent IDs that fall outside the range.
59 $start = (int)$this->getArg( 0 ) ?
: null;
60 $end = (int)$this->getOption( 'e' ) ?
: null;
61 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
62 $ns = $this->getOption( 'namespace' );
64 $this->namespace = false;
66 $this->namespace = (int)$ns;
68 if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
69 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
71 $this->error( "'$category' is an invalid category name!\n", true );
73 $this->refreshCategory( $category );
74 } elseif ( ( $category = $this->getOption( 'tracking-category', false ) ) !== false ) {
75 $this->refreshTrackingCategory( $category );
76 } elseif ( !$this->hasOption( 'dfn-only' ) ) {
77 $new = $this->getOption( 'new-only', false );
78 $redir = $this->getOption( 'redirects-only', false );
79 $oldRedir = $this->getOption( 'old-redirects-only', false );
80 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
81 $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize
, $dfnChunkSize );
83 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize
, $dfnChunkSize );
87 private function namespaceCond() {
88 return $this->namespace !== false
89 ?
[ 'page_namespace' => $this->namespace ]
94 * Do the actual link refreshing.
95 * @param int|null $start Page_id to start from
96 * @param bool $newOnly Only do pages with 1 edit
97 * @param int|null $end Page_id to stop at
98 * @param bool $redirectsOnly Only fix redirects
99 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
101 private function doRefreshLinks( $start, $newOnly = false,
102 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
104 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
106 if ( $start === null ) {
110 // Give extensions a chance to optimize settings
111 Hooks
::run( 'MaintenanceRefreshLinksInit', [ $this ] );
113 $what = $redirectsOnly ?
"redirects" : "links";
115 if ( $oldRedirectsOnly ) {
116 # This entire code path is cut-and-pasted from below. Hurrah.
119 "page_is_redirect=1",
121 self
::intervalCond( $dbr, 'page_id', $start, $end ),
122 ] +
$this->namespaceCond();
125 [ 'page', 'redirect' ],
130 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
132 $num = $res->numRows();
133 $this->output( "Refreshing $num old redirects from $start...\n" );
137 foreach ( $res as $row ) {
138 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
139 $this->output( "$i\n" );
142 $this->fixRedirect( $row->page_id
);
144 } elseif ( $newOnly ) {
145 $this->output( "Refreshing $what from " );
146 $res = $dbr->select( 'page',
150 self
::intervalCond( $dbr, 'page_id', $start, $end ),
151 ] +
$this->namespaceCond(),
154 $num = $res->numRows();
155 $this->output( "$num new articles...\n" );
158 foreach ( $res as $row ) {
159 if ( !( ++
$i % self
::REPORTING_INTERVAL
) ) {
160 $this->output( "$i\n" );
163 if ( $redirectsOnly ) {
164 $this->fixRedirect( $row->page_id
);
166 self
::fixLinksFromArticle( $row->page_id
, $this->namespace );
171 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
172 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
173 $end = max( $maxPage, $maxRD );
175 $this->output( "Refreshing redirects table.\n" );
176 $this->output( "Starting from page_id $start of $end.\n" );
178 for ( $id = $start; $id <= $end; $id++
) {
180 if ( !( $id % self
::REPORTING_INTERVAL
) ) {
181 $this->output( "$id\n" );
184 $this->fixRedirect( $id );
187 if ( !$redirectsOnly ) {
188 $this->output( "Refreshing links tables.\n" );
189 $this->output( "Starting from page_id $start of $end.\n" );
191 for ( $id = $start; $id <= $end; $id++
) {
193 if ( !( $id % self
::REPORTING_INTERVAL
) ) {
194 $this->output( "$id\n" );
197 self
::fixLinksFromArticle( $id, $this->namespace );
204 * Update the redirect entry for a given page.
206 * This methods bypasses the "redirect" table to get the redirect target,
207 * and parses the page's content to fetch it. This allows to be sure that
208 * the redirect target is up to date and valid.
209 * This is particularly useful when modifying namespaces to be sure the
210 * entry in the "redirect" table points to the correct page and not to an
213 * @param int $id The page ID to check
215 private function fixRedirect( $id ) {
216 $page = WikiPage
::newFromID( $id );
217 $dbw = $this->getDB( DB_MASTER
);
219 if ( $page === null ) {
220 // This page doesn't exist (any more)
221 // Delete any redirect table entry for it
222 $dbw->delete( 'redirect', [ 'rd_from' => $id ],
226 } elseif ( $this->namespace !== false
227 && !$page->getTitle()->inNamespace( $this->namespace )
233 $content = $page->getContent( Revision
::RAW
);
234 if ( $content !== null ) {
235 $rt = $content->getUltimateRedirectTarget();
238 if ( $rt === null ) {
239 // The page is not a redirect
240 // Delete any redirect table entry for it
241 $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__
);
244 $page->insertRedirectEntry( $rt );
248 // Update the page table to be sure it is an a consistent state
249 $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
250 [ 'page_id' => $id ], __METHOD__
);
254 * Run LinksUpdate for all links on a given page_id
255 * @param int $id The page_id
256 * @param int|bool $ns Only fix links if it is in this namespace
258 public static function fixLinksFromArticle( $id, $ns = false ) {
259 $page = WikiPage
::newFromID( $id );
261 LinkCache
::singleton()->clear();
263 if ( $page === null ) {
265 } elseif ( $ns !== false
266 && !$page->getTitle()->inNamespace( $ns ) ) {
270 $content = $page->getContent( Revision
::RAW
);
271 if ( $content === null ) {
275 $updates = $content->getSecondaryDataUpdates(
276 $page->getTitle(), /* $old = */ null, /* $recursive = */ false );
277 foreach ( $updates as $update ) {
278 DeferredUpdates
::addUpdate( $update );
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 Database connection
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->mBatchSize
,
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->mBatchSize
);
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->error( "Unknown tracking category {$categoryKey}\n", true );
491 $maintClass = 'RefreshLinks';
492 require_once RUN_MAINTENANCE_IF_MAIN
;