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