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
78 $reportingInterval = 100;
79 $dbr = $this->getDB( 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();
91 $what = $redirectsOnly ?
"redirects" : "links";
93 if ( $oldRedirectsOnly ) {
94 # This entire code path is cut-and-pasted from below. Hurrah.
99 self
::intervalCond( $dbr, 'page_id', $start, $end ),
103 array( 'page', 'redirect' ),
108 array( 'redirect' => array( "LEFT JOIN", "page_id=rd_from" ) )
110 $num = $res->numRows();
111 $this->output( "Refreshing $num old redirects from $start...\n" );
115 foreach ( $res as $row ) {
116 if ( !( ++
$i %
$reportingInterval ) ) {
117 $this->output( "$i\n" );
120 $this->fixRedirect( $row->page_id
);
122 } elseif ( $newOnly ) {
123 $this->output( "Refreshing $what from " );
124 $res = $dbr->select( 'page',
128 self
::intervalCond( $dbr, 'page_id', $start, $end ),
132 $num = $res->numRows();
133 $this->output( "$num new articles...\n" );
136 foreach ( $res as $row ) {
137 if ( !( ++
$i %
$reportingInterval ) ) {
138 $this->output( "$i\n" );
141 if ( $redirectsOnly ) {
142 $this->fixRedirect( $row->page_id
);
144 self
::fixLinksFromArticle( $row->page_id
);
149 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
150 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
151 $end = max( $maxPage, $maxRD );
153 $this->output( "Refreshing redirects table.\n" );
154 $this->output( "Starting from page_id $start of $end.\n" );
156 for ( $id = $start; $id <= $end; $id++
) {
158 if ( !( $id %
$reportingInterval ) ) {
159 $this->output( "$id\n" );
162 $this->fixRedirect( $id );
165 if ( !$redirectsOnly ) {
166 $this->output( "Refreshing links tables.\n" );
167 $this->output( "Starting from page_id $start of $end.\n" );
169 for ( $id = $start; $id <= $end; $id++
) {
171 if ( !( $id %
$reportingInterval ) ) {
172 $this->output( "$id\n" );
175 self
::fixLinksFromArticle( $id );
182 * Update the redirect entry for a given page.
184 * This methods bypasses the "redirect" table to get the redirect target,
185 * and parses the page's content to fetch it. This allows to be sure that
186 * the redirect target is up to date and valid.
187 * This is particularly useful when modifying namespaces to be sure the
188 * entry in the "redirect" table points to the correct page and not to an
191 * @param int $id The page ID to check
193 private function fixRedirect( $id ) {
194 $page = WikiPage
::newFromID( $id );
195 $dbw = $this->getDB( DB_MASTER
);
197 if ( $page === null ) {
198 // This page doesn't exist (any more)
199 // Delete any redirect table entry for it
200 $dbw->delete( 'redirect', array( 'rd_from' => $id ),
207 $content = $page->getContent( Revision
::RAW
);
208 if ( $content !== null ) {
209 $rt = $content->getUltimateRedirectTarget();
212 if ( $rt === null ) {
213 // The page is not a redirect
214 // Delete any redirect table entry for it
215 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
218 $page->insertRedirectEntry( $rt );
222 // Update the page table to be sure it is an a consistent state
223 $dbw->update( 'page', array( 'page_is_redirect' => $fieldValue ),
224 array( 'page_id' => $id ), __METHOD__
);
228 * Run LinksUpdate for all links on a given page_id
229 * @param int $id The page_id
231 public static function fixLinksFromArticle( $id ) {
232 $page = WikiPage
::newFromID( $id );
234 LinkCache
::singleton()->clear();
236 if ( $page === null ) {
240 $content = $page->getContent( Revision
::RAW
);
241 if ( $content === null ) {
245 $updates = $content->getSecondaryDataUpdates( $page->getTitle() );
246 DataUpdate
::runUpdates( $updates );
250 * Removes non-existing links from pages from pagelinks, imagelinks,
251 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
253 * @param int|null $start Page_id to start from
254 * @param int|null $end Page_id to stop at
255 * @param int $batchSize The size of deletion batches
256 * @param int $chunkSize Maximum number of existent IDs to check per query
258 * @author Merlijn van Deen <valhallasw@arctus.nl>
260 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
264 $this->output( "Deleting illegal entries from the links tables...\n" );
265 $dbr = $this->getDB( DB_SLAVE
);
267 // Find the start of the next chunk. This is based only
268 // on existent page_ids.
269 $nextStart = $dbr->selectField(
272 self
::intervalCond( $dbr, 'page_id', $start, $end ),
274 array( 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize )
277 if ( $nextStart !== false ) {
278 // To find the end of the current chunk, subtract one.
279 // This will serve to limit the number of rows scanned in
280 // dfnCheckInterval(), per query, to at most the sum of
281 // the chunk size and deletion batch size.
282 $chunkEnd = $nextStart - 1;
284 // This is the last chunk. Check all page_ids up to $end.
288 $fmtStart = $start !== null ?
"[$start" : '(-INF';
289 $fmtChunkEnd = $chunkEnd !== null ?
"$chunkEnd]" : 'INF)';
290 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
291 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
295 } while ( $nextStart !== false );
299 * @see RefreshLinks::deleteLinksFromNonexistent()
300 * @param int|null $start Page_id to start from
301 * @param int|null $end Page_id to stop at
302 * @param int $batchSize The size of deletion batches
304 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
305 $dbw = $this->getDB( DB_MASTER
);
306 $dbr = $this->getDB( DB_SLAVE
);
308 $linksTables = array( // table name => page_id field
309 'pagelinks' => 'pl_from',
310 'imagelinks' => 'il_from',
311 'categorylinks' => 'cl_from',
312 'templatelinks' => 'tl_from',
313 'externallinks' => 'el_from',
314 'iwlinks' => 'iwl_from',
315 'langlinks' => 'll_from',
316 'redirect' => 'rd_from',
317 'page_props' => 'pp_page',
320 foreach ( $linksTables as $table => $field ) {
321 $this->output( " $table: 0" );
322 $tableStart = $start;
325 $ids = $dbr->selectFieldValues(
329 self
::intervalCond( $dbr, $field, $tableStart, $end ),
330 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
333 array( 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize )
336 $numIds = count( $ids );
339 $dbw->delete( $table, array( $field => $ids ), __METHOD__
);
340 $this->output( ", $counter" );
341 $tableStart = $ids[$numIds - 1] +
1;
345 } while ( $numIds >= $batchSize && ( $end === null ||
$tableStart <= $end ) );
347 $this->output( " deleted.\n" );
352 * Build a SQL expression for a closed interval (i.e. BETWEEN).
354 * By specifying a null $start or $end, it is also possible to create
355 * half-bounded or unbounded intervals using this function.
357 * @param IDatabase $db Database connection
358 * @param string $var Field name
359 * @param mixed $start First value to include or null
360 * @param mixed $end Last value to include or null
362 private static function intervalCond( IDatabase
$db, $var, $start, $end ) {
363 if ( $start === null && $end === null ) {
364 return "$var IS NOT NULL";
365 } elseif ( $end === null ) {
366 return "$var >= {$db->addQuotes( $start )}";
367 } elseif ( $start === null ) {
368 return "$var <= {$db->addQuotes( $end )}";
370 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
375 $maintClass = 'RefreshLinks';
376 require_once RUN_MAINTENANCE_IF_MAIN
;