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