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 $reportingInterval = 100;
77 $dbr = $this->getDB( DB_SLAVE
);
79 if ( $start === null ) {
83 // Give extensions a chance to optimize settings
84 Hooks
::run( 'MaintenanceRefreshLinksInit', array( $this ) );
86 $what = $redirectsOnly ?
"redirects" : "links";
88 if ( $oldRedirectsOnly ) {
89 # This entire code path is cut-and-pasted from below. Hurrah.
94 self
::intervalCond( $dbr, 'page_id', $start, $end ),
98 array( 'page', 'redirect' ),
103 array( 'redirect' => array( "LEFT JOIN", "page_id=rd_from" ) )
105 $num = $res->numRows();
106 $this->output( "Refreshing $num old redirects from $start...\n" );
110 foreach ( $res as $row ) {
111 if ( !( ++
$i %
$reportingInterval ) ) {
112 $this->output( "$i\n" );
115 $this->fixRedirect( $row->page_id
);
117 } elseif ( $newOnly ) {
118 $this->output( "Refreshing $what from " );
119 $res = $dbr->select( 'page',
123 self
::intervalCond( $dbr, 'page_id', $start, $end ),
127 $num = $res->numRows();
128 $this->output( "$num new articles...\n" );
131 foreach ( $res as $row ) {
132 if ( !( ++
$i %
$reportingInterval ) ) {
133 $this->output( "$i\n" );
136 if ( $redirectsOnly ) {
137 $this->fixRedirect( $row->page_id
);
139 self
::fixLinksFromArticle( $row->page_id
);
144 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
145 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
146 $end = max( $maxPage, $maxRD );
148 $this->output( "Refreshing redirects table.\n" );
149 $this->output( "Starting from page_id $start of $end.\n" );
151 for ( $id = $start; $id <= $end; $id++
) {
153 if ( !( $id %
$reportingInterval ) ) {
154 $this->output( "$id\n" );
157 $this->fixRedirect( $id );
160 if ( !$redirectsOnly ) {
161 $this->output( "Refreshing links tables.\n" );
162 $this->output( "Starting from page_id $start of $end.\n" );
164 for ( $id = $start; $id <= $end; $id++
) {
166 if ( !( $id %
$reportingInterval ) ) {
167 $this->output( "$id\n" );
170 self
::fixLinksFromArticle( $id );
177 * Update the redirect entry for a given page.
179 * This methods bypasses the "redirect" table to get the redirect target,
180 * and parses the page's content to fetch it. This allows to be sure that
181 * the redirect target is up to date and valid.
182 * This is particularly useful when modifying namespaces to be sure the
183 * entry in the "redirect" table points to the correct page and not to an
186 * @param int $id The page ID to check
188 private function fixRedirect( $id ) {
189 $page = WikiPage
::newFromID( $id );
190 $dbw = $this->getDB( DB_MASTER
);
192 if ( $page === null ) {
193 // This page doesn't exist (any more)
194 // Delete any redirect table entry for it
195 $dbw->delete( 'redirect', array( 'rd_from' => $id ),
202 $content = $page->getContent( Revision
::RAW
);
203 if ( $content !== null ) {
204 $rt = $content->getUltimateRedirectTarget();
207 if ( $rt === null ) {
208 // The page is not a redirect
209 // Delete any redirect table entry for it
210 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__
);
213 $page->insertRedirectEntry( $rt );
217 // Update the page table to be sure it is an a consistent state
218 $dbw->update( 'page', array( 'page_is_redirect' => $fieldValue ),
219 array( 'page_id' => $id ), __METHOD__
);
223 * Run LinksUpdate for all links on a given page_id
224 * @param int $id The page_id
226 public static function fixLinksFromArticle( $id ) {
227 $page = WikiPage
::newFromID( $id );
229 LinkCache
::singleton()->clear();
231 if ( $page === null ) {
235 $content = $page->getContent( Revision
::RAW
);
236 if ( $content === null ) {
240 $updates = $content->getSecondaryDataUpdates( $page->getTitle() );
241 DataUpdate
::runUpdates( $updates );
245 * Removes non-existing links from pages from pagelinks, imagelinks,
246 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
248 * @param int|null $start Page_id to start from
249 * @param int|null $end Page_id to stop at
250 * @param int $batchSize The size of deletion batches
251 * @param int $chunkSize Maximum number of existent IDs to check per query
253 * @author Merlijn van Deen <valhallasw@arctus.nl>
255 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
259 $this->output( "Deleting illegal entries from the links tables...\n" );
260 $dbr = $this->getDB( DB_SLAVE
);
262 // Find the start of the next chunk. This is based only
263 // on existent page_ids.
264 $nextStart = $dbr->selectField(
267 self
::intervalCond( $dbr, 'page_id', $start, $end ),
269 array( 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize )
272 if ( $nextStart !== false ) {
273 // To find the end of the current chunk, subtract one.
274 // This will serve to limit the number of rows scanned in
275 // dfnCheckInterval(), per query, to at most the sum of
276 // the chunk size and deletion batch size.
277 $chunkEnd = $nextStart - 1;
279 // This is the last chunk. Check all page_ids up to $end.
283 $fmtStart = $start !== null ?
"[$start" : '(-INF';
284 $fmtChunkEnd = $chunkEnd !== null ?
"$chunkEnd]" : 'INF)';
285 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
286 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
290 } while ( $nextStart !== false );
294 * @see RefreshLinks::deleteLinksFromNonexistent()
295 * @param int|null $start Page_id to start from
296 * @param int|null $end Page_id to stop at
297 * @param int $batchSize The size of deletion batches
299 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
300 $dbw = $this->getDB( DB_MASTER
);
301 $dbr = $this->getDB( DB_SLAVE
);
303 $linksTables = array( // table name => page_id field
304 'pagelinks' => 'pl_from',
305 'imagelinks' => 'il_from',
306 'categorylinks' => 'cl_from',
307 'templatelinks' => 'tl_from',
308 'externallinks' => 'el_from',
309 'iwlinks' => 'iwl_from',
310 'langlinks' => 'll_from',
311 'redirect' => 'rd_from',
312 'page_props' => 'pp_page',
315 foreach ( $linksTables as $table => $field ) {
316 $this->output( " $table: 0" );
317 $tableStart = $start;
320 $ids = $dbr->selectFieldValues(
324 self
::intervalCond( $dbr, $field, $tableStart, $end ),
325 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
328 array( 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize )
331 $numIds = count( $ids );
334 $dbw->delete( $table, array( $field => $ids ), __METHOD__
);
335 $this->output( ", $counter" );
336 $tableStart = $ids[$numIds - 1] +
1;
340 } while ( $numIds >= $batchSize && ( $end === null ||
$tableStart <= $end ) );
342 $this->output( " deleted.\n" );
347 * Build a SQL expression for a closed interval (i.e. BETWEEN).
349 * By specifying a null $start or $end, it is also possible to create
350 * half-bounded or unbounded intervals using this function.
352 * @param IDatabase $db Database connection
353 * @param string $var Field name
354 * @param mixed $start First value to include or null
355 * @param mixed $end Last value to include or null
357 private static function intervalCond( IDatabase
$db, $var, $start, $end ) {
358 if ( $start === null && $end === null ) {
359 return "$var IS NOT NULL";
360 } elseif ( $end === null ) {
361 return "$var >= {$db->addQuotes( $start )}";
362 } elseif ( $start === null ) {
363 return "$var <= {$db->addQuotes( $end )}";
365 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
370 $maintClass = 'RefreshLinks';
371 require_once RUN_MAINTENANCE_IF_MAIN
;