Merge "SpecialMovepage: Convert form to use OOUI controls"
[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 public function __construct() {
33 parent::__construct();
34 $this->mDescription = "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
65 /**
66 * Do the actual link refreshing.
67 * @param int|null $start Page_id to start from
68 * @param bool $newOnly Only do pages with 1 edit
69 * @param int|null $end Page_id to stop at
70 * @param bool $redirectsOnly Only fix redirects
71 * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
72 */
73 private function doRefreshLinks( $start, $newOnly = false,
74 $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
75 ) {
76 global $wgParser;
77
78 $reportingInterval = 100;
79 $dbr = wfGetDB( DB_SLAVE );
80
81 if ( $start === null ) {
82 $start = 1;
83 }
84
85 // Give extensions a chance to optimize settings
86 Hooks::run( 'MaintenanceRefreshLinksInit', array( $this ) );
87
88 # Don't generate extension images (e.g. Timeline)
89 $wgParser->clearTagHooks();
90
91 $what = $redirectsOnly ? "redirects" : "links";
92
93 if ( $oldRedirectsOnly ) {
94 # This entire code path is cut-and-pasted from below. Hurrah.
95
96 $conds = array(
97 "page_is_redirect=1",
98 "rd_from IS NULL",
99 self::intervalCond( $dbr, 'page_id', $start, $end ),
100 );
101
102 $res = $dbr->select(
103 array( 'page', 'redirect' ),
104 'page_id',
105 $conds,
106 __METHOD__,
107 array(),
108 array( 'redirect' => array( "LEFT JOIN", "page_id=rd_from" ) )
109 );
110 $num = $res->numRows();
111 $this->output( "Refreshing $num old redirects from $start...\n" );
112
113 $i = 0;
114
115 foreach ( $res as $row ) {
116 if ( !( ++$i % $reportingInterval ) ) {
117 $this->output( "$i\n" );
118 wfWaitForSlaves();
119 }
120 $this->fixRedirect( $row->page_id );
121 }
122 } elseif ( $newOnly ) {
123 $this->output( "Refreshing $what from " );
124 $res = $dbr->select( 'page',
125 array( 'page_id' ),
126 array(
127 'page_is_new' => 1,
128 self::intervalCond( $dbr, 'page_id', $start, $end ),
129 ),
130 __METHOD__
131 );
132 $num = $res->numRows();
133 $this->output( "$num new articles...\n" );
134
135 $i = 0;
136 foreach ( $res as $row ) {
137 if ( !( ++$i % $reportingInterval ) ) {
138 $this->output( "$i\n" );
139 wfWaitForSlaves();
140 }
141 if ( $redirectsOnly ) {
142 $this->fixRedirect( $row->page_id );
143 } else {
144 self::fixLinksFromArticle( $row->page_id );
145 }
146 }
147 } else {
148 if ( !$end ) {
149 $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
150 $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
151 $end = max( $maxPage, $maxRD );
152 }
153 $this->output( "Refreshing redirects table.\n" );
154 $this->output( "Starting from page_id $start of $end.\n" );
155
156 for ( $id = $start; $id <= $end; $id++ ) {
157
158 if ( !( $id % $reportingInterval ) ) {
159 $this->output( "$id\n" );
160 wfWaitForSlaves();
161 }
162 $this->fixRedirect( $id );
163 }
164
165 if ( !$redirectsOnly ) {
166 $this->output( "Refreshing links tables.\n" );
167 $this->output( "Starting from page_id $start of $end.\n" );
168
169 for ( $id = $start; $id <= $end; $id++ ) {
170
171 if ( !( $id % $reportingInterval ) ) {
172 $this->output( "$id\n" );
173 wfWaitForSlaves();
174 }
175 self::fixLinksFromArticle( $id );
176 }
177 }
178 }
179 }
180
181 /**
182 * Update the redirect entry for a given page.
183 *
184 * This methods bypasses the "redirect" table to get the redirect target,
185 * and parses the page's content to fetch it. This allows to be sure that
186 * the redirect target is up to date and valid.
187 * This is particularly useful when modifying namespaces to be sure the
188 * entry in the "redirect" table points to the correct page and not to an
189 * invalid one.
190 *
191 * @param int $id The page ID to check
192 */
193 private function fixRedirect( $id ) {
194 $page = WikiPage::newFromID( $id );
195 $dbw = wfGetDB( DB_MASTER );
196
197 if ( $page === null ) {
198 // This page doesn't exist (any more)
199 // Delete any redirect table entry for it
200 $dbw->delete( 'redirect', array( 'rd_from' => $id ),
201 __METHOD__ );
202
203 return;
204 }
205
206 $rt = null;
207 $content = $page->getContent( Revision::RAW );
208 if ( $content !== null ) {
209 $rt = $content->getUltimateRedirectTarget();
210 }
211
212 if ( $rt === null ) {
213 // The page is not a redirect
214 // Delete any redirect table entry for it
215 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__ );
216 $fieldValue = 0;
217 } else {
218 $page->insertRedirectEntry( $rt );
219 $fieldValue = 1;
220 }
221
222 // Update the page table to be sure it is an a consistent state
223 $dbw->update( 'page', array( 'page_is_redirect' => $fieldValue ),
224 array( 'page_id' => $id ), __METHOD__ );
225 }
226
227 /**
228 * Run LinksUpdate for all links on a given page_id
229 * @param int $id The page_id
230 */
231 public static function fixLinksFromArticle( $id ) {
232 $page = WikiPage::newFromID( $id );
233
234 LinkCache::singleton()->clear();
235
236 if ( $page === null ) {
237 return;
238 }
239
240 $content = $page->getContent( Revision::RAW );
241 if ( $content === null ) {
242 return;
243 }
244
245 $dbw = wfGetDB( DB_MASTER );
246 $dbw->begin( __METHOD__ );
247
248 $updates = $content->getSecondaryDataUpdates( $page->getTitle() );
249 DataUpdate::runUpdates( $updates );
250
251 $dbw->commit( __METHOD__ );
252 }
253
254 /**
255 * Removes non-existing links from pages from pagelinks, imagelinks,
256 * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
257 *
258 * @param int|null $start Page_id to start from
259 * @param int|null $end Page_id to stop at
260 * @param int $batchSize The size of deletion batches
261 * @param int $chunkSize Maximum number of existent IDs to check per query
262 *
263 * @author Merlijn van Deen <valhallasw@arctus.nl>
264 */
265 private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
266 $chunkSize = 100000
267 ) {
268 wfWaitForSlaves();
269 $this->output( "Deleting illegal entries from the links tables...\n" );
270 $dbr = wfGetDB( DB_SLAVE );
271 do {
272 // Find the start of the next chunk. This is based only
273 // on existent page_ids.
274 $nextStart = $dbr->selectField(
275 'page',
276 'page_id',
277 self::intervalCond( $dbr, 'page_id', $start, $end ),
278 __METHOD__,
279 array( 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize )
280 );
281
282 if ( $nextStart !== false ) {
283 // To find the end of the current chunk, subtract one.
284 // This will serve to limit the number of rows scanned in
285 // dfnCheckInterval(), per query, to at most the sum of
286 // the chunk size and deletion batch size.
287 $chunkEnd = $nextStart - 1;
288 } else {
289 // This is the last chunk. Check all page_ids up to $end.
290 $chunkEnd = $end;
291 }
292
293 $fmtStart = $start !== null ? "[$start" : '(-INF';
294 $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
295 $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
296 $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
297
298 $start = $nextStart;
299
300 } while ( $nextStart !== false );
301 }
302
303 /**
304 * @see RefreshLinks::deleteLinksFromNonexistent()
305 * @param int|null $start Page_id to start from
306 * @param int|null $end Page_id to stop at
307 * @param int $batchSize The size of deletion batches
308 */
309 private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
310 $dbw = wfGetDB( DB_MASTER );
311 $dbr = wfGetDB( DB_SLAVE );
312
313 $linksTables = array( // table name => page_id field
314 'pagelinks' => 'pl_from',
315 'imagelinks' => 'il_from',
316 'categorylinks' => 'cl_from',
317 'templatelinks' => 'tl_from',
318 'externallinks' => 'el_from',
319 'iwlinks' => 'iwl_from',
320 'langlinks' => 'll_from',
321 'redirect' => 'rd_from',
322 'page_props' => 'pp_page',
323 );
324
325 foreach ( $linksTables as $table => $field ) {
326 $this->output( " $table: 0" );
327 $tableStart = $start;
328 $counter = 0;
329 do {
330 $ids = $dbr->selectFieldValues(
331 $table,
332 $field,
333 array(
334 self::intervalCond( $dbr, $field, $tableStart, $end ),
335 "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
336 ),
337 __METHOD__,
338 array( 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize )
339 );
340
341 $numIds = count( $ids );
342 if ( $numIds ) {
343 $counter += $numIds;
344 $dbw->delete( $table, array( $field => $ids ), __METHOD__ );
345 $this->output( ", $counter" );
346 $tableStart = $ids[$numIds - 1] + 1;
347 wfWaitForSlaves();
348 }
349
350 } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
351
352 $this->output( " deleted.\n" );
353 }
354 }
355
356 /**
357 * Build a SQL expression for a closed interval (i.e. BETWEEN).
358 *
359 * By specifying a null $start or $end, it is also possible to create
360 * half-bounded or unbounded intervals using this function.
361 *
362 * @param IDatabase $db Database connection
363 * @param string $var Field name
364 * @param mixed $start First value to include or null
365 * @param mixed $end Last value to include or null
366 */
367 private static function intervalCond( IDatabase $db, $var, $start, $end ) {
368 if ( $start === null && $end === null ) {
369 return "$var IS NOT NULL";
370 } elseif ( $end === null ) {
371 return "$var >= {$db->addQuotes( $start )}";
372 } elseif ( $start === null ) {
373 return "$var <= {$db->addQuotes( $end )}";
374 } else {
375 return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
376 }
377 }
378 }
379
380 $maintClass = 'RefreshLinks';
381 require_once RUN_MAINTENANCE_IF_MAIN;