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