MediaWiki 1.40.4
cleanupImages.php
Go to the documentation of this file.
1<?php
30
31require_once __DIR__ . '/TableCleanup.php';
32
39 protected $defaultParams = [
40 'table' => 'image',
41 'conds' => [],
42 'index' => 'img_name',
43 'callback' => 'processRow',
44 ];
45
47 private $repo;
48
49 public function __construct() {
50 parent::__construct();
51 $this->addDescription( 'Script to clean up broken, unparseable upload filenames' );
52 }
53
54 protected function processRow( $row ) {
55 $source = $row->img_name;
56 if ( $source == '' ) {
57 // Ye olde empty rows. Just kill them.
58 $this->killRow( $source );
59
60 return $this->progress( 1 );
61 }
62
63 $cleaned = $source;
64
65 // About half of old bad image names have percent-codes
66 $cleaned = rawurldecode( $cleaned );
67
68 // We also have some HTML entities there
69 $cleaned = Sanitizer::decodeCharReferences( $cleaned );
70
71 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
72
73 // Some are old latin-1
74 $cleaned = $contLang->checkTitleEncoding( $cleaned );
75
76 // Many of remainder look like non-normalized unicode
77 $cleaned = $contLang->normalize( $cleaned );
78
79 $title = Title::makeTitleSafe( NS_FILE, $cleaned );
80
81 if ( $title === null ) {
82 $this->output( "page $source ($cleaned) is illegal.\n" );
83 $safe = $this->buildSafeTitle( $cleaned );
84 if ( $safe === false ) {
85 return $this->progress( 0 );
86 }
87 $this->pokeFile( $source, $safe );
88
89 return $this->progress( 1 );
90 }
91
92 if ( $title->getDBkey() !== $source ) {
93 $munged = $title->getDBkey();
94 $this->output( "page $source ($munged) doesn't match self.\n" );
95 $this->pokeFile( $source, $munged );
96
97 return $this->progress( 1 );
98 }
99
100 return $this->progress( 0 );
101 }
102
106 private function killRow( $name ) {
107 if ( $this->dryrun ) {
108 $this->output( "DRY RUN: would delete bogus row '$name'\n" );
109 } else {
110 $this->output( "deleting bogus row '$name'\n" );
111 $db = $this->getDB( DB_PRIMARY );
112 $db->delete( 'image',
113 [ 'img_name' => $name ],
114 __METHOD__ );
115 }
116 }
117
122 private function filePath( $name ) {
123 if ( $this->repo === null ) {
124 $this->repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
125 }
126
127 return $this->repo->getRootDirectory() . '/' . $this->repo->getHashPath( $name ) . $name;
128 }
129
130 private function imageExists( $name, $db ) {
131 return (bool)$db->newSelectQueryBuilder()
132 ->select( '1' )
133 ->from( 'image' )
134 ->where( [ 'img_name' => $name ] )
135 ->caller( __METHOD__ )
136 ->fetchField();
137 }
138
139 private function pageExists( $name, $db ) {
140 return (bool)$db->newSelectQueryBuilder()
141 ->select( '1' )
142 ->from( 'page' )
143 ->where( [
144 'page_namespace' => NS_FILE,
145 'page_title' => $name,
146 ] )
147 ->caller( __METHOD__ )
148 ->fetchField();
149 }
150
151 private function pokeFile( $orig, $new ) {
152 $path = $this->filePath( $orig );
153 if ( !file_exists( $path ) ) {
154 $this->output( "missing file: $path\n" );
155 $this->killRow( $orig );
156
157 return;
158 }
159
160 $db = $this->getDB( DB_PRIMARY );
161
162 /*
163 * To prevent key collisions in the update() statements below,
164 * if the target title exists in the image table, or if both the
165 * original and target titles exist in the page table, append
166 * increasing version numbers until the target title exists in
167 * neither. (See also T18916.)
168 */
169 $version = 0;
170 $final = $new;
171 $conflict = ( $this->imageExists( $final, $db ) ||
172 ( $this->pageExists( $orig, $db ) && $this->pageExists( $final, $db ) ) );
173
174 while ( $conflict ) {
175 $this->output( "Rename conflicts with '$final'...\n" );
176 $version++;
177 $final = $this->appendTitle( $new, "_$version" );
178 $conflict = ( $this->imageExists( $final, $db ) || $this->pageExists( $final, $db ) );
179 }
180
181 $finalPath = $this->filePath( $final );
182
183 if ( $this->dryrun ) {
184 $this->output( "DRY RUN: would rename $path to $finalPath\n" );
185 } else {
186 $this->output( "renaming $path to $finalPath\n" );
187 // @todo FIXME: Should this use File::move()?
188 $this->beginTransaction( $db, __METHOD__ );
189 $db->update( 'image',
190 [ 'img_name' => $final ],
191 [ 'img_name' => $orig ],
192 __METHOD__ );
193 $db->update( 'oldimage',
194 [ 'oi_name' => $final ],
195 [ 'oi_name' => $orig ],
196 __METHOD__ );
197 $db->update( 'page',
198 [ 'page_title' => $final ],
199 [ 'page_title' => $orig, 'page_namespace' => NS_FILE ],
200 __METHOD__ );
201 $dir = dirname( $finalPath );
202 if ( !file_exists( $dir ) ) {
203 if ( !wfMkdirParents( $dir, null, __METHOD__ ) ) {
204 $this->output( "RENAME FAILED, COULD NOT CREATE $dir" );
205 $this->rollbackTransaction( $db, __METHOD__ );
206
207 return;
208 }
209 }
210 if ( rename( $path, $finalPath ) ) {
211 $this->commitTransaction( $db, __METHOD__ );
212 } else {
213 $this->error( "RENAME FAILED" );
214 $this->rollbackTransaction( $db, __METHOD__ );
215 }
216 }
217 }
218
219 private function appendTitle( $name, $suffix ) {
220 return preg_replace( '/^(.*)(\..*?)$/',
221 "\\1$suffix\\2", $name );
222 }
223
224 private function buildSafeTitle( $name ) {
225 $x = preg_replace_callback(
226 '/([^' . Title::legalChars() . ']|~)/',
227 [ $this, 'hexChar' ],
228 $name );
229
230 $test = Title::makeTitleSafe( NS_FILE, $x );
231 if ( $test === null || $test->getDBkey() !== $x ) {
232 $this->error( "Unable to generate safe title from '$name', got '$x'" );
233
234 return false;
235 }
236
237 return $x;
238 }
239}
240
241$maintClass = CleanupImages::class;
242require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
const NS_FILE
Definition Defines.php:70
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Maintenance script to clean up broken, unparseable upload filenames.
__construct()
Default constructor.
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:41
error( $err, $die=0)
Throw an error to the user.
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
output( $out, $channel=null)
Throw some output to the user.
addDescription( $text)
Set the description text.
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transaction on a DB handle.
Service locator for MediaWiki core services.
Represents a title within MediaWiki.
Definition Title.php:82
Generic class to cleanup a database table.
progress( $updated)
$maintClass
$source
const DB_PRIMARY
Definition defines.php:28