Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / maintenance / refreshLinks.php
blobe7a4d06902c6cd831ee6650cfb8440f576a9d254
1 <?php
2 /**
3 * Refresh link tables.
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
20 * @file
21 * @ingroup Maintenance
24 require_once __DIR__ . '/Maintenance.php';
26 /**
27 * Maintenance script to refresh link tables.
29 * @ingroup Maintenance
31 class RefreshLinks extends Maintenance {
32 /** @var int|bool */
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' );
59 if ( $ns === null ) {
60 $this->namespace = false;
61 } else {
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 );
70 } else {
71 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize, $dfnChunkSize );
75 private function namespaceCond() {
76 return $this->namespace !== false
77 ? [ 'page_namespace' => $this->namespace ]
78 : [];
81 /**
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
91 ) {
92 $reportingInterval = 100;
93 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
95 if ( $start === null ) {
96 $start = 1;
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.
107 $conds = [
108 "page_is_redirect=1",
109 "rd_from IS NULL",
110 self::intervalCond( $dbr, 'page_id', $start, $end ),
111 ] + $this->namespaceCond();
113 $res = $dbr->select(
114 [ 'page', 'redirect' ],
115 'page_id',
116 $conds,
117 __METHOD__,
119 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
121 $num = $res->numRows();
122 $this->output( "Refreshing $num old redirects from $start...\n" );
124 $i = 0;
126 foreach ( $res as $row ) {
127 if ( !( ++$i % $reportingInterval ) ) {
128 $this->output( "$i\n" );
129 wfWaitForSlaves();
131 $this->fixRedirect( $row->page_id );
133 } elseif ( $newOnly ) {
134 $this->output( "Refreshing $what from " );
135 $res = $dbr->select( 'page',
136 [ 'page_id' ],
138 'page_is_new' => 1,
139 self::intervalCond( $dbr, 'page_id', $start, $end ),
140 ] + $this->namespaceCond(),
141 __METHOD__
143 $num = $res->numRows();
144 $this->output( "$num new articles...\n" );
146 $i = 0;
147 foreach ( $res as $row ) {
148 if ( !( ++$i % $reportingInterval ) ) {
149 $this->output( "$i\n" );
150 wfWaitForSlaves();
152 if ( $redirectsOnly ) {
153 $this->fixRedirect( $row->page_id );
154 } else {
155 self::fixLinksFromArticle( $row->page_id, $this->namespace );
158 } else {
159 if ( !$end ) {
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" );
171 wfWaitForSlaves();
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" );
184 wfWaitForSlaves();
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
200 * invalid one.
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 ],
212 __METHOD__ );
214 return;
215 } elseif ( $this->namespace !== false
216 && !$page->getTitle()->inNamespace( $this->namespace )
218 return;
221 $rt = null;
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__ );
231 $fieldValue = 0;
232 } else {
233 $page->insertRedirectEntry( $rt );
234 $fieldValue = 1;
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 ) {
253 return;
254 } elseif ( $ns !== false
255 && !$page->getTitle()->inNamespace( $ns ) ) {
256 return;
259 $content = $page->getContent( Revision::RAW );
260 if ( $content === null ) {
261 return;
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,
281 $chunkSize = 100000
283 wfWaitForSlaves();
284 $this->output( "Deleting illegal entries from the links tables...\n" );
285 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
286 do {
287 // Find the start of the next chunk. This is based only
288 // on existent page_ids.
289 $nextStart = $dbr->selectField(
290 'page',
291 'page_id',
292 [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
293 + $this->namespaceCond(),
294 __METHOD__,
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;
304 } else {
305 // This is the last chunk. Check all page_ids up to $end.
306 $chunkEnd = $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 );
314 $start = $nextStart;
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;
344 $counter = 0;
345 do {
346 $ids = $dbr->selectFieldValues(
347 $table,
348 $field,
350 self::intervalCond( $dbr, $field, $tableStart, $end ),
351 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
353 __METHOD__,
354 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
357 $numIds = count( $ids );
358 if ( $numIds ) {
359 $counter += $numIds;
360 $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
361 $this->output( ", $counter" );
362 $tableStart = $ids[$numIds - 1] + 1;
363 wfWaitForSlaves();
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 )}";
390 } else {
391 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
396 $maintClass = 'RefreshLinks';
397 require_once RUN_MAINTENANCE_IF_MAIN;