MediaWiki  1.28.0
refreshLinks.php
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/Maintenance.php';
25 
31 class RefreshLinks extends Maintenance {
33  protected $namespace = false;
34 
35  public function __construct() {
36  parent::__construct();
37  $this->addDescription( 'Refresh link tables' );
38  $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
39  $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
40  $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
41  $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
42  $this->addOption( 'e', 'Last page id to refresh', false, true );
43  $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
44  'query, default 100000', false, true );
45  $this->addOption( 'namespace', 'Only fix pages in this namespace', false, true );
46  $this->addArg( 'start', 'Page_id to start from, default 1', false );
47  $this->setBatchSize( 100 );
48  }
49 
50  public function execute() {
51  // Note that there is a difference between not specifying the start
52  // and end IDs and using the minimum and maximum values from the page
53  // table. In the latter case, deleteLinksFromNonexistent() will not
54  // delete entries for nonexistent IDs that fall outside the range.
55  $start = (int)$this->getArg( 0 ) ?: null;
56  $end = (int)$this->getOption( 'e' ) ?: null;
57  $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
58  $ns = $this->getOption( 'namespace' );
59  if ( $ns === null ) {
60  $this->namespace = false;
61  } else {
62  $this->namespace = (int)$ns;
63  }
64  if ( !$this->hasOption( 'dfn-only' ) ) {
65  $new = $this->getOption( 'new-only', false );
66  $redir = $this->getOption( 'redirects-only', false );
67  $oldRedir = $this->getOption( 'old-redirects-only', false );
68  $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
69  $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize, $dfnChunkSize );
70  } else {
71  $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize, $dfnChunkSize );
72  }
73  }
74 
75  private function namespaceCond() {
76  return $this->namespace !== false
77  ? [ 'page_namespace' => $this->namespace ]
78  : [];
79  }
80 
89  private function doRefreshLinks( $start, $newOnly = false,
90  $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
91  ) {
92  $reportingInterval = 100;
93  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
94 
95  if ( $start === null ) {
96  $start = 1;
97  }
98 
99  // Give extensions a chance to optimize settings
100  Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
101 
102  $what = $redirectsOnly ? "redirects" : "links";
103 
104  if ( $oldRedirectsOnly ) {
105  # This entire code path is cut-and-pasted from below. Hurrah.
106 
107  $conds = [
108  "page_is_redirect=1",
109  "rd_from IS NULL",
110  self::intervalCond( $dbr, 'page_id', $start, $end ),
111  ] + $this->namespaceCond();
112 
113  $res = $dbr->select(
114  [ 'page', 'redirect' ],
115  'page_id',
116  $conds,
117  __METHOD__,
118  [],
119  [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
120  );
121  $num = $res->numRows();
122  $this->output( "Refreshing $num old redirects from $start...\n" );
123 
124  $i = 0;
125 
126  foreach ( $res as $row ) {
127  if ( !( ++$i % $reportingInterval ) ) {
128  $this->output( "$i\n" );
129  wfWaitForSlaves();
130  }
131  $this->fixRedirect( $row->page_id );
132  }
133  } elseif ( $newOnly ) {
134  $this->output( "Refreshing $what from " );
135  $res = $dbr->select( 'page',
136  [ 'page_id' ],
137  [
138  'page_is_new' => 1,
139  self::intervalCond( $dbr, 'page_id', $start, $end ),
140  ] + $this->namespaceCond(),
141  __METHOD__
142  );
143  $num = $res->numRows();
144  $this->output( "$num new articles...\n" );
145 
146  $i = 0;
147  foreach ( $res as $row ) {
148  if ( !( ++$i % $reportingInterval ) ) {
149  $this->output( "$i\n" );
150  wfWaitForSlaves();
151  }
152  if ( $redirectsOnly ) {
153  $this->fixRedirect( $row->page_id );
154  } else {
155  self::fixLinksFromArticle( $row->page_id, $this->namespace );
156  }
157  }
158  } else {
159  if ( !$end ) {
160  $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
161  $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
162  $end = max( $maxPage, $maxRD );
163  }
164  $this->output( "Refreshing redirects table.\n" );
165  $this->output( "Starting from page_id $start of $end.\n" );
166 
167  for ( $id = $start; $id <= $end; $id++ ) {
168 
169  if ( !( $id % $reportingInterval ) ) {
170  $this->output( "$id\n" );
171  wfWaitForSlaves();
172  }
173  $this->fixRedirect( $id );
174  }
175 
176  if ( !$redirectsOnly ) {
177  $this->output( "Refreshing links tables.\n" );
178  $this->output( "Starting from page_id $start of $end.\n" );
179 
180  for ( $id = $start; $id <= $end; $id++ ) {
181 
182  if ( !( $id % $reportingInterval ) ) {
183  $this->output( "$id\n" );
184  wfWaitForSlaves();
185  }
186  self::fixLinksFromArticle( $id, $this->namespace );
187  }
188  }
189  }
190  }
191 
204  private function fixRedirect( $id ) {
205  $page = WikiPage::newFromID( $id );
206  $dbw = $this->getDB( DB_MASTER );
207 
208  if ( $page === null ) {
209  // This page doesn't exist (any more)
210  // Delete any redirect table entry for it
211  $dbw->delete( 'redirect', [ 'rd_from' => $id ],
212  __METHOD__ );
213 
214  return;
215  } elseif ( $this->namespace !== false
216  && !$page->getTitle()->inNamespace( $this->namespace )
217  ) {
218  return;
219  }
220 
221  $rt = null;
222  $content = $page->getContent( Revision::RAW );
223  if ( $content !== null ) {
224  $rt = $content->getUltimateRedirectTarget();
225  }
226 
227  if ( $rt === null ) {
228  // The page is not a redirect
229  // Delete any redirect table entry for it
230  $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
231  $fieldValue = 0;
232  } else {
233  $page->insertRedirectEntry( $rt );
234  $fieldValue = 1;
235  }
236 
237  // Update the page table to be sure it is an a consistent state
238  $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
239  [ 'page_id' => $id ], __METHOD__ );
240  }
241 
247  public static function fixLinksFromArticle( $id, $ns = false ) {
248  $page = WikiPage::newFromID( $id );
249 
250  LinkCache::singleton()->clear();
251 
252  if ( $page === null ) {
253  return;
254  } elseif ( $ns !== false
255  && !$page->getTitle()->inNamespace( $ns ) ) {
256  return;
257  }
258 
259  $content = $page->getContent( Revision::RAW );
260  if ( $content === null ) {
261  return;
262  }
263 
264  foreach ( $content->getSecondaryDataUpdates( $page->getTitle() ) as $update ) {
265  DeferredUpdates::addUpdate( $update );
266  }
267  }
268 
280  private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
281  $chunkSize = 100000
282  ) {
283  wfWaitForSlaves();
284  $this->output( "Deleting illegal entries from the links tables...\n" );
285  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
286  do {
287  // Find the start of the next chunk. This is based only
288  // on existent page_ids.
289  $nextStart = $dbr->selectField(
290  'page',
291  'page_id',
292  [ self::intervalCond( $dbr, 'page_id', $start, $end ) ]
293  + $this->namespaceCond(),
294  __METHOD__,
295  [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
296  );
297 
298  if ( $nextStart !== false ) {
299  // To find the end of the current chunk, subtract one.
300  // This will serve to limit the number of rows scanned in
301  // dfnCheckInterval(), per query, to at most the sum of
302  // the chunk size and deletion batch size.
303  $chunkEnd = $nextStart - 1;
304  } else {
305  // This is the last chunk. Check all page_ids up to $end.
306  $chunkEnd = $end;
307  }
308 
309  $fmtStart = $start !== null ? "[$start" : '(-INF';
310  $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
311  $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
312  $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
313 
314  $start = $nextStart;
315 
316  } while ( $nextStart !== false );
317  }
318 
325  private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
326  $dbw = $this->getDB( DB_MASTER );
327  $dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
328 
329  $linksTables = [ // table name => page_id field
330  'pagelinks' => 'pl_from',
331  'imagelinks' => 'il_from',
332  'categorylinks' => 'cl_from',
333  'templatelinks' => 'tl_from',
334  'externallinks' => 'el_from',
335  'iwlinks' => 'iwl_from',
336  'langlinks' => 'll_from',
337  'redirect' => 'rd_from',
338  'page_props' => 'pp_page',
339  ];
340 
341  foreach ( $linksTables as $table => $field ) {
342  $this->output( " $table: 0" );
343  $tableStart = $start;
344  $counter = 0;
345  do {
346  $ids = $dbr->selectFieldValues(
347  $table,
348  $field,
349  [
350  self::intervalCond( $dbr, $field, $tableStart, $end ),
351  "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
352  ],
353  __METHOD__,
354  [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
355  );
356 
357  $numIds = count( $ids );
358  if ( $numIds ) {
359  $counter += $numIds;
360  $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
361  $this->output( ", $counter" );
362  $tableStart = $ids[$numIds - 1] + 1;
363  wfWaitForSlaves();
364  }
365 
366  } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
367 
368  $this->output( " deleted.\n" );
369  }
370  }
371 
383  private static function intervalCond( IDatabase $db, $var, $start, $end ) {
384  if ( $start === null && $end === null ) {
385  return "$var IS NOT NULL";
386  } elseif ( $end === null ) {
387  return "$var >= {$db->addQuotes( $start )}";
388  } elseif ( $start === null ) {
389  return "$var <= {$db->addQuotes( $end )}";
390  } else {
391  return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
392  }
393  }
394 }
395 
396 $maintClass = 'RefreshLinks';
397 require_once RUN_MAINTENANCE_IF_MAIN;
wfWaitForSlaves($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
addArg($arg, $description, $required=true)
Add some args that are needed.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
getDB($db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
hasOption($name)
Checks to see if a particular param exists.
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
const DB_MASTER
Definition: defines.php:23
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
static singleton()
Get an instance of this class.
Definition: LinkCache.php:64
$res
Definition: database.txt:21
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
addDescription($text)
Set the description text.
const RAW
Definition: Revision.php:94
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
getOption($name, $default=null)
Get an option, or return the default.
output($out, $channel=null)
Throw some output to the user.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1046
static newFromID($id, $from= 'fromdb')
Constructor from a page id.
Definition: WikiPage.php:153
getArg($argId=0, $default=null)
Get an argument.
const DB_REPLICA
Definition: defines.php:22
setBatchSize($s=0)
Set the batch size.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:34
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2491