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 public function __construct() {
33 parent
::__construct();
34 $this->mDescription
= "Refresh link tables";
35 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
36 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
37 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
38 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
39 $this->addOption( 'e', 'Last page id to refresh', false, true );
40 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
41 'query, default 100000', false, true );
42 $this->addArg( 'start', 'Page_id to start from, default 1', false );
43 $this->setBatchSize( 100 );
46 public function execute() {
47 // Note that there is a difference between not specifying the start
48 // and end IDs and using the minimum and maximum values from the page
49 // table. In the latter case, deleteLinksFromNonexistent() will not
50 // delete entries for nonexistent IDs that fall outside the range.
51 $start = (int)$this->getArg( 0 ) ?
: null;
52 $end = (int)$this->getOption( 'e' ) ?
: null;
53 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
54 if ( !$this->hasOption( 'dfn-only' ) ) {
55 $new = $this->getOption( 'new-only', false );
56 $redir = $this->getOption( 'redirects-only', false );
57 $oldRedir = $this->getOption( 'old-redirects-only', false );
58 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
59 $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize
, $dfnChunkSize );
61 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize
, $dfnChunkSize );
66 * Do the actual link refreshing.
67 * @param int|null $start Page_id to start from
68 * @param bool $newOnly Only do pages with 1 edit
69 * @param int|null $end Page_id to stop at
70 * @param bool $redirectsOnly Only fix redirects
71 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
73 private function doRefreshLinks( $start, $newOnly = false,
74 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
76 global $wgParser, $wgUseTidy;
78 $reportingInterval = 100;
79 $dbr = wfGetDB( DB_SLAVE
);
81 if ( $start === null ) {
85 // Give extensions a chance to optimize settings
86 Hooks
::run( 'MaintenanceRefreshLinksInit', array( $this ) );
88 # Don't generate extension images (e.g. Timeline)
89 $wgParser->clearTagHooks();
94 $what = $redirectsOnly ?
"redirects" : "links";
96 if ( $oldRedirectsOnly ) {
97 # This entire code path is cut-and-pasted from below. Hurrah.
100 "page_is_redirect=1",
102 self
::intervalCond( $dbr, 'page_id', $start, $end ),
106 array( 'page', 'redirect' ),
111 array( 'redirect' => array( "LEFT JOIN", "page_id=rd_from" ) )
113 $num = $res->numRows();
114 $this->output( "Refreshing $num old redirects from $start...\n" );
118 foreach ( $res as $row ) {
119 if ( !( ++
$i %
$reportingInterval ) ) {
120 $this->output( "$i\n" );
123 $this->fixRedirect( $row->page_id
);
125 } elseif ( $newOnly ) {
126 $this->output( "Refreshing $what from " );
127 $res = $dbr->select( 'page',
131 self
::intervalCond( $dbr, 'page_id', $start, $end ),
135 $num = $res->numRows();
136 $this->output( "$num new articles...\n" );
139 foreach ( $res as $row ) {
140 if ( !( ++
$i %
$reportingInterval ) ) {
141 $this->output( "$i\n" );
144 if ( $redirectsOnly ) {
145 $this->fixRedirect( $row->page_id
);
147 self
::fixLinksFromArticle( $row->page_id
);
152 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
153 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
154 $end = max( $maxPage, $maxRD );
156 $this->output( "Refreshing redirects table.\n" );
157 $this->output( "Starting from page_id $start of $end.\n" );
159 for ( $id = $start; $id <= $end; $id++
) {
161 if ( !( $id %
$reportingInterval ) ) {
162 $this->output( "$id\n" );
165 $this->fixRedirect( $id );
168 if ( !$redirectsOnly ) {
169 $this->output( "Refreshing links tables.\n" );
170 $this->output( "Starting from page_id $start of $end.\n" );
172 for ( $id = $start; $id <= $end; $id++
) {
174 if ( !( $id %
$reportingInterval ) ) {
175 $this->output( "$id\n" );
178 self
::fixLinksFromArticle( $id );
185 * Update the redirect entry for a given page.
187 * This methods bypasses the "redirect" table to get the redirect target,
188 * and parses the page's content to fetch it. This allows to be sure that
189 * the redirect target is up to date and valid.
190 * This is particularly useful when modifying namespaces to be sure the
191 * entry in the "redirect" table points to the correct page and not to an
194 * @param int $id The page ID to check
196 private function fixRedirect( $id ) {
197 $page = WikiPage
::newFromID( $id );
198 $dbw = wfGetDB( DB_MASTER
);
200 if ( $page === null ) {
201 // This page doesn't exist (any more)
202 // Delete any redirect table entry for it
203 $dbw->delete( 'redirect', array( 'rd_from' => $id ),
210 $content = $page->getContent( Revision
::RAW
);
211 if ( $content !== null ) {
212 $rt = $content->getUltimateRedirectTarget();
215 if ( $rt === null ) {
216 // The page is not a redirect
217 // Delete any redirect table entry for it
218 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
221 $page->insertRedirectEntry( $rt );
225 // Update the page table to be sure it is an a consistent state
226 $dbw->update( 'page', array( 'page_is_redirect' => $fieldValue ),
227 array( 'page_id' => $id ), __METHOD__
);
231 * Run LinksUpdate for all links on a given page_id
232 * @param int $id The page_id
234 public static function fixLinksFromArticle( $id ) {
235 $page = WikiPage
::newFromID( $id );
237 LinkCache
::singleton()->clear();
239 if ( $page === null ) {
243 $content = $page->getContent( Revision
::RAW
);
244 if ( $content === null ) {
248 $dbw = wfGetDB( DB_MASTER
);
249 $dbw->begin( __METHOD__
);
251 $updates = $content->getSecondaryDataUpdates( $page->getTitle() );
252 DataUpdate
::runUpdates( $updates );
254 $dbw->commit( __METHOD__
);
258 * Removes non-existing links from pages from pagelinks, imagelinks,
259 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
261 * @param int|null $start Page_id to start from
262 * @param int|null $end Page_id to stop at
263 * @param int $batchSize The size of deletion batches
264 * @param int $chunkSize Maximum number of existent IDs to check per query
266 * @author Merlijn van Deen <valhallasw@arctus.nl>
268 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
272 $this->output( "Deleting illegal entries from the links tables...\n" );
273 $dbr = wfGetDB( DB_SLAVE
);
275 // Find the start of the next chunk. This is based only
276 // on existent page_ids.
277 $nextStart = $dbr->selectField(
280 self
::intervalCond( $dbr, 'page_id', $start, $end ),
282 array( 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize )
285 if ( $nextStart !== false ) {
286 // To find the end of the current chunk, subtract one.
287 // This will serve to limit the number of rows scanned in
288 // dfnCheckInterval(), per query, to at most the sum of
289 // the chunk size and deletion batch size.
290 $chunkEnd = $nextStart - 1;
292 // This is the last chunk. Check all page_ids up to $end.
296 $fmtStart = $start !== null ?
"[$start" : '(-INF';
297 $fmtChunkEnd = $chunkEnd !== null ?
"$chunkEnd]" : 'INF)';
298 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
299 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
303 } while ( $nextStart !== false );
307 * @see RefreshLinks::deleteLinksFromNonexistent()
308 * @param int|null $start Page_id to start from
309 * @param int|null $end Page_id to stop at
310 * @param int $batchSize The size of deletion batches
312 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
313 $dbw = wfGetDB( DB_MASTER
);
314 $dbr = wfGetDB( DB_SLAVE
);
316 $linksTables = array( // table name => page_id field
317 'pagelinks' => 'pl_from',
318 'imagelinks' => 'il_from',
319 'categorylinks' => 'cl_from',
320 'templatelinks' => 'tl_from',
321 'externallinks' => 'el_from',
322 'iwlinks' => 'iwl_from',
323 'langlinks' => 'll_from',
324 'redirect' => 'rd_from',
325 'page_props' => 'pp_page',
328 foreach ( $linksTables as $table => $field ) {
329 $this->output( " $table: 0" );
330 $tableStart = $start;
333 $ids = $dbr->selectFieldValues(
337 self
::intervalCond( $dbr, $field, $tableStart, $end ),
338 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
341 array( 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize )
344 $numIds = count( $ids );
347 $dbw->delete( $table, array( $field => $ids ), __METHOD__
);
348 $this->output( ", $counter" );
349 $tableStart = $ids[$numIds - 1] +
1;
353 } while ( $numIds >= $batchSize && ( $end === null ||
$tableStart <= $end ) );
355 $this->output( " deleted.\n" );
360 * Build a SQL expression for a closed interval (i.e. BETWEEN).
362 * By specifying a null $start or $end, it is also possible to create
363 * half-bounded or unbounded intervals using this function.
365 * @param IDatabase $db Database connection
366 * @param string $var Field name
367 * @param mixed $start First value to include or null
368 * @param mixed $end Last value to include or null
370 private static function intervalCond( IDatabase
$db, $var, $start, $end ) {
371 if ( $start === null && $end === null ) {
372 return "$var IS NOT NULL";
373 } elseif ( $end === null ) {
374 return "$var >= {$db->addQuotes( $start )}";
375 } elseif ( $start === null ) {
376 return "$var <= {$db->addQuotes( $end )}";
378 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
383 $maintClass = 'RefreshLinks';
384 require_once RUN_MAINTENANCE_IF_MAIN
;