54 private $resolvablePages = 0;
60 private $totalPages = 0;
66 private $resolvableLinks = 0;
72 private $totalLinks = 0;
79 private $deletedLinks = 0;
82 parent::__construct();
83 $this->
addDescription(
'Find and fix pages affected by namespace addition/removal' );
84 $this->
addOption(
'fix',
'Attempt to automatically fix errors and delete broken links' );
85 $this->
addOption(
'merge',
"Instead of renaming conflicts, do a history merge with " .
86 "the correct title" );
87 $this->
addOption(
'add-suffix',
"Dupes will be renamed with correct namespace with " .
88 "<text> appended after the article name",
false,
true );
89 $this->
addOption(
'add-prefix',
"Dupes will be renamed with correct namespace with " .
90 "<text> prepended before the article name",
false,
true );
91 $this->
addOption(
'source-pseudo-namespace',
"Move all pages with the given source " .
92 "prefix (with an implied colon following it). If --dest-namespace is not specified, " .
93 "the colon will be replaced with a hyphen.",
95 $this->
addOption(
'dest-namespace',
"In combination with --source-pseudo-namespace, " .
96 "specify the namespace ID of the destination.",
false,
true );
97 $this->
addOption(
'move-talk',
"If this is specified, pages in the Talk namespace that " .
98 "begin with a conflicting prefix will be renamed, for example " .
99 "Talk:File:Foo -> File_Talk:Foo" );
106 'add-suffix' => $this->
getOption(
'add-suffix',
'' ),
107 'add-prefix' => $this->
getOption(
'add-prefix',
'' ),
108 'move-talk' => $this->
hasOption(
'move-talk' ),
109 'source-pseudo-namespace' => $this->
getOption(
'source-pseudo-namespace',
'' ),
110 'dest-namespace' => intval( $this->
getOption(
'dest-namespace', 0 ) )
113 if ( $options[
'source-pseudo-namespace'] !==
'' ) {
114 $retval = $this->checkPrefix( $options );
116 $retval = $this->checkAll( $options );
120 $this->
output(
"\nLooks good!\n" );
122 $this->
output(
"\nOh noeees\n" );
133 private function checkAll( $options ) {
139 foreach ( $this->getInterwikiList() as $prefix ) {
140 $name = $contLang->ucfirst( $prefix );
150 if ( $name !==
'' ) {
151 $spaces[$name] = $ns;
154 foreach ( $contLang->getNamespaces() as $ns => $name ) {
155 if ( $name !==
'' ) {
156 $spaces[$name] = $ns;
159 foreach ( $contLang->getNamespaceAliases() as $name => $ns ) {
160 $spaces[$name] = $ns;
165 $capitalLinks = $this->
getConfig()->get( MainConfigNames::CapitalLinks );
166 foreach ( $spaces as $name => $ns ) {
168 $moreNames[] = $contLang->uc( $name );
169 $moreNames[] = $contLang->ucfirst( $contLang->lc( $name ) );
170 $moreNames[] = $contLang->ucwords( $name );
171 $moreNames[] = $contLang->ucwords( $contLang->lc( $name ) );
172 $moreNames[] = $contLang->ucwordbreaks( $name );
173 $moreNames[] = $contLang->ucwordbreaks( $contLang->lc( $name ) );
174 if ( !$capitalLinks ) {
175 foreach ( $moreNames as $altName ) {
176 $moreNames[] = $contLang->lcfirst( $altName );
178 $moreNames[] = $contLang->lcfirst( $name );
180 foreach ( array_unique( $moreNames ) as $altName ) {
181 if ( $altName !== $name ) {
182 $spaces[$altName] = $ns;
189 $origSpaces = $spaces;
190 uksort( $spaces,
static function ( $a, $b ) use ( $origSpaces ) {
191 return $origSpaces[$a] <=> $origSpaces[$b]
196 foreach ( $spaces as $name => $ns ) {
197 $ok = $this->checkNamespace( $ns, $name, $options ) && $ok;
201 "{$this->totalPages} pages to fix, " .
202 "{$this->resolvablePages} were resolvable.\n\n"
205 foreach ( $spaces as $name => $ns ) {
224 $this->checkLinkTable(
'pagelinks',
'pl', $ns, $name, $options );
225 $this->checkLinkTable(
'templatelinks',
'tl', $ns, $name, $options );
231 $this->checkLinkTable(
'redirect',
'rd', $ns, $name, $options,
232 [
'rd_interwiki' =>
'' ] );
237 "{$this->totalLinks} links to fix, " .
238 "{$this->resolvableLinks} were resolvable, " .
239 "{$this->deletedLinks} were deleted.\n"
248 private function getInterwikiList() {
250 return array_column( $result,
'iw_prefix' );
261 private function checkNamespace( $ns, $name, $options ) {
262 $targets = $this->getTargetList( $ns, $name, $options );
263 $count = $targets->numRows();
264 $this->totalPages += $count;
269 $dryRunNote = $options[
'fix'] ?
'' :
' DRY RUN ONLY';
272 foreach ( $targets as $row ) {
275 $newTitle = $this->getDestinationTitle(
276 $ns, $name, $row->page_namespace, $row->page_title );
279 if ( $options[
'add-prefix'] ==
'' && $options[
'add-suffix'] ==
'' ) {
280 $logStatus =
'invalid title and --add-prefix not specified';
283 $action =
'alternate';
285 } elseif ( $newTitle->
exists( IDBAccessObject::READ_LATEST ) ) {
286 if ( $options[
'merge'] ) {
287 if ( $this->canMerge( $row->page_id, $newTitle, $logStatus ) ) {
292 } elseif ( $options[
'add-prefix'] ==
'' && $options[
'add-suffix'] ==
'' ) {
294 $logStatus =
'dest title exists and --add-prefix not specified';
296 $action =
'alternate';
300 $logStatus =
'no conflict';
302 if ( $action ===
'alternate' ) {
303 [ $ns, $dbk ] = $this->getDestination( $ns, $name, $row->page_namespace,
305 $newTitle = $this->getAlternateTitle( $ns, $dbk, $options );
308 $logStatus =
'alternate title is invalid';
309 } elseif ( $newTitle->
exists() ) {
311 $logStatus =
'alternate title conflicts';
314 $logStatus =
'alternate';
320 $logTitle =
"id={$row->page_id} ns={$row->page_namespace} dbk={$row->page_title}";
325 $this->
output(
"$logTitle *** $logStatus\n" );
329 $this->
output(
"$logTitle -> " .
332 if ( $options[
'fix'] ) {
333 $pageOK = $this->movePage( $row->page_id, $newTitle );
337 $this->
output(
"$logTitle => " .
340 if ( $options[
'fix'] ) {
341 $pageOK = $this->mergePage( $row, $newTitle );
347 $this->resolvablePages++;
365 private function checkLinkTable( $table, $fieldPrefix, $ns, $name, $options,
371 $fromField =
"{$fieldPrefix}_from";
373 $sqb = $dbw->newSelectQueryBuilder()
374 ->select( $fromField )
375 ->where( $extraConds )
376 ->limit( $batchSize );
379 if ( isset( $linksMigration::$mapping[$table] ) ) {
380 $sqb->queryInfo( $linksMigration->getQueryInfo( $table ) );
381 [ $namespaceField, $titleField ] = $linksMigration->getTitleFields( $table );
382 $schemaMigrationStage = $linksMigration::$mapping[$table][
'config'] === -1
384 : $this->
getConfig()->get( $linksMigration::$mapping[$table][
'config'] );
386 $targetIdField = $linksMigration::$mapping[$table][
'target_id'];
388 $sqb->table( $table );
389 $namespaceField =
"{$fieldPrefix}_namespace";
390 $titleField =
"{$fieldPrefix}_title";
391 $sqb->fields( [ $namespaceField, $titleField ] );
393 $schemaMigrationStage = -1;
394 $linkTargetLookup =
null;
398 $namespaceField => 0,
399 $dbw->expr( $titleField, IExpression::LIKE,
new LikeValue(
"$name:", $dbw->anyString() ) ),
401 ->orderBy( [ $titleField, $fromField ] )
402 ->caller( __METHOD__ );
404 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
406 $res = ( clone $sqb )
407 ->andWhere( $batchConds )
409 if ( $res->numRows() == 0 ) {
413 $rowsToDeleteIfStillExists = [];
415 foreach ( $res as $row ) {
416 $logTitle =
"from={$row->$fromField} ns={$row->$namespaceField} " .
417 "dbk={$row->$titleField}";
418 $destTitle = $this->getDestinationTitle(
419 $ns, $name, $row->$namespaceField, $row->$titleField );
422 $this->
output(
"$table $logTitle *** INVALID\n" );
425 $this->resolvableLinks++;
426 if ( !$options[
'fix'] ) {
427 $this->
output(
"$table $logTitle -> " .
428 $destTitle->getPrefixedDBkey() .
" DRY RUN\n" );
432 if ( isset( $linksMigration::$mapping[$table] ) ) {
435 $setValue[$targetIdField] = $linkTargetLookup->acquireLinkTargetId( $destTitle, $dbw );
438 $setValue[
"{$fieldPrefix}_namespace"] = $destTitle->getNamespace();
439 $setValue[
"{$fieldPrefix}_title"] = $destTitle->getDBkey();
441 $whereCondition = $linksMigration->getLinksConditions(
445 $deleteCondition = $linksMigration->getLinksConditions(
447 new TitleValue( (
int)$row->$namespaceField, $row->$titleField )
451 $namespaceField => $destTitle->getNamespace(),
452 $titleField => $destTitle->getDBkey()
455 $namespaceField => 0,
456 $titleField => $row->$titleField
459 $namespaceField => $row->$namespaceField,
460 $titleField => $row->$titleField,
464 $dbw->newUpdateQueryBuilder()
468 ->where( [ $fromField => $row->$fromField ] )
469 ->andWhere( $whereCondition )
470 ->caller( __METHOD__ )
474 $rowsToDeleteIfStillExists[] = array_merge( [ $fromField => $row->$fromField ], $deleteCondition );
476 $this->
output(
"$table $logTitle -> " .
477 $destTitle->getPrefixedDBkey() .
"\n"
481 if ( $options[
'fix'] && count( $rowsToDeleteIfStillExists ) > 0 ) {
483 $deleteBatches = array_chunk( $rowsToDeleteIfStillExists, $updateRowsPerQuery );
484 foreach ( $deleteBatches as $deleteBatch ) {
485 $dbw->newDeleteQueryBuilder()
486 ->deleteFrom( $table )
487 ->where( $dbw->factorConds( $deleteBatch ) )
488 ->caller( __METHOD__ )
490 $affectedRows += $dbw->affectedRows();
491 if ( count( $deleteBatches ) > 1 ) {
496 $this->deletedLinks += $affectedRows;
497 $this->resolvableLinks -= $affectedRows;
501 $dbw->buildComparison(
'>', [
503 $titleField => $row->$titleField,
505 $fromField => $row->$fromField,
520 private function checkPrefix( $options ) {
521 $prefix = $options[
'source-pseudo-namespace'];
522 $ns = $options[
'dest-namespace'];
523 $this->
output(
"Checking prefix \"$prefix\" vs namespace $ns\n" );
525 return $this->checkNamespace( $ns, $prefix, $options );
538 private function getTargetList( $ns, $name, $options ) {
542 $options[
'move-talk'] &&
550 return $dbw->newSelectQueryBuilder()
551 ->select( [
'page_id',
'page_title',
'page_namespace' ] )
554 'page_namespace' => $checkNamespaces,
555 $dbw->expr(
'page_title', IExpression::LIKE,
new LikeValue(
"$name:", $dbw->anyString() ) ),
557 ->caller( __METHOD__ )->fetchResultSet();
568 private function getDestination( $ns, $name, $sourceNs, $sourceDbk ) {
569 $dbk = substr( $sourceDbk, strlen(
"$name:" ) );
573 $dbk =
"$name-" . $dbk;
578 if ( $sourceNs ==
NS_TALK && $nsInfo->isSubject( $ns ) ) {
580 $destNS = $nsInfo->getTalk( $destNS );
582 return [ $destNS, $dbk ];
593 private function getDestinationTitle( $ns, $name, $sourceNs, $sourceDbk ) {
594 [ $destNS, $dbk ] = $this->getDestination( $ns, $name, $sourceNs, $sourceDbk );
595 $newTitle = Title::makeTitleSafe( $destNS, $dbk );
596 if ( !$newTitle || !$newTitle->
canExist() ) {
611 private function getAlternateTitle( $ns, $dbk, $options ) {
612 $prefix = $options[
'add-prefix'];
613 $suffix = $options[
'add-suffix'];
614 if ( $prefix ==
'' && $suffix ==
'' ) {
617 $newDbk = $prefix . $dbk . $suffix;
618 return Title::makeTitleSafe( $ns, $newDbk );
628 private function movePage( $id,
LinkTarget $newLinkTarget ) {
631 $dbw->newUpdateQueryBuilder()
635 "page_title" => $newLinkTarget->
getDBkey(),
640 ->caller( __METHOD__ )
644 $fromNamespaceTables = [
645 [
'templatelinks',
'tl', [
'tl_target_id' ] ],
646 [
'imagelinks',
'il', [
'il_to' ] ]
649 $fromNamespaceTables[] = [
'pagelinks',
'pl', [
'pl_namespace',
'pl_title' ] ];
651 $fromNamespaceTables[] = [
'pagelinks',
'pl', [
'pl_target_id' ] ];
653 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
654 foreach ( $fromNamespaceTables as [ $table, $fieldPrefix, $additionalPrimaryKeyFields ] ) {
655 $fromField =
"{$fieldPrefix}_from";
656 $fromNamespaceField =
"{$fieldPrefix}_from_namespace";
658 $res = $dbw->newSelectQueryBuilder()
659 ->select( $additionalPrimaryKeyFields )
661 ->where( [ $fromField => $id ] )
662 ->andWhere( $dbw->expr( $fromNamespaceField,
'!=', $newLinkTarget->
getNamespace() ) )
663 ->caller( __METHOD__ )
670 foreach ( $res as $row ) {
671 $updateConds[] = array_merge( [ $fromField => $id ], (array)$row );
673 $updateBatches = array_chunk( $updateConds, $updateRowsPerQuery );
674 foreach ( $updateBatches as $updateBatch ) {
675 $dbw->newUpdateQueryBuilder()
677 ->set( [ $fromNamespaceField => $newLinkTarget->
getNamespace() ] )
678 ->where( $dbw->factorConds( $updateBatch ) )
679 ->caller( __METHOD__ )
681 if ( count( $updateBatches ) > 1 ) {
702 private function canMerge( $id,
LinkTarget $linkTarget, &$logStatus ) {
704 $latestDest = $revisionLookup->getRevisionByTitle( $linkTarget, 0,
705 IDBAccessObject::READ_LATEST );
706 $latestSource = $revisionLookup->getRevisionByPageId( $id, 0,
707 IDBAccessObject::READ_LATEST );
708 if ( $latestSource->getTimestamp() > $latestDest->getTimestamp() ) {
709 $logStatus =
'cannot merge since source is later';
723 private function mergePage( $row,
Title $newTitle ) {
725 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
732 $sourceTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
733 $sourceTitle->resetArticleID( $id );
734 $wikiPage = $this->
getServiceContainer()->getWikiPageFactory()->newFromTitle( $sourceTitle );
735 $wikiPage->loadPageData( IDBAccessObject::READ_LATEST );
739 $revIds = $dbw->newSelectQueryBuilder()
742 ->where( [
'rev_page' => $id ] )
743 ->caller( __METHOD__ )
744 ->fetchFieldValues();
745 $updateBatches = array_chunk( array_map(
'intval', $revIds ), $updateRowsPerQuery );
746 foreach ( $updateBatches as $updateBatch ) {
747 $dbw->newUpdateQueryBuilder()
748 ->update(
'revision' )
749 ->set( [
'rev_page' => $destId ] )
750 ->where( [
'rev_id' => $updateBatch ] )
751 ->caller( __METHOD__ )
753 if ( count( $updateBatches ) > 1 ) {
758 $dbw->newDeleteQueryBuilder()
759 ->deleteFrom(
'page' )
760 ->where( [
'page_id' => $id ] )
761 ->caller( __METHOD__ )
776 DeferredUpdates::doUpdates();