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
;
28 use MediaWiki\MediaWikiServices
;
30 require_once __DIR__
. '/Maintenance.php';
33 * Maintenance script that checks for articles to fix after
34 * adding/deleting namespaces.
36 * @ingroup Maintenance
38 class NamespaceConflictChecker
extends Maintenance
{
45 private $resolvablePages = 0;
46 private $totalPages = 0;
48 private $resolvableLinks = 0;
49 private $totalLinks = 0;
51 public function __construct() {
52 parent
::__construct();
53 $this->addDescription( 'Find and fix pages affected by namespace addition/removal' );
54 $this->addOption( 'fix', 'Attempt to automatically fix errors' );
55 $this->addOption( 'merge', "Instead of renaming conflicts, do a history merge with " .
56 "the correct title" );
57 $this->addOption( 'add-suffix', "Dupes will be renamed with correct namespace with " .
58 "<text> appended after the article name", false, true );
59 $this->addOption( 'add-prefix', "Dupes will be renamed with correct namespace with " .
60 "<text> prepended before the article name", false, true );
61 $this->addOption( 'source-pseudo-namespace', "Move all pages with the given source " .
62 "prefix (with an implied colon following it). If --dest-namespace is not specified, " .
63 "the colon will be replaced with a hyphen.",
65 $this->addOption( 'dest-namespace', "In combination with --source-pseudo-namespace, " .
66 "specify the namespace ID of the destination.", false, true );
67 $this->addOption( 'move-talk', "If this is specified, pages in the Talk namespace that " .
68 "begin with a conflicting prefix will be renamed, for example " .
69 "Talk:File:Foo -> File_Talk:Foo" );
72 public function execute() {
73 $this->db
= $this->getDB( DB_MASTER
);
76 'fix' => $this->hasOption( 'fix' ),
77 'merge' => $this->hasOption( 'merge' ),
78 'add-suffix' => $this->getOption( 'add-suffix', '' ),
79 'add-prefix' => $this->getOption( 'add-prefix', '' ),
80 'move-talk' => $this->hasOption( 'move-talk' ),
81 'source-pseudo-namespace' => $this->getOption( 'source-pseudo-namespace', '' ),
82 'dest-namespace' => intval( $this->getOption( 'dest-namespace', 0 ) ) ];
84 if ( $options['source-pseudo-namespace'] !== '' ) {
85 $retval = $this->checkPrefix( $options );
87 $retval = $this->checkAll( $options );
91 $this->output( "\nLooks good!\n" );
93 $this->output( "\nOh noeees\n" );
98 * Check all namespaces
100 * @param array $options Associative array of validated command-line options
104 private function checkAll( $options ) {
105 global $wgContLang, $wgNamespaceAliases, $wgCapitalLinks;
109 // List interwikis first, so they'll be overridden
110 // by any conflicting local namespaces.
111 foreach ( $this->getInterwikiList() as $prefix ) {
112 $name = $wgContLang->ucfirst( $prefix );
116 // Now pull in all canonical and alias namespaces...
117 foreach ( MWNamespace
::getCanonicalNamespaces() as $ns => $name ) {
118 // This includes $wgExtraNamespaces
119 if ( $name !== '' ) {
120 $spaces[$name] = $ns;
123 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
124 if ( $name !== '' ) {
125 $spaces[$name] = $ns;
128 foreach ( $wgNamespaceAliases as $name => $ns ) {
129 $spaces[$name] = $ns;
131 foreach ( $wgContLang->getNamespaceAliases() as $name => $ns ) {
132 $spaces[$name] = $ns;
135 // We'll need to check for lowercase keys as well,
136 // since we're doing case-sensitive searches in the db.
137 foreach ( $spaces as $name => $ns ) {
139 $moreNames[] = $wgContLang->uc( $name );
140 $moreNames[] = $wgContLang->ucfirst( $wgContLang->lc( $name ) );
141 $moreNames[] = $wgContLang->ucwords( $name );
142 $moreNames[] = $wgContLang->ucwords( $wgContLang->lc( $name ) );
143 $moreNames[] = $wgContLang->ucwordbreaks( $name );
144 $moreNames[] = $wgContLang->ucwordbreaks( $wgContLang->lc( $name ) );
145 if ( !$wgCapitalLinks ) {
146 foreach ( $moreNames as $altName ) {
147 $moreNames[] = $wgContLang->lcfirst( $altName );
149 $moreNames[] = $wgContLang->lcfirst( $name );
151 foreach ( array_unique( $moreNames ) as $altName ) {
152 if ( $altName !== $name ) {
153 $spaces[$altName] = $ns;
158 // Sort by namespace index, and if there are two with the same index,
159 // break the tie by sorting by name
160 $origSpaces = $spaces;
161 uksort( $spaces, function ( $a, $b ) use ( $origSpaces ) {
162 if ( $origSpaces[$a] < $origSpaces[$b] ) {
164 } elseif ( $origSpaces[$a] > $origSpaces[$b] ) {
166 } elseif ( $a < $b ) {
168 } elseif ( $a > $b ) {
176 foreach ( $spaces as $name => $ns ) {
177 $ok = $this->checkNamespace( $ns, $name, $options ) && $ok;
180 $this->output( "{$this->totalPages} pages to fix, " .
181 "{$this->resolvablePages} were resolvable.\n\n" );
183 foreach ( $spaces as $name => $ns ) {
185 /* Fix up link destinations for non-interwiki links only.
187 * For example if a page has [[Foo:Bar]] and then a Foo namespace
188 * is introduced, pagelinks needs to be updated to have
189 * page_namespace = NS_FOO.
191 * If instead an interwiki prefix was introduced called "Foo",
192 * the link should instead be moved to the iwlinks table. If a new
193 * language is introduced called "Foo", or if there is a pagelink
194 * [[fr:Bar]] when interlanguage magic links are turned on, the
195 * link would have to be moved to the langlinks table. Let's put
196 * those cases in the too-hard basket for now. The consequences are
197 * not especially severe.
198 * @fixme Handle interwiki links, and pagelinks to Category:, File:
199 * which probably need reparsing.
202 $this->checkLinkTable( 'pagelinks', 'pl', $ns, $name, $options );
203 $this->checkLinkTable( 'templatelinks', 'tl', $ns, $name, $options );
205 // The redirect table has interwiki links randomly mixed in, we
206 // need to filter those out. For example [[w:Foo:Bar]] would
207 // have rd_interwiki=w and rd_namespace=0, which would match the
208 // query for a conflicting namespace "Foo" if filtering wasn't done.
209 $this->checkLinkTable( 'redirect', 'rd', $ns, $name, $options,
210 [ 'rd_interwiki' => null ] );
211 $this->checkLinkTable( 'redirect', 'rd', $ns, $name, $options,
212 [ 'rd_interwiki' => '' ] );
216 $this->output( "{$this->totalLinks} links to fix, " .
217 "{$this->resolvableLinks} were resolvable.\n" );
223 * Get the interwiki list
227 private function getInterwikiList() {
228 $result = MediaWikiServices
::getInstance()->getInterwikiLookup()->getAllPrefixes();
230 foreach ( $result as $row ) {
231 $prefixes[] = $row['iw_prefix'];
238 * Check a given prefix and try to move it into the given destination namespace
240 * @param int $ns Destination namespace id
241 * @param string $name
242 * @param array $options Associative array of validated command-line options
245 private function checkNamespace( $ns, $name, $options ) {
246 $targets = $this->getTargetList( $ns, $name, $options );
247 $count = $targets->numRows();
248 $this->totalPages +
= $count;
253 $dryRunNote = $options['fix'] ?
'' : ' DRY RUN ONLY';
256 foreach ( $targets as $row ) {
258 // Find the new title and determine the action to take
260 $newTitle = $this->getDestinationTitle( $ns, $name,
261 $row->page_namespace
, $row->page_title
, $options );
264 $logStatus = 'invalid title';
266 } elseif ( $newTitle->exists() ) {
267 if ( $options['merge'] ) {
268 if ( $this->canMerge( $row->page_id
, $newTitle, $logStatus ) ) {
273 } elseif ( $options['add-prefix'] == '' && $options['add-suffix'] == '' ) {
275 $logStatus = 'dest title exists and --add-prefix not specified';
277 $newTitle = $this->getAlternateTitle( $newTitle, $options );
280 $logStatus = 'alternate title is invalid';
281 } elseif ( $newTitle->exists() ) {
283 $logStatus = 'title conflict';
286 $logStatus = 'alternate';
291 $logStatus = 'no conflict';
294 // Take the action or log a dry run message
296 $logTitle = "id={$row->page_id} ns={$row->page_namespace} dbk={$row->page_title}";
301 $this->output( "$logTitle *** $logStatus\n" );
305 $this->output( "$logTitle -> " .
306 $newTitle->getPrefixedDBkey() . " ($logStatus)$dryRunNote\n" );
308 if ( $options['fix'] ) {
309 $pageOK = $this->movePage( $row->page_id
, $newTitle );
313 $this->output( "$logTitle => " .
314 $newTitle->getPrefixedDBkey() . " (merge)$dryRunNote\n" );
316 if ( $options['fix'] ) {
317 $pageOK = $this->mergePage( $row, $newTitle );
323 $this->resolvablePages++
;
333 * Check and repair the destination fields in a link table
334 * @param string $table The link table name
335 * @param string $fieldPrefix The field prefix in the link table
336 * @param int $ns Destination namespace id
337 * @param string $name
338 * @param array $options Associative array of validated command-line options
339 * @param array $extraConds Extra conditions for the SQL query
341 private function checkLinkTable( $table, $fieldPrefix, $ns, $name, $options,
345 $fromField = "{$fieldPrefix}_from";
346 $namespaceField = "{$fieldPrefix}_namespace";
347 $titleField = "{$fieldPrefix}_title";
350 $res = $this->db
->select(
352 [ $fromField, $namespaceField, $titleField ],
353 array_merge( $batchConds, $extraConds, [
354 $namespaceField => 0,
355 $titleField . $this->db
->buildLike( "$name:", $this->db
->anyString() )
359 'ORDER BY' => [ $titleField, $fromField ],
360 'LIMIT' => $batchSize
364 if ( $res->numRows() == 0 ) {
367 foreach ( $res as $row ) {
368 $logTitle = "from={$row->$fromField} ns={$row->$namespaceField} " .
369 "dbk={$row->$titleField}";
370 $destTitle = $this->getDestinationTitle( $ns, $name,
371 $row->$namespaceField, $row->$titleField, $options );
374 $this->output( "$table $logTitle *** INVALID\n" );
377 $this->resolvableLinks++
;
378 if ( !$options['fix'] ) {
379 $this->output( "$table $logTitle -> " .
380 $destTitle->getPrefixedDBkey() . " DRY RUN\n" );
384 $this->db
->update( $table,
387 $namespaceField => $destTitle->getNamespace(),
388 $titleField => $destTitle->getDBkey()
392 $namespaceField => 0,
393 $titleField => $row->$titleField,
394 $fromField => $row->$fromField
399 $this->output( "$table $logTitle -> " .
400 $destTitle->getPrefixedDBkey() . "\n" );
402 $encLastTitle = $this->db
->addQuotes( $row->$titleField );
403 $encLastFrom = $this->db
->addQuotes( $row->$fromField );
406 "$titleField > $encLastTitle " .
407 "OR ($titleField = $encLastTitle AND $fromField > $encLastFrom)" ];
414 * Move the given pseudo-namespace, either replacing the colon with a hyphen
415 * (useful for pseudo-namespaces that conflict with interwiki links) or move
416 * them to another namespace if specified.
417 * @param array $options Associative array of validated command-line options
420 private function checkPrefix( $options ) {
421 $prefix = $options['source-pseudo-namespace'];
422 $ns = $options['dest-namespace'];
423 $this->output( "Checking prefix \"$prefix\" vs namespace $ns\n" );
425 return $this->checkNamespace( $ns, $prefix, $options );
429 * Find pages in main and talk namespaces that have a prefix of the new
430 * namespace so we know titles that will need migrating
432 * @param int $ns Destination namespace id
433 * @param string $name Prefix that is being made a namespace
434 * @param array $options Associative array of validated command-line options
436 * @return ResultWrapper
438 private function getTargetList( $ns, $name, $options ) {
439 if ( $options['move-talk'] && MWNamespace
::isSubject( $ns ) ) {
440 $checkNamespaces = [ NS_MAIN
, NS_TALK
];
442 $checkNamespaces = NS_MAIN
;
445 return $this->db
->select( 'page',
452 'page_namespace' => $checkNamespaces,
453 'page_title' . $this->db
->buildLike( "$name:", $this->db
->anyString() ),
460 * Get the preferred destination title for a given target page.
461 * @param integer $ns The destination namespace ID
462 * @param string $name The conflicting prefix
463 * @param integer $sourceNs The source namespace
464 * @param integer $sourceDbk The source DB key (i.e. page_title)
465 * @param array $options Associative array of validated command-line options
466 * @return Title|false
468 private function getDestinationTitle( $ns, $name, $sourceNs, $sourceDbk, $options ) {
469 $dbk = substr( $sourceDbk, strlen( "$name:" ) );
471 // An interwiki; try an alternate encoding with '-' for ':'
472 $dbk = "$name-" . $dbk;
475 if ( $sourceNs == NS_TALK
&& MWNamespace
::isSubject( $ns ) ) {
476 // This is an associated talk page moved with the --move-talk feature.
477 $destNS = MWNamespace
::getTalk( $destNS );
479 $newTitle = Title
::makeTitleSafe( $destNS, $dbk );
480 if ( !$newTitle ||
!$newTitle->canExist() ) {
487 * Get an alternative title to move a page to. This is used if the
488 * preferred destination title already exists.
490 * @param LinkTarget $linkTarget
491 * @param array $options Associative array of validated command-line options
494 private function getAlternateTitle( LinkTarget
$linkTarget, $options ) {
495 $prefix = $options['add-prefix'];
496 $suffix = $options['add-suffix'];
497 if ( $prefix == '' && $suffix == '' ) {
501 $dbk = $prefix . $linkTarget->getDBkey() . $suffix;
502 $title = Title
::makeTitleSafe( $linkTarget->getNamespace(), $dbk );
506 if ( !$title->exists() ) {
515 * @param integer $id The page_id
516 * @param LinkTarget $newLinkTarget The new title link target
519 private function movePage( $id, LinkTarget
$newLinkTarget ) {
520 $this->db
->update( 'page',
522 "page_namespace" => $newLinkTarget->getNamespace(),
523 "page_title" => $newLinkTarget->getDBkey(),
530 // Update *_from_namespace in links tables
531 $fromNamespaceTables = [
532 [ 'pagelinks', 'pl' ],
533 [ 'templatelinks', 'tl' ],
534 [ 'imagelinks', 'il' ] ];
535 foreach ( $fromNamespaceTables as $tableInfo ) {
536 list( $table, $fieldPrefix ) = $tableInfo;
537 $this->db
->update( $table,
539 [ "{$fieldPrefix}_from_namespace" => $newLinkTarget->getNamespace() ],
541 [ "{$fieldPrefix}_from" => $id ],
549 * Determine if we can merge a page.
550 * We check if an inaccessible revision would become the latest and
551 * deny the merge if so -- it's theoretically possible to update the
552 * latest revision, but opens a can of worms -- search engine updates,
553 * recentchanges review, etc.
555 * @param integer $id The page_id
556 * @param LinkTarget $linkTarget The new link target
557 * @param string $logStatus This is set to the log status message on failure
560 private function canMerge( $id, LinkTarget
$linkTarget, &$logStatus ) {
561 $latestDest = Revision
::newFromTitle( $linkTarget, 0, Revision
::READ_LATEST
);
562 $latestSource = Revision
::newFromPageId( $id, 0, Revision
::READ_LATEST
);
563 if ( $latestSource->getTimestamp() > $latestDest->getTimestamp() ) {
564 $logStatus = 'cannot merge since source is later';
572 * Merge page histories
574 * @param integer $id The page_id
575 * @param Title $newTitle The new title
578 private function mergePage( $row, Title
$newTitle ) {
581 // Construct the WikiPage object we will need later, while the
582 // page_id still exists. Note that this cannot use makeTitleSafe(),
583 // we are deliberately constructing an invalid title.
584 $sourceTitle = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
585 $sourceTitle->resetArticleID( $id );
586 $wikiPage = new WikiPage( $sourceTitle );
587 $wikiPage->loadPageData( 'fromdbmaster' );
589 $destId = $newTitle->getArticleID();
590 $this->beginTransaction( $this->db
, __METHOD__
);
591 $this->db
->update( 'revision',
593 [ 'rev_page' => $destId ],
595 [ 'rev_page' => $id ],
598 $this->db
->delete( 'page', [ 'page_id' => $id ], __METHOD__
);
600 $this->commitTransaction( $this->db
, __METHOD__
);
602 /* Call LinksDeletionUpdate to delete outgoing links from the old title,
603 * and update category counts.
605 * Calling external code with a fake broken Title is a fairly dubious
606 * idea. It's necessary because it's quite a lot of code to duplicate,
607 * but that also makes it fragile since it would be easy for someone to
608 * accidentally introduce an assumption of title validity to the code we
611 DeferredUpdates
::addUpdate( new LinksDeletionUpdate( $wikiPage ) );
612 DeferredUpdates
::doUpdates();
618 $maintClass = "NamespaceConflictChecker";
619 require_once RUN_MAINTENANCE_IF_MAIN
;