MediaWiki  1.33.0
cleanupImages.php
Go to the documentation of this file.
1 <?php
29 
30 require_once __DIR__ . '/cleanupTable.inc';
31 
37 class CleanupImages extends TableCleanup {
38  protected $defaultParams = [
39  'table' => 'image',
40  'conds' => [],
41  'index' => 'img_name',
42  'callback' => 'processRow',
43  ];
44 
45  public function __construct() {
46  parent::__construct();
47  $this->addDescription( 'Script to clean up broken, unparseable upload filenames' );
48  }
49 
50  protected function processRow( $row ) {
51  $source = $row->img_name;
52  if ( $source == '' ) {
53  // Ye olde empty rows. Just kill them.
54  $this->killRow( $source );
55 
56  return $this->progress( 1 );
57  }
58 
59  $cleaned = $source;
60 
61  // About half of old bad image names have percent-codes
62  $cleaned = rawurldecode( $cleaned );
63 
64  // We also have some HTML entities there
65  $cleaned = Sanitizer::decodeCharReferences( $cleaned );
66 
67  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
68 
69  // Some are old latin-1
70  $cleaned = $contLang->checkTitleEncoding( $cleaned );
71 
72  // Many of remainder look like non-normalized unicode
73  $cleaned = $contLang->normalize( $cleaned );
74 
75  $title = Title::makeTitleSafe( NS_FILE, $cleaned );
76 
77  if ( is_null( $title ) ) {
78  $this->output( "page $source ($cleaned) is illegal.\n" );
79  $safe = $this->buildSafeTitle( $cleaned );
80  if ( $safe === false ) {
81  return $this->progress( 0 );
82  }
83  $this->pokeFile( $source, $safe );
84 
85  return $this->progress( 1 );
86  }
87 
88  if ( $title->getDBkey() !== $source ) {
89  $munged = $title->getDBkey();
90  $this->output( "page $source ($munged) doesn't match self.\n" );
91  $this->pokeFile( $source, $munged );
92 
93  return $this->progress( 1 );
94  }
95 
96  return $this->progress( 0 );
97  }
98 
102  private function killRow( $name ) {
103  if ( $this->dryrun ) {
104  $this->output( "DRY RUN: would delete bogus row '$name'\n" );
105  } else {
106  $this->output( "deleting bogus row '$name'\n" );
107  $db = $this->getDB( DB_MASTER );
108  $db->delete( 'image',
109  [ 'img_name' => $name ],
110  __METHOD__ );
111  }
112  }
113 
114  private function filePath( $name ) {
115  if ( !isset( $this->repo ) ) {
116  $this->repo = RepoGroup::singleton()->getLocalRepo();
117  }
118 
119  return $this->repo->getRootDirectory() . '/' . $this->repo->getHashPath( $name ) . $name;
120  }
121 
122  private function imageExists( $name, $db ) {
123  return $db->selectField( 'image', '1', [ 'img_name' => $name ], __METHOD__ );
124  }
125 
126  private function pageExists( $name, $db ) {
127  return $db->selectField(
128  'page',
129  '1',
130  [ 'page_namespace' => NS_FILE, 'page_title' => $name ],
131  __METHOD__
132  );
133  }
134 
135  private function pokeFile( $orig, $new ) {
136  $path = $this->filePath( $orig );
137  if ( !file_exists( $path ) ) {
138  $this->output( "missing file: $path\n" );
139  $this->killRow( $orig );
140 
141  return;
142  }
143 
144  $db = $this->getDB( DB_MASTER );
145 
146  /*
147  * To prevent key collisions in the update() statements below,
148  * if the target title exists in the image table, or if both the
149  * original and target titles exist in the page table, append
150  * increasing version numbers until the target title exists in
151  * neither. (See also T18916.)
152  */
153  $version = 0;
154  $final = $new;
155  $conflict = ( $this->imageExists( $final, $db ) ||
156  ( $this->pageExists( $orig, $db ) && $this->pageExists( $final, $db ) ) );
157 
158  while ( $conflict ) {
159  $this->output( "Rename conflicts with '$final'...\n" );
160  $version++;
161  $final = $this->appendTitle( $new, "_$version" );
162  $conflict = ( $this->imageExists( $final, $db ) || $this->pageExists( $final, $db ) );
163  }
164 
165  $finalPath = $this->filePath( $final );
166 
167  if ( $this->dryrun ) {
168  $this->output( "DRY RUN: would rename $path to $finalPath\n" );
169  } else {
170  $this->output( "renaming $path to $finalPath\n" );
171  // @todo FIXME: Should this use File::move()?
172  $this->beginTransaction( $db, __METHOD__ );
173  $db->update( 'image',
174  [ 'img_name' => $final ],
175  [ 'img_name' => $orig ],
176  __METHOD__ );
177  $db->update( 'oldimage',
178  [ 'oi_name' => $final ],
179  [ 'oi_name' => $orig ],
180  __METHOD__ );
181  $db->update( 'page',
182  [ 'page_title' => $final ],
183  [ 'page_title' => $orig, 'page_namespace' => NS_FILE ],
184  __METHOD__ );
185  $dir = dirname( $finalPath );
186  if ( !file_exists( $dir ) ) {
187  if ( !wfMkdirParents( $dir, null, __METHOD__ ) ) {
188  $this->output( "RENAME FAILED, COULD NOT CREATE $dir" );
189  $this->rollbackTransaction( $db, __METHOD__ );
190 
191  return;
192  }
193  }
194  if ( rename( $path, $finalPath ) ) {
195  $this->commitTransaction( $db, __METHOD__ );
196  } else {
197  $this->error( "RENAME FAILED" );
198  $this->rollbackTransaction( $db, __METHOD__ );
199  }
200  }
201  }
202 
203  private function appendTitle( $name, $suffix ) {
204  return preg_replace( '/^(.*)(\..*?)$/',
205  "\\1$suffix\\2", $name );
206  }
207 
208  private function buildSafeTitle( $name ) {
209  $x = preg_replace_callback(
210  '/([^' . Title::legalChars() . ']|~)/',
211  [ $this, 'hexChar' ],
212  $name );
213 
214  $test = Title::makeTitleSafe( NS_FILE, $x );
215  if ( is_null( $test ) || $test->getDBkey() !== $x ) {
216  $this->error( "Unable to generate safe title from '$name', got '$x'" );
217 
218  return false;
219  }
220 
221  return $x;
222  }
223 }
224 
226 require_once RUN_MAINTENANCE_IF_MAIN;
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:61
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2008
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:329
CleanupImages\imageExists
imageExists( $name, $db)
Definition: cleanupImages.php:122
NS_FILE
const NS_FILE
Definition: Defines.php:70
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
CleanupImages\processRow
processRow( $row)
Definition: cleanupImages.php:50
CleanupImages\$defaultParams
$defaultParams
Definition: cleanupImages.php:38
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1434
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1399
CleanupImages\killRow
killRow( $name)
Definition: cleanupImages.php:102
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DB_MASTER
const DB_MASTER
Definition: defines.php:26
TableCleanup\progress
progress( $updated)
Definition: cleanupTable.inc:74
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:604
TableCleanup
Generic class to cleanup a database table.
Definition: cleanupTable.inc:31
$maintClass
$maintClass
Definition: cleanupImages.php:225
CleanupImages
Maintenance script to clean up broken, unparseable upload filenames.
Definition: cleanupImages.php:37
CleanupImages\__construct
__construct()
Default constructor.
Definition: cleanupImages.php:45
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1414
CleanupImages\pokeFile
pokeFile( $orig, $new)
Definition: cleanupImages.php:135
$path
$path
Definition: NoLocalSettings.php:25
Maintenance\getDB
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1373
$source
$source
Definition: mwdoc-filter.php:46
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:462
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:434
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
CleanupImages\buildSafeTitle
buildSafeTitle( $name)
Definition: cleanupImages.php:208
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:669
CleanupImages\pageExists
pageExists( $name, $db)
Definition: cleanupImages.php:126
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
CleanupImages\appendTitle
appendTitle( $name, $suffix)
Definition: cleanupImages.php:203
CleanupImages\filePath
filePath( $name)
Definition: cleanupImages.php:114