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