Debian Codegraph @

maintenance/refreshLinks.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Deferred\DeferredUpdates;
22 use MediaWiki\Linker\LinkTarget;
23 use MediaWiki\Maintenance\Maintenance;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Revision\RevisionRecord;
26 use MediaWiki\Title\Title;
27 use Wikimedia\Rdbms\IExpression;
28 use Wikimedia\Rdbms\IReadableDatabase;
29 use Wikimedia\Rdbms\RawSQLExpression;
30 use Wikimedia\Rdbms\SelectQueryBuilder;
31
32 // @codeCoverageIgnoreStart
33 require_once __DIR__ . '/Maintenance.php';
34 // @codeCoverageIgnoreEnd
35
36 /**
37 * Refresh link tables.
38 *
39 * @ingroup Maintenance
40 */
41 class RefreshLinks extends Maintenance {
42 private const REPORTING_INTERVAL = 100;
43
44 public function __construct() {
45 parent::__construct();
46 $this->addDescription( 'Refresh link tables' );
47 $this->addOption( 'verbose', 'Output information about link refresh progress', false, false, 'v' );
48 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
49 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
50 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
51 $this->addOption( 'touched-only', 'Only fix pages that have been touched after last update' );
52 $this->addOption( 'e', 'Last page id to refresh', false, true );
53 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
54 'query, default 100,000', false, true );
55 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
56 $this->addOption( 'category', 'Only fix pages in this category', false, true );
57 $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
58 $this->addOption( 'before-timestamp', 'Only fix pages that were last updated before this timestamp',
59 false, true );
60 $this->addArg( 'start', 'Page_id to start from, default 1', false );
61 $this->setBatchSize( 100 );
62 }
63
64 public function execute() {
65 // Note that there is a difference between not specifying the start
66 // and end IDs and using the minimum and maximum values from the page
67 // table. In the latter case, deleteLinksFromNonexistent() will not
68 // delete entries for nonexistent IDs that fall outside the range.
69 $start = (int)$this->getArg( 0 ) ?: null;
70 $end = (int)$this->getOption( 'e' ) ?: null;
71 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100_000 );
72
73 if ( $this->hasOption( 'dfn-only' ) ) {
74 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
75 return;
76 }
77
78 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
79 $builder = $dbr->newSelectQueryBuilder()
80 ->from( 'page' )
81 ->where( self::intervalCond( $dbr, 'page_id', $start, $end ) )
82 ->limit( $this->getBatchSize() );
83
84 if ( $this->hasOption( 'namespace' ) ) {
85 $builder->andWhere( [ 'page_namespace' => (int)$this->getOption( 'namespace' ) ] );
86 }
87
88 if ( $this->hasOption( 'before-timestamp' ) ) {
89 $builder->andWhere(
90 $dbr->expr( 'page_links_updated', '<', $this->getOption( 'before-timestamp' ) )
91 ->or( 'page_links_updated', '=', null )
92 );
93 }
94
95 if ( $this->hasOption( 'category' ) ) {
96 $category = $this->getOption( 'category' );
97 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
98 if ( !$title ) {
99 $this->fatalError( "'$category' is an invalid category name!\n" );
100 }
101 $this->refreshCategory( $builder, $title );
102 } elseif ( $this->hasOption( 'tracking-category' ) ) {
103 // See TrackingCategories::CORE_TRACKING_CATEGORIES for tracking category keys defined by core
104 $this->refreshTrackingCategory( $builder, $this->getOption( 'tracking-category' ) );
105 } else {
106 $new = $this->hasOption( 'new-only' );
107 $redir = $this->hasOption( 'redirects-only' );
108 $touched = $this->hasOption( 'touched-only' );
109 $what = $redir ? 'redirects' : 'links';
110 if ( $new ) {
111 $builder->andWhere( [ 'page_is_new' => 1 ] );
112 $this->output( "Refreshing $what from new pages...\n" );
113 } else {
114 if ( $touched ) {
115 $builder->andWhere( [
116 $dbr->expr( 'page_links_updated', '=', null )
117 ->orExpr( new RawSQLExpression( 'page_touched > page_links_updated' ) ),
118 ] );
119 }
120 $this->output( "Refreshing $what from pages...\n" );
121 }
122 $this->doRefreshLinks( $builder, $redir );
123 if ( !$this->hasOption( 'namespace' ) ) {
124 $this->deleteLinksFromNonexistent( $start, $end, $this->getBatchSize(), $dfnChunkSize );
125 }
126 }
127 }
128
129 /**
130 * Do the actual link refreshing.
131 * @param SelectQueryBuilder $builder
132 * @param bool $redirectsOnly Only fix redirects
133 * @param array $indexFields
134 */
135 private function doRefreshLinks(
136 SelectQueryBuilder $builder,
137 bool $redirectsOnly = false,
138 array $indexFields = [ 'page_id' ]
139 ) {
140 // Give extensions a chance to optimize settings
141 $this->getHookRunner()->onMaintenanceRefreshLinksInit( $this );
142
143 $estimateCount = $builder->caller( __METHOD__ )->estimateRowCount();
144 $this->output( "Estimated page count: $estimateCount\n" );
145
146 $i = 0;
147 $lastIndexes = array_fill_keys( $indexFields, 0 );
148 $selectFields = in_array( 'page_id', $indexFields )
149 ? $indexFields : [ 'page_id', ...$indexFields ];
150 $verbose = $this->hasOption( 'verbose' );
151 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
152 do {
153 $batchCond = $dbr->buildComparison( '>', $lastIndexes );
154 $res = ( clone $builder )->select( $selectFields )
155 ->andWhere( [ $batchCond ] )
156 ->orderBy( $indexFields )
157 ->caller( __METHOD__ )->fetchResultSet();
158
159 if ( $verbose ) {
160 $this->output( "Refreshing links for {$res->numRows()} pages\n" );
161 }
162
163 foreach ( $res as $row ) {
164 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
165 $this->output( "$i\n" );
166 $this->waitForReplication();
167 }
168 if ( $verbose ) {
169 $this->output( "Refreshing links for page ID {$row->page_id}\n" );
170 }
171 self::fixRedirect( $this, $row->page_id );
172 if ( !$redirectsOnly ) {
173 self::fixLinksFromArticle( $row->page_id );
174 }
175 }
176 if ( $res->numRows() ) {
177 $res->seek( $res->numRows() - 1 );
178 foreach ( $indexFields as $field ) {
179 $lastIndexes[$field] = $res->current()->$field;
180 }
181 }
182
183 } while ( $res->numRows() == $this->getBatchSize() );
184 }
185
186 /**
187 * Update the redirect entry for a given page.
188 *
189 * This methods bypasses the "redirect" table to get the redirect target,
190 * and parses the page's content to fetch it. This allows to be sure that
191 * the redirect target is up to date and valid.
192 * This is particularly useful when modifying namespaces to be sure the
193 * entry in the "redirect" table points to the correct page and not to an
194 * invalid one.
195 *
196 * @internal
197 * @param Maintenance $maint
198 * @param int $id The page ID to check
199 */
200 public static function fixRedirect( Maintenance $maint, $id ) {
201 $page = $maint->getServiceContainer()->getWikiPageFactory()->newFromID( $id );
202
203 // In case the page just got deleted.
204 if ( $page === null ) {
205 return;
206 }
207
208 $rt = null;
209 $content = $page->getContent( RevisionRecord::RAW );
210 if ( $content !== null ) {
211 $rt = $content->getRedirectTarget();
212 }
213
214 $dbw = $maint->getDB( DB_PRIMARY );
215 if ( $rt === null ) {
216 // The page is not a redirect
217 // Delete any redirect table entry for it
218 $dbw->newDeleteQueryBuilder()
219 ->deleteFrom( 'redirect' )
220 ->where( [ 'rd_from' => $id ] )
221 ->caller( __METHOD__ )->execute();
222 $fieldValue = 0;
223 } else {
224 $page->insertRedirectEntry( $rt );
225 $fieldValue = 1;
226 }
227
228 // Update the page table to be sure it is an a consistent state
229 $dbw->newUpdateQueryBuilder()
230 ->update( 'page' )
231 ->set( [ 'page_is_redirect' => $fieldValue ] )
232 ->where( [ 'page_id' => $id ] )
233 ->caller( __METHOD__ )
234 ->execute();
235 }
236
237 /**
238 * Run LinksUpdate for all links on a given page_id
239 * @param int $id The page_id
240 */
241 public static function fixLinksFromArticle( $id ) {
242 $services = MediaWikiServices::getInstance();
243 $page = $services->getWikiPageFactory()->newFromID( $id );
244
245 // In case the page just got deleted.
246 if ( $page === null ) {
247 return;
248 }
249
250 // Defer updates to post-send but then immediately execute deferred updates;
251 // this is the simplest way to run all updates immediately (including updates
252 // scheduled by other updates).
253 $page->doSecondaryDataUpdates( [
254 'defer' => DeferredUpdates::POSTSEND,
255 'causeAction' => 'refresh-links-maintenance',
256 'recursive' => false,
257 ] );
258 DeferredUpdates::doUpdates();
259 }
260
261 /**
262 * Removes non-existing links from pages from pagelinks, imagelinks,
263 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
264 *
265 * @param int|null $start Page_id to start from
266 * @param int|null $end Page_id to stop at
267 * @param int $batchSize The size of deletion batches
268 * @param int $chunkSize Maximum number of existent IDs to check per query
269 *
270 * @author Merlijn van Deen <[email protected]>
271 */
272 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
273 $chunkSize = 100_000
274 ) {
275 $this->waitForReplication();
276 $this->output( "Deleting illegal entries from the links tables...\n" );
277 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
278 do {
279 // Find the start of the next chunk. This is based only
280 // on existent page_ids.
281 $nextStart = $dbr->newSelectQueryBuilder()
282 ->select( 'page_id' )
283 ->from( 'page' )
284 ->where( [ self::intervalCond( $dbr, 'page_id', $start, $end ) ] )
285 ->orderBy( 'page_id' )
286 ->offset( $chunkSize )
287 ->caller( __METHOD__ )->fetchField();
288
289 if ( $nextStart !== false ) {
290 // To find the end of the current chunk, subtract one.
291 // This will serve to limit the number of rows scanned in
292 // dfnCheckInterval(), per query, to at most the sum of
293 // the chunk size and deletion batch size.
294 $chunkEnd = $nextStart - 1;
295 } else {
296 // This is the last chunk. Check all page_ids up to $end.
297 $chunkEnd = $end;
298 }
299
300 $fmtStart = $start !== null ? "[$start" : '(-INF';
301 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
302 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
303 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
304
305 $start = $nextStart;
306
307 } while ( $nextStart !== false );
308 }
309
310 /**
311 * @see RefreshLinks::deleteLinksFromNonexistent()
312 * @param int|null $start Page_id to start from
313 * @param int|null $end Page_id to stop at
314 * @param int $batchSize The size of deletion batches
315 */
316 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
317 $dbw = $this->getPrimaryDB();
318 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
319
320 $linksTables = [
321 // table name => page_id field
322 'pagelinks' => 'pl_from',
323 'imagelinks' => 'il_from',
324 'categorylinks' => 'cl_from',
325 'templatelinks' => 'tl_from',
326 'externallinks' => 'el_from',
327 'iwlinks' => 'iwl_from',
328 'langlinks' => 'll_from',
329 'redirect' => 'rd_from',
330 'page_props' => 'pp_page',
331 ];
332
333 foreach ( $linksTables as $table => $field ) {
334 $this->output( " $table: 0" );
335 $tableStart = $start;
336 $counter = 0;
337 do {
338 $ids = $dbr->newSelectQueryBuilder()
339 ->select( $field )
340 ->distinct()
341 ->from( $table )
342 ->leftJoin( 'page', null, "$field = page_id" )
343 ->where( self::intervalCond( $dbr, $field, $tableStart, $end ) )
344 ->andWhere( [ 'page_id' => null ] )
345 ->orderBy( $field )
346 ->limit( $batchSize )
347 ->caller( __METHOD__ )->fetchFieldValues();
348
349 $numIds = count( $ids );
350 if ( $numIds ) {
351 $counter += $numIds;
352 $dbw->newDeleteQueryBuilder()
353 ->deleteFrom( $table )
354 ->where( [ $field => $ids ] )
355 ->caller( __METHOD__ )->execute();
356 $this->output( ", $counter" );
357 $tableStart = $ids[$numIds - 1] + 1;
358 $this->waitForReplication();
359 }
360
361 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
362
363 $this->output( " deleted.\n" );
364 }
365 }
366
367 /**
368 * Build a SQL expression for a closed interval.
369 *
370 * By specifying a null $start or $end, it is also possible to create
371 * half-bounded or unbounded intervals using this function.
372 *
373 * @param IReadableDatabase $db
374 * @param string $var Field name
375 * @param mixed $start First value to include or null
376 * @param mixed $end Last value to include or null
377 * @return IExpression
378 */
379 private static function intervalCond( IReadableDatabase $db, $var, $start, $end ) {
380 if ( $start === null && $end === null ) {
381 return $db->expr( $var, '!=', null );
382 } elseif ( $end === null ) {
383 return $db->expr( $var, '>=', $start );
384 } elseif ( $start === null ) {
385 return $db->expr( $var, '<=', $end );
386 } else {
387 return $db->expr( $var, '>=', $start )->and( $var, '<=', $end );
388 }
389 }
390
391 /**
392 * Refershes links for pages in a tracking category
393 *
394 * @param SelectQueryBuilder $builder
395 * @param string $category Category key
396 */
397 private function refreshTrackingCategory( SelectQueryBuilder $builder, $category ) {
398 $cats = $this->getPossibleCategories( $category );
399
400 if ( !$cats ) {
401 $this->error( "Tracking category '$category' is disabled\n" );
402 // Output to stderr but don't bail out.
403 }
404
405 foreach ( $cats as $cat ) {
406 $this->refreshCategory( clone $builder, $cat );
407 }
408 }
409
410 /**
411 * Refreshes links to a category
412 *
413 * @param SelectQueryBuilder $builder
414 * @param LinkTarget $category
415 */
416 private function refreshCategory( SelectQueryBuilder $builder, LinkTarget $category ) {
417 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
418
419 $builder->join( 'categorylinks', null, 'page_id=cl_from' )
420 ->andWhere( [ 'cl_to' => $category->getDBkey() ] );
421 $this->doRefreshLinks( $builder, false, [ 'cl_timestamp', 'cl_from' ] );
422 }
423
424 /**
425 * Returns a list of possible categories for a given tracking category key
426 *
427 * @param string $categoryKey
428 * @return LinkTarget[]
429 */
430 private function getPossibleCategories( $categoryKey ) {
431 $cats = $this->getServiceContainer()->getTrackingCategories()->getTrackingCategories();
432 if ( isset( $cats[$categoryKey] ) ) {
433 return $cats[$categoryKey]['cats'];
434 }
435 $this->fatalError( "Unknown tracking category {$categoryKey}\n" );
436 }
437 }
438
439 // @codeCoverageIgnoreStart
440 $maintClass = RefreshLinks::class;
441 require_once RUN_MAINTENANCE_IF_MAIN;
442 // @codeCoverageIgnoreEnd