Merge "Exclude redirects from Special:Fewestrevisions"
[lhc/web/wiklou.git] / maintenance / refreshLinks.php
1 <?php
2 /**
3 * Refresh link tables.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Storage\RevisionRecord;
26 use Wikimedia\Rdbms\IDatabase;
27
28 require_once __DIR__ . '/Maintenance.php';
29
30 /**
31 * Maintenance script to refresh link tables.
32 *
33 * @ingroup Maintenance
34 */
35 class RefreshLinks extends Maintenance {
36 const REPORTING_INTERVAL = 100;
37
38 /** @var int|bool */
39 protected $namespace = false;
40
41 public function __construct() {
42 parent::__construct();
43 $this->addDescription( 'Refresh link tables' );
44 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
45 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
46 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
47 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
48 $this->addOption( 'e', 'Last page id to refresh', false, true );
49 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
50 'query, default 100000', false, true );
51 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
52 $this->addOption( 'category', 'Only fix pages in this category', false, true );
53 $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
54 $this->addArg( 'start', 'Page_id to start from, default 1', false );
55 $this->setBatchSize( 100 );
56 }
57
58 public function execute() {
59 // Note that there is a difference between not specifying the start
60 // and end IDs and using the minimum and maximum values from the page
61 // table. In the latter case, deleteLinksFromNonexistent() will not
62 // delete entries for nonexistent IDs that fall outside the range.
63 $start = (int)$this->getArg( 0 ) ?: null;
64 $end = (int)$this->getOption( 'e' ) ?: null;
65 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
66 $ns = $this->getOption( 'namespace' );
67 if ( $ns === null ) {
68 $this->namespace = false;
69 } else {
70 $this->namespace = (int)$ns;
71 }
72 if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
73 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
74 if ( !$title ) {
75 $this->fatalError( "'$category' is an invalid category name!\n" );
76 }
77 $this->refreshCategory( $title );
78 } elseif ( ( $category = $this->getOption( 'tracking-category', false ) ) !== false ) {
79 $this->refreshTrackingCategory( $category );
80 } elseif ( !$this->hasOption( 'dfn-only' ) ) {
81 $new = $this->hasOption( 'new-only' );
82 $redir = $this->hasOption( 'redirects-only' );
83 $oldRedir = $this->hasOption( 'old-redirects-only' );
84 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
85 $this->deleteLinksFromNonexistent( null, null, $this->getBatchSize(), $dfnChunkSize );
86 } else {
87 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
88 }
89 }
90
91 private function namespaceCond() {
92 return $this->namespace !== false
93 ? [ 'page_namespace' => $this->namespace ]
94 : [];
95 }
96
97 /**
98 * Do the actual link refreshing.
99 * @param int|null $start Page_id to start from
100 * @param bool $newOnly Only do pages with 1 edit
101 * @param int|null $end Page_id to stop at
102 * @param bool $redirectsOnly Only fix redirects
103 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
104 */
105 private function doRefreshLinks( $start, $newOnly = false,
106 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
107 ) {
108 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
109
110 if ( $start === null ) {
111 $start = 1;
112 }
113
114 // Give extensions a chance to optimize settings
115 Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
116
117 $what = $redirectsOnly ? "redirects" : "links";
118
119 if ( $oldRedirectsOnly ) {
120 # This entire code path is cut-and-pasted from below. Hurrah.
121
122 $conds = [
123 "page_is_redirect=1",
124 "rd_from IS NULL",
125 self::intervalCond( $dbr, 'page_id', $start, $end ),
126 ] + $this->namespaceCond();
127
128 $res = $dbr->select(
129 [ 'page', 'redirect' ],
130 'page_id',
131 $conds,
132 __METHOD__,
133 [],
134 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
135 );
136 $num = $res->numRows();
137 $this->output( "Refreshing $num old redirects from $start...\n" );
138
139 $i = 0;
140
141 foreach ( $res as $row ) {
142 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
143 $this->output( "$i\n" );
144 wfWaitForSlaves();
145 }
146 $this->fixRedirect( $row->page_id );
147 }
148 } elseif ( $newOnly ) {
149 $this->output( "Refreshing $what from " );
150 $res = $dbr->select( 'page',
151 [ 'page_id' ],
152 [
153 'page_is_new' => 1,
154 self::intervalCond( $dbr, 'page_id', $start, $end ),
155 ] + $this->namespaceCond(),
156 __METHOD__
157 );
158 $num = $res->numRows();
159 $this->output( "$num new articles...\n" );
160
161 $i = 0;
162 foreach ( $res as $row ) {
163 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
164 $this->output( "$i\n" );
165 wfWaitForSlaves();
166 }
167 if ( $redirectsOnly ) {
168 $this->fixRedirect( $row->page_id );
169 } else {
170 self::fixLinksFromArticle( $row->page_id, $this->namespace );
171 }
172 }
173 } else {
174 if ( !$end ) {
175 $maxPage = $dbr->selectField( 'page', 'max(page_id)', '', __METHOD__ );
176 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', '', __METHOD__ );
177 $end = max( $maxPage, $maxRD );
178 }
179 $this->output( "Refreshing redirects table.\n" );
180 $this->output( "Starting from page_id $start of $end.\n" );
181
182 for ( $id = $start; $id <= $end; $id++ ) {
183 if ( !( $id % self::REPORTING_INTERVAL ) ) {
184 $this->output( "$id\n" );
185 wfWaitForSlaves();
186 }
187 $this->fixRedirect( $id );
188 }
189
190 if ( !$redirectsOnly ) {
191 $this->output( "Refreshing links tables.\n" );
192 $this->output( "Starting from page_id $start of $end.\n" );
193
194 for ( $id = $start; $id <= $end; $id++ ) {
195 if ( !( $id % self::REPORTING_INTERVAL ) ) {
196 $this->output( "$id\n" );
197 wfWaitForSlaves();
198 }
199 self::fixLinksFromArticle( $id, $this->namespace );
200 }
201 }
202 }
203 }
204
205 /**
206 * Update the redirect entry for a given page.
207 *
208 * This methods bypasses the "redirect" table to get the redirect target,
209 * and parses the page's content to fetch it. This allows to be sure that
210 * the redirect target is up to date and valid.
211 * This is particularly useful when modifying namespaces to be sure the
212 * entry in the "redirect" table points to the correct page and not to an
213 * invalid one.
214 *
215 * @param int $id The page ID to check
216 */
217 private function fixRedirect( $id ) {
218 $page = WikiPage::newFromID( $id );
219 $dbw = $this->getDB( DB_MASTER );
220
221 if ( $page === null ) {
222 // This page doesn't exist (any more)
223 // Delete any redirect table entry for it
224 $dbw->delete( 'redirect', [ 'rd_from' => $id ],
225 __METHOD__ );
226
227 return;
228 } elseif ( $this->namespace !== false
229 && !$page->getTitle()->inNamespace( $this->namespace )
230 ) {
231 return;
232 }
233
234 $rt = null;
235 $content = $page->getContent( RevisionRecord::RAW );
236 if ( $content !== null ) {
237 $rt = $content->getUltimateRedirectTarget();
238 }
239
240 if ( $rt === null ) {
241 // The page is not a redirect
242 // Delete any redirect table entry for it
243 $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
244 $fieldValue = 0;
245 } else {
246 $page->insertRedirectEntry( $rt );
247 $fieldValue = 1;
248 }
249
250 // Update the page table to be sure it is an a consistent state
251 $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
252 [ 'page_id' => $id ], __METHOD__ );
253 }
254
255 /**
256 * Run LinksUpdate for all links on a given page_id
257 * @param int $id The page_id
258 * @param int|bool $ns Only fix links if it is in this namespace
259 */
260 public static function fixLinksFromArticle( $id, $ns = false ) {
261 $page = WikiPage::newFromID( $id );
262
263 MediaWikiServices::getInstance()->getLinkCache()->clear();
264
265 if ( $page === null ) {
266 return;
267 } elseif ( $ns !== false
268 && !$page->getTitle()->inNamespace( $ns ) ) {
269 return;
270 }
271
272 // Defer updates to post-send but then immediately execute deferred updates;
273 // this is the simplest way to run all updates immediately (including updates
274 // scheduled by other updates).
275 $page->doSecondaryDataUpdates( [
276 'defer' => DeferredUpdates::POSTSEND,
277 'recursive' => false,
278 ] );
279 DeferredUpdates::doUpdates();
280 }
281
282 /**
283 * Removes non-existing links from pages from pagelinks, imagelinks,
284 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
285 *
286 * @param int|null $start Page_id to start from
287 * @param int|null $end Page_id to stop at
288 * @param int $batchSize The size of deletion batches
289 * @param int $chunkSize Maximum number of existent IDs to check per query
290 *
291 * @author Merlijn van Deen <valhallasw@arctus.nl>
292 */
293 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
294 $chunkSize = 100000
295 ) {
296 wfWaitForSlaves();
297 $this->output( "Deleting illegal entries from the links tables...\n" );
298 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
299 do {
300 // Find the start of the next chunk. This is based only
301 // on existent page_ids.
302 $nextStart = $dbr->selectField(
303 'page',
304 'page_id',
305 [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
306 + $this->namespaceCond(),
307 __METHOD__,
308 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
309 );
310
311 if ( $nextStart !== false ) {
312 // To find the end of the current chunk, subtract one.
313 // This will serve to limit the number of rows scanned in
314 // dfnCheckInterval(), per query, to at most the sum of
315 // the chunk size and deletion batch size.
316 $chunkEnd = $nextStart - 1;
317 } else {
318 // This is the last chunk. Check all page_ids up to $end.
319 $chunkEnd = $end;
320 }
321
322 $fmtStart = $start !== null ? "[$start" : '(-INF';
323 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
324 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
325 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
326
327 $start = $nextStart;
328
329 } while ( $nextStart !== false );
330 }
331
332 /**
333 * @see RefreshLinks::deleteLinksFromNonexistent()
334 * @param int|null $start Page_id to start from
335 * @param int|null $end Page_id to stop at
336 * @param int $batchSize The size of deletion batches
337 */
338 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
339 $dbw = $this->getDB( DB_MASTER );
340 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
341
342 $linksTables = [ // table name => page_id field
343 'pagelinks' => 'pl_from',
344 'imagelinks' => 'il_from',
345 'categorylinks' => 'cl_from',
346 'templatelinks' => 'tl_from',
347 'externallinks' => 'el_from',
348 'iwlinks' => 'iwl_from',
349 'langlinks' => 'll_from',
350 'redirect' => 'rd_from',
351 'page_props' => 'pp_page',
352 ];
353
354 foreach ( $linksTables as $table => $field ) {
355 $this->output( " $table: 0" );
356 $tableStart = $start;
357 $counter = 0;
358 do {
359 $ids = $dbr->selectFieldValues(
360 $table,
361 $field,
362 [
363 self::intervalCond( $dbr, $field, $tableStart, $end ),
364 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
365 ],
366 __METHOD__,
367 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
368 );
369
370 $numIds = count( $ids );
371 if ( $numIds ) {
372 $counter += $numIds;
373 $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
374 $this->output( ", $counter" );
375 $tableStart = $ids[$numIds - 1] + 1;
376 wfWaitForSlaves();
377 }
378
379 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
380
381 $this->output( " deleted.\n" );
382 }
383 }
384
385 /**
386 * Build a SQL expression for a closed interval (i.e. BETWEEN).
387 *
388 * By specifying a null $start or $end, it is also possible to create
389 * half-bounded or unbounded intervals using this function.
390 *
391 * @param IDatabase $db
392 * @param string $var Field name
393 * @param mixed $start First value to include or null
394 * @param mixed $end Last value to include or null
395 * @return string
396 */
397 private static function intervalCond( IDatabase $db, $var, $start, $end ) {
398 if ( $start === null && $end === null ) {
399 return "$var IS NOT NULL";
400 } elseif ( $end === null ) {
401 return "$var >= {$db->addQuotes( $start )}";
402 } elseif ( $start === null ) {
403 return "$var <= {$db->addQuotes( $end )}";
404 } else {
405 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
406 }
407 }
408
409 /**
410 * Refershes links for pages in a tracking category
411 *
412 * @param string $category Category key
413 */
414 private function refreshTrackingCategory( $category ) {
415 $cats = $this->getPossibleCategories( $category );
416
417 if ( !$cats ) {
418 $this->error( "Tracking category '$category' is disabled\n" );
419 // Output to stderr but don't bail out,
420 }
421
422 foreach ( $cats as $cat ) {
423 $this->refreshCategory( $cat );
424 }
425 }
426
427 /**
428 * Refreshes links to a category
429 *
430 * @param Title $category
431 */
432 private function refreshCategory( Title $category ) {
433 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
434
435 $dbr = $this->getDB( DB_REPLICA );
436 $conds = [
437 'page_id=cl_from',
438 'cl_to' => $category->getDBkey(),
439 ];
440 if ( $this->namespace !== false ) {
441 $conds['page_namespace'] = $this->namespace;
442 }
443
444 $i = 0;
445 $timestamp = '';
446 $lastId = 0;
447 do {
448 $finalConds = $conds;
449 $timestamp = $dbr->addQuotes( $timestamp );
450 $finalConds [] =
451 "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
452 $res = $dbr->select( [ 'page', 'categorylinks' ],
453 [ 'page_id', 'cl_timestamp' ],
454 $finalConds,
455 __METHOD__,
456 [
457 'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
458 'LIMIT' => $this->getBatchSize(),
459 ]
460 );
461
462 foreach ( $res as $row ) {
463 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
464 $this->output( "$i\n" );
465 wfWaitForSlaves();
466 }
467 $lastId = $row->page_id;
468 $timestamp = $row->cl_timestamp;
469 self::fixLinksFromArticle( $row->page_id );
470 }
471
472 } while ( $res->numRows() == $this->getBatchSize() );
473 }
474
475 /**
476 * Returns a list of possible categories for a given tracking category key
477 *
478 * @param string $categoryKey
479 * @return Title[]
480 */
481 private function getPossibleCategories( $categoryKey ) {
482 $trackingCategories = new TrackingCategories( $this->getConfig() );
483 $cats = $trackingCategories->getTrackingCategories();
484 if ( isset( $cats[$categoryKey] ) ) {
485 return $cats[$categoryKey]['cats'];
486 }
487 $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
488 }
489 }
490
491 $maintClass = RefreshLinks::class;
492 require_once RUN_MAINTENANCE_IF_MAIN;