55 private $resolvablePages = 0;
61 private $totalPages = 0;
67 private $resolvableLinks = 0;
73 private $totalLinks = 0;
80 private $deletedLinks = 0;
83 parent::__construct();
84 $this->
addDescription(
'Find and fix pages affected by namespace addition/removal' );
85 $this->
addOption(
'fix',
'Attempt to automatically fix errors and delete broken links' );
86 $this->
addOption(
'merge',
"Instead of renaming conflicts, do a history merge with " .
87 "the correct title" );
88 $this->
addOption(
'add-suffix',
"Dupes will be renamed with correct namespace with " .
89 "<text> appended after the article name",
false,
true );
90 $this->
addOption(
'add-prefix',
"Dupes will be renamed with correct namespace with " .
91 "<text> prepended before the article name",
false,
true );
92 $this->
addOption(
'source-pseudo-namespace',
"Move all pages with the given source " .
93 "prefix (with an implied colon following it). If --dest-namespace is not specified, " .
94 "the colon will be replaced with a hyphen.",
96 $this->
addOption(
'dest-namespace',
"In combination with --source-pseudo-namespace, " .
97 "specify the namespace ID of the destination.",
false,
true );
98 $this->
addOption(
'move-talk',
"If this is specified, pages in the Talk namespace that " .
99 "begin with a conflicting prefix will be renamed, for example " .
100 "Talk:File:Foo -> File_Talk:Foo" );
107 'add-suffix' => $this->
getOption(
'add-suffix',
'' ),
108 'add-prefix' => $this->
getOption(
'add-prefix',
'' ),
109 'move-talk' => $this->
hasOption(
'move-talk' ),
110 'source-pseudo-namespace' => $this->
getOption(
'source-pseudo-namespace',
'' ),
111 'dest-namespace' => intval( $this->
getOption(
'dest-namespace', 0 ) )
114 if ( $options[
'source-pseudo-namespace'] !==
'' ) {
115 $retval = $this->checkPrefix( $options );
117 $retval = $this->checkAll( $options );
121 $this->
output(
"\nLooks good!\n" );
123 $this->
output(
"\nOh noeees\n" );
134 private function checkAll( $options ) {
140 foreach ( $this->getInterwikiList() as $prefix ) {
141 $name = $contLang->ucfirst( $prefix );
151 if ( $name !==
'' ) {
152 $spaces[$name] = $ns;
155 foreach ( $contLang->getNamespaces() as $ns => $name ) {
156 if ( $name !==
'' ) {
157 $spaces[$name] = $ns;
160 foreach ( $contLang->getNamespaceAliases() as $name => $ns ) {
161 $spaces[$name] = $ns;
166 $capitalLinks = $this->
getConfig()->get( MainConfigNames::CapitalLinks );
167 foreach ( $spaces as $name => $ns ) {
169 $moreNames[] = $contLang->uc( $name );
170 $moreNames[] = $contLang->ucfirst( $contLang->lc( $name ) );
171 $moreNames[] = $contLang->ucwords( $name );
172 $moreNames[] = $contLang->ucwords( $contLang->lc( $name ) );
173 $moreNames[] = $contLang->ucwordbreaks( $name );
174 $moreNames[] = $contLang->ucwordbreaks( $contLang->lc( $name ) );
175 if ( !$capitalLinks ) {
176 foreach ( $moreNames as $altName ) {
177 $moreNames[] = $contLang->lcfirst( $altName );
179 $moreNames[] = $contLang->lcfirst( $name );
181 foreach ( array_unique( $moreNames ) as $altName ) {
182 if ( $altName !== $name ) {
183 $spaces[$altName] = $ns;
190 $origSpaces = $spaces;
191 uksort( $spaces,
static function ( $a, $b ) use ( $origSpaces ) {
192 return $origSpaces[$a] <=> $origSpaces[$b]
197 foreach ( $spaces as $name => $ns ) {
198 $ok = $this->checkNamespace( $ns, $name, $options ) && $ok;
202 "{$this->totalPages} pages to fix, " .
203 "{$this->resolvablePages} were resolvable.\n\n"
206 foreach ( $spaces as $name => $ns ) {
225 $this->checkLinkTable(
'pagelinks',
'pl', $ns, $name, $options );
226 $this->checkLinkTable(
'templatelinks',
'tl', $ns, $name, $options );
232 $this->checkLinkTable(
'redirect',
'rd', $ns, $name, $options,
233 [
'rd_interwiki' =>
'' ] );
238 "{$this->totalLinks} links to fix, " .
239 "{$this->resolvableLinks} were resolvable, " .
240 "{$this->deletedLinks} were deleted.\n"
249 private function getInterwikiList() {
251 return array_column( $result,
'iw_prefix' );
262 private function checkNamespace( $ns, $name, $options ) {
263 $targets = $this->getTargetList( $ns, $name, $options );
264 $count = $targets->numRows();
265 $this->totalPages += $count;
270 $dryRunNote = $options[
'fix'] ?
'' :
' DRY RUN ONLY';
273 foreach ( $targets as $row ) {
276 $newTitle = $this->getDestinationTitle(
277 $ns, $name, $row->page_namespace, $row->page_title );
280 if ( $options[
'add-prefix'] ==
'' && $options[
'add-suffix'] ==
'' ) {
281 $logStatus =
'invalid title and --add-prefix not specified';
284 $action =
'alternate';
286 } elseif ( $newTitle->
exists( IDBAccessObject::READ_LATEST ) ) {
287 if ( $options[
'merge'] ) {
288 if ( $this->canMerge( $row->page_id, $newTitle, $logStatus ) ) {
293 } elseif ( $options[
'add-prefix'] ==
'' && $options[
'add-suffix'] ==
'' ) {
295 $logStatus =
'dest title exists and --add-prefix not specified';
297 $action =
'alternate';
301 $logStatus =
'no conflict';
303 if ( $action ===
'alternate' ) {
304 [ $ns, $dbk ] = $this->getDestination( $ns, $name, $row->page_namespace,
306 $newTitle = $this->getAlternateTitle( $ns, $dbk, $options );
309 $logStatus =
'alternate title is invalid';
310 } elseif ( $newTitle->
exists() ) {
312 $logStatus =
'alternate title conflicts';
315 $logStatus =
'alternate';
321 $logTitle =
"id={$row->page_id} ns={$row->page_namespace} dbk={$row->page_title}";
326 $this->
output(
"$logTitle *** $logStatus\n" );
330 $this->
output(
"$logTitle -> " .
333 if ( $options[
'fix'] ) {
334 $pageOK = $this->movePage( $row->page_id, $newTitle );
338 $this->
output(
"$logTitle => " .
341 if ( $options[
'fix'] ) {
342 $pageOK = $this->mergePage( $row, $newTitle );
348 $this->resolvablePages++;
366 private function checkLinkTable( $table, $fieldPrefix, $ns, $name, $options,
372 $fromField =
"{$fieldPrefix}_from";
374 $sqb = $dbw->newSelectQueryBuilder()
375 ->select( $fromField )
376 ->where( $extraConds )
377 ->limit( $batchSize );
380 if ( isset( $linksMigration::$mapping[$table] ) ) {
381 $sqb->queryInfo( $linksMigration->getQueryInfo( $table ) );
382 [ $namespaceField, $titleField ] = $linksMigration->getTitleFields( $table );
383 $schemaMigrationStage = $linksMigration::$mapping[$table][
'config'] === -1
385 : $this->
getConfig()->get( $linksMigration::$mapping[$table][
'config'] );
387 $targetIdField = $linksMigration::$mapping[$table][
'target_id'];
389 $sqb->table( $table );
390 $namespaceField =
"{$fieldPrefix}_namespace";
391 $titleField =
"{$fieldPrefix}_title";
392 $sqb->fields( [ $namespaceField, $titleField ] );
394 $schemaMigrationStage = -1;
395 $linkTargetLookup =
null;
399 $namespaceField => 0,
400 $dbw->expr( $titleField, IExpression::LIKE,
new LikeValue(
"$name:", $dbw->anyString() ) ),
402 ->orderBy( [ $titleField, $fromField ] )
403 ->caller( __METHOD__ );
405 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
407 $res = ( clone $sqb )
408 ->andWhere( $batchConds )
410 if ( $res->numRows() == 0 ) {
414 $rowsToDeleteIfStillExists = [];
416 foreach ( $res as $row ) {
417 $logTitle =
"from={$row->$fromField} ns={$row->$namespaceField} " .
418 "dbk={$row->$titleField}";
419 $destTitle = $this->getDestinationTitle(
420 $ns, $name, $row->$namespaceField, $row->$titleField );
423 $this->
output(
"$table $logTitle *** INVALID\n" );
426 $this->resolvableLinks++;
427 if ( !$options[
'fix'] ) {
428 $this->
output(
"$table $logTitle -> " .
429 $destTitle->getPrefixedDBkey() .
" DRY RUN\n" );
433 if ( isset( $linksMigration::$mapping[$table] ) ) {
436 $setValue[$targetIdField] = $linkTargetLookup->acquireLinkTargetId( $destTitle, $dbw );
439 $setValue[
"{$fieldPrefix}_namespace"] = $destTitle->getNamespace();
440 $setValue[
"{$fieldPrefix}_title"] = $destTitle->getDBkey();
442 $whereCondition = $linksMigration->getLinksConditions(
446 $deleteCondition = $linksMigration->getLinksConditions(
448 new TitleValue( (
int)$row->$namespaceField, $row->$titleField )
452 $namespaceField => $destTitle->getNamespace(),
453 $titleField => $destTitle->getDBkey()
456 $namespaceField => 0,
457 $titleField => $row->$titleField
460 $namespaceField => $row->$namespaceField,
461 $titleField => $row->$titleField,
465 $dbw->newUpdateQueryBuilder()
469 ->where( [ $fromField => $row->$fromField ] )
470 ->andWhere( $whereCondition )
471 ->caller( __METHOD__ )
475 $rowsToDeleteIfStillExists[] = array_merge( [ $fromField => $row->$fromField ], $deleteCondition );
477 $this->
output(
"$table $logTitle -> " .
478 $destTitle->getPrefixedDBkey() .
"\n"
482 if ( $options[
'fix'] && count( $rowsToDeleteIfStillExists ) > 0 ) {
484 $deleteBatches = array_chunk( $rowsToDeleteIfStillExists, $updateRowsPerQuery );
485 foreach ( $deleteBatches as $deleteBatch ) {
486 $dbw->newDeleteQueryBuilder()
487 ->deleteFrom( $table )
488 ->where( $dbw->factorConds( $deleteBatch ) )
489 ->caller( __METHOD__ )
491 $affectedRows += $dbw->affectedRows();
492 if ( count( $deleteBatches ) > 1 ) {
497 $this->deletedLinks += $affectedRows;
498 $this->resolvableLinks -= $affectedRows;
502 $dbw->buildComparison(
'>', [
504 $titleField => $row->$titleField,
506 $fromField => $row->$fromField,
521 private function checkPrefix( $options ) {
522 $prefix = $options[
'source-pseudo-namespace'];
523 $ns = $options[
'dest-namespace'];
524 $this->
output(
"Checking prefix \"$prefix\" vs namespace $ns\n" );
526 return $this->checkNamespace( $ns, $prefix, $options );
539 private function getTargetList( $ns, $name, $options ) {
543 $options[
'move-talk'] &&
551 return $dbw->newSelectQueryBuilder()
552 ->select( [
'page_id',
'page_title',
'page_namespace' ] )
555 'page_namespace' => $checkNamespaces,
556 $dbw->expr(
'page_title', IExpression::LIKE,
new LikeValue(
"$name:", $dbw->anyString() ) ),
558 ->caller( __METHOD__ )->fetchResultSet();
569 private function getDestination( $ns, $name, $sourceNs, $sourceDbk ) {
570 $dbk = substr( $sourceDbk, strlen(
"$name:" ) );
574 $dbk =
"$name-" . $dbk;
579 if ( $sourceNs ==
NS_TALK && $nsInfo->isSubject( $ns ) ) {
581 $destNS = $nsInfo->getTalk( $destNS );
583 return [ $destNS, $dbk ];
594 private function getDestinationTitle( $ns, $name, $sourceNs, $sourceDbk ) {
595 [ $destNS, $dbk ] = $this->getDestination( $ns, $name, $sourceNs, $sourceDbk );
596 $newTitle = Title::makeTitleSafe( $destNS, $dbk );
597 if ( !$newTitle || !$newTitle->
canExist() ) {
612 private function getAlternateTitle( $ns, $dbk, $options ) {
613 $prefix = $options[
'add-prefix'];
614 $suffix = $options[
'add-suffix'];
615 if ( $prefix ==
'' && $suffix ==
'' ) {
618 $newDbk = $prefix . $dbk . $suffix;
619 return Title::makeTitleSafe( $ns, $newDbk );
629 private function movePage( $id,
LinkTarget $newLinkTarget ) {
632 $dbw->newUpdateQueryBuilder()
636 "page_title" => $newLinkTarget->
getDBkey(),
641 ->caller( __METHOD__ )
645 $fromNamespaceTables = [
646 [
'templatelinks',
'tl', [
'tl_target_id' ] ],
647 [
'imagelinks',
'il', [
'il_to' ] ]
650 $fromNamespaceTables[] = [
'pagelinks',
'pl', [
'pl_namespace',
'pl_title' ] ];
652 $fromNamespaceTables[] = [
'pagelinks',
'pl', [
'pl_target_id' ] ];
654 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
655 foreach ( $fromNamespaceTables as [ $table, $fieldPrefix, $additionalPrimaryKeyFields ] ) {
656 $fromField =
"{$fieldPrefix}_from";
657 $fromNamespaceField =
"{$fieldPrefix}_from_namespace";
659 $res = $dbw->newSelectQueryBuilder()
660 ->select( $additionalPrimaryKeyFields )
662 ->where( [ $fromField => $id ] )
663 ->andWhere( $dbw->expr( $fromNamespaceField,
'!=', $newLinkTarget->
getNamespace() ) )
664 ->caller( __METHOD__ )
671 foreach ( $res as $row ) {
672 $updateConds[] = array_merge( [ $fromField => $id ], (array)$row );
674 $updateBatches = array_chunk( $updateConds, $updateRowsPerQuery );
675 foreach ( $updateBatches as $updateBatch ) {
677 $dbw->newUpdateQueryBuilder()
679 ->set( [ $fromNamespaceField => $newLinkTarget->
getNamespace() ] )
680 ->where( $dbw->factorConds( $updateBatch ) )
681 ->caller( __METHOD__ )
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 ) {
724 $updateRowsPerQuery = $this->
getConfig()->get( MainConfigNames::UpdateRowsPerQuery );
731 $sourceTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
732 $sourceTitle->resetArticleID( $id );
733 $wikiPage = $this->
getServiceContainer()->getWikiPageFactory()->newFromTitle( $sourceTitle );
734 $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__ )
775 DeferredUpdates::doUpdates();