composer.json: Add a phan script command
[mediawiki.git] / maintenance / rebuildImages.php
blob5237b1a84d4248906725c55a241bb8c8fa85378c
1 <?php
2 /**
3 * Update image metadata records.
5 * Usage: php rebuildImages.php [--missing] [--dry-run]
6 * Options:
7 * --missing Crawl the uploads dir for images without records, and
8 * add them only.
10 * Copyright © 2005 Brion Vibber <brion@pobox.com>
11 * https://www.mediawiki.org/
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
28 * @file
29 * @author Brion Vibber <brion at pobox.com>
30 * @ingroup Maintenance
33 require_once __DIR__ . '/Maintenance.php';
35 use MediaWiki\MediaWikiServices;
36 use Wikimedia\Rdbms\IMaintainableDatabase;
38 /**
39 * Maintenance script to update image metadata records.
41 * @ingroup Maintenance
43 class ImageBuilder extends Maintenance {
44 /**
45 * @var IMaintainableDatabase
47 protected $dbw;
49 /** @var bool */
50 private $dryrun;
52 /** @var LocalRepo|null */
53 private $repo;
55 /** @var int */
56 private $updated;
58 /** @var int */
59 private $processed;
61 /** @var int */
62 private $count;
64 /** @var int */
65 private $startTime;
67 /** @var string */
68 private $table;
70 public function __construct() {
71 parent::__construct();
73 global $wgUpdateCompatibleMetadata;
74 // make sure to update old, but compatible img_metadata fields.
75 $wgUpdateCompatibleMetadata = true;
77 $this->addDescription( 'Script to update image metadata records' );
79 $this->addOption( 'missing', 'Check for files without associated database record' );
80 $this->addOption( 'dry-run', 'Only report, don\'t update the database' );
83 public function execute() {
84 $this->dbw = $this->getDB( DB_MASTER );
85 $this->dryrun = $this->hasOption( 'dry-run' );
86 if ( $this->dryrun ) {
87 MediaWiki\MediaWikiServices::getInstance()->getReadOnlyMode()
88 ->setReason( 'Dry run mode, image upgrades are suppressed' );
91 if ( $this->hasOption( 'missing' ) ) {
92 $this->crawlMissing();
93 } else {
94 $this->build();
98 /**
99 * @return LocalRepo
101 private function getRepo() {
102 if ( $this->repo === null ) {
103 $this->repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
106 return $this->repo;
109 private function build() {
110 $this->buildImage();
111 $this->buildOldImage();
115 * @param int $count
116 * @param string $table
118 private function init( $count, $table ) {
119 $this->processed = 0;
120 $this->updated = 0;
121 $this->count = $count;
122 $this->startTime = microtime( true );
123 $this->table = $table;
126 private function progress( $updated ) {
127 $this->updated += $updated;
128 $this->processed++;
129 if ( $this->processed % 100 != 0 ) {
130 return;
132 $portion = $this->processed / $this->count;
133 $updateRate = $this->updated / $this->processed;
135 $now = microtime( true );
136 $delta = $now - $this->startTime;
137 $estimatedTotalTime = $delta / $portion;
138 $eta = $this->startTime + $estimatedTotalTime;
139 $rate = $this->processed / $delta;
141 $this->output( sprintf( "%s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec <%.2f%% updated>\n",
142 wfTimestamp( TS_DB, intval( $now ) ),
143 $portion * 100.0,
144 $this->table,
145 wfTimestamp( TS_DB, intval( $eta ) ),
146 $this->processed,
147 $this->count,
148 $rate,
149 $updateRate * 100.0 ) );
150 flush();
153 private function buildTable( $table, $key, $queryInfo, $callback ) {
154 $count = $this->dbw->selectField( $table, 'count(*)', '', __METHOD__ );
155 $this->init( $count, $table );
156 $this->output( "Processing $table...\n" );
158 $result = $this->getDB( DB_REPLICA )->select(
159 $queryInfo['tables'], $queryInfo['fields'], [], __METHOD__, [], $queryInfo['joins']
162 foreach ( $result as $row ) {
163 $update = call_user_func( $callback, $row, null );
164 if ( $update ) {
165 $this->progress( 1 );
166 } else {
167 $this->progress( 0 );
170 $this->output( "Finished $table... $this->updated of $this->processed rows updated\n" );
173 private function buildImage() {
174 $callback = [ $this, 'imageCallback' ];
175 $this->buildTable( 'image', 'img_name', LocalFile::getQueryInfo(), $callback );
178 private function imageCallback( $row, $copy ) {
179 // Create a File object from the row
180 // This will also upgrade it
181 $file = $this->getRepo()->newFileFromRow( $row );
183 return $file->getUpgraded();
186 private function buildOldImage() {
187 $this->buildTable( 'oldimage', 'oi_archive_name', OldLocalFile::getQueryInfo(),
188 [ $this, 'oldimageCallback' ] );
191 private function oldimageCallback( $row, $copy ) {
192 // Create a File object from the row
193 // This will also upgrade it
194 if ( $row->oi_archive_name == '' ) {
195 $this->output( "Empty oi_archive_name for oi_name={$row->oi_name}\n" );
197 return false;
199 $file = $this->getRepo()->newFileFromRow( $row );
201 return $file->getUpgraded();
204 private function crawlMissing() {
205 $this->getRepo()->enumFiles( [ $this, 'checkMissingImage' ] );
208 public function checkMissingImage( $fullpath ) {
209 $filename = wfBaseName( $fullpath );
210 $row = $this->dbw->selectRow( 'image',
211 [ 'img_name' ],
212 [ 'img_name' => $filename ],
213 __METHOD__ );
215 if ( !$row ) {
216 // file not registered
217 $this->addMissingImage( $filename, $fullpath );
221 private function addMissingImage( $filename, $fullpath ) {
222 $timestamp = $this->dbw->timestamp( $this->getRepo()->getFileTimestamp( $fullpath ) );
223 $services = MediaWikiServices::getInstance();
225 $altname = $services->getContentLanguage()->checkTitleEncoding( $filename );
226 if ( $altname != $filename ) {
227 if ( $this->dryrun ) {
228 $filename = $altname;
229 $this->output( "Estimating transcoding... $altname\n" );
230 } else {
231 // @fixme create renameFile()
232 // @phan-suppress-next-line PhanUndeclaredMethod See comment above...
233 $filename = $this->renameFile( $filename );
237 if ( $filename == '' ) {
238 $this->output( "Empty filename for $fullpath\n" );
240 return;
242 if ( !$this->dryrun ) {
243 $file = $services->getRepoGroup()->getLocalRepo()->newFile( $filename );
244 $pageText = SpecialUpload::getInitialPageText(
245 '(recovered file, missing upload log entry)'
247 $user = User::newSystemUser( 'Maintenance script', [ 'steal' => true ] );
248 $status = $file->recordUpload3(
250 '(recovered file, missing upload log entry)',
251 $pageText,
252 $user,
253 false,
254 $timestamp
256 if ( !$status->isOK() ) {
257 $this->output( "Error uploading file $fullpath\n" );
259 return;
262 $this->output( $fullpath . "\n" );
266 $maintClass = ImageBuilder::class;
267 require_once RUN_MAINTENANCE_IF_MAIN;