3 * Check for articles to fix after adding/deleting namespaces
5 * Copyright © 2005-2007 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup Maintenance
27 use MediaWiki\Linker\LinkTarget
;
29 require_once __DIR__
. '/Maintenance.php';
32 * Maintenance script that checks for articles to fix after
33 * adding/deleting namespaces.
35 * @ingroup Maintenance
37 class NamespaceConflictChecker
extends Maintenance
{
44 private $resolvablePages = 0;
45 private $totalPages = 0;
47 private $resolvableLinks = 0;
48 private $totalLinks = 0;
50 public function __construct() {
51 parent
::__construct();
52 $this->addDescription( 'Find and fix pages affected by namespace addition/removal' );
53 $this->addOption( 'fix', 'Attempt to automatically fix errors' );
54 $this->addOption( 'merge', "Instead of renaming conflicts, do a history merge with " .
55 "the correct title" );
56 $this->addOption( 'add-suffix', "Dupes will be renamed with correct namespace with " .
57 "<text> appended after the article name", false, true );
58 $this->addOption( 'add-prefix', "Dupes will be renamed with correct namespace with " .
59 "<text> prepended before the article name", false, true );
60 $this->addOption( 'source-pseudo-namespace', "Move all pages with the given source " .
61 "prefix (with an implied colon following it). If --dest-namespace is not specified, " .
62 "the colon will be replaced with a hyphen.",
64 $this->addOption( 'dest-namespace', "In combination with --source-pseudo-namespace, " .
65 "specify the namespace ID of the destination.", false, true );
66 $this->addOption( 'move-talk', "If this is specified, pages in the Talk namespace that " .
67 "begin with a conflicting prefix will be renamed, for example " .
68 "Talk:File:Foo -> File_Talk:Foo" );
71 public function execute() {
72 $this->db
= $this->getDB( DB_MASTER
);
75 'fix' => $this->hasOption( 'fix' ),
76 'merge' => $this->hasOption( 'merge' ),
77 'add-suffix' => $this->getOption( 'add-suffix', '' ),
78 'add-prefix' => $this->getOption( 'add-prefix', '' ),
79 'move-talk' => $this->hasOption( 'move-talk' ),
80 'source-pseudo-namespace' => $this->getOption( 'source-pseudo-namespace', '' ),
81 'dest-namespace' => intval( $this->getOption( 'dest-namespace', 0 ) ) ];
83 if ( $options['source-pseudo-namespace'] !== '' ) {
84 $retval = $this->checkPrefix( $options );
86 $retval = $this->checkAll( $options );
90 $this->output( "\nLooks good!\n" );
92 $this->output( "\nOh noeees\n" );
97 * Check all namespaces
99 * @param array $options Associative array of validated command-line options
103 private function checkAll( $options ) {
104 global $wgContLang, $wgNamespaceAliases, $wgCapitalLinks;
108 // List interwikis first, so they'll be overridden
109 // by any conflicting local namespaces.
110 foreach ( $this->getInterwikiList() as $prefix ) {
111 $name = $wgContLang->ucfirst( $prefix );
115 // Now pull in all canonical and alias namespaces...
116 foreach ( MWNamespace
::getCanonicalNamespaces() as $ns => $name ) {
117 // This includes $wgExtraNamespaces
118 if ( $name !== '' ) {
119 $spaces[$name] = $ns;
122 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
123 if ( $name !== '' ) {
124 $spaces[$name] = $ns;
127 foreach ( $wgNamespaceAliases as $name => $ns ) {
128 $spaces[$name] = $ns;
130 foreach ( $wgContLang->getNamespaceAliases() as $name => $ns ) {
131 $spaces[$name] = $ns;
134 // We'll need to check for lowercase keys as well,
135 // since we're doing case-sensitive searches in the db.
136 foreach ( $spaces as $name => $ns ) {
138 $moreNames[] = $wgContLang->uc( $name );
139 $moreNames[] = $wgContLang->ucfirst( $wgContLang->lc( $name ) );
140 $moreNames[] = $wgContLang->ucwords( $name );
141 $moreNames[] = $wgContLang->ucwords( $wgContLang->lc( $name ) );
142 $moreNames[] = $wgContLang->ucwordbreaks( $name );
143 $moreNames[] = $wgContLang->ucwordbreaks( $wgContLang->lc( $name ) );
144 if ( !$wgCapitalLinks ) {
145 foreach ( $moreNames as $altName ) {
146 $moreNames[] = $wgContLang->lcfirst( $altName );
148 $moreNames[] = $wgContLang->lcfirst( $name );
150 foreach ( array_unique( $moreNames ) as $altName ) {
151 if ( $altName !== $name ) {
152 $spaces[$altName] = $ns;
157 // Sort by namespace index, and if there are two with the same index,
158 // break the tie by sorting by name
159 $origSpaces = $spaces;
160 uksort( $spaces, function ( $a, $b ) use ( $origSpaces ) {
161 if ( $origSpaces[$a] < $origSpaces[$b] ) {
163 } elseif ( $origSpaces[$a] > $origSpaces[$b] ) {
165 } elseif ( $a < $b ) {
167 } elseif ( $a > $b ) {
175 foreach ( $spaces as $name => $ns ) {
176 $ok = $this->checkNamespace( $ns, $name, $options ) && $ok;
179 $this->output( "{$this->totalPages} pages to fix, " .
180 "{$this->resolvablePages} were resolvable.\n\n" );
182 foreach ( $spaces as $name => $ns ) {
184 /* Fix up link destinations for non-interwiki links only.
186 * For example if a page has [[Foo:Bar]] and then a Foo namespace
187 * is introduced, pagelinks needs to be updated to have
188 * page_namespace = NS_FOO.
190 * If instead an interwiki prefix was introduced called "Foo",
191 * the link should instead be moved to the iwlinks table. If a new
192 * language is introduced called "Foo", or if there is a pagelink
193 * [[fr:Bar]] when interlanguage magic links are turned on, the
194 * link would have to be moved to the langlinks table. Let's put
195 * those cases in the too-hard basket for now. The consequences are
196 * not especially severe.
197 * @fixme Handle interwiki links, and pagelinks to Category:, File:
198 * which probably need reparsing.
201 $this->checkLinkTable( 'pagelinks', 'pl', $ns, $name, $options );
202 $this->checkLinkTable( 'templatelinks', 'tl', $ns, $name, $options );
204 // The redirect table has interwiki links randomly mixed in, we
205 // need to filter those out. For example [[w:Foo:Bar]] would
206 // have rd_interwiki=w and rd_namespace=0, which would match the
207 // query for a conflicting namespace "Foo" if filtering wasn't done.
208 $this->checkLinkTable( 'redirect', 'rd', $ns, $name, $options,
209 [ 'rd_interwiki' => null ] );
210 $this->checkLinkTable( 'redirect', 'rd', $ns, $name, $options,
211 [ 'rd_interwiki' => '' ] );
215 $this->output( "{$this->totalLinks} links to fix, " .
216 "{$this->resolvableLinks} were resolvable.\n" );
222 * Get the interwiki list
226 private function getInterwikiList() {
227 $result = Interwiki
::getAllPrefixes();
229 foreach ( $result as $row ) {
230 $prefixes[] = $row['iw_prefix'];
237 * Check a given prefix and try to move it into the given destination namespace
239 * @param int $ns Destination namespace id
240 * @param string $name
241 * @param array $options Associative array of validated command-line options
244 private function checkNamespace( $ns, $name, $options ) {
245 $targets = $this->getTargetList( $ns, $name, $options );
246 $count = $targets->numRows();
247 $this->totalPages +
= $count;
252 $dryRunNote = $options['fix'] ?
'' : ' DRY RUN ONLY';
255 foreach ( $targets as $row ) {
257 // Find the new title and determine the action to take
259 $newTitle = $this->getDestinationTitle( $ns, $name,
260 $row->page_namespace
, $row->page_title
, $options );
263 $logStatus = 'invalid title';
265 } elseif ( $newTitle->exists() ) {
266 if ( $options['merge'] ) {
267 if ( $this->canMerge( $row->page_id
, $newTitle, $logStatus ) ) {
272 } elseif ( $options['add-prefix'] == '' && $options['add-suffix'] == '' ) {
274 $logStatus = 'dest title exists and --add-prefix not specified';
276 $newTitle = $this->getAlternateTitle( $newTitle, $options );
279 $logStatus = 'alternate title is invalid';
280 } elseif ( $newTitle->exists() ) {
282 $logStatus = 'title conflict';
285 $logStatus = 'alternate';
290 $logStatus = 'no conflict';
293 // Take the action or log a dry run message
295 $logTitle = "id={$row->page_id} ns={$row->page_namespace} dbk={$row->page_title}";
300 $this->output( "$logTitle *** $logStatus\n" );
304 $this->output( "$logTitle -> " .
305 $newTitle->getPrefixedDBkey() . " ($logStatus)$dryRunNote\n" );
307 if ( $options['fix'] ) {
308 $pageOK = $this->movePage( $row->page_id
, $newTitle );
312 $this->output( "$logTitle => " .
313 $newTitle->getPrefixedDBkey() . " (merge)$dryRunNote\n" );
315 if ( $options['fix'] ) {
316 $pageOK = $this->mergePage( $row, $newTitle );
322 $this->resolvablePages++
;
332 * Check and repair the destination fields in a link table
333 * @param string $table The link table name
334 * @param string $fieldPrefix The field prefix in the link table
335 * @param int $ns Destination namespace id
336 * @param string $name
337 * @param array $options Associative array of validated command-line options
338 * @param array $extraConds Extra conditions for the SQL query
340 private function checkLinkTable( $table, $fieldPrefix, $ns, $name, $options,
344 $fromField = "{$fieldPrefix}_from";
345 $namespaceField = "{$fieldPrefix}_namespace";
346 $titleField = "{$fieldPrefix}_title";
349 $res = $this->db
->select(
351 [ $fromField, $namespaceField, $titleField ],
352 array_merge( $batchConds, $extraConds, [
353 $namespaceField => 0,
354 $titleField . $this->db
->buildLike( "$name:", $this->db
->anyString() )
358 'ORDER BY' => [ $titleField, $fromField ],
359 'LIMIT' => $batchSize
363 if ( $res->numRows() == 0 ) {
366 foreach ( $res as $row ) {
367 $logTitle = "from={$row->$fromField} ns={$row->$namespaceField} " .
368 "dbk={$row->$titleField}";
369 $destTitle = $this->getDestinationTitle( $ns, $name,
370 $row->$namespaceField, $row->$titleField, $options );
373 $this->output( "$table $logTitle *** INVALID\n" );
376 $this->resolvableLinks++
;
377 if ( !$options['fix'] ) {
378 $this->output( "$table $logTitle -> " .
379 $destTitle->getPrefixedDBkey() . " DRY RUN\n" );
383 $this->db
->update( $table,
386 $namespaceField => $destTitle->getNamespace(),
387 $titleField => $destTitle->getDBkey()
391 $namespaceField => 0,
392 $titleField => $row->$titleField,
393 $fromField => $row->$fromField
398 $this->output( "$table $logTitle -> " .
399 $destTitle->getPrefixedDBkey() . "\n" );
401 $encLastTitle = $this->db
->addQuotes( $row->$titleField );
402 $encLastFrom = $this->db
->addQuotes( $row->$fromField );
405 "$titleField > $encLastTitle " .
406 "OR ($titleField = $encLastTitle AND $fromField > $encLastFrom)" ];
413 * Move the given pseudo-namespace, either replacing the colon with a hyphen
414 * (useful for pseudo-namespaces that conflict with interwiki links) or move
415 * them to another namespace if specified.
416 * @param array $options Associative array of validated command-line options
419 private function checkPrefix( $options ) {
420 $prefix = $options['source-pseudo-namespace'];
421 $ns = $options['dest-namespace'];
422 $this->output( "Checking prefix \"$prefix\" vs namespace $ns\n" );
424 return $this->checkNamespace( $ns, $prefix, $options );
428 * Find pages in main and talk namespaces that have a prefix of the new
429 * namespace so we know titles that will need migrating
431 * @param int $ns Destination namespace id
432 * @param string $name Prefix that is being made a namespace
433 * @param array $options Associative array of validated command-line options
435 * @return ResultWrapper
437 private function getTargetList( $ns, $name, $options ) {
438 if ( $options['move-talk'] && MWNamespace
::isSubject( $ns ) ) {
439 $checkNamespaces = [ NS_MAIN
, NS_TALK
];
441 $checkNamespaces = NS_MAIN
;
444 return $this->db
->select( 'page',
451 'page_namespace' => $checkNamespaces,
452 'page_title' . $this->db
->buildLike( "$name:", $this->db
->anyString() ),
459 * Get the preferred destination title for a given target page.
460 * @param integer $ns The destination namespace ID
461 * @param string $name The conflicting prefix
462 * @param integer $sourceNs The source namespace
463 * @param integer $sourceDbk The source DB key (i.e. page_title)
464 * @param array $options Associative array of validated command-line options
465 * @return Title|false
467 private function getDestinationTitle( $ns, $name, $sourceNs, $sourceDbk, $options ) {
468 $dbk = substr( $sourceDbk, strlen( "$name:" ) );
470 // An interwiki; try an alternate encoding with '-' for ':'
471 $dbk = "$name-" . $dbk;
474 if ( $sourceNs == NS_TALK
&& MWNamespace
::isSubject( $ns ) ) {
475 // This is an associated talk page moved with the --move-talk feature.
476 $destNS = MWNamespace
::getTalk( $destNS );
478 $newTitle = Title
::makeTitleSafe( $destNS, $dbk );
479 if ( !$newTitle ||
!$newTitle->canExist() ) {
486 * Get an alternative title to move a page to. This is used if the
487 * preferred destination title already exists.
489 * @param LinkTarget $linkTarget
490 * @param array $options Associative array of validated command-line options
493 private function getAlternateTitle( LinkTarget
$linkTarget, $options ) {
494 $prefix = $options['add-prefix'];
495 $suffix = $options['add-suffix'];
496 if ( $prefix == '' && $suffix == '' ) {
500 $dbk = $prefix . $linkTarget->getDBkey() . $suffix;
501 $title = Title
::makeTitleSafe( $linkTarget->getNamespace(), $dbk );
505 if ( !$title->exists() ) {
514 * @param integer $id The page_id
515 * @param LinkTarget $newLinkTarget The new title link target
518 private function movePage( $id, LinkTarget
$newLinkTarget ) {
519 $this->db
->update( 'page',
521 "page_namespace" => $newLinkTarget->getNamespace(),
522 "page_title" => $newLinkTarget->getDBkey(),
529 // Update *_from_namespace in links tables
530 $fromNamespaceTables = [
531 [ 'pagelinks', 'pl' ],
532 [ 'templatelinks', 'tl' ],
533 [ 'imagelinks', 'il' ] ];
534 foreach ( $fromNamespaceTables as $tableInfo ) {
535 list( $table, $fieldPrefix ) = $tableInfo;
536 $this->db
->update( $table,
538 [ "{$fieldPrefix}_from_namespace" => $newLinkTarget->getNamespace() ],
540 [ "{$fieldPrefix}_from" => $id ],
548 * Determine if we can merge a page.
549 * We check if an inaccessible revision would become the latest and
550 * deny the merge if so -- it's theoretically possible to update the
551 * latest revision, but opens a can of worms -- search engine updates,
552 * recentchanges review, etc.
554 * @param integer $id The page_id
555 * @param LinkTarget $linkTarget The new link target
556 * @param string $logStatus This is set to the log status message on failure
559 private function canMerge( $id, LinkTarget
$linkTarget, &$logStatus ) {
560 $latestDest = Revision
::newFromTitle( $linkTarget, 0, Revision
::READ_LATEST
);
561 $latestSource = Revision
::newFromPageId( $id, 0, Revision
::READ_LATEST
);
562 if ( $latestSource->getTimestamp() > $latestDest->getTimestamp() ) {
563 $logStatus = 'cannot merge since source is later';
571 * Merge page histories
573 * @param integer $id The page_id
574 * @param Title $newTitle The new title
577 private function mergePage( $row, Title
$newTitle ) {
580 // Construct the WikiPage object we will need later, while the
581 // page_id still exists. Note that this cannot use makeTitleSafe(),
582 // we are deliberately constructing an invalid title.
583 $sourceTitle = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
584 $sourceTitle->resetArticleID( $id );
585 $wikiPage = new WikiPage( $sourceTitle );
586 $wikiPage->loadPageData( 'fromdbmaster' );
588 $destId = $newTitle->getArticleID();
589 $this->beginTransaction( $this->db
, __METHOD__
);
590 $this->db
->update( 'revision',
592 [ 'rev_page' => $destId ],
594 [ 'rev_page' => $id ],
597 $this->db
->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
599 /* Call LinksDeletionUpdate to delete outgoing links from the old title,
600 * and update category counts.
602 * Calling external code with a fake broken Title is a fairly dubious
603 * idea. It's necessary because it's quite a lot of code to duplicate,
604 * but that also makes it fragile since it would be easy for someone to
605 * accidentally introduce an assumption of title validity to the code we
608 $update = new LinksDeletionUpdate( $wikiPage );
610 $this->commitTransaction( $this->db
, __METHOD__
);
616 $maintClass = "NamespaceConflictChecker";
617 require_once RUN_MAINTENANCE_IF_MAIN
;