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