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
{
33 protected $namespace = false;
35 public function __construct() {
36 parent
::__construct();
37 $this->addDescription( 'Refresh link tables' );
38 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
39 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
40 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
41 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
42 $this->addOption( 'e', 'Last page id to refresh', false, true );
43 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
44 'query, default 100000', false, true );
45 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
46 $this->addArg( 'start', 'Page_id to start from, default 1', false );
47 $this->setBatchSize( 100 );
50 public function execute() {
51 // Note that there is a difference between not specifying the start
52 // and end IDs and using the minimum and maximum values from the page
53 // table. In the latter case, deleteLinksFromNonexistent() will not
54 // delete entries for nonexistent IDs that fall outside the range.
55 $start = (int)$this->getArg( 0 ) ?
: null;
56 $end = (int)$this->getOption( 'e' ) ?
: null;
57 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
58 $ns = $this->getOption( 'namespace' );
60 $this->namespace = false;
62 $this->namespace = (int)$ns;
64 if ( !$this->hasOption( 'dfn-only' ) ) {
65 $new = $this->getOption( 'new-only', false );
66 $redir = $this->getOption( 'redirects-only', false );
67 $oldRedir = $this->getOption( 'old-redirects-only', false );
68 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
69 $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize
, $dfnChunkSize );
71 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize
, $dfnChunkSize );
75 private function namespaceCond() {
76 return $this->namespace !== false
77 ?
[ 'page_namespace' => $this->namespace ]
82 * Do the actual link refreshing.
83 * @param int|null $start Page_id to start from
84 * @param bool $newOnly Only do pages with 1 edit
85 * @param int|null $end Page_id to stop at
86 * @param bool $redirectsOnly Only fix redirects
87 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
89 private function doRefreshLinks( $start, $newOnly = false,
90 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
92 $reportingInterval = 100;
93 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
95 if ( $start === null ) {
99 // Give extensions a chance to optimize settings
100 Hooks
::run( 'MaintenanceRefreshLinksInit', [ $this ] );
102 $what = $redirectsOnly ?
"redirects" : "links";
104 if ( $oldRedirectsOnly ) {
105 # This entire code path is cut-and-pasted from below. Hurrah.
108 "page_is_redirect=1",
110 self
::intervalCond( $dbr, 'page_id', $start, $end ),
111 ] +
$this->namespaceCond();
114 [ 'page', 'redirect' ],
119 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
121 $num = $res->numRows();
122 $this->output( "Refreshing $num old redirects from $start...\n" );
126 foreach ( $res as $row ) {
127 if ( !( ++
$i %
$reportingInterval ) ) {
128 $this->output( "$i\n" );
131 $this->fixRedirect( $row->page_id
);
133 } elseif ( $newOnly ) {
134 $this->output( "Refreshing $what from " );
135 $res = $dbr->select( 'page',
139 self
::intervalCond( $dbr, 'page_id', $start, $end ),
140 ] +
$this->namespaceCond(),
143 $num = $res->numRows();
144 $this->output( "$num new articles...\n" );
147 foreach ( $res as $row ) {
148 if ( !( ++
$i %
$reportingInterval ) ) {
149 $this->output( "$i\n" );
152 if ( $redirectsOnly ) {
153 $this->fixRedirect( $row->page_id
);
155 self
::fixLinksFromArticle( $row->page_id
, $this->namespace );
160 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
161 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
162 $end = max( $maxPage, $maxRD );
164 $this->output( "Refreshing redirects table.\n" );
165 $this->output( "Starting from page_id $start of $end.\n" );
167 for ( $id = $start; $id <= $end; $id++
) {
169 if ( !( $id %
$reportingInterval ) ) {
170 $this->output( "$id\n" );
173 $this->fixRedirect( $id );
176 if ( !$redirectsOnly ) {
177 $this->output( "Refreshing links tables.\n" );
178 $this->output( "Starting from page_id $start of $end.\n" );
180 for ( $id = $start; $id <= $end; $id++
) {
182 if ( !( $id %
$reportingInterval ) ) {
183 $this->output( "$id\n" );
186 self
::fixLinksFromArticle( $id, $this->namespace );
193 * Update the redirect entry for a given page.
195 * This methods bypasses the "redirect" table to get the redirect target,
196 * and parses the page's content to fetch it. This allows to be sure that
197 * the redirect target is up to date and valid.
198 * This is particularly useful when modifying namespaces to be sure the
199 * entry in the "redirect" table points to the correct page and not to an
202 * @param int $id The page ID to check
204 private function fixRedirect( $id ) {
205 $page = WikiPage
::newFromID( $id );
206 $dbw = $this->getDB( DB_MASTER
);
208 if ( $page === null ) {
209 // This page doesn't exist (any more)
210 // Delete any redirect table entry for it
211 $dbw->delete( 'redirect', [ 'rd_from' => $id ],
215 } elseif ( $this->namespace !== false
216 && !$page->getTitle()->inNamespace( $this->namespace )
222 $content = $page->getContent( Revision
::RAW
);
223 if ( $content !== null ) {
224 $rt = $content->getUltimateRedirectTarget();
227 if ( $rt === null ) {
228 // The page is not a redirect
229 // Delete any redirect table entry for it
230 $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__
);
233 $page->insertRedirectEntry( $rt );
237 // Update the page table to be sure it is an a consistent state
238 $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
239 [ 'page_id' => $id ], __METHOD__
);
243 * Run LinksUpdate for all links on a given page_id
244 * @param int $id The page_id
245 * @param int|bool $ns Only fix links if it is in this namespace
247 public static function fixLinksFromArticle( $id, $ns = false ) {
248 $page = WikiPage
::newFromID( $id );
250 LinkCache
::singleton()->clear();
252 if ( $page === null ) {
254 } elseif ( $ns !== false
255 && !$page->getTitle()->inNamespace( $ns ) ) {
259 $content = $page->getContent( Revision
::RAW
);
260 if ( $content === null ) {
264 foreach ( $content->getSecondaryDataUpdates( $page->getTitle() ) as $update ) {
265 DeferredUpdates
::addUpdate( $update );
270 * Removes non-existing links from pages from pagelinks, imagelinks,
271 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
273 * @param int|null $start Page_id to start from
274 * @param int|null $end Page_id to stop at
275 * @param int $batchSize The size of deletion batches
276 * @param int $chunkSize Maximum number of existent IDs to check per query
278 * @author Merlijn van Deen <valhallasw@arctus.nl>
280 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
284 $this->output( "Deleting illegal entries from the links tables...\n" );
285 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
287 // Find the start of the next chunk. This is based only
288 // on existent page_ids.
289 $nextStart = $dbr->selectField(
292 [ self
::intervalCond( $dbr, 'page_id', $start, $end ) ]
293 +
$this->namespaceCond(),
295 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
298 if ( $nextStart !== false ) {
299 // To find the end of the current chunk, subtract one.
300 // This will serve to limit the number of rows scanned in
301 // dfnCheckInterval(), per query, to at most the sum of
302 // the chunk size and deletion batch size.
303 $chunkEnd = $nextStart - 1;
305 // This is the last chunk. Check all page_ids up to $end.
309 $fmtStart = $start !== null ?
"[$start" : '(-INF';
310 $fmtChunkEnd = $chunkEnd !== null ?
"$chunkEnd]" : 'INF)';
311 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
312 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
316 } while ( $nextStart !== false );
320 * @see RefreshLinks::deleteLinksFromNonexistent()
321 * @param int|null $start Page_id to start from
322 * @param int|null $end Page_id to stop at
323 * @param int $batchSize The size of deletion batches
325 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
326 $dbw = $this->getDB( DB_MASTER
);
327 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
329 $linksTables = [ // table name => page_id field
330 'pagelinks' => 'pl_from',
331 'imagelinks' => 'il_from',
332 'categorylinks' => 'cl_from',
333 'templatelinks' => 'tl_from',
334 'externallinks' => 'el_from',
335 'iwlinks' => 'iwl_from',
336 'langlinks' => 'll_from',
337 'redirect' => 'rd_from',
338 'page_props' => 'pp_page',
341 foreach ( $linksTables as $table => $field ) {
342 $this->output( " $table: 0" );
343 $tableStart = $start;
346 $ids = $dbr->selectFieldValues(
350 self
::intervalCond( $dbr, $field, $tableStart, $end ),
351 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
354 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
357 $numIds = count( $ids );
360 $dbw->delete( $table, [ $field => $ids ], __METHOD__
);
361 $this->output( ", $counter" );
362 $tableStart = $ids[$numIds - 1] +
1;
366 } while ( $numIds >= $batchSize && ( $end === null ||
$tableStart <= $end ) );
368 $this->output( " deleted.\n" );
373 * Build a SQL expression for a closed interval (i.e. BETWEEN).
375 * By specifying a null $start or $end, it is also possible to create
376 * half-bounded or unbounded intervals using this function.
378 * @param IDatabase $db Database connection
379 * @param string $var Field name
380 * @param mixed $start First value to include or null
381 * @param mixed $end Last value to include or null
383 private static function intervalCond( IDatabase
$db, $var, $start, $end ) {
384 if ( $start === null && $end === null ) {
385 return "$var IS NOT NULL";
386 } elseif ( $end === null ) {
387 return "$var >= {$db->addQuotes( $start )}";
388 } elseif ( $start === null ) {
389 return "$var <= {$db->addQuotes( $end )}";
391 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
396 $maintClass = 'RefreshLinks';
397 require_once RUN_MAINTENANCE_IF_MAIN
;