Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
72.78% covered (warning)
72.78%
115 / 158
16.67% covered (danger)
16.67%
1 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
TitleCleanup
72.78% covered (warning)
72.78%
115 / 158
16.67% covered (danger)
16.67%
1 / 6
97.40
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 execute
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
5.20
 processRow
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
8.07
 fileExists
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
6
 moveIllegalPage
76.27% covered (warning)
76.27%
45 / 59
0.00% covered (danger)
0.00%
0 / 1
20.86
 moveInconsistentPage
89.80% covered (warning)
89.80%
44 / 49
0.00% covered (danger)
0.00%
0 / 1
16.27
1<?php
2/**
3 * Clean up broken, unparseable titles.
4 *
5 * Copyright © 2005 Brooke Vibber <bvibber@wikimedia.org>
6 * https://www.mediawiki.org/
7 *
8 * @license GPL-2.0-or-later
9 * @file
10 * @author Brooke Vibber <bvibber@wikimedia.org>
11 * @ingroup Maintenance
12 */
13
14use MediaWiki\MainConfigNames;
15use MediaWiki\Title\Title;
16use Wikimedia\Rdbms\IDBAccessObject;
17
18// @codeCoverageIgnoreStart
19require_once __DIR__ . '/TableCleanup.php';
20// @codeCoverageIgnoreEnd
21
22/**
23 * Maintenance script to clean up broken, unparseable titles.
24 *
25 * @ingroup Maintenance
26 */
27class TitleCleanup extends TableCleanup {
28
29    private string $prefix;
30
31    public function __construct() {
32        parent::__construct();
33        $this->addDescription( 'Script to clean up broken, unparseable titles' );
34        $this->addOption( 'prefix', "Broken pages will be renamed to titles with  " .
35            "<prefix> prepended before the article name. Defaults to 'Broken'", false, true );
36        $this->setBatchSize( 1000 );
37    }
38
39    /**
40     * @inheritDoc
41     */
42    public function execute() {
43        $this->prefix = $this->getOption( 'prefix', 'Broken' ) . "/";
44        // Make sure the prefix itself is a valid title now
45        // rather than spewing errors for every page being cleaned up
46        // if it's not (We assume below that concatenating the prefix to a title leaves it in NS0)
47        // The trailing slash above ensures that concatenating the title to something
48        // can't turn it into a namespace or interwiki
49        $title = Title::newFromText( $this->prefix );
50        if ( !$title || !$title->canExist() || $title->getInterwiki() || $title->getNamespace() !== 0 ) {
51            $this->fatalError( "Invalid prefix {$this->prefix}. Must be a valid mainspace title." );
52        }
53        parent::execute();
54    }
55
56    /**
57     * @param stdClass $row
58     */
59    protected function processRow( $row ) {
60        $display = Title::makeName( $row->page_namespace, $row->page_title );
61        $verified = $this->getServiceContainer()->getContentLanguage()->normalize( $display );
62        $title = Title::newFromText( $verified );
63
64        if ( $title !== null
65            && $title->canExist()
66            && $title->getNamespace() == $row->page_namespace
67            && $title->getDBkey() === $row->page_title
68        ) {
69            // all is fine
70            $this->progress( 0 );
71
72            return;
73        }
74
75        if ( $row->page_namespace == NS_FILE && $this->fileExists( $row->page_title ) ) {
76            $this->output( "file $row->page_title needs cleanup, please run cleanupImages.php.\n" );
77            $this->progress( 0 );
78        } elseif ( $title === null ) {
79            $this->output( "page $row->page_id ($display) is illegal.\n" );
80            $this->moveIllegalPage( $row );
81            $this->progress( 1 );
82        } else {
83            $this->output( "page $row->page_id ($display) doesn't match self.\n" );
84            $this->moveInconsistentPage( $row, $title );
85            $this->progress( 1 );
86        }
87    }
88
89    /**
90     * @param string $name
91     * @return bool
92     */
93    protected function fileExists( $name ) {
94        // XXX: Doesn't actually check for file existence, just presence of image/file record.
95        // This is reasonable, since cleanupImages.php only iterates over the image/file table.
96        $dbr = $this->getReplicaDB();
97        $migrationStage = $this->getServiceContainer()->getMainConfig()->get(
98            MainConfigNames::FileSchemaMigrationStage
99        );
100        if ( $migrationStage & SCHEMA_COMPAT_READ_OLD ) {
101            $row = $dbr->newSelectQueryBuilder()
102                ->select( '*' )
103                ->from( 'image' )
104                ->where( [ 'img_name' => $name ] )
105                ->caller( __METHOD__ )
106                ->fetchRow();
107        } else {
108            $row = $dbr->newSelectQueryBuilder()
109                ->select( '*' )
110                ->from( 'file' )
111                ->where( [
112                    'file_name' => $name,
113                    'file_deleted' => 0,
114                ] )
115                ->caller( __METHOD__ )
116                ->fetchRow();
117        }
118
119        return $row !== false;
120    }
121
122    /**
123     * @param stdClass $row
124     */
125    protected function moveIllegalPage( $row ) {
126        $legalChars = Title::legalChars();
127        $legalizedUnprefixed = preg_replace_callback( "/([^$legalChars])/",
128            $this->hexChar( ... ),
129            $row->page_title );
130        if ( $legalizedUnprefixed == '.' ) {
131            $legalizedUnprefixed = '(dot)';
132        }
133        if ( $legalizedUnprefixed == '_' ) {
134            $legalizedUnprefixed = '(space)';
135        }
136        $ns = (int)$row->page_namespace;
137
138        $title = null;
139        // Try to move "Talk:Project:Foo" -> "Project talk:Foo"
140        if ( $ns === 1 ) {
141            $subjectTitle = Title::newFromText( $legalizedUnprefixed );
142            if ( $subjectTitle && !$subjectTitle->isTalkPage() ) {
143                $talkTitle = $subjectTitle->getTalkPageIfDefined();
144                if ( $talkTitle !== null && !$talkTitle->exists() ) {
145                    $ns = $talkTitle->getNamespace();
146                    $title = $talkTitle;
147                }
148            }
149        }
150
151        if ( $title === null ) {
152            // Not a talk page or that didn't work
153            // move any other broken pages to the main namespace so they can be found together
154            if ( $ns !== 0 ) {
155                $namespaceInfo = $this->getServiceContainer()->getNamespaceInfo();
156                $namespaceName = $namespaceInfo->getCanonicalName( $ns );
157                if ( $namespaceName === false ) {
158                    $namespaceName = "NS$ns"; // Fallback for unknown namespaces
159                }
160                $ns = 0;
161                $legalizedUnprefixed = "$namespaceName:$legalizedUnprefixed";
162            }
163            $title = Title::newFromText( $this->prefix . $legalizedUnprefixed );
164        }
165
166        if ( $title === null ) {
167            // It's still not a valid title, try again with a much smaller
168            // allowed character set. This will mangle any titles with non-ASCII
169            // characters, but if we don't do this the result will be
170            // falling back to the Broken/id:foo failsafe below which is worse
171            $legalizedUnprefixed = preg_replace_callback( '!([^A-Za-z0-9_:\\-])!',
172                $this->hexChar( ... ),
173                $legalizedUnprefixed
174            );
175            $title = Title::newFromText( $this->prefix . $legalizedUnprefixed );
176        }
177
178        if ( $title === null ) {
179            // Oh well, we tried
180            $clean = $this->prefix . 'id:' . $row->page_id;
181            $legalized = $this->prefix . $legalizedUnprefixed;
182            $this->output( "Couldn't legalize; form '$legalized' still invalid; using '$clean'\n" );
183            $title = Title::newFromText( $clean );
184        } elseif ( $title->exists( IDBAccessObject::READ_LATEST ) ) {
185            $clean = $this->prefix . 'id:' . $row->page_id;
186            $conflict = $title->getDBKey();
187            $this->output( "Legalized for '$conflict' exists; using '$clean'\n" );
188            $title = Title::newFromText( $clean );
189        }
190
191        if ( !$title || $title->exists( IDBAccessObject::READ_LATEST ) ) {
192            // This can happen in corner cases like if numbers are made not valid
193            // title characters using the (deprecated) $wgLegalTitleChars or
194            // a 'Broken/id:foo' title already exists
195            $this->error( "Destination page {$title->getText()} is invalid or already exists, skipping." );
196            return;
197        }
198
199        $dest = $title->getDBkey();
200        if ( $this->dryrun ) {
201            $this->output( "DRY RUN: would rename $row->page_id ($row->page_namespace," .
202                "'$row->page_title') to ($ns,'$dest')\n" );
203        } else {
204            $this->output( "renaming $row->page_id ($row->page_namespace," .
205                "'$row->page_title') to ($ns,'$dest')\n" );
206            $update = $this->getPrimaryDB()
207                ->newUpdateQueryBuilder()
208                ->update( 'page' )
209                ->set( [ 'page_title' => $dest, 'page_namespace' => $ns ] )
210                ->where( [ 'page_id' => $row->page_id ] )
211                ->caller( __METHOD__ );
212            $update->execute();
213            $this->getServiceContainer()->getLinkWriteDuplicator()->duplicate( $update );
214        }
215    }
216
217    /**
218     * @param stdClass $row
219     * @param Title $title
220     */
221    protected function moveInconsistentPage( $row, Title $title ) {
222        $titleImpossible = $title->getInterwiki() || !$title->canExist();
223        if ( $title->exists( IDBAccessObject::READ_LATEST ) || $titleImpossible ) {
224            if ( $titleImpossible ) {
225                $prior = $title->getPrefixedDBkey();
226            } else {
227                $prior = $title->getDBkey();
228            }
229
230            $ns = (int)$row->page_namespace;
231            # If a page is saved in the main namespace with a namespace prefix then try to move it into
232            # that namespace. If there's no conflict then it will succeed. Otherwise it will hit the condition
233            # } else if ($ns !== 0) { and be moved to Broken/Namespace:Title
234            # whereas without this check it would just go to Broken/Title
235            if ( $ns === 0 ) {
236                $ns = $title->getNamespace();
237            }
238
239            # Old cleanupTitles could move articles there. See T25147.
240            # or a page could be stored as (0, "Special:Foo") in which case the $titleImpossible
241            # condition would be true and we've already added a prefix so pretend we're in mainspace
242            # and don't add another
243            if ( $ns < 0 ) {
244                $ns = 0;
245            }
246
247            # Namespace which no longer exists. Put the page in the main namespace
248            # since we don't have any idea of the old namespace name. See T70501.
249            # We build the new title ourself rather than relying on getDBKey() because
250            # that will return Special:BadTitle
251            $namespaceInfo = $this->getServiceContainer()->getNamespaceInfo();
252            if ( !$namespaceInfo->exists( $ns ) ) {
253                $clean = "{$this->prefix}NS$ns:$row->page_title";
254                $ns = 0;
255            } elseif ( !$titleImpossible && !$title->exists( IDBAccessObject::READ_LATEST ) ) {
256                // Looks like the current title, after cleaning it up, is valid and available
257                $clean = $prior;
258            } elseif ( $ns !== 0 ) {
259                // Put all broken pages in the main namespace so that they can be found via Special:PrefixIndex
260                $nsName = $namespaceInfo->getCanonicalName( $ns );
261                $clean = "{$this->prefix}$nsName:{$prior}";
262                $ns = 0;
263            } else {
264                $clean = $this->prefix . $prior;
265            }
266            $verified = Title::makeTitleSafe( $ns, $clean );
267            if ( !$verified || $verified->exists( IDBAccessObject::READ_LATEST ) ) {
268                $lastResort = "{$this->prefix}id: {$row->page_id}";
269                $this->output( "Couldn't legalize; form '$clean' exists; using '$lastResort'\n" );
270                $verified = Title::makeTitleSafe( $ns, $lastResort );
271                if ( !$verified || $verified->exists( IDBAccessObject::READ_LATEST ) ) {
272                    // This can happen in corner cases like if numbers are made not valid
273                    // title characters using the (deprecated) $wgLegalTitleChars or
274                    // a 'Broken/id:foo' title already exists
275                    $this->error( "Destination page $lastResort invalid or already exists." );
276                    return;
277                }
278            }
279            $title = $verified;
280        }
281
282        $ns = $title->getNamespace();
283        $dest = $title->getDBkey();
284
285        if ( $this->dryrun ) {
286            $this->output( "DRY RUN: would rename $row->page_id ($row->page_namespace," .
287                "'$row->page_title') to ($ns,'$dest')\n" );
288        } else {
289            $this->output( "renaming $row->page_id ($row->page_namespace," .
290                "'$row->page_title') to ($ns,'$dest')\n" );
291            $update = $this->getPrimaryDB()
292                ->newUpdateQueryBuilder()
293                ->update( 'page' )
294                ->set( [
295                    'page_namespace' => $ns,
296                    'page_title' => $dest
297                ] )
298                ->where( [ 'page_id' => $row->page_id ] )
299                ->caller( __METHOD__ );
300            $update->execute();
301            $this->getServiceContainer()->getLinkWriteDuplicator()->duplicate( $update );
302            $this->getServiceContainer()->getLinkCache()->clear();
303        }
304    }
305}
306
307// @codeCoverageIgnoreStart
308$maintClass = TitleCleanup::class;
309require_once RUN_MAINTENANCE_IF_MAIN;
310// @codeCoverageIgnoreEnd