MediaWiki  1.29.1
refreshImageMetadata.php
Go to the documentation of this file.
1 <?php
30 require_once __DIR__ . '/Maintenance.php';
31 
34 
41 
45  protected $dbw;
46 
47  function __construct() {
48  parent::__construct();
49 
50  $this->addDescription( 'Script to update image metadata records' );
51  $this->setBatchSize( 200 );
52 
53  $this->addOption(
54  'force',
55  'Reload metadata from file even if the metadata looks ok',
56  false,
57  false,
58  'f'
59  );
60  $this->addOption(
61  'broken-only',
62  'Only fix really broken records, leave old but still compatible records alone.'
63  );
64  $this->addOption(
65  'verbose',
66  'Output extra information about each upgraded/non-upgraded file.',
67  false,
68  false,
69  'v'
70  );
71  $this->addOption( 'start', 'Name of file to start with', false, true );
72  $this->addOption( 'end', 'Name of file to end with', false, true );
73 
74  $this->addOption(
75  'mediatype',
76  'Only refresh files with this media type, e.g. BITMAP, UNKNOWN etc.',
77  false,
78  true
79  );
80  $this->addOption(
81  'mime',
82  "Only refresh files with this MIME type. Can accept wild-card 'image/*'. "
83  . "Potentially inefficient unless 'mediatype' is also specified",
84  false,
85  true
86  );
87  $this->addOption(
88  'metadata-contains',
89  '(Inefficient!) Only refresh files where the img_metadata field '
90  . 'contains this string. Can be used if its known a specific '
91  . 'property was being extracted incorrectly.',
92  false,
93  true
94  );
95  }
96 
97  public function execute() {
98  $force = $this->hasOption( 'force' );
99  $brokenOnly = $this->hasOption( 'broken-only' );
100  $verbose = $this->hasOption( 'verbose' );
101  $start = $this->getOption( 'start', false );
102  $this->setupParameters( $force, $brokenOnly );
103 
104  $upgraded = 0;
105  $leftAlone = 0;
106  $error = 0;
107 
108  $dbw = $this->getDB( DB_MASTER );
109  if ( $this->mBatchSize <= 0 ) {
110  $this->error( "Batch size is too low...", 12 );
111  }
112 
113  $repo = RepoGroup::singleton()->getLocalRepo();
114  $conds = $this->getConditions( $dbw );
115 
116  // For the WHERE img_name > 'foo' condition that comes after doing a batch
117  $conds2 = [];
118  if ( $start !== false ) {
119  $conds2[] = 'img_name >= ' . $dbw->addQuotes( $start );
120  }
121 
122  $options = [
123  'LIMIT' => $this->mBatchSize,
124  'ORDER BY' => 'img_name ASC',
125  ];
126 
127  do {
128  $res = $dbw->select(
129  'image',
130  '*',
131  array_merge( $conds, $conds2 ),
132  __METHOD__,
133  $options
134  );
135 
136  if ( $res->numRows() > 0 ) {
137  $row1 = $res->current();
138  $this->output( "Processing next {$this->mBatchSize} rows starting with {$row1->img_name}.\n" );
139  $res->rewind();
140  } else {
141  $this->error( "No images to process.", 4 );
142  }
143 
144  foreach ( $res as $row ) {
145  try {
146  // LocalFile will upgrade immediately here if obsolete
147  $file = $repo->newFileFromRow( $row );
148  if ( $file->getUpgraded() ) {
149  // File was upgraded.
150  $upgraded++;
151  $newLength = strlen( $file->getMetadata() );
152  $oldLength = strlen( $row->img_metadata );
153  if ( $newLength < $oldLength - 5 ) {
154  // If after updating, the metadata is smaller then
155  // what it was before, that's probably not a good thing
156  // because we extract more data with time, not less.
157  // Thus this probably indicates an error of some sort,
158  // or at the very least is suspicious. Have the - 5 just
159  // to weed out any inconsequential changes.
160  $error++;
161  $this->output(
162  "Warning: File:{$row->img_name} used to have " .
163  "$oldLength bytes of metadata but now has $newLength bytes.\n"
164  );
165  } elseif ( $verbose ) {
166  $this->output( "Refreshed File:{$row->img_name}.\n" );
167  }
168  } else {
169  $leftAlone++;
170  if ( $force ) {
171  $file->upgradeRow();
172  $newLength = strlen( $file->getMetadata() );
173  $oldLength = strlen( $row->img_metadata );
174  if ( $newLength < $oldLength - 5 ) {
175  $error++;
176  $this->output(
177  "Warning: File:{$row->img_name} used to have " .
178  "$oldLength bytes of metadata but now has $newLength bytes. (forced)\n"
179  );
180  }
181  if ( $verbose ) {
182  $this->output( "Forcibly refreshed File:{$row->img_name}.\n" );
183  }
184  } else {
185  if ( $verbose ) {
186  $this->output( "Skipping File:{$row->img_name}.\n" );
187  }
188  }
189  }
190  } catch ( Exception $e ) {
191  $this->output( "{$row->img_name} failed. {$e->getMessage()}\n" );
192  }
193  }
194  $conds2 = [ 'img_name > ' . $dbw->addQuotes( $row->img_name ) ];
195  wfWaitForSlaves();
196  } while ( $res->numRows() === $this->mBatchSize );
197 
198  $total = $upgraded + $leftAlone;
199  if ( $force ) {
200  $this->output( "\nFinished refreshing file metadata for $total files. "
201  . "$upgraded needed to be refreshed, $leftAlone did not need to "
202  . "be but were refreshed anyways, and $error refreshes were suspicious.\n" );
203  } else {
204  $this->output( "\nFinished refreshing file metadata for $total files. "
205  . "$upgraded were refreshed, $leftAlone were already up to date, "
206  . "and $error refreshes were suspicious.\n" );
207  }
208  }
209 
214  function getConditions( $dbw ) {
215  $conds = [];
216 
217  $end = $this->getOption( 'end', false );
218  $mime = $this->getOption( 'mime', false );
219  $mediatype = $this->getOption( 'mediatype', false );
220  $like = $this->getOption( 'metadata-contains', false );
221 
222  if ( $end !== false ) {
223  $conds[] = 'img_name <= ' . $dbw->addQuotes( $end );
224  }
225  if ( $mime !== false ) {
226  list( $major, $minor ) = File::splitMime( $mime );
227  $conds['img_major_mime'] = $major;
228  if ( $minor !== '*' ) {
229  $conds['img_minor_mime'] = $minor;
230  }
231  }
232  if ( $mediatype !== false ) {
233  $conds['img_media_type'] = $mediatype;
234  }
235  if ( $like ) {
236  $conds[] = 'img_metadata ' . $dbw->buildLike( $dbw->anyString(), $like, $dbw->anyString() );
237  }
238 
239  return $conds;
240  }
241 
246  function setupParameters( $force, $brokenOnly ) {
248 
249  if ( $brokenOnly ) {
251  } else {
253  }
254 
255  if ( $brokenOnly && $force ) {
256  $this->error( 'Cannot use --broken-only and --force together. ', 2 );
257  }
258  }
259 }
260 
261 $maintClass = 'RefreshImageMetadata';
262 require_once RUN_MAINTENANCE_IF_MAIN;
Maintenance\$mBatchSize
int $mBatchSize
Batch size.
Definition: Maintenance.php:103
$wgUpdateCompatibleMetadata
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
Definition: DefaultSettings.php:676
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:287
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
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
$res
$res
Definition: database.txt:21
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
File\splitMime
static splitMime( $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
Definition: File.php:273
RefreshImageMetadata\__construct
__construct()
Default constructor.
Definition: refreshImageMetadata.php:47
RefreshImageMetadata
Maintenance script to refresh image metadata fields.
Definition: refreshImageMetadata.php:40
wfWaitForSlaves
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
Definition: GlobalFunctions.php:3214
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
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:215
Wikimedia\Rdbms\IDatabase\buildLike
buildLike()
LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match conta...
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_MASTER
const DB_MASTER
Definition: defines.php:26
RefreshImageMetadata\getConditions
getConditions( $dbw)
Definition: refreshImageMetadata.php:214
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
$mime
if( $ext=='php'|| $ext=='php5') $mime
Definition: router.php:65
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
RefreshImageMetadata\$dbw
IMaintainableDatabase $dbw
Definition: refreshImageMetadata.php:45
Wikimedia\Rdbms\IDatabase\anyString
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:250
Wikimedia\Rdbms\IDatabase\addQuotes
addQuotes( $s)
Adds quotes and backslashes.
RefreshImageMetadata\setupParameters
setupParameters( $force, $brokenOnly)
Definition: refreshImageMetadata.php:246
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Maintenance\getDB
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1251
Wikimedia\Rdbms\IDatabase\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:392
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:373
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:236
$maintClass
$maintClass
Definition: refreshImageMetadata.php:261
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:39
RefreshImageMetadata\execute
execute()
Do the actual work.
Definition: refreshImageMetadata.php:97
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:314