51 private $resolvablePages = 0;
57 private $totalPages = 0;
63 private $resolvableLinks = 0;
69 private $totalLinks = 0;
76 private $deletedLinks = 0;
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.",
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" );
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 $this->
fatalError(
"Unsafe to run at this time. See: T364546\n" );
115 if ( $options[
'source-pseudo-namespace'] !==
'' ) {
116 $retval = $this->checkPrefix( $options );
118 $retval = $this->checkAll( $options );
122 $this->
output(
"\nLooks good!\n" );
124 $this->
output(
"\nOh noeees\n" );
135 private function checkAll( $options ) {
141 foreach ( $this->getInterwikiList() as $prefix ) {
142 $name = $contLang->ucfirst( $prefix );
152 if ( $name !==
'' ) {
153 $spaces[$name] = $ns;
156 foreach ( $contLang->getNamespaces() as $ns => $name ) {
157 if ( $name !==
'' ) {
158 $spaces[$name] = $ns;
161 foreach ( $contLang->getNamespaceAliases() as $name => $ns ) {
162 $spaces[$name] = $ns;
167 $capitalLinks = $this->
getConfig()->get( MainConfigNames::CapitalLinks );
168 foreach ( $spaces as $name => $ns ) {
170 $moreNames[] = $contLang->uc( $name );
171 $moreNames[] = $contLang->ucfirst( $contLang->lc( $name ) );
172 $moreNames[] = $contLang->ucwords( $name );
173 $moreNames[] = $contLang->ucwords( $contLang->lc( $name ) );
174 $moreNames[] = $contLang->ucwordbreaks( $name );
175 $moreNames[] = $contLang->ucwordbreaks( $contLang->lc( $name ) );
176 if ( !$capitalLinks ) {
177 foreach ( $moreNames as $altName ) {
178 $moreNames[] = $contLang->lcfirst( $altName );
180 $moreNames[] = $contLang->lcfirst( $name );
182 foreach ( array_unique( $moreNames ) as $altName ) {
183 if ( $altName !== $name ) {
184 $spaces[$altName] = $ns;
191 $origSpaces = $spaces;
192 uksort( $spaces,
static function ( $a, $b ) use ( $origSpaces ) {
193 return $origSpaces[$a] <=> $origSpaces[$b]
198 foreach ( $spaces as $name => $ns ) {
199 $ok = $this->checkNamespace( $ns, $name, $options ) && $ok;
203 "{$this->totalPages} pages to fix, " .
204 "{$this->resolvablePages} were resolvable.\n\n"
207 foreach ( $spaces as $name => $ns ) {
226 $this->checkLinkTable(
'pagelinks',
'pl', $ns, $name, $options );
227 $this->checkLinkTable(
'templatelinks',
'tl', $ns, $name, $options );
233 $this->checkLinkTable(
'redirect',
'rd', $ns, $name, $options,
234 [
'rd_interwiki' =>
'' ] );
239 "{$this->totalLinks} links to fix, " .
240 "{$this->resolvableLinks} were resolvable, " .
241 "{$this->deletedLinks} were deleted.\n"
250 private function getInterwikiList() {
252 return array_column( $result,
'iw_prefix' );
263 private function checkNamespace( $ns, $name, $options ) {
264 $targets = $this->getTargetList( $ns, $name, $options );
265 $count = $targets->numRows();
266 $this->totalPages += $count;
271 $dryRunNote = $options[
'fix'] ?
'' :
' DRY RUN ONLY';
274 foreach ( $targets as $row ) {
277 $newTitle = $this->getDestinationTitle(
278 $ns, $name, $row->page_namespace, $row->page_title );
281 if ( $options[
'add-prefix'] ==
'' && $options[
'add-suffix'] ==
'' ) {
282 $logStatus =
'invalid title and --add-prefix not specified';
285 $action =
'alternate';
287 } elseif ( $newTitle->
exists() ) {
288 if ( $options[
'merge'] ) {
289 if ( $this->canMerge( $row->page_id, $newTitle, $logStatus ) ) {
294 } elseif ( $options[
'add-prefix'] ==
'' && $options[
'add-suffix'] ==
'' ) {
296 $logStatus =
'dest title exists and --add-prefix not specified';
298 $action =
'alternate';
302 $logStatus =
'no conflict';
304 if ( $action ===
'alternate' ) {
305 [ $ns, $dbk ] = $this->getDestination( $ns, $name, $row->page_namespace,
307 $newTitle = $this->getAlternateTitle( $ns, $dbk, $options );
310 $logStatus =
'alternate title is invalid';
311 } elseif ( $newTitle->
exists() ) {
313 $logStatus =
'alternate title conflicts';
316 $logStatus =
'alternate';
322 $logTitle =
"id={$row->page_id} ns={$row->page_namespace} dbk={$row->page_title}";
327 $this->
output(
"$logTitle *** $logStatus\n" );
331 $this->
output(
"$logTitle -> " .
334 if ( $options[
'fix'] ) {
335 $pageOK = $this->movePage( $row->page_id, $newTitle );
339 $this->
output(
"$logTitle => " .
342 if ( $options[
'fix'] ) {
343 $pageOK = $this->mergePage( $row, $newTitle );
349 $this->resolvablePages++;
367 private function checkLinkTable( $table, $fieldPrefix, $ns, $name, $options,
373 $fromField =
"{$fieldPrefix}_from";
375 $sqb = $dbw->newSelectQueryBuilder()
376 ->select( $fromField )
377 ->where( $extraConds )
378 ->limit( $batchSize );
381 if ( isset( $linksMigration::$mapping[$table] ) ) {
382 $sqb->queryInfo( $linksMigration->getQueryInfo( $table ) );
383 [ $namespaceField, $titleField ] = $linksMigration->getTitleFields( $table );
384 $schemaMigrationStage = $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:" ) );
572 $dbk =
"$name-" . $dbk;
576 if ( $sourceNs ==
NS_TALK && $nsInfo->isSubject( $ns ) ) {
578 $destNS = $nsInfo->getTalk( $destNS );
580 return [ $destNS, $dbk ];
591 private function getDestinationTitle( $ns, $name, $sourceNs, $sourceDbk ) {
592 [ $destNS, $dbk ] = $this->getDestination( $ns, $name, $sourceNs, $sourceDbk );
593 $newTitle = Title::makeTitleSafe( $destNS, $dbk );
594 if ( !$newTitle || !$newTitle->
canExist() ) {
609 private function getAlternateTitle( $ns, $dbk, $options ) {
610 $prefix = $options[
'add-prefix'];
611 $suffix = $options[
'add-suffix'];
612 if ( $prefix ==
'' && $suffix ==
'' ) {
615 $newDbk = $prefix . $dbk . $suffix;
616 return Title::makeTitleSafe( $ns, $newDbk );
626 private function movePage( $id,
LinkTarget $newLinkTarget ) {
629 $dbw->newUpdateQueryBuilder()
633 "page_title" => $newLinkTarget->
getDBkey(),
638 ->caller( __METHOD__ )
642 $fromNamespaceTables = [
643 [
'pagelinks',
'pl', [
'pl_namespace',
'pl_title' ] ],
644 [
'templatelinks',
'tl', [
'tl_target_id' ] ],
645 [
'imagelinks',
'il', [
'il_to' ] ]
647 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
648 foreach ( $fromNamespaceTables as [ $table, $fieldPrefix, $additionalPrimaryKeyFields ] ) {
649 $fromField =
"{$fieldPrefix}_from";
650 $fromNamespaceField =
"{$fieldPrefix}_from_namespace";
652 $res = $dbw->newSelectQueryBuilder()
653 ->select( $additionalPrimaryKeyFields )
655 ->where( [ $fromField => $id ] )
656 ->andWhere( $dbw->expr( $fromNamespaceField,
'!=', $newLinkTarget->
getNamespace() ) )
657 ->caller( __METHOD__ )
664 foreach ( $res as $row ) {
665 $updateConds[] = array_merge( [ $fromField => $id ], (array)$row );
667 $updateBatches = array_chunk( $updateConds, $updateRowsPerQuery );
668 foreach ( $updateBatches as $updateBatch ) {
669 $dbw->newUpdateQueryBuilder()
671 ->set( [ $fromNamespaceField => $newLinkTarget->
getNamespace() ] )
672 ->where( $dbw->factorConds( $updateBatch ) )
673 ->caller( __METHOD__ )
675 if ( count( $updateBatches ) > 1 ) {
696 private function canMerge( $id,
LinkTarget $linkTarget, &$logStatus ) {
698 $latestDest = $revisionLookup->getRevisionByTitle( $linkTarget, 0,
699 IDBAccessObject::READ_LATEST );
700 $latestSource = $revisionLookup->getRevisionByPageId( $id, 0,
701 IDBAccessObject::READ_LATEST );
702 if ( $latestSource->getTimestamp() > $latestDest->getTimestamp() ) {
703 $logStatus =
'cannot merge since source is later';
717 private function mergePage( $row,
Title $newTitle ) {
719 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
726 $sourceTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
727 $sourceTitle->resetArticleID( $id );
728 $wikiPage = $this->
getServiceContainer()->getWikiPageFactory()->newFromTitle( $sourceTitle );
729 $wikiPage->loadPageData( IDBAccessObject::READ_LATEST );
733 $revIds = $dbw->newSelectQueryBuilder()
736 ->where( [
'rev_page' => $id ] )
737 ->caller( __METHOD__ )
738 ->fetchFieldValues();
739 $updateBatches = array_chunk( array_map(
'intval', $revIds ), $updateRowsPerQuery );
740 foreach ( $updateBatches as $updateBatch ) {
741 $dbw->newUpdateQueryBuilder()
742 ->update(
'revision' )
743 ->set( [
'rev_page' => $destId ] )
744 ->where( [
'rev_id' => $updateBatch ] )
745 ->caller( __METHOD__ )
747 if ( count( $updateBatches ) > 1 ) {
752 $dbw->newDeleteQueryBuilder()
753 ->deleteFrom(
'page' )
754 ->where( [
'page_id' => $id ] )
755 ->caller( __METHOD__ )
770 DeferredUpdates::doUpdates();