MediaWiki REL1_27
refreshLinks.php
Go to the documentation of this file.
1<?php
24require_once __DIR__ . '/Maintenance.php';
25
32 public function __construct() {
33 parent::__construct();
34 $this->addDescription( 'Refresh link tables' );
35 $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
36 $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
37 $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
38 $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
39 $this->addOption( 'e', 'Last page id to refresh', false, true );
40 $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
41 'query, default 100000', false, true );
42 $this->addArg( 'start', 'Page_id to start from, default 1', false );
43 $this->setBatchSize( 100 );
44 }
45
46 public function execute() {
47 // Note that there is a difference between not specifying the start
48 // and end IDs and using the minimum and maximum values from the page
49 // table. In the latter case, deleteLinksFromNonexistent() will not
50 // delete entries for nonexistent IDs that fall outside the range.
51 $start = (int)$this->getArg( 0 ) ?: null;
52 $end = (int)$this->getOption( 'e' ) ?: null;
53 $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
54 if ( !$this->hasOption( 'dfn-only' ) ) {
55 $new = $this->getOption( 'new-only', false );
56 $redir = $this->getOption( 'redirects-only', false );
57 $oldRedir = $this->getOption( 'old-redirects-only', false );
58 $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
59 $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize, $dfnChunkSize );
60 } else {
61 $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize, $dfnChunkSize );
62 }
63 }
64
73 private function doRefreshLinks( $start, $newOnly = false,
74 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
75 ) {
76 $reportingInterval = 100;
77 $dbr = $this->getDB( DB_SLAVE );
78
79 if ( $start === null ) {
80 $start = 1;
81 }
82
83 // Give extensions a chance to optimize settings
84 Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
85
86 $what = $redirectsOnly ? "redirects" : "links";
87
88 if ( $oldRedirectsOnly ) {
89 # This entire code path is cut-and-pasted from below. Hurrah.
90
91 $conds = [
92 "page_is_redirect=1",
93 "rd_from IS NULL",
94 self::intervalCond( $dbr, 'page_id', $start, $end ),
95 ];
96
97 $res = $dbr->select(
98 [ 'page', 'redirect' ],
99 'page_id',
100 $conds,
101 __METHOD__,
102 [],
103 [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
104 );
105 $num = $res->numRows();
106 $this->output( "Refreshing $num old redirects from $start...\n" );
107
108 $i = 0;
109
110 foreach ( $res as $row ) {
111 if ( !( ++$i % $reportingInterval ) ) {
112 $this->output( "$i\n" );
114 }
115 $this->fixRedirect( $row->page_id );
116 }
117 } elseif ( $newOnly ) {
118 $this->output( "Refreshing $what from " );
119 $res = $dbr->select( 'page',
120 [ 'page_id' ],
121 [
122 'page_is_new' => 1,
123 self::intervalCond( $dbr, 'page_id', $start, $end ),
124 ],
125 __METHOD__
126 );
127 $num = $res->numRows();
128 $this->output( "$num new articles...\n" );
129
130 $i = 0;
131 foreach ( $res as $row ) {
132 if ( !( ++$i % $reportingInterval ) ) {
133 $this->output( "$i\n" );
135 }
136 if ( $redirectsOnly ) {
137 $this->fixRedirect( $row->page_id );
138 } else {
139 self::fixLinksFromArticle( $row->page_id );
140 }
141 }
142 } else {
143 if ( !$end ) {
144 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
145 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
146 $end = max( $maxPage, $maxRD );
147 }
148 $this->output( "Refreshing redirects table.\n" );
149 $this->output( "Starting from page_id $start of $end.\n" );
150
151 for ( $id = $start; $id <= $end; $id++ ) {
152
153 if ( !( $id % $reportingInterval ) ) {
154 $this->output( "$id\n" );
156 }
157 $this->fixRedirect( $id );
158 }
159
160 if ( !$redirectsOnly ) {
161 $this->output( "Refreshing links tables.\n" );
162 $this->output( "Starting from page_id $start of $end.\n" );
163
164 for ( $id = $start; $id <= $end; $id++ ) {
165
166 if ( !( $id % $reportingInterval ) ) {
167 $this->output( "$id\n" );
169 }
171 }
172 }
173 }
174 }
175
188 private function fixRedirect( $id ) {
189 $page = WikiPage::newFromID( $id );
190 $dbw = $this->getDB( DB_MASTER );
191
192 if ( $page === null ) {
193 // This page doesn't exist (any more)
194 // Delete any redirect table entry for it
195 $dbw->delete( 'redirect', [ 'rd_from' => $id ],
196 __METHOD__ );
197
198 return;
199 }
200
201 $rt = null;
202 $content = $page->getContent( Revision::RAW );
203 if ( $content !== null ) {
204 $rt = $content->getUltimateRedirectTarget();
205 }
206
207 if ( $rt === null ) {
208 // The page is not a redirect
209 // Delete any redirect table entry for it
210 $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
211 $fieldValue = 0;
212 } else {
213 $page->insertRedirectEntry( $rt );
214 $fieldValue = 1;
215 }
216
217 // Update the page table to be sure it is an a consistent state
218 $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
219 [ 'page_id' => $id ], __METHOD__ );
220 }
221
226 public static function fixLinksFromArticle( $id ) {
227 $page = WikiPage::newFromID( $id );
228
229 LinkCache::singleton()->clear();
230
231 if ( $page === null ) {
232 return;
233 }
234
235 $content = $page->getContent( Revision::RAW );
236 if ( $content === null ) {
237 return;
238 }
239
240 $updates = $content->getSecondaryDataUpdates( $page->getTitle() );
241 DataUpdate::runUpdates( $updates );
242 }
243
255 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
256 $chunkSize = 100000
257 ) {
259 $this->output( "Deleting illegal entries from the links tables...\n" );
260 $dbr = $this->getDB( DB_SLAVE );
261 do {
262 // Find the start of the next chunk. This is based only
263 // on existent page_ids.
264 $nextStart = $dbr->selectField(
265 'page',
266 'page_id',
267 self::intervalCond( $dbr, 'page_id', $start, $end ),
268 __METHOD__,
269 [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
270 );
271
272 if ( $nextStart !== false ) {
273 // To find the end of the current chunk, subtract one.
274 // This will serve to limit the number of rows scanned in
275 // dfnCheckInterval(), per query, to at most the sum of
276 // the chunk size and deletion batch size.
277 $chunkEnd = $nextStart - 1;
278 } else {
279 // This is the last chunk. Check all page_ids up to $end.
280 $chunkEnd = $end;
281 }
282
283 $fmtStart = $start !== null ? "[$start" : '(-INF';
284 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
285 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
286 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
287
288 $start = $nextStart;
289
290 } while ( $nextStart !== false );
291 }
292
299 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
300 $dbw = $this->getDB( DB_MASTER );
301 $dbr = $this->getDB( DB_SLAVE );
302
303 $linksTables = [ // table name => page_id field
304 'pagelinks' => 'pl_from',
305 'imagelinks' => 'il_from',
306 'categorylinks' => 'cl_from',
307 'templatelinks' => 'tl_from',
308 'externallinks' => 'el_from',
309 'iwlinks' => 'iwl_from',
310 'langlinks' => 'll_from',
311 'redirect' => 'rd_from',
312 'page_props' => 'pp_page',
313 ];
314
315 foreach ( $linksTables as $table => $field ) {
316 $this->output( " $table: 0" );
317 $tableStart = $start;
318 $counter = 0;
319 do {
320 $ids = $dbr->selectFieldValues(
321 $table,
322 $field,
323 [
324 self::intervalCond( $dbr, $field, $tableStart, $end ),
325 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
326 ],
327 __METHOD__,
328 [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
329 );
330
331 $numIds = count( $ids );
332 if ( $numIds ) {
333 $counter += $numIds;
334 $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
335 $this->output( ", $counter" );
336 $tableStart = $ids[$numIds - 1] + 1;
338 }
339
340 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
341
342 $this->output( " deleted.\n" );
343 }
344 }
345
357 private static function intervalCond( IDatabase $db, $var, $start, $end ) {
358 if ( $start === null && $end === null ) {
359 return "$var IS NOT NULL";
360 } elseif ( $end === null ) {
361 return "$var >= {$db->addQuotes( $start )}";
362 } elseif ( $start === null ) {
363 return "$var <= {$db->addQuotes( $end )}";
364 } else {
365 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
366 }
367 }
368}
369
370$maintClass = 'RefreshLinks';
371require_once RUN_MAINTENANCE_IF_MAIN;
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the slaves to catch up to the master position.
$i
Definition Parser.php:1694
static runUpdates(array $updates, $mode='run')
Convenience method, calls doUpdate() on every DataUpdate in the array.
static singleton()
Get an instance of this class.
Definition LinkCache.php:61
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true)
Add some args that are needed.
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.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
Set the batch size.
const RAW
Definition Revision.php:85
static newFromID( $id, $from='fromdb')
Constructor from a page id.
Definition WikiPage.php:132
$res
Definition database.txt:21
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling output() to send it all. It could be easily changed to send incrementally if that becomes useful
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
const DB_MASTER
Definition Defines.php:48
const DB_SLAVE
Definition Defines.php:47
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:2379
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:1040
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:37
Basic database interface for live and lazy-loaded DB handles.
Definition IDatabase.php:35
require_once RUN_MAINTENANCE_IF_MAIN