aboutsummaryrefslogtreecommitdiffstats
path: root/maintenance/refreshImageMetadata.php
blob: 5418efeae105d00402e7d78054287da318ccd4be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
/**
 * Refresh image metadata fields. See also rebuildImages.php
 *
 * Usage: php refreshImageMetadata.php
 *
 * Copyright © 2011 Brian Wolff
 * https://www.mediawiki.org/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @author Brian Wolff
 * @ingroup Maintenance
 */

// @codeCoverageIgnoreStart
require_once __DIR__ . '/Maintenance.php';
// @codeCoverageIgnoreEnd

use MediaWiki\FileRepo\File\FileSelectQueryBuilder;
use MediaWiki\Maintenance\Maintenance;
use Wikimedia\Rdbms\IExpression;
use Wikimedia\Rdbms\IMaintainableDatabase;
use Wikimedia\Rdbms\IReadableDatabase;
use Wikimedia\Rdbms\LikeValue;
use Wikimedia\Rdbms\SelectQueryBuilder;

/**
 * Maintenance script to refresh image metadata fields.
 *
 * @ingroup Maintenance
 */
class RefreshImageMetadata extends Maintenance {

	/**
	 * @var IMaintainableDatabase
	 */
	protected $dbw;

	public function __construct() {
		parent::__construct();

		$this->addDescription( 'Script to update image metadata records' );
		$this->setBatchSize( 200 );

		$this->addOption(
			'force',
			'Reload metadata from file even if the metadata looks ok',
			false,
			false,
			'f'
		);
		$this->addOption(
			'broken-only',
			'Only fix really broken records, leave old but still compatible records alone.'
		);
		$this->addOption(
			'convert-to-json',
			'Fix records with an out of date serialization format.'
		);
		$this->addOption(
			'split',
			'Enable splitting out large metadata items to the text table. Implies --convert-to-json.'
		);
		$this->addOption(
			'verbose',
			'Output extra information about each upgraded/non-upgraded file.',
			false,
			false,
			'v'
		);
		$this->addOption( 'start', 'Name of file to start with', false, true );
		$this->addOption( 'end', 'Name of file to end with', false, true );

		$this->addOption(
			'mediatype',
			'Only refresh files with this media type, e.g. BITMAP, UNKNOWN etc.',
			false,
			true
		);
		$this->addOption(
			'mime',
			"Only refresh files with this MIME type. Can accept wild-card 'image/*'. "
				. "Potentially inefficient unless 'mediatype' is also specified",
			false,
			true
		);
		$this->addOption(
			'metadata-contains',
			'(Inefficient!) Only refresh files where the img_metadata field '
				. 'contains this string. Can be used if its known a specific '
				. 'property was being extracted incorrectly.',
			false,
			true
		);
		$this->addOption(
			'sleep',
			'Time to sleep between each batch (in seconds). Default: 0',
			false,
			true
		);
		$this->addOption( 'oldimage', 'Run and refresh on oldimage table.' );
	}

	public function execute() {
		$force = $this->hasOption( 'force' );
		$brokenOnly = $this->hasOption( 'broken-only' );
		$verbose = $this->hasOption( 'verbose' );
		$start = $this->getOption( 'start', false );
		$split = $this->hasOption( 'split' );
		$sleep = (int)$this->getOption( 'sleep', 0 );
		$reserialize = $this->hasOption( 'convert-to-json' );
		$oldimage = $this->hasOption( 'oldimage' );

		$dbw = $this->getPrimaryDB();
		if ( $oldimage ) {
			$fieldPrefix = 'oi_';
			$queryBuilderTemplate  = FileSelectQueryBuilder::newForOldFile( $dbw );
		} else {
			$fieldPrefix = 'img_';
			$queryBuilderTemplate  = FileSelectQueryBuilder::newForFile( $dbw );
		}

		$upgraded = 0;
		$leftAlone = 0;
		$error = 0;
		$batchSize = intval( $this->getBatchSize() );
		if ( $batchSize <= 0 ) {
			$this->fatalError( "Batch size is too low...", 12 );
		}
		$repo = $this->newLocalRepo( $force, $brokenOnly, $reserialize, $split );
		$this->setConditions( $dbw, $queryBuilderTemplate, $fieldPrefix );
		$queryBuilderTemplate
			->orderBy( $fieldPrefix . 'name', SelectQueryBuilder::SORT_ASC )
			->limit( $batchSize );

		$batchCondition = [];
		// For the WHERE img_name > 'foo' condition that comes after doing a batch
		if ( $start !== false ) {
			$batchCondition[] = $dbw->expr( $fieldPrefix . 'name', '>=', $start );
		}
		do {
			$queryBuilder = clone $queryBuilderTemplate;
			$res = $queryBuilder->andWhere( $batchCondition )
				->caller( __METHOD__ )->fetchResultSet();
			$nameField = $fieldPrefix . 'name';
			if ( $res->numRows() > 0 ) {
				$row1 = $res->current();
				$this->output( "Processing next {$res->numRows()} row(s) starting with {$row1->$nameField}.\n" );
				$res->rewind();
			}

			foreach ( $res as $row ) {
				try {
					// LocalFile will upgrade immediately here if obsolete
					$file = $repo->newFileFromRow( $row );
					$file->maybeUpgradeRow();
					if ( $file->getUpgraded() ) {
						// File was upgraded.
						$upgraded++;
						$this->output( "Refreshed File:{$row->$nameField}.\n" );
					} else {
						$leftAlone++;
						if ( $force ) {
							$file->upgradeRow();
							if ( $verbose ) {
								$this->output( "Forcibly refreshed File:{$row->$nameField}.\n" );
							}
						} else {
							if ( $verbose ) {
								$this->output( "Skipping File:{$row->$nameField}.\n" );
							}
						}
					}
				} catch ( Exception $e ) {
					$this->output( "{$row->$nameField} failed. {$e->getMessage()}\n" );
				}
			}
			if ( $res->numRows() > 0 ) {
				// @phan-suppress-next-line PhanPossiblyUndeclaredVariable rows contains at least one item
				$batchCondition = [ $dbw->expr( $fieldPrefix . 'name', '>', $row->$nameField ) ];
			}
			$this->waitForReplication();
			if ( $sleep ) {
				sleep( $sleep );
			}
		} while ( $res->numRows() === $batchSize );

		$total = $upgraded + $leftAlone;
		if ( $force ) {
			$this->output( "\nFinished refreshing file metadata for $total files. "
				. "$upgraded needed to be refreshed, $leftAlone did not need to "
				. "be but were refreshed anyways, and $error refreshes were suspicious.\n" );
		} else {
			$this->output( "\nFinished refreshing file metadata for $total files. "
				. "$upgraded were refreshed, $leftAlone were already up to date, "
				. "and $error refreshes were suspicious.\n" );
		}
	}

	/**
	 * @param IReadableDatabase $dbw
	 * @param SelectQueryBuilder $queryBuilder
	 * @param string $fieldPrefix like img_ or oi_
	 * @return void
	 */
	private function setConditions( IReadableDatabase $dbw, SelectQueryBuilder $queryBuilder, $fieldPrefix ) {
		$end = $this->getOption( 'end', false );
		$mime = $this->getOption( 'mime', false );
		$mediatype = $this->getOption( 'mediatype', false );
		$like = $this->getOption( 'metadata-contains', false );

		if ( $end !== false ) {
			$queryBuilder->andWhere( $dbw->expr( $fieldPrefix . 'name', '<=', $end ) );
		}
		if ( $mime !== false ) {
			[ $major, $minor ] = File::splitMime( $mime );
			$queryBuilder->andWhere( [ $fieldPrefix . 'major_mime' => $major ] );
			if ( $minor !== '*' ) {
				$queryBuilder->andWhere( [ $fieldPrefix . 'minor_mime' => $minor ] );
			}
		}
		if ( $mediatype !== false ) {
			$queryBuilder->andWhere( [ $fieldPrefix . 'media_type' => $mediatype ] );
		}
		if ( $like ) {
			$queryBuilder->andWhere(
				$dbw->expr( $fieldPrefix . 'metadata', IExpression::LIKE,
					new LikeValue( $dbw->anyString(), $like, $dbw->anyString() ) )
			);
		}
	}

	/**
	 * @param bool $force
	 * @param bool $brokenOnly
	 * @param bool $reserialize
	 * @param bool $split
	 *
	 * @return LocalRepo
	 */
	private function newLocalRepo( $force, $brokenOnly, $reserialize, $split ): LocalRepo {
		if ( $brokenOnly && $force ) {
			$this->fatalError( 'Cannot use --broken-only and --force together. ', 2 );
		}
		$reserialize = $reserialize || $split;
		if ( $brokenOnly && $reserialize ) {
			$this->fatalError( 'Cannot use --broken-only with --convert-to-json or --split. ',
				2 );
		}

		$overrides = [
			'updateCompatibleMetadata' => !$brokenOnly,
		];
		if ( $reserialize ) {
			$overrides['reserializeMetadata'] = true;
			$overrides['useJsonMetadata'] = true;
		}
		if ( $split ) {
			$overrides['useSplitMetadata'] = true;
		}

		return $this->getServiceContainer()->getRepoGroup()
			->newCustomLocalRepo( $overrides );
	}
}

// @codeCoverageIgnoreStart
$maintClass = RefreshImageMetadata::class;
require_once RUN_MAINTENANCE_IF_MAIN;
// @codeCoverageIgnoreEnd