Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 387
0.00% covered (danger)
0.00%
0 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
NamespaceDupes
0.00% covered (danger)
0.00%
0 / 384
0.00% covered (danger)
0.00%
0 / 14
6806
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 checkAll
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
306
 getInterwikiList
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 checkNamespace
0.00% covered (danger)
0.00%
0 / 61
0.00% covered (danger)
0.00%
0 / 1
462
 checkLinkTable
0.00% covered (danger)
0.00%
0 / 111
0.00% covered (danger)
0.00%
0 / 1
210
 checkPrefix
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getTargetList
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 getDestination
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 getDestinationTitle
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 getAlternateTitle
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 movePage
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
42
 canMerge
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 mergePage
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * Check for articles to fix after adding/deleting namespaces
4 *
5 * Copyright © 2005-2007 Brooke Vibber <bvibber@wikimedia.org>
6 * https://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @ingroup Maintenance
25 */
26
27require_once __DIR__ . '/Maintenance.php';
28
29use MediaWiki\Deferred\DeferredUpdates;
30use MediaWiki\Deferred\LinksUpdate\LinksDeletionUpdate;
31use MediaWiki\Linker\LinkTarget;
32use MediaWiki\MainConfigNames;
33use MediaWiki\Title\Title;
34use MediaWiki\Title\TitleValue;
35use Wikimedia\Rdbms\IExpression;
36use Wikimedia\Rdbms\IResultWrapper;
37use Wikimedia\Rdbms\LikeValue;
38
39/**
40 * Maintenance script that checks for articles to fix after
41 * adding/deleting namespaces.
42 *
43 * @ingroup Maintenance
44 */
45class NamespaceDupes extends Maintenance {
46
47    /**
48     * Total number of pages that need fixing that are automatically resolveable
49     * @var int
50     */
51    private $resolvablePages = 0;
52
53    /**
54     * Total number of pages that need fixing
55     * @var int
56     */
57    private $totalPages = 0;
58
59    /**
60     * Total number of links that need fixing that are automatically resolveable
61     * @var int
62     */
63    private $resolvableLinks = 0;
64
65    /**
66     * Total number of erroneous links
67     * @var int
68     */
69    private $totalLinks = 0;
70
71    /**
72     * Total number of links deleted because they weren't automatically resolveable due to the
73     * target already existing
74     * @var int
75     */
76    private $deletedLinks = 0;
77
78    public function __construct() {
79        parent::__construct();
80        $this->addDescription( 'Find and fix pages affected by namespace addition/removal' );
81        $this->addOption( 'fix', 'Attempt to automatically fix errors and delete broken links' );
82        $this->addOption( 'merge', "Instead of renaming conflicts, do a history merge with " .
83            "the correct title" );
84        $this->addOption( 'add-suffix', "Dupes will be renamed with correct namespace with " .
85            "<text> appended after the article name", false, true );
86        $this->addOption( 'add-prefix', "Dupes will be renamed with correct namespace with " .
87            "<text> prepended before the article name", false, true );
88        $this->addOption( 'source-pseudo-namespace', "Move all pages with the given source " .
89            "prefix (with an implied colon following it). If --dest-namespace is not specified, " .
90            "the colon will be replaced with a hyphen.",
91            false, true );
92        $this->addOption( 'dest-namespace', "In combination with --source-pseudo-namespace, " .
93            "specify the namespace ID of the destination.", false, true );
94        $this->addOption( 'move-talk', "If this is specified, pages in the Talk namespace that " .
95            "begin with a conflicting prefix will be renamed, for example " .
96            "Talk:File:Foo -> File_Talk:Foo" );
97    }
98
99    public function execute() {
100        $options = [
101            'fix' => $this->hasOption( 'fix' ),
102            'merge' => $this->hasOption( 'merge' ),
103            'add-suffix' => $this->getOption( 'add-suffix', '' ),
104            'add-prefix' => $this->getOption( 'add-prefix', '' ),
105            'move-talk' => $this->hasOption( 'move-talk' ),
106            'source-pseudo-namespace' => $this->getOption( 'source-pseudo-namespace', '' ),
107            'dest-namespace' => intval( $this->getOption( 'dest-namespace', 0 ) )
108        ];
109
110        if ( $options['source-pseudo-namespace'] !== '' ) {
111            $retval = $this->checkPrefix( $options );
112        } else {
113            $retval = $this->checkAll( $options );
114        }
115
116        if ( $retval ) {
117            $this->output( "\nLooks good!\n" );
118        } else {
119            $this->output( "\nOh noeees\n" );
120        }
121    }
122
123    /**
124     * Check all namespaces
125     *
126     * @param array $options Associative array of validated command-line options
127     *
128     * @return bool
129     */
130    private function checkAll( $options ) {
131        $contLang = $this->getServiceContainer()->getContentLanguage();
132        $spaces = [];
133
134        // List interwikis first, so they'll be overridden
135        // by any conflicting local namespaces.
136        foreach ( $this->getInterwikiList() as $prefix ) {
137            $name = $contLang->ucfirst( $prefix );
138            $spaces[$name] = 0;
139        }
140
141        // Now pull in all canonical and alias namespaces...
142        foreach (
143            $this->getServiceContainer()->getNamespaceInfo()->getCanonicalNamespaces()
144            as $ns => $name
145        ) {
146            // This includes $wgExtraNamespaces
147            if ( $name !== '' ) {
148                $spaces[$name] = $ns;
149            }
150        }
151        foreach ( $contLang->getNamespaces() as $ns => $name ) {
152            if ( $name !== '' ) {
153                $spaces[$name] = $ns;
154            }
155        }
156        foreach ( $contLang->getNamespaceAliases() as $name => $ns ) {
157            $spaces[$name] = $ns;
158        }
159
160        // We'll need to check for lowercase keys as well,
161        // since we're doing case-sensitive searches in the db.
162        $capitalLinks = $this->getConfig()->get( MainConfigNames::CapitalLinks );
163        foreach ( $spaces as $name => $ns ) {
164            $moreNames = [];
165            $moreNames[] = $contLang->uc( $name );
166            $moreNames[] = $contLang->ucfirst( $contLang->lc( $name ) );
167            $moreNames[] = $contLang->ucwords( $name );
168            $moreNames[] = $contLang->ucwords( $contLang->lc( $name ) );
169            $moreNames[] = $contLang->ucwordbreaks( $name );
170            $moreNames[] = $contLang->ucwordbreaks( $contLang->lc( $name ) );
171            if ( !$capitalLinks ) {
172                foreach ( $moreNames as $altName ) {
173                    $moreNames[] = $contLang->lcfirst( $altName );
174                }
175                $moreNames[] = $contLang->lcfirst( $name );
176            }
177            foreach ( array_unique( $moreNames ) as $altName ) {
178                if ( $altName !== $name ) {
179                    $spaces[$altName] = $ns;
180                }
181            }
182        }
183
184        // Sort by namespace index, and if there are two with the same index,
185        // break the tie by sorting by name
186        $origSpaces = $spaces;
187        uksort( $spaces, static function ( $a, $b ) use ( $origSpaces ) {
188            return $origSpaces[$a] <=> $origSpaces[$b]
189                ?: $a <=> $b;
190        } );
191
192        $ok = true;
193        foreach ( $spaces as $name => $ns ) {
194            $ok = $this->checkNamespace( $ns, $name, $options ) && $ok;
195        }
196
197        $this->output(
198            "{$this->totalPages} pages to fix, " .
199            "{$this->resolvablePages} were resolvable.\n\n"
200        );
201
202        foreach ( $spaces as $name => $ns ) {
203            if ( $ns != 0 ) {
204                /* Fix up link destinations for non-interwiki links only.
205                 *
206                 * For example if a page has [[Foo:Bar]] and then a Foo namespace
207                 * is introduced, pagelinks needs to be updated to have
208                 * page_namespace = NS_FOO.
209                 *
210                 * If instead an interwiki prefix was introduced called "Foo",
211                 * the link should instead be moved to the iwlinks table. If a new
212                 * language is introduced called "Foo", or if there is a pagelink
213                 * [[fr:Bar]] when interlanguage magic links are turned on, the
214                 * link would have to be moved to the langlinks table. Let's put
215                 * those cases in the too-hard basket for now. The consequences are
216                 * not especially severe.
217                 * @fixme Handle interwiki links, and pagelinks to Category:, File:
218                 * which probably need reparsing.
219                 */
220
221                $this->checkLinkTable( 'pagelinks', 'pl', $ns, $name, $options );
222                $this->checkLinkTable( 'templatelinks', 'tl', $ns, $name, $options );
223
224                // The redirect table has interwiki links randomly mixed in, we
225                // need to filter those out. For example [[w:Foo:Bar]] would
226                // have rd_interwiki=w and rd_namespace=0, which would match the
227                // query for a conflicting namespace "Foo" if filtering wasn't done.
228                $this->checkLinkTable( 'redirect', 'rd', $ns, $name, $options,
229                    [ 'rd_interwiki' => '' ] );
230            }
231        }
232
233        $this->output(
234            "{$this->totalLinks} links to fix, " .
235            "{$this->resolvableLinks} were resolvable, " .
236            "{$this->deletedLinks} were deleted.\n"
237        );
238
239        return $ok;
240    }
241
242    /**
243     * @return string[]
244     */
245    private function getInterwikiList() {
246        $result = $this->getServiceContainer()->getInterwikiLookup()->getAllPrefixes();
247        return array_column( $result, 'iw_prefix' );
248    }
249
250    /**
251     * Check a given prefix and try to move it into the given destination namespace
252     *
253     * @param int $ns Destination namespace id
254     * @param string $name
255     * @param array $options Associative array of validated command-line options
256     * @return bool
257     */
258    private function checkNamespace( $ns, $name, $options ) {
259        $targets = $this->getTargetList( $ns, $name, $options );
260        $count = $targets->numRows();
261        $this->totalPages += $count;
262        if ( $count == 0 ) {
263            return true;
264        }
265
266        $dryRunNote = $options['fix'] ? '' : ' DRY RUN ONLY';
267
268        $ok = true;
269        foreach ( $targets as $row ) {
270            // Find the new title and determine the action to take
271
272            $newTitle = $this->getDestinationTitle(
273                $ns, $name, $row->page_namespace, $row->page_title );
274            $logStatus = false;
275            if ( !$newTitle ) {
276                if ( $options['add-prefix'] == '' && $options['add-suffix'] == '' ) {
277                    $logStatus = 'invalid title and --add-prefix not specified';
278                    $action = 'abort';
279                } else {
280                    $action = 'alternate';
281                }
282            } elseif ( $newTitle->exists() ) {
283                if ( $options['merge'] ) {
284                    if ( $this->canMerge( $row->page_id, $newTitle, $logStatus ) ) {
285                        $action = 'merge';
286                    } else {
287                        $action = 'abort';
288                    }
289                } elseif ( $options['add-prefix'] == '' && $options['add-suffix'] == '' ) {
290                    $action = 'abort';
291                    $logStatus = 'dest title exists and --add-prefix not specified';
292                } else {
293                    $action = 'alternate';
294                }
295            } else {
296                $action = 'move';
297                $logStatus = 'no conflict';
298            }
299            if ( $action === 'alternate' ) {
300                [ $ns, $dbk ] = $this->getDestination( $ns, $name, $row->page_namespace,
301                    $row->page_title );
302                $newTitle = $this->getAlternateTitle( $ns, $dbk, $options );
303                if ( !$newTitle ) {
304                    $action = 'abort';
305                    $logStatus = 'alternate title is invalid';
306                } elseif ( $newTitle->exists() ) {
307                    $action = 'abort';
308                    $logStatus = 'alternate title conflicts';
309                } else {
310                    $action = 'move';
311                    $logStatus = 'alternate';
312                }
313            }
314
315            // Take the action or log a dry run message
316
317            $logTitle = "id={$row->page_id} ns={$row->page_namespace} dbk={$row->page_title}";
318            $pageOK = true;
319
320            switch ( $action ) {
321                case 'abort':
322                    $this->output( "$logTitle *** $logStatus\n" );
323                    $pageOK = false;
324                    break;
325                case 'move':
326                    $this->output( "$logTitle -> " .
327                        $newTitle->getPrefixedDBkey() . " ($logStatus)$dryRunNote\n" );
328
329                    if ( $options['fix'] ) {
330                        $pageOK = $this->movePage( $row->page_id, $newTitle );
331                    }
332                    break;
333                case 'merge':
334                    $this->output( "$logTitle => " .
335                        $newTitle->getPrefixedDBkey() . " (merge)$dryRunNote\n" );
336
337                    if ( $options['fix'] ) {
338                        $pageOK = $this->mergePage( $row, $newTitle );
339                    }
340                    break;
341            }
342
343            if ( $pageOK ) {
344                $this->resolvablePages++;
345            } else {
346                $ok = false;
347            }
348        }
349
350        return $ok;
351    }
352
353    /**
354     * Check and repair the destination fields in a link table
355     * @param string $table The link table name
356     * @param string $fieldPrefix The field prefix in the link table
357     * @param int $ns Destination namespace id
358     * @param string $name
359     * @param array $options Associative array of validated command-line options
360     * @param array $extraConds Extra conditions for the SQL query
361     */
362    private function checkLinkTable( $table, $fieldPrefix, $ns, $name, $options,
363        $extraConds = []
364    ) {
365        $dbw = $this->getPrimaryDB();
366
367        $batchConds = [];
368        $fromField = "{$fieldPrefix}_from";
369        $batchSize = 100;
370        $sqb = $dbw->newSelectQueryBuilder()
371            ->select( $fromField )
372            ->where( $extraConds )
373            ->limit( $batchSize );
374
375        $linksMigration = $this->getServiceContainer()->getLinksMigration();
376        if ( isset( $linksMigration::$mapping[$table] ) ) {
377            $sqb->queryInfo( $linksMigration->getQueryInfo( $table ) );
378            [ $namespaceField, $titleField ] = $linksMigration->getTitleFields( $table );
379            $schemaMigrationStage = $this->getConfig()->get( $linksMigration::$mapping[$table]['config'] );
380            $linkTargetLookup = $this->getServiceContainer()->getLinkTargetLookup();
381            $targetIdField = $linksMigration::$mapping[$table]['target_id'];
382        } else {
383            $sqb->table( $table );
384            $namespaceField = "{$fieldPrefix}_namespace";
385            $titleField = "{$fieldPrefix}_title";
386            $sqb->fields( [ $namespaceField, $titleField ] );
387            // Variables only used for links migration, init only
388            $schemaMigrationStage = -1;
389            $linkTargetLookup = null;
390            $targetIdField = '';
391        }
392        $sqb->andWhere( [
393                $namespaceField => 0,
394                $dbw->expr( $titleField, IExpression::LIKE, new LikeValue( "$name:", $dbw->anyString() ) ),
395            ] )
396            ->orderBy( [ $titleField, $fromField ] )
397            ->caller( __METHOD__ );
398
399        $updateRowsPerQuery = $this->getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
400        while ( true ) {
401            $res = ( clone $sqb )
402                ->andWhere( $batchConds )
403                ->fetchResultSet();
404            if ( $res->numRows() == 0 ) {
405                break;
406            }
407
408            $rowsToDeleteIfStillExists = [];
409
410            foreach ( $res as $row ) {
411                $logTitle = "from={$row->$fromField} ns={$row->$namespaceField} " .
412                    "dbk={$row->$titleField}";
413                $destTitle = $this->getDestinationTitle(
414                    $ns, $name, $row->$namespaceField, $row->$titleField );
415                $this->totalLinks++;
416                if ( !$destTitle ) {
417                    $this->output( "$table $logTitle *** INVALID\n" );
418                    continue;
419                }
420                $this->resolvableLinks++;
421                if ( !$options['fix'] ) {
422                    $this->output( "$table $logTitle -> " .
423                        $destTitle->getPrefixedDBkey() . " DRY RUN\n" );
424                    continue;
425                }
426
427                if ( isset( $linksMigration::$mapping[$table] ) ) {
428                    $setValue = [];
429                    if ( $schemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
430                        $setValue[$targetIdField] = $linkTargetLookup->acquireLinkTargetId( $destTitle, $dbw );
431                    }
432                    if ( $schemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
433                        $setValue["{$fieldPrefix}_namespace"] = $destTitle->getNamespace();
434                        $setValue["{$fieldPrefix}_title"] = $destTitle->getDBkey();
435                    }
436                    $whereCondition = $linksMigration->getLinksConditions(
437                        $table,
438                        new TitleValue( 0, $row->$titleField )
439                    );
440                    $deleteCondition = $linksMigration->getLinksConditions(
441                        $table,
442                        new TitleValue( (int)$row->$namespaceField, $row->$titleField )
443                    );
444                } else {
445                    $setValue = [
446                        $namespaceField => $destTitle->getNamespace(),
447                        $titleField => $destTitle->getDBkey()
448                    ];
449                    $whereCondition = [
450                        $namespaceField => 0,
451                        $titleField => $row->$titleField
452                    ];
453                    $deleteCondition = [
454                        $namespaceField => $row->$namespaceField,
455                        $titleField => $row->$titleField,
456                    ];
457                }
458
459                $dbw->newUpdateQueryBuilder()
460                    ->update( $table )
461                    ->ignore()
462                    ->set( $setValue )
463                    ->where( [ $fromField => $row->$fromField ] )
464                    ->andWhere( $whereCondition )
465                    ->caller( __METHOD__ )
466                    ->execute();
467
468                // In case there is a key conflict on UPDATE IGNORE the row needs deletion
469                $rowsToDeleteIfStillExists[] = array_merge( [ $fromField => $row->$fromField ], $deleteCondition );
470
471                $this->output( "$table $logTitle -> " .
472                    $destTitle->getPrefixedDBkey() . "\n"
473                );
474            }
475
476            if ( $options['fix'] && count( $rowsToDeleteIfStillExists ) > 0 ) {
477                $affectedRows = 0;
478                $deleteBatches = array_chunk( $rowsToDeleteIfStillExists, $updateRowsPerQuery );
479                foreach ( $deleteBatches as $deleteBatch ) {
480                    $dbw->newDeleteQueryBuilder()
481                        ->deleteFrom( $table )
482                        ->where( $dbw->factorConds( $deleteBatch ) )
483                        ->caller( __METHOD__ )
484                        ->execute();
485                    $affectedRows += $dbw->affectedRows();
486                    if ( count( $deleteBatches ) > 1 ) {
487                        $this->waitForReplication();
488                    }
489                }
490
491                $this->deletedLinks += $affectedRows;
492                $this->resolvableLinks -= $affectedRows;
493            }
494
495            $batchConds = [
496                $dbw->buildComparison( '>', [
497                    // @phan-suppress-next-line PhanPossiblyUndeclaredVariable rows contains at least one item
498                    $titleField => $row->$titleField,
499                    // @phan-suppress-next-line PhanPossiblyUndeclaredVariable rows contains at least one item
500                    $fromField => $row->$fromField,
501                ] )
502            ];
503
504            $this->waitForReplication();
505        }
506    }
507
508    /**
509     * Move the given pseudo-namespace, either replacing the colon with a hyphen
510     * (useful for pseudo-namespaces that conflict with interwiki links) or move
511     * them to another namespace if specified.
512     * @param array $options Associative array of validated command-line options
513     * @return bool
514     */
515    private function checkPrefix( $options ) {
516        $prefix = $options['source-pseudo-namespace'];
517        $ns = $options['dest-namespace'];
518        $this->output( "Checking prefix \"$prefix\" vs namespace $ns\n" );
519
520        return $this->checkNamespace( $ns, $prefix, $options );
521    }
522
523    /**
524     * Find pages in main and talk namespaces that have a prefix of the new
525     * namespace so we know titles that will need migrating
526     *
527     * @param int $ns Destination namespace id
528     * @param string $name Prefix that is being made a namespace
529     * @param array $options Associative array of validated command-line options
530     *
531     * @return IResultWrapper
532     */
533    private function getTargetList( $ns, $name, $options ) {
534        $dbw = $this->getPrimaryDB();
535
536        if (
537            $options['move-talk'] &&
538            $this->getServiceContainer()->getNamespaceInfo()->isSubject( $ns )
539        ) {
540            $checkNamespaces = [ NS_MAIN, NS_TALK ];
541        } else {
542            $checkNamespaces = NS_MAIN;
543        }
544
545        return $dbw->newSelectQueryBuilder()
546            ->select( [ 'page_id', 'page_title', 'page_namespace' ] )
547            ->from( 'page' )
548            ->where( [
549                'page_namespace' => $checkNamespaces,
550                $dbw->expr( 'page_title', IExpression::LIKE, new LikeValue( "$name:", $dbw->anyString() ) ),
551            ] )
552            ->caller( __METHOD__ )->fetchResultSet();
553    }
554
555    /**
556     * Get the preferred destination for a given target page.
557     * @param int $ns The destination namespace ID
558     * @param string $name The conflicting prefix
559     * @param int $sourceNs The source namespace
560     * @param string $sourceDbk The source DB key (i.e. page_title)
561     * @return array [ ns, dbkey ], not necessarily valid
562     */
563    private function getDestination( $ns, $name, $sourceNs, $sourceDbk ) {
564        $dbk = substr( $sourceDbk, strlen( "$name:" ) );
565        if ( $ns == 0 ) {
566            // An interwiki; try an alternate encoding with '-' for ':'
567            $dbk = "$name-" . $dbk;
568        }
569        $destNS = $ns;
570        $nsInfo = $this->getServiceContainer()->getNamespaceInfo();
571        if ( $sourceNs == NS_TALK && $nsInfo->isSubject( $ns ) ) {
572            // This is an associated talk page moved with the --move-talk feature.
573            $destNS = $nsInfo->getTalk( $destNS );
574        }
575        return [ $destNS, $dbk ];
576    }
577
578    /**
579     * Get the preferred destination title for a given target page.
580     * @param int $ns The destination namespace ID
581     * @param string $name The conflicting prefix
582     * @param int $sourceNs The source namespace
583     * @param string $sourceDbk The source DB key (i.e. page_title)
584     * @return Title|false
585     */
586    private function getDestinationTitle( $ns, $name, $sourceNs, $sourceDbk ) {
587        [ $destNS, $dbk ] = $this->getDestination( $ns, $name, $sourceNs, $sourceDbk );
588        $newTitle = Title::makeTitleSafe( $destNS, $dbk );
589        if ( !$newTitle || !$newTitle->canExist() ) {
590            return false;
591        }
592        return $newTitle;
593    }
594
595    /**
596     * Get an alternative title to move a page to. This is used if the
597     * preferred destination title already exists.
598     *
599     * @param int $ns The destination namespace ID
600     * @param string $dbk The source DB key (i.e. page_title)
601     * @param array $options Associative array of validated command-line options
602     * @return Title|false
603     */
604    private function getAlternateTitle( $ns, $dbk, $options ) {
605        $prefix = $options['add-prefix'];
606        $suffix = $options['add-suffix'];
607        if ( $prefix == '' && $suffix == '' ) {
608            return false;
609        }
610        $newDbk = $prefix . $dbk . $suffix;
611        return Title::makeTitleSafe( $ns, $newDbk );
612    }
613
614    /**
615     * Move a page
616     *
617     * @param int $id The page_id
618     * @param LinkTarget $newLinkTarget The new title link target
619     * @return bool
620     */
621    private function movePage( $id, LinkTarget $newLinkTarget ) {
622        $dbw = $this->getPrimaryDB();
623
624        $dbw->newUpdateQueryBuilder()
625            ->update( 'page' )
626            ->set( [
627                "page_namespace" => $newLinkTarget->getNamespace(),
628                "page_title" => $newLinkTarget->getDBkey(),
629            ] )
630            ->where( [
631                "page_id" => $id,
632            ] )
633            ->caller( __METHOD__ )
634            ->execute();
635
636        // Update *_from_namespace in links tables
637        $fromNamespaceTables = [
638            [ 'pagelinks', 'pl', [ 'pl_namespace', 'pl_title' ] ],
639            [ 'templatelinks', 'tl', [ 'tl_target_id' ] ],
640            [ 'imagelinks', 'il', [ 'il_to' ] ]
641        ];
642        $updateRowsPerQuery = $this->getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
643        foreach ( $fromNamespaceTables as [ $table, $fieldPrefix, $additionalPrimaryKeyFields ] ) {
644            $fromField = "{$fieldPrefix}_from";
645            $fromNamespaceField = "{$fieldPrefix}_from_namespace";
646
647            $res = $dbw->newSelectQueryBuilder()
648                ->select( $additionalPrimaryKeyFields )
649                ->from( $table )
650                ->where( [ $fromField => $id ] )
651                ->andWhere( $dbw->expr( $fromNamespaceField, '!=', $newLinkTarget->getNamespace() ) )
652                ->caller( __METHOD__ )
653                ->fetchResultSet();
654            if ( !$res ) {
655                continue;
656            }
657
658            $updateConds = [];
659            foreach ( $res as $row ) {
660                $updateConds[] = array_merge( [ $fromField => $id ], (array)$row );
661            }
662            $updateBatches = array_chunk( $updateConds, $updateRowsPerQuery );
663            foreach ( $updateBatches as $updateBatch ) {
664                $dbw->newUpdateQueryBuilder()
665                    ->update( $table )
666                    ->set( [ $fromNamespaceField => $newLinkTarget->getNamespace() ] )
667                    ->where( $dbw->factorConds( $updateBatch ) )
668                    ->caller( __METHOD__ )
669                    ->execute();
670                if ( count( $updateBatches ) > 1 ) {
671                    $this->waitForReplication();
672                }
673            }
674        }
675
676        return true;
677    }
678
679    /**
680     * Determine if we can merge a page.
681     * We check if an inaccessible revision would become the latest and
682     * deny the merge if so -- it's theoretically possible to update the
683     * latest revision, but opens a can of worms -- search engine updates,
684     * recentchanges review, etc.
685     *
686     * @param int $id The page_id
687     * @param LinkTarget $linkTarget The new link target
688     * @param string &$logStatus This is set to the log status message on failure @phan-output-reference
689     * @return bool
690     */
691    private function canMerge( $id, LinkTarget $linkTarget, &$logStatus ) {
692        $revisionLookup = $this->getServiceContainer()->getRevisionLookup();
693        $latestDest = $revisionLookup->getRevisionByTitle( $linkTarget, 0,
694            IDBAccessObject::READ_LATEST );
695        $latestSource = $revisionLookup->getRevisionByPageId( $id, 0,
696            IDBAccessObject::READ_LATEST );
697        if ( $latestSource->getTimestamp() > $latestDest->getTimestamp() ) {
698            $logStatus = 'cannot merge since source is later';
699            return false;
700        } else {
701            return true;
702        }
703    }
704
705    /**
706     * Merge page histories
707     *
708     * @param stdClass $row Page row
709     * @param Title $newTitle
710     * @return bool
711     */
712    private function mergePage( $row, Title $newTitle ) {
713        $dbw = $this->getPrimaryDB();
714        $updateRowsPerQuery = $this->getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
715
716        $id = $row->page_id;
717
718        // Construct the WikiPage object we will need later, while the
719        // page_id still exists. Note that this cannot use makeTitleSafe(),
720        // we are deliberately constructing an invalid title.
721        $sourceTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
722        $sourceTitle->resetArticleID( $id );
723        $wikiPage = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $sourceTitle );
724        $wikiPage->loadPageData( IDBAccessObject::READ_LATEST );
725
726        $destId = $newTitle->getArticleID();
727        $this->beginTransaction( $dbw, __METHOD__ );
728        $revIds = $dbw->newSelectQueryBuilder()
729            ->select( 'rev_id' )
730            ->from( 'revision' )
731            ->where( [ 'rev_page' => $id ] )
732            ->caller( __METHOD__ )
733            ->fetchFieldValues();
734        $updateBatches = array_chunk( array_map( 'intval', $revIds ), $updateRowsPerQuery );
735        foreach ( $updateBatches as $updateBatch ) {
736            $dbw->newUpdateQueryBuilder()
737                ->update( 'revision' )
738                ->set( [ 'rev_page' => $destId ] )
739                ->where( [ 'rev_id' => $updateBatch ] )
740                ->caller( __METHOD__ )
741                ->execute();
742            if ( count( $updateBatches ) > 1 ) {
743                $this->waitForReplication();
744            }
745        }
746
747        $dbw->newDeleteQueryBuilder()
748            ->deleteFrom( 'page' )
749            ->where( [ 'page_id' => $id ] )
750            ->caller( __METHOD__ )
751            ->execute();
752
753        $this->commitTransaction( $dbw, __METHOD__ );
754
755        /* Call LinksDeletionUpdate to delete outgoing links from the old title,
756         * and update category counts.
757         *
758         * Calling external code with a fake broken Title is a fairly dubious
759         * idea. It's necessary because it's quite a lot of code to duplicate,
760         * but that also makes it fragile since it would be easy for someone to
761         * accidentally introduce an assumption of title validity to the code we
762         * are calling.
763         */
764        DeferredUpdates::addUpdate( new LinksDeletionUpdate( $wikiPage ) );
765        DeferredUpdates::doUpdates();
766
767        return true;
768    }
769}
770
771$maintClass = NamespaceDupes::class;
772require_once RUN_MAINTENANCE_IF_MAIN;