Merge "Handle missing namespace prefix in XML dumps more gracefully"
[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 require_once __DIR__ . '/Maintenance.php';
25
26 /**
27 * Maintenance script to refresh link tables.
28 *
29 * @ingroup Maintenance
30 */
31 class RefreshLinks extends Maintenance {
32 const REPORTING_INTERVAL = 100;
33
34 /** @var int|bool */
35 protected $namespace = false;
36
37 public function __construct() {
38 parent::__construct();
39 $this->addDescription( 'Refresh link tables' );
40 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
41 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
42 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
43 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
44 $this->addOption( 'e', 'Last page id to refresh', false, true );
45 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
46 'query, default 100000', false, true );
47 $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
48 $this->addOption( 'category', 'Only fix pages in this category', false, true );
49 $this->addOption( 'tracking-category', 'Only fix pages in this tracking category', false, true );
50 $this->addArg( 'start', 'Page_id to start from, default 1', false );
51 $this->setBatchSize( 100 );
52 }
53
54 public function execute() {
55 // Note that there is a difference between not specifying the start
56 // and end IDs and using the minimum and maximum values from the page
57 // table. In the latter case, deleteLinksFromNonexistent() will not
58 // delete entries for nonexistent IDs that fall outside the range.
59 $start = (int)$this->getArg( 0 ) ?: null;
60 $end = (int)$this->getOption( 'e' ) ?: null;
61 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
62 $ns = $this->getOption( 'namespace' );
63 if ( $ns === null ) {
64 $this->namespace = false;
65 } else {
66 $this->namespace = (int)$ns;
67 }
68 if ( ( $category = $this->getOption( 'category', false ) ) !== false ) {
69 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
70 if ( !$title ) {
71 $this->error( "'$category' is an invalid category name!\n", true );
72 }
73 $this->refreshCategory( $category );
74 } elseif ( ( $category = $this->getOption( 'tracking-category', false ) ) !== false ) {
75 $this->refreshTrackingCategory( $category );
76 } elseif ( !$this->hasOption( 'dfn-only' ) ) {
77 $new = $this->getOption( 'new-only', false );
78 $redir = $this->getOption( 'redirects-only', false );
79 $oldRedir = $this->getOption( 'old-redirects-only', false );
80 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
81 $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize, $dfnChunkSize );
82 } else {
83 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize, $dfnChunkSize );
84 }
85 }
86
87 private function namespaceCond() {
88 return $this->namespace !== false
89 ? [ 'page_namespace' => $this->namespace ]
90 : [];
91 }
92
93 /**
94 * Do the actual link refreshing.
95 * @param int|null $start Page_id to start from
96 * @param bool $newOnly Only do pages with 1 edit
97 * @param int|null $end Page_id to stop at
98 * @param bool $redirectsOnly Only fix redirects
99 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
100 */
101 private function doRefreshLinks( $start, $newOnly = false,
102 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
103 ) {
104 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
105
106 if ( $start === null ) {
107 $start = 1;
108 }
109
110 // Give extensions a chance to optimize settings
111 Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
112
113 $what = $redirectsOnly ? "redirects" : "links";
114
115 if ( $oldRedirectsOnly ) {
116 # This entire code path is cut-and-pasted from below. Hurrah.
117
118 $conds = [
119 "page_is_redirect=1",
120 "rd_from IS NULL",
121 self::intervalCond( $dbr, 'page_id', $start, $end ),
122 ] + $this->namespaceCond();
123
124 $res = $dbr->select(
125 [ 'page', 'redirect' ],
126 'page_id',
127 $conds,
128 __METHOD__,
129 [],
130 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
131 );
132 $num = $res->numRows();
133 $this->output( "Refreshing $num old redirects from $start...\n" );
134
135 $i = 0;
136
137 foreach ( $res as $row ) {
138 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
139 $this->output( "$i\n" );
140 wfWaitForSlaves();
141 }
142 $this->fixRedirect( $row->page_id );
143 }
144 } elseif ( $newOnly ) {
145 $this->output( "Refreshing $what from " );
146 $res = $dbr->select( 'page',
147 [ 'page_id' ],
148 [
149 'page_is_new' => 1,
150 self::intervalCond( $dbr, 'page_id', $start, $end ),
151 ] + $this->namespaceCond(),
152 __METHOD__
153 );
154 $num = $res->numRows();
155 $this->output( "$num new articles...\n" );
156
157 $i = 0;
158 foreach ( $res as $row ) {
159 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
160 $this->output( "$i\n" );
161 wfWaitForSlaves();
162 }
163 if ( $redirectsOnly ) {
164 $this->fixRedirect( $row->page_id );
165 } else {
166 self::fixLinksFromArticle( $row->page_id, $this->namespace );
167 }
168 }
169 } else {
170 if ( !$end ) {
171 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
172 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
173 $end = max( $maxPage, $maxRD );
174 }
175 $this->output( "Refreshing redirects table.\n" );
176 $this->output( "Starting from page_id $start of $end.\n" );
177
178 for ( $id = $start; $id <= $end; $id++ ) {
179
180 if ( !( $id % self::REPORTING_INTERVAL ) ) {
181 $this->output( "$id\n" );
182 wfWaitForSlaves();
183 }
184 $this->fixRedirect( $id );
185 }
186
187 if ( !$redirectsOnly ) {
188 $this->output( "Refreshing links tables.\n" );
189 $this->output( "Starting from page_id $start of $end.\n" );
190
191 for ( $id = $start; $id <= $end; $id++ ) {
192
193 if ( !( $id % self::REPORTING_INTERVAL ) ) {
194 $this->output( "$id\n" );
195 wfWaitForSlaves();
196 }
197 self::fixLinksFromArticle( $id, $this->namespace );
198 }
199 }
200 }
201 }
202
203 /**
204 * Update the redirect entry for a given page.
205 *
206 * This methods bypasses the "redirect" table to get the redirect target,
207 * and parses the page's content to fetch it. This allows to be sure that
208 * the redirect target is up to date and valid.
209 * This is particularly useful when modifying namespaces to be sure the
210 * entry in the "redirect" table points to the correct page and not to an
211 * invalid one.
212 *
213 * @param int $id The page ID to check
214 */
215 private function fixRedirect( $id ) {
216 $page = WikiPage::newFromID( $id );
217 $dbw = $this->getDB( DB_MASTER );
218
219 if ( $page === null ) {
220 // This page doesn't exist (any more)
221 // Delete any redirect table entry for it
222 $dbw->delete( 'redirect', [ 'rd_from' => $id ],
223 __METHOD__ );
224
225 return;
226 } elseif ( $this->namespace !== false
227 && !$page->getTitle()->inNamespace( $this->namespace )
228 ) {
229 return;
230 }
231
232 $rt = null;
233 $content = $page->getContent( Revision::RAW );
234 if ( $content !== null ) {
235 $rt = $content->getUltimateRedirectTarget();
236 }
237
238 if ( $rt === null ) {
239 // The page is not a redirect
240 // Delete any redirect table entry for it
241 $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
242 $fieldValue = 0;
243 } else {
244 $page->insertRedirectEntry( $rt );
245 $fieldValue = 1;
246 }
247
248 // Update the page table to be sure it is an a consistent state
249 $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
250 [ 'page_id' => $id ], __METHOD__ );
251 }
252
253 /**
254 * Run LinksUpdate for all links on a given page_id
255 * @param int $id The page_id
256 * @param int|bool $ns Only fix links if it is in this namespace
257 */
258 public static function fixLinksFromArticle( $id, $ns = false ) {
259 $page = WikiPage::newFromID( $id );
260
261 LinkCache::singleton()->clear();
262
263 if ( $page === null ) {
264 return;
265 } elseif ( $ns !== false
266 && !$page->getTitle()->inNamespace( $ns ) ) {
267 return;
268 }
269
270 $content = $page->getContent( Revision::RAW );
271 if ( $content === null ) {
272 return;
273 }
274
275 $updates = $content->getSecondaryDataUpdates(
276 $page->getTitle(), /* $old = */ null, /* $recursive = */ false );
277 foreach ( $updates as $update ) {
278 DeferredUpdates::addUpdate( $update );
279 }
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 Database connection
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->mBatchSize,
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->mBatchSize );
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->error( "Unknown tracking category {$categoryKey}\n", true );
488 }
489 }
490
491 $maintClass = 'RefreshLinks';
492 require_once RUN_MAINTENANCE_IF_MAIN;