resourceloader: Add purgeModuleDeps.php maintenance script
[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 foreach ( $content->getSecondaryDataUpdates( $page->getTitle() ) as $update ) {
276 DeferredUpdates::addUpdate( $update );
277 }
278 }
279
280 /**
281 * Removes non-existing links from pages from pagelinks, imagelinks,
282 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
283 *
284 * @param int|null $start Page_id to start from
285 * @param int|null $end Page_id to stop at
286 * @param int $batchSize The size of deletion batches
287 * @param int $chunkSize Maximum number of existent IDs to check per query
288 *
289 * @author Merlijn van Deen <valhallasw@arctus.nl>
290 */
291 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
292 $chunkSize = 100000
293 ) {
294 wfWaitForSlaves();
295 $this->output( "Deleting illegal entries from the links tables...\n" );
296 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
297 do {
298 // Find the start of the next chunk. This is based only
299 // on existent page_ids.
300 $nextStart = $dbr->selectField(
301 'page',
302 'page_id',
303 [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
304 + $this->namespaceCond(),
305 __METHOD__,
306 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
307 );
308
309 if ( $nextStart !== false ) {
310 // To find the end of the current chunk, subtract one.
311 // This will serve to limit the number of rows scanned in
312 // dfnCheckInterval(), per query, to at most the sum of
313 // the chunk size and deletion batch size.
314 $chunkEnd = $nextStart - 1;
315 } else {
316 // This is the last chunk. Check all page_ids up to $end.
317 $chunkEnd = $end;
318 }
319
320 $fmtStart = $start !== null ? "[$start" : '(-INF';
321 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
322 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
323 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
324
325 $start = $nextStart;
326
327 } while ( $nextStart !== false );
328 }
329
330 /**
331 * @see RefreshLinks::deleteLinksFromNonexistent()
332 * @param int|null $start Page_id to start from
333 * @param int|null $end Page_id to stop at
334 * @param int $batchSize The size of deletion batches
335 */
336 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
337 $dbw = $this->getDB( DB_MASTER );
338 $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
339
340 $linksTables = [ // table name => page_id field
341 'pagelinks' => 'pl_from',
342 'imagelinks' => 'il_from',
343 'categorylinks' => 'cl_from',
344 'templatelinks' => 'tl_from',
345 'externallinks' => 'el_from',
346 'iwlinks' => 'iwl_from',
347 'langlinks' => 'll_from',
348 'redirect' => 'rd_from',
349 'page_props' => 'pp_page',
350 ];
351
352 foreach ( $linksTables as $table => $field ) {
353 $this->output( " $table: 0" );
354 $tableStart = $start;
355 $counter = 0;
356 do {
357 $ids = $dbr->selectFieldValues(
358 $table,
359 $field,
360 [
361 self::intervalCond( $dbr, $field, $tableStart, $end ),
362 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
363 ],
364 __METHOD__,
365 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
366 );
367
368 $numIds = count( $ids );
369 if ( $numIds ) {
370 $counter += $numIds;
371 $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
372 $this->output( ", $counter" );
373 $tableStart = $ids[$numIds - 1] + 1;
374 wfWaitForSlaves();
375 }
376
377 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
378
379 $this->output( " deleted.\n" );
380 }
381 }
382
383 /**
384 * Build a SQL expression for a closed interval (i.e. BETWEEN).
385 *
386 * By specifying a null $start or $end, it is also possible to create
387 * half-bounded or unbounded intervals using this function.
388 *
389 * @param IDatabase $db Database connection
390 * @param string $var Field name
391 * @param mixed $start First value to include or null
392 * @param mixed $end Last value to include or null
393 * @return string
394 */
395 private static function intervalCond( IDatabase $db, $var, $start, $end ) {
396 if ( $start === null && $end === null ) {
397 return "$var IS NOT NULL";
398 } elseif ( $end === null ) {
399 return "$var >= {$db->addQuotes( $start )}";
400 } elseif ( $start === null ) {
401 return "$var <= {$db->addQuotes( $end )}";
402 } else {
403 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
404 }
405 }
406
407 /**
408 * Refershes links for pages in a tracking category
409 *
410 * @param string $category Category key
411 */
412 private function refreshTrackingCategory( $category ) {
413 $cats = $this->getPossibleCategories( $category );
414
415 if ( !$cats ) {
416 $this->error( "Tracking category '$category' is disabled\n" );
417 // Output to stderr but don't bail out,
418 }
419
420 foreach ( $cats as $cat ) {
421 $this->refreshCategory( $cat );
422 }
423 }
424
425 /**
426 * Refreshes links to a category
427 *
428 * @param Title $category
429 */
430 private function refreshCategory( Title $category ) {
431 $this->output( "Refreshing pages in category '{$category->getText()}'...\n" );
432
433 $dbr = $this->getDB( DB_REPLICA );
434 $conds = [
435 'page_id=cl_from',
436 'cl_to' => $category->getDBkey(),
437 ];
438 if ( $this->namespace !== false ) {
439 $conds['page_namespace'] = $this->namespace;
440 }
441
442 $i = 0;
443 $timestamp = '';
444 $lastId = 0;
445 do {
446 $finalConds = $conds;
447 $timestamp = $dbr->addQuotes( $timestamp );
448 $finalConds []=
449 "(cl_timestamp > $timestamp OR (cl_timestamp = $timestamp AND cl_from > $lastId))";
450 $res = $dbr->select( [ 'page', 'categorylinks' ],
451 [ 'page_id', 'cl_timestamp' ],
452 $finalConds,
453 __METHOD__,
454 [
455 'ORDER BY' => [ 'cl_timestamp', 'cl_from' ],
456 'LIMIT' => $this->mBatchSize,
457 ]
458 );
459
460 foreach ( $res as $row ) {
461 if ( !( ++$i % self::REPORTING_INTERVAL ) ) {
462 $this->output( "$i\n" );
463 wfWaitForSlaves();
464 }
465 $lastId = $row->page_id;
466 $timestamp = $row->cl_timestamp;
467 self::fixLinksFromArticle( $row->page_id );
468 }
469
470 } while ( $res->numRows() == $this->mBatchSize );
471 }
472
473 /**
474 * Returns a list of possible categories for a given tracking category key
475 *
476 * @param string $categoryKey
477 * @return Title[]
478 */
479 private function getPossibleCategories( $categoryKey ) {
480 $trackingCategories = new TrackingCategories( $this->getConfig() );
481 $cats = $trackingCategories->getTrackingCategories();
482 if ( isset( $cats[$categoryKey] ) ) {
483 return $cats[$categoryKey]['cats'];
484 }
485 $this->error( "Unknown tracking category {$categoryKey}\n", true );
486 }
487 }
488
489 $maintClass = 'RefreshLinks';
490 require_once RUN_MAINTENANCE_IF_MAIN;