MediaWiki master
refreshImageMetadata.php
Go to the documentation of this file.
1<?php
30require_once __DIR__ . '/Maintenance.php';
31
38
45
49 protected $dbw;
50
51 public function __construct() {
52 parent::__construct();
53
54 $this->addDescription( 'Script to update image metadata records' );
55 $this->setBatchSize( 200 );
56
57 $this->addOption(
58 'force',
59 'Reload metadata from file even if the metadata looks ok',
60 false,
61 false,
62 'f'
63 );
64 $this->addOption(
65 'broken-only',
66 'Only fix really broken records, leave old but still compatible records alone.'
67 );
68 $this->addOption(
69 'convert-to-json',
70 'Fix records with an out of date serialization format.'
71 );
72 $this->addOption(
73 'split',
74 'Enable splitting out large metadata items to the text table. Implies --convert-to-json.'
75 );
76 $this->addOption(
77 'verbose',
78 'Output extra information about each upgraded/non-upgraded file.',
79 false,
80 false,
81 'v'
82 );
83 $this->addOption( 'start', 'Name of file to start with', false, true );
84 $this->addOption( 'end', 'Name of file to end with', false, true );
85
86 $this->addOption(
87 'mediatype',
88 'Only refresh files with this media type, e.g. BITMAP, UNKNOWN etc.',
89 false,
90 true
91 );
92 $this->addOption(
93 'mime',
94 "Only refresh files with this MIME type. Can accept wild-card 'image/*'. "
95 . "Potentially inefficient unless 'mediatype' is also specified",
96 false,
97 true
98 );
99 $this->addOption(
100 'metadata-contains',
101 '(Inefficient!) Only refresh files where the img_metadata field '
102 . 'contains this string. Can be used if its known a specific '
103 . 'property was being extracted incorrectly.',
104 false,
105 true
106 );
107 $this->addOption(
108 'sleep',
109 'Time to sleep between each batch (in seconds). Default: 0',
110 false,
111 true
112 );
113 $this->addOption( 'oldimage', 'Run and refresh on oldimage table.' );
114 }
115
116 public function execute() {
117 $force = $this->hasOption( 'force' );
118 $brokenOnly = $this->hasOption( 'broken-only' );
119 $verbose = $this->hasOption( 'verbose' );
120 $start = $this->getOption( 'start', false );
121 $split = $this->hasOption( 'split' );
122 $sleep = (int)$this->getOption( 'sleep', 0 );
123 $reserialize = $this->hasOption( 'convert-to-json' );
124 $oldimage = $this->hasOption( 'oldimage' );
125
126 $dbw = $this->getPrimaryDB();
127 if ( $oldimage ) {
128 $fieldPrefix = 'oi_';
129 $queryBuilderTemplate = FileSelectQueryBuilder::newForOldFile( $dbw );
130 } else {
131 $fieldPrefix = 'img_';
132 $queryBuilderTemplate = FileSelectQueryBuilder::newForFile( $dbw );
133 }
134
135 $upgraded = 0;
136 $leftAlone = 0;
137 $error = 0;
138 $batchSize = intval( $this->getBatchSize() );
139 if ( $batchSize <= 0 ) {
140 $this->fatalError( "Batch size is too low...", 12 );
141 }
142 $repo = $this->newLocalRepo( $force, $brokenOnly, $reserialize, $split );
143 $this->setConditions( $dbw, $queryBuilderTemplate, $fieldPrefix );
144 $queryBuilderTemplate
145 ->orderBy( $fieldPrefix . 'name', SelectQueryBuilder::SORT_ASC )
146 ->limit( $batchSize );
147
148 $batchCondition = [];
149 // For the WHERE img_name > 'foo' condition that comes after doing a batch
150 if ( $start !== false ) {
151 $batchCondition[] = $dbw->expr( $fieldPrefix . 'name', '>=', $start );
152 }
153 do {
154 $queryBuilder = clone $queryBuilderTemplate;
155 $res = $queryBuilder->andWhere( $batchCondition )
156 ->caller( __METHOD__ )->fetchResultSet();
157 $nameField = $fieldPrefix . 'name';
158 if ( $res->numRows() > 0 ) {
159 $row1 = $res->current();
160 $this->output( "Processing next {$res->numRows()} row(s) starting with {$row1->$nameField}.\n" );
161 $res->rewind();
162 }
163
164 foreach ( $res as $row ) {
165 try {
166 // LocalFile will upgrade immediately here if obsolete
167 $file = $repo->newFileFromRow( $row );
168 $file->maybeUpgradeRow();
169 if ( $file->getUpgraded() ) {
170 // File was upgraded.
171 $upgraded++;
172 $this->output( "Refreshed File:{$row->$nameField}.\n" );
173 } else {
174 $leftAlone++;
175 if ( $force ) {
176 $file->upgradeRow();
177 if ( $verbose ) {
178 $this->output( "Forcibly refreshed File:{$row->$nameField}.\n" );
179 }
180 } else {
181 if ( $verbose ) {
182 $this->output( "Skipping File:{$row->$nameField}.\n" );
183 }
184 }
185 }
186 } catch ( Exception $e ) {
187 $this->output( "{$row->$nameField} failed. {$e->getMessage()}\n" );
188 }
189 }
190 if ( $res->numRows() > 0 ) {
191 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable rows contains at least one item
192 $batchCondition = [ $dbw->expr( $fieldPrefix . 'name', '>', $row->$nameField ) ];
193 }
194 $this->waitForReplication();
195 if ( $sleep ) {
196 sleep( $sleep );
197 }
198 } while ( $res->numRows() === $batchSize );
199
200 $total = $upgraded + $leftAlone;
201 if ( $force ) {
202 $this->output( "\nFinished refreshing file metadata for $total files. "
203 . "$upgraded needed to be refreshed, $leftAlone did not need to "
204 . "be but were refreshed anyways, and $error refreshes were suspicious.\n" );
205 } else {
206 $this->output( "\nFinished refreshing file metadata for $total files. "
207 . "$upgraded were refreshed, $leftAlone were already up to date, "
208 . "and $error refreshes were suspicious.\n" );
209 }
210 }
211
218 private function setConditions( IReadableDatabase $dbw, SelectQueryBuilder $queryBuilder, $fieldPrefix ) {
219 $end = $this->getOption( 'end', false );
220 $mime = $this->getOption( 'mime', false );
221 $mediatype = $this->getOption( 'mediatype', false );
222 $like = $this->getOption( 'metadata-contains', false );
223
224 if ( $end !== false ) {
225 $queryBuilder->andWhere( $dbw->expr( $fieldPrefix . 'name', '<=', $end ) );
226 }
227 if ( $mime !== false ) {
228 [ $major, $minor ] = File::splitMime( $mime );
229 $queryBuilder->andWhere( [ $fieldPrefix . 'major_mime' => $major ] );
230 if ( $minor !== '*' ) {
231 $queryBuilder->andWhere( [ $fieldPrefix . 'minor_mime' => $minor ] );
232 }
233 }
234 if ( $mediatype !== false ) {
235 $queryBuilder->andWhere( [ $fieldPrefix . 'media_type' => $mediatype ] );
236 }
237 if ( $like ) {
238 $queryBuilder->andWhere(
239 $dbw->expr( $fieldPrefix . 'metadata', IExpression::LIKE,
240 new LikeValue( $dbw->anyString(), $like, $dbw->anyString() ) )
241 );
242 }
243 }
244
253 private function newLocalRepo( $force, $brokenOnly, $reserialize, $split ): LocalRepo {
254 if ( $brokenOnly && $force ) {
255 $this->fatalError( 'Cannot use --broken-only and --force together. ', 2 );
256 }
257 $reserialize = $reserialize || $split;
258 if ( $brokenOnly && $reserialize ) {
259 $this->fatalError( 'Cannot use --broken-only with --convert-to-json or --split. ',
260 2 );
261 }
262
263 $overrides = [
264 'updateCompatibleMetadata' => !$brokenOnly,
265 ];
266 if ( $reserialize ) {
267 $overrides['reserializeMetadata'] = true;
268 $overrides['useJsonMetadata'] = true;
269 }
270 if ( $split ) {
271 $overrides['useSplitMetadata'] = true;
272 }
273
274 return $this->getServiceContainer()->getRepoGroup()
275 ->newCustomLocalRepo( $overrides );
276 }
277}
278
279$maintClass = RefreshImageMetadata::class;
280require_once RUN_MAINTENANCE_IF_MAIN;
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
static splitMime(?string $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
Definition File.php:315
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:48
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
waitForReplication()
Wait for replica DBs to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
getBatchSize()
Returns batch size.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Maintenance script to refresh image metadata fields.
IMaintainableDatabase $dbw
__construct()
Default constructor.
execute()
Do the actual work.
Content of like value.
Definition LikeValue.php:14
Build SELECT queries with a fluent interface.
andWhere( $conds)
Add conditions to the query.
Advanced database interface for IDatabase handles that include maintenance methods.
A database connection without write operations.
expr(string $field, string $op, $value)
See Expression::__construct()
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.