Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
55.56% covered (warning)
55.56%
650 / 1170
27.03% covered (danger)
27.03%
20 / 74
CRAP
0.00% covered (danger)
0.00%
0 / 1
LocalFile
55.60% covered (warning)
55.60%
650 / 1169
27.03% covered (danger)
27.03%
20 / 74
8554.75
0.00% covered (danger)
0.00%
0 / 1
 newFromTitle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 newFromRow
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 newFromKey
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 getQueryInfo
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 getRepo
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCacheKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 loadFromCache
95.74% covered (success)
95.74%
45 / 47
0.00% covered (danger)
0.00%
0 / 1
14
 invalidateCache
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
2.01
 loadFromFile
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getCacheFields
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
2.50
 getLazyCacheFields
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
2.86
 loadFromDB
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
3.00
 loadExtraFromDB
69.23% covered (warning)
69.23%
9 / 13
0.00% covered (danger)
0.00%
0 / 1
5.73
 loadExtraFieldsWithTimestamp
57.14% covered (warning)
57.14%
8 / 14
0.00% covered (danger)
0.00%
0 / 1
3.71
 unprefixRow
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 loadFromRow
75.00% covered (warning)
75.00%
36 / 48
0.00% covered (danger)
0.00%
0 / 1
5.39
 load
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
5.12
 maybeUpgradeRow
86.67% covered (warning)
86.67%
26 / 30
0.00% covered (danger)
0.00%
0 / 1
19.86
 getUpgraded
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getFileIdFromName
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 acquireFileIdFromName
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
20
 getFileTypeId
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
20
 upgradeRow
64.29% covered (warning)
64.29%
27 / 42
0.00% covered (danger)
0.00%
0 / 1
4.73
 reserializeMetadata
66.67% covered (warning)
66.67%
14 / 21
0.00% covered (danger)
0.00%
0 / 1
4.59
 setProps
75.76% covered (warning)
75.76%
25 / 33
0.00% covered (danger)
0.00%
0 / 1
14.05
 isMissing
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getWidth
38.46% covered (danger)
38.46%
5 / 13
0.00% covered (danger)
0.00%
0 / 1
10.83
 getHeight
38.46% covered (danger)
38.46%
5 / 13
0.00% covered (danger)
0.00%
0 / 1
10.83
 getDescriptionShortUrl
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 getMetadata
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 getMetadataArray
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 getMetadataItems
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
7
 getMetadataForDb
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
5.93
 getJsonMetadata
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
2.01
 isMetadataOversize
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 loadMetadataFromDbFieldValue
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 loadMetadataFromString
91.67% covered (success)
91.67%
22 / 24
0.00% covered (danger)
0.00%
0 / 1
7.03
 getBitDepth
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getSize
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getMimeType
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getMediaType
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 exists
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getThumbnails
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
5.51
 purgeCache
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 purgeOldThumbnails
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 purgeThumbnails
72.22% covered (warning)
72.22%
13 / 18
0.00% covered (danger)
0.00%
0 / 1
5.54
 prerenderThumbnails
30.43% covered (danger)
30.43%
7 / 23
0.00% covered (danger)
0.00%
0 / 1
18.12
 purgeThumbList
73.33% covered (warning)
73.33%
11 / 15
0.00% covered (danger)
0.00%
0 / 1
5.47
 getHistory
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
110
 nextHistoryLine
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 resetHistory
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 upload
80.00% covered (warning)
80.00%
32 / 40
0.00% covered (danger)
0.00%
0 / 1
14.35
 recordUpload3
78.21% covered (warning)
78.21%
201 / 257
0.00% covered (danger)
0.00%
0 / 1
42.59
 publish
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 publishTo
53.33% covered (warning)
53.33%
16 / 30
0.00% covered (danger)
0.00%
0 / 1
23.30
 move
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
30
 deleteFile
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
30
 deleteOldFile
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 restore
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 getDescriptionUrl
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 getDescriptionText
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
4.04
 getUploader
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 getDescription
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 getTimestamp
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getDescriptionTouched
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 getSha1
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 isCacheable
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 acquireFileLock
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 releaseFileLock
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 lock
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
20
 unlock
16.67% covered (danger)
16.67%
1 / 6
0.00% covered (danger)
0.00%
0 / 1
8.21
 readOnlyFatalStatus
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 __destruct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\FileRepo\File;
8
9use InvalidArgumentException;
10use MediaWiki\Content\ContentHandler;
11use MediaWiki\Context\RequestContext;
12use MediaWiki\Deferred\AutoCommitUpdate;
13use MediaWiki\Deferred\DeferredUpdates;
14use MediaWiki\Deferred\LinksUpdate\LinksUpdate;
15use MediaWiki\Deferred\SiteStatsUpdate;
16use MediaWiki\FileRepo\FileBackendDBRepoWrapper;
17use MediaWiki\FileRepo\FileRepo;
18use MediaWiki\FileRepo\LocalRepo;
19use MediaWiki\JobQueue\Jobs\HTMLCacheUpdateJob;
20use MediaWiki\JobQueue\Jobs\ThumbnailRenderJob;
21use MediaWiki\Language\Language;
22use MediaWiki\Logger\LoggerFactory;
23use MediaWiki\Logging\LogEntryBase;
24use MediaWiki\Logging\ManualLogEntry;
25use MediaWiki\MainConfigNames;
26use MediaWiki\Media\MediaHandler;
27use MediaWiki\MediaWikiServices;
28use MediaWiki\Page\Article;
29use MediaWiki\Page\WikiFilePage;
30use MediaWiki\Parser\ParserOptions;
31use MediaWiki\Permissions\Authority;
32use MediaWiki\Revision\SlotRecord;
33use MediaWiki\Status\Status;
34use MediaWiki\Storage\PageUpdater;
35use MediaWiki\Title\Title;
36use MediaWiki\User\UserIdentity;
37use MediaWiki\User\UserIdentityValue;
38use MediaWiki\Utils\MWFileProps;
39use RuntimeException;
40use stdClass;
41use UnexpectedValueException;
42use Wikimedia\FileBackend\FileBackend;
43use Wikimedia\FileBackend\FileBackendError;
44use Wikimedia\FileBackend\FSFile\FSFile;
45use Wikimedia\LockManager\LockManager;
46use Wikimedia\Rdbms\Blob;
47use Wikimedia\Rdbms\Database;
48use Wikimedia\Rdbms\IDBAccessObject;
49use Wikimedia\Rdbms\IReadableDatabase;
50use Wikimedia\Rdbms\IResultWrapper;
51use Wikimedia\Rdbms\SelectQueryBuilder;
52use Wikimedia\Timestamp\ConvertibleTimestamp;
53use Wikimedia\Timestamp\TimestampFormat as TS;
54
55/**
56 * Local file in the wiki's own database.
57 *
58 * Provides methods to retrieve paths (physical, logical, URL),
59 * to generate image thumbnails or for uploading.
60 *
61 * Note that only the repo object knows what its file class is called. You should
62 * never name a file class explicitly outside of the repo class. Instead use the
63 * repo's factory functions to generate file objects, for example:
64 *
65 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
66 *
67 * Consider the services container below;
68 *
69 * $services = MediaWikiServices::getInstance();
70 *
71 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
72 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
73 *
74 * @todo DI - Instead of using MediaWikiServices::getInstance(), a service should
75 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
76 * and $this->repoGroup->getLocalRepo()->newFile().
77 *
78 * @stable to extend
79 * @ingroup FileAbstraction
80 */
81class LocalFile extends File {
82    private const VERSION = 13; // cache version
83
84    private const CACHE_FIELD_MAX_LEN = 1000;
85
86    /** @var string Metadata serialization: empty string. This is a compact non-legacy format. */
87    private const MDS_EMPTY = 'empty';
88
89    /** @var string Metadata serialization: some other string */
90    private const MDS_LEGACY = 'legacy';
91
92    /** @var string Metadata serialization: PHP serialize() */
93    private const MDS_PHP = 'php';
94
95    /** @var string Metadata serialization: JSON */
96    private const MDS_JSON = 'json';
97
98    /** @var int Maximum number of pages for which to trigger render jobs */
99    private const MAX_PAGE_RENDER_JOBS = 50;
100
101    /** @var bool Does the file exist on disk? (loadFromXxx) */
102    protected $fileExists;
103
104    /** @var int Id of the file */
105    private $fileId;
106
107    /** @var int Id of the file type */
108    private $fileTypeId;
109
110    /** @var int Image width */
111    protected $width;
112
113    /** @var int Image height */
114    protected $height;
115
116    /** @var int Returned by getimagesize (loadFromXxx) */
117    protected $bits;
118
119    /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
120    protected $media_type;
121
122    /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
123    protected $mime;
124
125    /** @var int Size in bytes (loadFromXxx) */
126    protected $size;
127
128    /** @var array Unserialized metadata */
129    protected $metadataArray = [];
130
131    /**
132     * One of the MDS_* constants, giving the format of the metadata as stored
133     * in the DB, or null if the data was not loaded from the DB.
134     *
135     * @var string|null
136     */
137    protected $metadataSerializationFormat;
138
139    /** @var string[] Map of metadata item name to blob address */
140    protected $metadataBlobs = [];
141
142    /**
143     * Map of metadata item name to blob address for items that exist but
144     * have not yet been loaded into $this->metadataArray
145     *
146     * @var string[]
147     */
148    protected $unloadedMetadataBlobs = [];
149
150    /** @var string SHA-1 base 36 content hash */
151    protected $sha1;
152
153    /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
154    protected $dataLoaded = false;
155
156    /** @var bool Whether or not lazy-loaded data has been loaded from the database */
157    protected $extraDataLoaded = false;
158
159    /** @var int Bitfield akin to rev_deleted */
160    protected $deleted;
161
162    /** @var int id in file table, null on read old */
163    protected $file_id;
164
165    /** @var int id in filerevision table, null on read old */
166    protected $filerevision_id;
167
168    /** @var string */
169    protected $repoClass = LocalRepo::class;
170
171    /** @var int Number of line to return by nextHistoryLine() (constructor) */
172    private $historyLine = 0;
173
174    /** @var IResultWrapper|null Result of the query for the file's history (nextHistoryLine) */
175    private $historyRes = null;
176
177    /** @var string Major MIME type */
178    private $major_mime;
179
180    /** @var string Minor MIME type */
181    private $minor_mime;
182
183    /** @var string Upload timestamp */
184    private $timestamp;
185
186    /** @var UserIdentity|null Uploader */
187    private $user;
188
189    /** @var string Description of latest revision of the file */
190    private $description;
191
192    /** @var string TS::MW timestamp of the last change of the file description */
193    private $descriptionTouched;
194
195    /** @var bool Whether the row was upgraded on load */
196    private $upgraded = false;
197
198    /** @var bool Whether the row was scheduled to upgrade on load */
199    private $upgrading;
200
201    /** @var int If >= 1 the image row is locked */
202    private $locked;
203
204    /** @var bool True if the image row is locked with a lock initiated transaction */
205    private $lockedOwnTrx;
206
207    /** @var bool True if file is not present in file system. Not to be cached in memcached */
208    private $missing;
209
210    /** @var MetadataStorageHelper */
211    private $metadataStorageHelper;
212
213    /** @var int */
214    private $migrationStage = SCHEMA_COMPAT_OLD;
215
216    // @note: higher than IDBAccessObject constants
217    private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
218
219    private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
220
221    /**
222     * Create a LocalFile from a title
223     * Do not call this except from inside a repo class.
224     *
225     * Note: $unused param is only here to avoid an E_STRICT
226     *
227     * @stable to override
228     *
229     * @param Title $title
230     * @param LocalRepo $repo
231     * @param null $unused
232     */
233    public static function newFromTitle( $title, $repo, $unused = null ): static {
234        return new static( $title, $repo );
235    }
236
237    /**
238     * Create a LocalFile from a title
239     * Do not call this except from inside a repo class.
240     *
241     * @stable to override
242     *
243     * @param stdClass $row
244     * @param LocalRepo $repo
245     */
246    public static function newFromRow( $row, $repo ): static {
247        $title = Title::makeTitle( NS_FILE, $row->img_name );
248        $file = new static( $title, $repo );
249        $file->loadFromRow( $row );
250
251        return $file;
252    }
253
254    /**
255     * Create a LocalFile from a SHA-1 key
256     * Do not call this except from inside a repo class.
257     *
258     * @stable to override
259     *
260     * @param string $sha1 Base-36 SHA-1
261     * @param LocalRepo $repo
262     * @param string|false $timestamp MW_timestamp (optional)
263     * @return static|false
264     */
265    public static function newFromKey( $sha1, $repo, $timestamp = false ): static|false {
266        $dbr = $repo->getReplicaDB();
267        $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
268
269        $queryBuilder->where( [ 'img_sha1' => $sha1 ] );
270
271        if ( $timestamp ) {
272            $queryBuilder->andWhere( [ 'img_timestamp' => $dbr->timestamp( $timestamp ) ] );
273        }
274
275        $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
276        if ( $row ) {
277            return static::newFromRow( $row, $repo );
278        } else {
279            return false;
280        }
281    }
282
283    /**
284     * Return the tables, fields, and join conditions to be selected to create
285     * a new localfile object.
286     *
287     * Since 1.34, img_user and img_user_text have not been present in the
288     * database, but they continue to be available in query results as
289     * aliases.
290     *
291     * @since 1.31
292     * @stable to override
293     *
294     * @deprecated since 1.41 use FileSelectQueryBuilder instead
295     * @param string[] $options
296     *   - omit-lazy: Omit fields that are lazily cached.
297     * @return array[] With three keys:
298     *   - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
299     *   - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
300     *   - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
301     * @phan-return array{tables:string[],fields:string[],joins:array}
302     */
303    public static function getQueryInfo( array $options = [] ) {
304        wfDeprecated( __METHOD__, '1.41' );
305        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
306        $queryInfo = FileSelectQueryBuilder::newForFile( $dbr, $options )->getQueryInfo();
307        // needs remapping...
308        return [
309            'tables' => $queryInfo['tables'],
310            'fields' => $queryInfo['fields'],
311            'joins' => $queryInfo['join_conds'],
312        ];
313    }
314
315    /**
316     * Do not call this except from inside a repo class.
317     * @stable to call
318     *
319     * @param Title $title
320     * @param LocalRepo $repo
321     */
322    public function __construct( $title, $repo ) {
323        parent::__construct( $title, $repo );
324        $this->metadataStorageHelper = new MetadataStorageHelper( $repo );
325        $this->migrationStage = MediaWikiServices::getInstance()->getMainConfig()->get(
326            MainConfigNames::FileSchemaMigrationStage
327        );
328
329        $this->assertRepoDefined();
330        $this->assertTitleDefined();
331    }
332
333    /**
334     * @return LocalRepo|false
335     */
336    public function getRepo() {
337        return $this->repo;
338    }
339
340    /**
341     * Get the memcached key for the main data for this file, or false if
342     * there is no access to the shared cache.
343     * @stable to override
344     * @return string|false
345     */
346    protected function getCacheKey() {
347        return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
348    }
349
350    /**
351     * Try to load file metadata from memcached, falling back to the database
352     */
353    private function loadFromCache() {
354        $this->dataLoaded = false;
355        $this->extraDataLoaded = false;
356
357        $key = $this->getCacheKey();
358        if ( !$key ) {
359            $this->loadFromDB( IDBAccessObject::READ_NORMAL );
360
361            return;
362        }
363
364        $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
365        $cachedValues = $cache->getWithSetCallback(
366            $key,
367            $cache::TTL_WEEK,
368            function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
369                $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
370
371                $this->loadFromDB( IDBAccessObject::READ_NORMAL );
372
373                $fields = $this->getCacheFields( '' );
374                $cacheVal = [];
375                $cacheVal['fileExists'] = $this->fileExists;
376                if ( $this->fileExists ) {
377                    foreach ( $fields as $field ) {
378                        $cacheVal[$field] = $this->$field;
379                    }
380                }
381                if ( $this->user ) {
382                    $cacheVal['user'] = $this->user->getId();
383                    $cacheVal['user_text'] = $this->user->getName();
384                }
385
386                // Don't cache metadata items stored as blobs, since they tend to be large
387                if ( $this->metadataBlobs ) {
388                    $cacheVal['metadata'] = array_diff_key(
389                        $this->metadataArray, $this->metadataBlobs );
390                    // Save the blob addresses
391                    $cacheVal['metadataBlobs'] = $this->metadataBlobs;
392                } else {
393                    $cacheVal['metadata'] = $this->metadataArray;
394                }
395
396                // Strip off excessive entries from the subset of fields that can become large.
397                // If the cache value gets too large and might not fit in the cache,
398                // causing repeat database queries for each access to the file.
399                foreach ( $this->getLazyCacheFields( '' ) as $field ) {
400                    if ( isset( $cacheVal[$field] )
401                        && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
402                    ) {
403                        unset( $cacheVal[$field] ); // don't let the value get too big
404                        if ( $field === 'metadata' ) {
405                            unset( $cacheVal['metadataBlobs'] );
406                        }
407                    }
408                }
409
410                if ( $this->fileExists ) {
411                    $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS::UNIX, $this->timestamp ), $ttl );
412                } else {
413                    $ttl = $cache::TTL_DAY;
414                }
415
416                return $cacheVal;
417            },
418            [ 'version' => self::VERSION ]
419        );
420
421        $this->fileExists = $cachedValues['fileExists'];
422        if ( $this->fileExists ) {
423            $this->setProps( $cachedValues );
424        }
425
426        $this->dataLoaded = true;
427        $this->extraDataLoaded = true;
428        foreach ( $this->getLazyCacheFields( '' ) as $field ) {
429            $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
430        }
431    }
432
433    /**
434     * Purge the file object/metadata cache
435     */
436    public function invalidateCache() {
437        $key = $this->getCacheKey();
438        if ( !$key ) {
439            return;
440        }
441
442        $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
443            static function () use ( $key ) {
444                MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
445            },
446            __METHOD__
447        );
448    }
449
450    /**
451     * Load metadata from the file itself
452     *
453     * @internal
454     * @param string|null $path The path or virtual URL to load from, or null
455     * to use the previously stored file.
456     */
457    public function loadFromFile( $path = null ) {
458        $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
459        $this->setProps( $props );
460    }
461
462    /**
463     * Returns the list of object properties that are included as-is in the cache.
464     * @stable to override
465     * @param string $prefix Must be the empty string
466     * @return string[]
467     * @since 1.31 No longer accepts a non-empty $prefix
468     */
469    protected function getCacheFields( $prefix = 'img_' ) {
470        if ( $prefix !== '' ) {
471            throw new InvalidArgumentException(
472                __METHOD__ . ' with a non-empty prefix is no longer supported.'
473            );
474        }
475
476        // See self::getQueryInfo() for the fetching of the data from the DB,
477        // self::loadFromRow() for the loading of the object from the DB row,
478        // and self::loadFromCache() for the caching, and self::setProps() for
479        // populating the object from an array of data.
480        return [ 'size', 'width', 'height', 'bits', 'media_type',
481            'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
482    }
483
484    /**
485     * Returns the list of object properties that are included as-is in the
486     * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
487     * @param string $prefix Must be the empty string
488     * @return string[]
489     * @since 1.31 No longer accepts a non-empty $prefix
490     */
491    protected function getLazyCacheFields( $prefix = 'img_' ) {
492        if ( $prefix !== '' ) {
493            throw new InvalidArgumentException(
494                __METHOD__ . ' with a non-empty prefix is no longer supported.'
495            );
496        }
497
498        // Keep this in sync with the omit-lazy option in self::getQueryInfo().
499        return [ 'metadata' ];
500    }
501
502    /**
503     * Load file metadata from the DB
504     * @stable to override
505     * @param int $flags
506     */
507    protected function loadFromDB( $flags = 0 ) {
508        $fname = static::class . '::' . __FUNCTION__;
509
510        # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
511        $this->dataLoaded = true;
512        $this->extraDataLoaded = true;
513
514        $dbr = ( $flags & IDBAccessObject::READ_LATEST )
515            ? $this->repo->getPrimaryDB()
516            : $this->repo->getReplicaDB();
517        $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
518
519        $queryBuilder->where( [ 'img_name' => $this->getName() ] );
520        $row = $queryBuilder->caller( $fname )->fetchRow();
521
522        if ( $row ) {
523            $this->loadFromRow( $row );
524        } else {
525            $this->fileExists = false;
526            $this->mime = 'unknown/unknown';
527        }
528    }
529
530    /**
531     * Load lazy file metadata from the DB.
532     * This covers fields that are sometimes not cached.
533     * @stable to override
534     */
535    protected function loadExtraFromDB() {
536        if ( !$this->title ) {
537            return; // Avoid hard failure when the file does not exist. T221812
538        }
539
540        $fname = static::class . '::' . __FUNCTION__;
541
542        # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
543        $this->extraDataLoaded = true;
544
545        $db = $this->repo->getReplicaDB();
546        $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
547        if ( !$fieldMap ) {
548            $db = $this->repo->getPrimaryDB();
549            $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
550        }
551
552        if ( $fieldMap ) {
553            if ( isset( $fieldMap['metadata'] ) ) {
554                $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
555            }
556        } else {
557            throw new RuntimeException( "Could not find data for image '{$this->getName()}'." );
558        }
559    }
560
561    /**
562     * @param IReadableDatabase $dbr
563     * @param string $fname
564     * @return string[]|false
565     */
566    private function loadExtraFieldsWithTimestamp( IReadableDatabase $dbr, $fname ) {
567        $fieldMap = false;
568
569        $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
570        $queryBuilder->where( [ 'img_name' => $this->getName() ] )
571            ->andWhere( [ 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] );
572        $row = $queryBuilder->caller( $fname )->fetchRow();
573        if ( $row ) {
574            $fieldMap = $this->unprefixRow( $row, 'img_' );
575        } else {
576            // File may have been uploaded over in the meantime; check the old versions
577            $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
578            $row = $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
579                ->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] )
580                ->caller( __METHOD__ )->fetchRow();
581            if ( $row ) {
582                $fieldMap = $this->unprefixRow( $row, 'oi_' );
583            }
584        }
585
586        return $fieldMap;
587    }
588
589    /**
590     * @param array|stdClass $row
591     * @param string $prefix
592     * @return array
593     */
594    protected function unprefixRow( $row, $prefix = 'img_' ) {
595        $array = (array)$row;
596        $prefixLength = strlen( $prefix );
597
598        // Double check prefix once
599        if ( !str_starts_with( array_key_first( $array ), $prefix ) ) {
600            throw new InvalidArgumentException( __METHOD__ . ': incorrect $prefix parameter' );
601        }
602
603        $decoded = [];
604        foreach ( $array as $name => $value ) {
605            $decoded[substr( $name, $prefixLength )] = $value;
606        }
607
608        return $decoded;
609    }
610
611    /**
612     * Load file metadata from a DB result row
613     * @stable to override
614     *
615     * Passing arbitrary fields in the row and expecting them to be translated
616     * to property names on $this is deprecated since 1.37. Instead, override
617     * loadFromRow(), and clone and unset the extra fields before passing them
618     * to the parent.
619     *
620     * After the deprecation period has passed, extra fields will be ignored,
621     * and the deprecation warning will be removed.
622     *
623     * @param stdClass $row
624     * @param string $prefix
625     */
626    public function loadFromRow( $row, $prefix = 'img_' ) {
627        $this->dataLoaded = true;
628
629        $unprefixed = $this->unprefixRow( $row, $prefix );
630
631        $this->name = $unprefixed['name'];
632        $this->media_type = $unprefixed['media_type'];
633
634        $services = MediaWikiServices::getInstance();
635        $this->description = $services->getCommentStore()
636            ->getComment( "{$prefix}description", $row )->text;
637
638        $this->user = $services->getUserFactory()->newFromAnyId(
639            $unprefixed['user'] ?? null,
640            $unprefixed['user_text'] ?? null,
641            $unprefixed['actor'] ?? null
642        );
643
644        $this->timestamp = wfTimestamp( TS::MW, $unprefixed['timestamp'] );
645
646        $this->loadMetadataFromDbFieldValue(
647            $this->repo->getReplicaDB(), $unprefixed['metadata'] );
648
649        if ( empty( $unprefixed['major_mime'] ) ) {
650            $this->major_mime = 'unknown';
651            $this->minor_mime = 'unknown';
652            $this->mime = 'unknown/unknown';
653        } else {
654            if ( !$unprefixed['minor_mime'] ) {
655                $unprefixed['minor_mime'] = 'unknown';
656            }
657            $this->major_mime = $unprefixed['major_mime'];
658            $this->minor_mime = $unprefixed['minor_mime'];
659            $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
660        }
661
662        // Trim zero padding from char/binary field
663        $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
664
665        // Normalize some fields to integer type, per their database definition.
666        // Use unary + so that overflows will be upgraded to double instead of
667        // being truncated as with intval(). This is important to allow > 2 GiB
668        // files on 32-bit systems.
669        $this->size = +$unprefixed['size'];
670        $this->width = +$unprefixed['width'];
671        $this->height = +$unprefixed['height'];
672        $this->bits = +$unprefixed['bits'];
673
674        // Check for extra fields (deprecated since MW 1.37)
675        $extraFields = array_diff(
676            array_keys( $unprefixed ),
677            [
678                'name', 'media_type', 'description_text', 'description_data',
679                'description_cid', 'user', 'user_text', 'actor', 'timestamp',
680                'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
681                'height', 'bits', 'file_id', 'filerevision_id'
682            ]
683        );
684        if ( $extraFields ) {
685            wfDeprecatedMsg(
686                'Passing extra fields (' .
687                implode( ', ', $extraFields )
688                . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
689                'Property assignment will be removed in a later version.',
690                '1.37' );
691            foreach ( $extraFields as $field ) {
692                $this->$field = $unprefixed[$field];
693            }
694        }
695
696        $this->fileExists = true;
697    }
698
699    /**
700     * Load file metadata from cache or DB, unless already loaded
701     * @stable to override
702     * @param int $flags
703     */
704    public function load( $flags = 0 ) {
705        if ( !$this->dataLoaded ) {
706            if ( $flags & IDBAccessObject::READ_LATEST ) {
707                $this->loadFromDB( $flags );
708            } else {
709                $this->loadFromCache();
710            }
711        }
712
713        if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
714            // @note: loads on name/timestamp to reduce race condition problems
715            $this->loadExtraFromDB();
716        }
717    }
718
719    /**
720     * Upgrade a row if it needs it
721     * @internal
722     */
723    public function maybeUpgradeRow() {
724        if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
725            return;
726        }
727
728        $upgrade = false;
729        $reserialize = false;
730        if ( $this->media_type === null || $this->mime == 'image/svg' ) {
731            $upgrade = true;
732        } else {
733            $handler = $this->getHandler();
734            if ( $handler ) {
735                $validity = $handler->isFileMetadataValid( $this );
736                if ( $validity === MediaHandler::METADATA_BAD ) {
737                    $upgrade = true;
738                } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
739                    && $this->repo->isMetadataUpdateEnabled()
740                ) {
741                    $upgrade = true;
742                } elseif ( $this->repo->isJsonMetadataEnabled()
743                    && $this->repo->isMetadataReserializeEnabled()
744                ) {
745                    if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
746                        $reserialize = true;
747                    } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
748                        $this->metadataSerializationFormat !== self::MDS_JSON ) {
749                        $reserialize = true;
750                    }
751                }
752            }
753        }
754
755        if ( $upgrade || $reserialize ) {
756            $this->upgrading = true;
757            // Defer updates unless in auto-commit CLI mode
758            DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
759                $this->upgrading = false; // avoid duplicate updates
760                try {
761                    if ( $upgrade ) {
762                        $this->upgradeRow();
763                    } else {
764                        $this->reserializeMetadata();
765                    }
766                } catch ( LocalFileLockError ) {
767                    // let the other process handle it (or do it next time)
768                }
769            } );
770        }
771    }
772
773    /**
774     * @return bool Whether upgradeRow() ran for this object
775     */
776    public function getUpgraded() {
777        return $this->upgraded;
778    }
779
780    /**
781     * This is mostly for the migration period.
782     *
783     * Since 1.44
784     * @return int|false
785     */
786    public function getFileIdFromName() {
787        if ( !$this->fileId ) {
788            $dbw = $this->repo->getPrimaryDB();
789            $id = $dbw->newSelectQueryBuilder()
790                ->select( 'file_id' )
791                ->from( 'file' )
792                ->where( [
793                    'file_name' => $this->getName(),
794                    'file_deleted' => 0
795                ] )
796                ->caller( __METHOD__ )
797                ->fetchField();
798            $this->fileId = $id;
799        }
800
801        return $this->fileId;
802    }
803
804    /**
805     * This is mostly for the migration period.
806     *
807     * @internal
808     * @return int
809     */
810    public function acquireFileIdFromName() {
811        $dbw = $this->repo->getPrimaryDB();
812        $id = $this->getFileIdFromName();
813        if ( $id ) {
814            return $id;
815        }
816        $id = $dbw->newSelectQueryBuilder()
817            ->select( 'file_id' )
818            ->from( 'file' )
819            ->where( [
820                'file_name' => $this->getName(),
821            ] )
822            ->caller( __METHOD__ )
823            ->fetchField();
824        if ( !$id ) {
825            $dbw->newInsertQueryBuilder()
826                ->insertInto( 'file' )
827                ->row( [
828                    'file_name' => $this->getName(),
829                    // The value will be updated later
830                    'file_latest' => 0,
831                    'file_deleted' => 0,
832                    'file_type' => $this->getFileTypeId(),
833                ] )
834                ->caller( __METHOD__ )->execute();
835            $insertId = $dbw->insertId();
836            if ( !$insertId ) {
837                throw new RuntimeException( 'File entry could not be inserted' );
838            }
839            return $insertId;
840        } else {
841            // Undelete
842            $dbw->newUpdateQueryBuilder()
843                ->update( 'file' )
844                ->set( [ 'file_deleted' => 0 ] )
845                ->where( [ 'file_id' => $id ] )
846                ->caller( __METHOD__ )->execute();
847            return $id;
848        }
849    }
850
851    protected function getFileTypeId(): int {
852        if ( $this->fileTypeId ) {
853            return $this->fileTypeId;
854        }
855        [ $major, $minor ] = self::splitMime( $this->mime );
856        $dbw = $this->repo->getPrimaryDB();
857        $id = $dbw->newSelectQueryBuilder()
858            ->select( 'ft_id' )
859            ->from( 'filetypes' )
860            ->where( [
861                'ft_media_type' => $this->getMediaType(),
862                'ft_major_mime' => $major,
863                'ft_minor_mime' => $minor,
864            ] )
865            ->caller( __METHOD__ )
866            ->fetchField();
867        if ( $id ) {
868            $this->fileTypeId = $id;
869            return $id;
870        }
871        $dbw->newInsertQueryBuilder()
872            ->insertInto( 'filetypes' )
873            ->row( [
874                'ft_media_type' => $this->getMediaType(),
875                'ft_major_mime' => $major,
876                'ft_minor_mime' => $minor,
877            ] )
878            ->caller( __METHOD__ )->execute();
879
880        $id = $dbw->insertId();
881        if ( !$id ) {
882            throw new RuntimeException( 'File entry could not be inserted' );
883        }
884
885        $this->fileTypeId = $id;
886        return $id;
887    }
888
889    /**
890     * Fix assorted version-related problems with the image row by reloading it from the file
891     * @stable to override
892     */
893    public function upgradeRow() {
894        $dbw = $this->repo->getPrimaryDB();
895
896        // Make a DB query condition that will fail to match the image row if the
897        // image was reuploaded while the upgrade was in process.
898        $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
899
900        $this->loadFromFile();
901
902        # Don't destroy file info of missing files
903        if ( !$this->fileExists ) {
904            wfDebug( __METHOD__ . ": file does not exist, aborting" );
905
906            return;
907        }
908
909        [ $major, $minor ] = self::splitMime( $this->mime );
910
911        wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
912
913        $metadata = $this->getMetadataForDb( $dbw );
914        if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
915            $dbw->newUpdateQueryBuilder()
916                ->update( 'image' )
917                ->set( [
918                    'img_size' => $this->size,
919                    'img_width' => $this->width,
920                    'img_height' => $this->height,
921                    'img_bits' => $this->bits,
922                    'img_media_type' => $this->media_type,
923                    'img_major_mime' => $major,
924                    'img_minor_mime' => $minor,
925                    'img_metadata' => $metadata,
926                    'img_sha1' => $this->sha1,
927                ] )
928                ->where( [ 'img_name' => $this->getName() ] )
929                ->andWhere( $freshnessCondition )
930                ->caller( __METHOD__ )->execute();
931        }
932
933        if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
934            $dbw->newUpdateQueryBuilder()
935                ->update( 'filerevision' )
936                ->set( [
937                    'fr_size' => $this->size,
938                    'fr_width' => $this->width,
939                    'fr_height' => $this->height,
940                    'fr_bits' => $this->bits,
941                    'fr_metadata' => $metadata,
942                    'fr_sha1' => $this->sha1,
943                ] )
944                ->where( [ 'fr_file' => $this->acquireFileIdFromName() ] )
945                ->andWhere( [ 'fr_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ] )
946                ->caller( __METHOD__ )->execute();
947        }
948
949        $this->invalidateCache();
950
951        $this->upgraded = true; // avoid rework/retries
952    }
953
954    /**
955     * Write the metadata back to the database with the current serialization
956     * format.
957     */
958    protected function reserializeMetadata() {
959        if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
960            return;
961        }
962        $dbw = $this->repo->getPrimaryDB();
963        $metadata = $this->getMetadataForDb( $dbw );
964        if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
965            $dbw->newUpdateQueryBuilder()
966                ->update( 'image' )
967                ->set( [ 'img_metadata' => $metadata ] )
968                ->where( [
969                    'img_name' => $this->name,
970                    'img_timestamp' => $dbw->timestamp( $this->timestamp ),
971                ] )
972                ->caller( __METHOD__ )->execute();
973        }
974        if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
975            $dbw->newUpdateQueryBuilder()
976                ->update( 'filerevision' )
977                ->set( [ 'fr_metadata' => $metadata ] )
978                ->where( [ 'fr_file' => $this->acquireFileIdFromName() ] )
979                ->andWhere( [ 'fr_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ] )
980                ->caller( __METHOD__ )->execute();
981        }
982        $this->upgraded = true;
983    }
984
985    /**
986     * Set properties in this object to be equal to those given in the
987     * associative array $info. Only cacheable fields can be set.
988     * All fields *must* be set in $info except for getLazyCacheFields().
989     *
990     * If 'mime' is given, it will be split into major_mime/minor_mime.
991     * If major_mime/minor_mime are given, $this->mime will also be set.
992     *
993     * @stable to override
994     * @unstable to call
995     * @param array $info
996     */
997    public function setProps( $info ) {
998        $this->dataLoaded = true;
999        $fields = $this->getCacheFields( '' );
1000        $fields[] = 'fileExists';
1001
1002        foreach ( $fields as $field ) {
1003            if ( isset( $info[$field] ) ) {
1004                $this->$field = $info[$field];
1005            }
1006        }
1007
1008        // Only our own cache sets these properties, so they both should be present.
1009        if ( isset( $info['user'] ) &&
1010            isset( $info['user_text'] ) &&
1011            $info['user_text'] !== ''
1012        ) {
1013            $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
1014        }
1015
1016        // Fix up mime fields
1017        if ( isset( $info['major_mime'] ) ) {
1018            $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
1019        } elseif ( isset( $info['mime'] ) ) {
1020            $this->mime = $info['mime'];
1021            [ $this->major_mime, $this->minor_mime ] = self::splitMime( $this->mime );
1022        }
1023
1024        if ( isset( $info['metadata'] ) ) {
1025            if ( is_string( $info['metadata'] ) ) {
1026                $this->loadMetadataFromString( $info['metadata'] );
1027            } elseif ( is_array( $info['metadata'] ) ) {
1028                $this->metadataArray = $info['metadata'];
1029                if ( isset( $info['metadataBlobs'] ) ) {
1030                    $this->metadataBlobs = $info['metadataBlobs'];
1031                    $this->unloadedMetadataBlobs = array_diff_key(
1032                        $this->metadataBlobs,
1033                        $this->metadataArray
1034                    );
1035                } else {
1036                    $this->metadataBlobs = [];
1037                    $this->unloadedMetadataBlobs = [];
1038                }
1039            } else {
1040                $logger = LoggerFactory::getInstance( 'LocalFile' );
1041                $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
1042                    get_debug_type( $info['metadata'] ) );
1043                $this->metadataArray = [];
1044            }
1045            $this->extraDataLoaded = true;
1046        }
1047    }
1048
1049    /** splitMime inherited */
1050    /** getName inherited */
1051    /** getTitle inherited */
1052    /** getURL inherited */
1053    /** getViewURL inherited */
1054    /** getPath inherited */
1055    /** isVisible inherited */
1056
1057    /**
1058     * Checks if this file exists in its parent repo, as referenced by its
1059     * virtual URL.
1060     * @stable to override
1061     *
1062     * @return bool
1063     */
1064    public function isMissing() {
1065        if ( $this->missing === null ) {
1066            $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
1067            $this->missing = !$fileExists;
1068        }
1069
1070        return $this->missing;
1071    }
1072
1073    /**
1074     * Return the width of the image
1075     * @stable to override
1076     *
1077     * @param int $page
1078     * @return int
1079     */
1080    public function getWidth( $page = 1 ) {
1081        $page = (int)$page;
1082        if ( $page < 1 ) {
1083            $page = 1;
1084        }
1085
1086        $this->load();
1087
1088        if ( $this->isMultipage() ) {
1089            $handler = $this->getHandler();
1090            if ( !$handler ) {
1091                return 0;
1092            }
1093            $dim = $handler->getPageDimensions( $this, $page );
1094            if ( $dim ) {
1095                return $dim['width'];
1096            } else {
1097                // For non-paged media, the false goes through an
1098                // intval, turning failure into 0, so do same here.
1099                return 0;
1100            }
1101        } else {
1102            return $this->width;
1103        }
1104    }
1105
1106    /**
1107     * Return the height of the image
1108     * @stable to override
1109     *
1110     * @param int $page
1111     * @return int
1112     */
1113    public function getHeight( $page = 1 ) {
1114        $page = (int)$page;
1115        if ( $page < 1 ) {
1116            $page = 1;
1117        }
1118
1119        $this->load();
1120
1121        if ( $this->isMultipage() ) {
1122            $handler = $this->getHandler();
1123            if ( !$handler ) {
1124                return 0;
1125            }
1126            $dim = $handler->getPageDimensions( $this, $page );
1127            if ( $dim ) {
1128                return $dim['height'];
1129            } else {
1130                // For non-paged media, the false goes through an
1131                // intval, turning failure into 0, so do same here.
1132                return 0;
1133            }
1134        } else {
1135            return $this->height;
1136        }
1137    }
1138
1139    /**
1140     * Get short description URL for a file based on the page ID.
1141     * @stable to override
1142     *
1143     * @return string|null
1144     * @since 1.27
1145     */
1146    public function getDescriptionShortUrl() {
1147        if ( !$this->title ) {
1148            return null; // Avoid hard failure when the file does not exist. T221812
1149        }
1150
1151        $pageId = $this->title->getArticleID();
1152
1153        if ( $pageId ) {
1154            $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
1155            if ( $url !== false ) {
1156                return $url;
1157            }
1158        }
1159        return null;
1160    }
1161
1162    /**
1163     * Get handler-specific metadata as a serialized string
1164     *
1165     * @deprecated since 1.37 use getMetadataArray() or getMetadataItem()
1166     * @return string
1167     */
1168    public function getMetadata() {
1169        $data = $this->getMetadataArray();
1170        if ( !$data ) {
1171            return '';
1172        } elseif ( array_keys( $data ) === [ '_error' ] ) {
1173            // Legacy error encoding
1174            return $data['_error'];
1175        } else {
1176            return serialize( $this->getMetadataArray() );
1177        }
1178    }
1179
1180    /**
1181     * Get unserialized handler-specific metadata
1182     *
1183     * @since 1.37
1184     * @return array
1185     */
1186    public function getMetadataArray(): array {
1187        $this->load( self::LOAD_ALL );
1188        if ( $this->unloadedMetadataBlobs ) {
1189            return $this->getMetadataItems(
1190                array_unique( array_merge(
1191                    array_keys( $this->metadataArray ),
1192                    array_keys( $this->unloadedMetadataBlobs )
1193                ) )
1194            );
1195        }
1196        return $this->metadataArray;
1197    }
1198
1199    public function getMetadataItems( array $itemNames ): array {
1200        $this->load( self::LOAD_ALL );
1201        $result = [];
1202        $addresses = [];
1203        foreach ( $itemNames as $itemName ) {
1204            if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1205                $result[$itemName] = $this->metadataArray[$itemName];
1206            } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1207                $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1208            }
1209        }
1210
1211        if ( $addresses ) {
1212            $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1213            foreach ( $addresses as $itemName => $address ) {
1214                unset( $this->unloadedMetadataBlobs[$itemName] );
1215                $value = $resultFromBlob[$itemName] ?? null;
1216                if ( $value !== null ) {
1217                    $result[$itemName] = $value;
1218                    $this->metadataArray[$itemName] = $value;
1219                }
1220            }
1221        }
1222        return $result;
1223    }
1224
1225    /**
1226     * Serialize the metadata array for insertion into img_metadata, oi_metadata
1227     * or fa_metadata.
1228     *
1229     * If metadata splitting is enabled, this may write blobs to the database,
1230     * returning their addresses.
1231     *
1232     * @internal
1233     * @param IReadableDatabase $db
1234     * @return string|Blob
1235     */
1236    public function getMetadataForDb( IReadableDatabase $db ) {
1237        $this->load( self::LOAD_ALL );
1238        if ( !$this->metadataArray && !$this->metadataBlobs ) {
1239            $s = '';
1240        } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1241            $s = $this->getJsonMetadata();
1242        } else {
1243            $s = serialize( $this->getMetadataArray() );
1244        }
1245        if ( !is_string( $s ) ) {
1246            throw new RuntimeException( 'Could not serialize image metadata value for DB' );
1247        }
1248        return $db->encodeBlob( $s );
1249    }
1250
1251    /**
1252     * Get metadata in JSON format ready for DB insertion, optionally splitting
1253     * items out to BlobStore.
1254     *
1255     * @return string
1256     */
1257    private function getJsonMetadata() {
1258        // Directly store data that is not already in BlobStore
1259        $envelope = [
1260            'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1261        ];
1262
1263        // Also store the blob addresses
1264        if ( $this->metadataBlobs ) {
1265            $envelope['blobs'] = $this->metadataBlobs;
1266        }
1267
1268        [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1269
1270        // Repeated calls to this function should not keep inserting more blobs
1271        $this->metadataBlobs += $blobAddresses;
1272
1273        return $s;
1274    }
1275
1276    /**
1277     * Determine whether the loaded metadata may be a candidate for splitting, by measuring its
1278     * serialized size. Helper for maybeUpgradeRow().
1279     *
1280     * @return bool
1281     */
1282    private function isMetadataOversize() {
1283        if ( !$this->repo->isSplitMetadataEnabled() ) {
1284            return false;
1285        }
1286        $threshold = $this->repo->getSplitMetadataThreshold();
1287        $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1288        foreach ( $directItems as $value ) {
1289            if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1290                return true;
1291            }
1292        }
1293        return false;
1294    }
1295
1296    /**
1297     * Unserialize a metadata blob which came from the database and store it
1298     * in $this.
1299     *
1300     * @since 1.37
1301     * @param IReadableDatabase $db
1302     * @param string|Blob $metadataBlob
1303     */
1304    protected function loadMetadataFromDbFieldValue( IReadableDatabase $db, $metadataBlob ) {
1305        $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1306    }
1307
1308    /**
1309     * Unserialize a metadata string which came from some non-DB source, or is
1310     * the return value of IReadableDatabase::decodeBlob().
1311     *
1312     * @since 1.37
1313     * @param string $metadataString
1314     */
1315    protected function loadMetadataFromString( $metadataString ) {
1316        $this->extraDataLoaded = true;
1317        $this->metadataArray = [];
1318        $this->metadataBlobs = [];
1319        $this->unloadedMetadataBlobs = [];
1320        $metadataString = (string)$metadataString;
1321        if ( $metadataString === '' ) {
1322            $this->metadataSerializationFormat = self::MDS_EMPTY;
1323            return;
1324        }
1325        if ( $metadataString[0] === '{' ) {
1326            $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1327            if ( !$envelope ) {
1328                // Legacy error encoding
1329                $this->metadataArray = [ '_error' => $metadataString ];
1330                $this->metadataSerializationFormat = self::MDS_LEGACY;
1331            } else {
1332                $this->metadataSerializationFormat = self::MDS_JSON;
1333                if ( isset( $envelope['data'] ) ) {
1334                    $this->metadataArray = $envelope['data'];
1335                }
1336                if ( isset( $envelope['blobs'] ) ) {
1337                    $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1338                }
1339            }
1340        } else {
1341            // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1342            $data = @unserialize( $metadataString );
1343            if ( !is_array( $data ) ) {
1344                // Legacy error encoding
1345                $data = [ '_error' => $metadataString ];
1346                $this->metadataSerializationFormat = self::MDS_LEGACY;
1347            } else {
1348                $this->metadataSerializationFormat = self::MDS_PHP;
1349            }
1350            $this->metadataArray = $data;
1351        }
1352    }
1353
1354    /**
1355     * @stable to override
1356     * @return int
1357     */
1358    public function getBitDepth() {
1359        $this->load();
1360
1361        return (int)$this->bits;
1362    }
1363
1364    /**
1365     * Returns the size of the image file, in bytes
1366     * @stable to override
1367     * @return int
1368     */
1369    public function getSize() {
1370        $this->load();
1371
1372        return $this->size;
1373    }
1374
1375    /**
1376     * Returns the MIME type of the file.
1377     * @stable to override
1378     * @return string
1379     */
1380    public function getMimeType() {
1381        $this->load();
1382
1383        return $this->mime;
1384    }
1385
1386    /**
1387     * Returns the type of the media in the file.
1388     * Use the value returned by this function with the MEDIATYPE_xxx constants.
1389     * @stable to override
1390     * @return string
1391     */
1392    public function getMediaType() {
1393        $this->load();
1394
1395        return $this->media_type;
1396    }
1397
1398    /** canRender inherited */
1399    /** mustRender inherited */
1400    /** allowInlineDisplay inherited */
1401    /** isSafeFile inherited */
1402    /** isTrustedFile inherited */
1403
1404    /**
1405     * Returns true if the file exists on disk.
1406     * @stable to override
1407     * @return bool Whether file exist on disk.
1408     */
1409    public function exists() {
1410        $this->load();
1411
1412        return $this->fileExists;
1413    }
1414
1415    /** getTransformScript inherited */
1416    /** getUnscaledThumb inherited */
1417    /** thumbName inherited */
1418    /** createThumb inherited */
1419    /** transform inherited */
1420
1421    /** getHandler inherited */
1422    /** iconThumb inherited */
1423    /** getLastError inherited */
1424
1425    /**
1426     * Get all thumbnail names previously generated for this file.
1427     *
1428     * This should be called during POST requests only (and other db-writing
1429     * contexts) as it may involve connections across multiple data centers
1430     * (e.g. both backends of a FileBackendMultiWrite setup).
1431     *
1432     * @stable to override
1433     * @param string|false $archiveName Name of an archive file, default false
1434     * @return array First element is the base dir, then files in that base dir.
1435     */
1436    protected function getThumbnails( $archiveName = false ) {
1437        if ( $archiveName ) {
1438            $dir = $this->getArchiveThumbPath( $archiveName );
1439        } else {
1440            $dir = $this->getThumbPath();
1441        }
1442
1443        $backend = $this->repo->getBackend();
1444        $files = [ $dir ];
1445        try {
1446            $iterator = $backend->getFileList( [ 'dir' => $dir, 'forWrite' => true ] );
1447            if ( $iterator !== null ) {
1448                foreach ( $iterator as $file ) {
1449                    $files[] = $file;
1450                }
1451            }
1452        } catch ( FileBackendError ) {
1453        } // suppress (T56674)
1454
1455        return $files;
1456    }
1457
1458    /**
1459     * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1460     * @stable to override
1461     *
1462     * @param array $options An array potentially with the key forThumbRefresh.
1463     *
1464     * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1465     */
1466    public function purgeCache( $options = [] ) {
1467        // Refresh metadata in memcached, but don't touch thumbnails or CDN
1468        $this->maybeUpgradeRow();
1469        $this->invalidateCache();
1470
1471        // Delete thumbnails
1472        $this->purgeThumbnails( $options );
1473
1474        // Purge CDN cache for this file
1475        $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
1476        $hcu->purgeUrls(
1477            $this->getUrl(),
1478            !empty( $options['forThumbRefresh'] )
1479                ? $hcu::PURGE_PRESEND // just a manual purge
1480                : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1481        );
1482    }
1483
1484    /**
1485     * Delete cached transformed files for an archived version only.
1486     * @stable to override
1487     * @param string $archiveName Name of the archived file
1488     */
1489    public function purgeOldThumbnails( $archiveName ) {
1490        // Get a list of old thumbnails
1491        $thumbs = $this->getThumbnails( $archiveName );
1492
1493        // Delete thumbnails from storage, and prevent the directory itself from being purged
1494        $dir = array_shift( $thumbs );
1495        $this->purgeThumbList( $dir, $thumbs );
1496
1497        $urls = [];
1498        foreach ( $thumbs as $thumb ) {
1499            $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1500        }
1501
1502        // Purge any custom thumbnail caches
1503        $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1504
1505        // Purge the CDN
1506        $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
1507        $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1508    }
1509
1510    /**
1511     * Delete cached transformed files for the current version only.
1512     * @stable to override
1513     * @param array $options
1514     * @phan-param array{forThumbRefresh?:bool} $options
1515     */
1516    public function purgeThumbnails( $options = [] ) {
1517        $thumbs = $this->getThumbnails();
1518
1519        // Delete thumbnails from storage, and prevent the directory itself from being purged
1520        $dir = array_shift( $thumbs );
1521        $this->purgeThumbList( $dir, $thumbs );
1522
1523        // Always purge all files from CDN regardless of handler filters
1524        $urls = [];
1525        foreach ( $thumbs as $thumb ) {
1526            $urls[] = $this->getThumbUrl( $thumb );
1527        }
1528
1529        // Give the media handler a chance to filter the file purge list
1530        if ( !empty( $options['forThumbRefresh'] ) ) {
1531            $handler = $this->getHandler();
1532            if ( $handler ) {
1533                $handler->filterThumbnailPurgeList( $thumbs, $options );
1534            }
1535        }
1536
1537        // Purge any custom thumbnail caches
1538        $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1539
1540        // Purge the CDN
1541        $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
1542        $hcu->purgeUrls(
1543            $urls,
1544            !empty( $options['forThumbRefresh'] )
1545                ? $hcu::PURGE_PRESEND // just a manual purge
1546                : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1547        );
1548    }
1549
1550    /**
1551     * Prerenders a configurable set of thumbnails
1552     * @stable to override
1553     *
1554     * @since 1.28
1555     */
1556    public function prerenderThumbnails() {
1557        $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1558            ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1559
1560        $jobs = [];
1561
1562        $sizes = $uploadThumbnailRenderMap;
1563        rsort( $sizes );
1564
1565        foreach ( $sizes as $size ) {
1566            if ( $this->isMultipage() ) {
1567                // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1568                // a flood of jobs for huge files.
1569                $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1570
1571                $jobs[] = new ThumbnailRenderJob(
1572                    $this->getTitle(),
1573                    [
1574                    'transformParams' => [ 'width' => $size, 'page' => 1 ],
1575                    'enqueueNextPage' => true,
1576                    'pageLimit' => $pageLimit
1577                    ]
1578                );
1579            } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1580                $jobs[] = new ThumbnailRenderJob(
1581                    $this->getTitle(),
1582                    [ 'transformParams' => [ 'width' => $size ] ]
1583                );
1584            }
1585        }
1586
1587        if ( $jobs ) {
1588            MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1589        }
1590    }
1591
1592    /**
1593     * Delete a list of thumbnails visible at urls
1594     * @stable to override
1595     * @param string $dir Base dir of the files.
1596     * @param array $files Array of strings: relative filenames (to $dir)
1597     */
1598    protected function purgeThumbList( $dir, $files ) {
1599        $fileListDebug = strtr(
1600            var_export( $files, true ),
1601            [ "\n" => '' ]
1602        );
1603        wfDebug( __METHOD__ . "$fileListDebug" );
1604
1605        if ( $this->repo->supportsSha1URLs() ) {
1606            $reference = $this->getSha1();
1607        } else {
1608            $reference = $this->getName();
1609        }
1610
1611        $purgeList = [];
1612        foreach ( $files as $file ) {
1613            # Check that the reference (filename or sha1) is part of the thumb name
1614            # This is a basic check to avoid erasing unrelated directories
1615            if ( str_contains( $file, $reference )
1616                || str_contains( $file, "-thumbnail" ) // "short" thumb name
1617            ) {
1618                $purgeList[] = "{$dir}/{$file}";
1619            }
1620        }
1621
1622        # Delete the thumbnails
1623        $this->repo->quickPurgeBatch( $purgeList );
1624        # Clear out the thumbnail directory if empty
1625        $this->repo->quickCleanDir( $dir );
1626    }
1627
1628    /** purgeDescription inherited */
1629    /** purgeEverything inherited */
1630
1631    /**
1632     * @stable to override
1633     * @param int|null $limit Optional: Limit to number of results
1634     * @param string|int|null $start Optional: Timestamp, start from
1635     * @param string|int|null $end Optional: Timestamp, end at
1636     * @param bool $inc
1637     * @return OldLocalFile[] Guaranteed to be in descending order
1638     */
1639    public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1640        if ( !$this->exists() ) {
1641            return []; // Avoid hard failure when the file does not exist. T221812
1642        }
1643
1644        $dbr = $this->repo->getReplicaDB();
1645        $oldFileQuery = FileSelectQueryBuilder::newForOldFile( $dbr )->getQueryInfo();
1646
1647        $tables = $oldFileQuery['tables'];
1648        $fields = $oldFileQuery['fields'];
1649        $join_conds = $oldFileQuery['join_conds'];
1650        $conds = $opts = [];
1651        $eq = $inc ? '=' : '';
1652        $conds[] = $dbr->expr( 'oi_name', '=', $this->title->getDBkey() );
1653
1654        if ( $start ) {
1655            $conds[] = $dbr->expr( 'oi_timestamp', "<$eq", $dbr->timestamp( $start ) );
1656        }
1657
1658        if ( $end ) {
1659            $conds[] = $dbr->expr( 'oi_timestamp', ">$eq", $dbr->timestamp( $end ) );
1660        }
1661
1662        if ( $limit ) {
1663            $opts['LIMIT'] = $limit;
1664        }
1665
1666        // Search backwards for time > x queries
1667        $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1668        $opts['ORDER BY'] = "oi_timestamp $order";
1669        $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1670
1671        $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1672            $conds, $opts, $join_conds );
1673
1674        $res = $dbr->newSelectQueryBuilder()
1675            ->tables( $tables )
1676            ->fields( $fields )
1677            ->conds( $conds )
1678            ->caller( __METHOD__ )
1679            ->options( $opts )
1680            ->joinConds( $join_conds )
1681            ->fetchResultSet();
1682        $r = [];
1683
1684        foreach ( $res as $row ) {
1685            $r[] = $this->repo->newFileFromRow( $row );
1686        }
1687
1688        if ( $order == 'ASC' ) {
1689            $r = array_reverse( $r ); // make sure it ends up descending
1690        }
1691
1692        return $r;
1693    }
1694
1695    /**
1696     * Returns the history of this file, line by line.
1697     * starts with current version, then old versions.
1698     * uses $this->historyLine to check which line to return:
1699     *  0      return line for current version
1700     *  1      query for old versions, return first one
1701     *  2, ... return next old version from above query
1702     * @stable to override
1703     * @return stdClass|false
1704     */
1705    public function nextHistoryLine() {
1706        if ( !$this->exists() ) {
1707            return false; // Avoid hard failure when the file does not exist. T221812
1708        }
1709
1710        # Polymorphic function name to distinguish foreign and local fetches
1711        $fname = static::class . '::' . __FUNCTION__;
1712
1713        $dbr = $this->repo->getReplicaDB();
1714
1715        if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1716            $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
1717
1718            $queryBuilder->fields( [ 'oi_archive_name' => $dbr->addQuotes( '' ), 'oi_deleted' => '0' ] )
1719                ->where( [ 'img_name' => $this->title->getDBkey() ] );
1720            $this->historyRes = $queryBuilder->caller( $fname )->fetchResultSet();
1721
1722            if ( $this->historyRes->numRows() == 0 ) {
1723                $this->historyRes = null;
1724
1725                return false;
1726            }
1727        } elseif ( $this->historyLine == 1 ) {
1728            $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
1729
1730            $this->historyRes = $queryBuilder->where( [ 'oi_name' => $this->title->getDBkey() ] )
1731                ->orderBy( 'oi_timestamp', SelectQueryBuilder::SORT_DESC )
1732                ->caller( $fname )->fetchResultSet();
1733        }
1734        $this->historyLine++;
1735
1736        return $this->historyRes->fetchObject();
1737    }
1738
1739    /**
1740     * Reset the history pointer to the first element of the history
1741     * @stable to override
1742     */
1743    public function resetHistory() {
1744        $this->historyLine = 0;
1745
1746        if ( $this->historyRes !== null ) {
1747            $this->historyRes = null;
1748        }
1749    }
1750
1751    /** getHashPath inherited */
1752    /** getRel inherited */
1753    /** getUrlRel inherited */
1754    /** getArchiveRel inherited */
1755    /** getArchivePath inherited */
1756    /** getThumbPath inherited */
1757    /** getArchiveUrl inherited */
1758    /** getThumbUrl inherited */
1759    /** getArchiveVirtualUrl inherited */
1760    /** getThumbVirtualUrl inherited */
1761    /** isHashed inherited */
1762
1763    /**
1764     * Upload a file and record it in the DB
1765     * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1766     * @param string $comment Upload description
1767     * @param string $pageText Text to use for the new description page,
1768     *   if a new description page is created
1769     * @param int $flags Flags for publish()
1770     * @param array|false $props File properties, if known. This can be used to
1771     *   reduce the upload time when uploading virtual URLs for which the file
1772     *   info is already known
1773     * @param string|false $timestamp Timestamp for img_timestamp, or false to use the
1774     *   current time. Can be in any format accepted by ConvertibleTimestamp.
1775     * @param Authority|null $uploader object or null to use the context authority
1776     * @param string[] $tags Change tags to add to the log entry and page revision.
1777     *   (This doesn't check $uploader's permissions.)
1778     * @param bool $createDummyRevision Set to false to avoid creation of a dummy revision on file
1779     *   upload, see T193621
1780     * @param bool $revert If this file upload is a revert
1781     * @return Status On success, the value member contains the
1782     *     archive name, or an empty string if it was a new file.
1783     */
1784    public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1785        $timestamp = false, ?Authority $uploader = null, $tags = [],
1786        $createDummyRevision = true, $revert = false
1787    ) {
1788        if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1789            return $this->readOnlyFatalStatus();
1790        } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1791            // Check this in advance to avoid writing to FileBackend and the file tables,
1792            // only to fail on insert the revision due to the text store being unavailable.
1793            return $this->readOnlyFatalStatus();
1794        }
1795
1796        $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1797        if ( !$props ) {
1798            if ( FileRepo::isVirtualUrl( $srcPath )
1799                || FileBackend::isStoragePath( $srcPath )
1800            ) {
1801                $props = $this->repo->getFileProps( $srcPath );
1802            } else {
1803                $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1804                $props = $mwProps->getPropsFromPath( $srcPath, true );
1805            }
1806        }
1807
1808        $options = [];
1809        $handler = MediaHandler::getHandler( $props['mime'] );
1810        if ( $handler ) {
1811            if ( is_string( $props['metadata'] ) ) {
1812                // This supports callers directly fabricating a metadata
1813                // property using serialize(). Normally the metadata property
1814                // comes from MWFileProps, in which case it won't be a string.
1815                // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1816                $metadata = @unserialize( $props['metadata'] );
1817            } else {
1818                $metadata = $props['metadata'];
1819            }
1820
1821            if ( is_array( $metadata ) ) {
1822                $options['headers'] = $handler->getContentHeaders( $metadata );
1823            }
1824        } else {
1825            $options['headers'] = [];
1826        }
1827
1828        // Trim spaces on user supplied text
1829        $comment = trim( $comment );
1830
1831        $status = $this->publish( $src, $flags, $options );
1832
1833        if ( $status->successCount >= 2 ) {
1834            // There will be a copy+(one of move,copy,store).
1835            // The first succeeding does not commit us to updating the DB
1836            // since it simply copied the current version to a timestamped file name.
1837            // It is only *preferable* to avoid leaving such files orphaned.
1838            // Once the second operation goes through, then the current version was
1839            // updated and we must therefore update the DB too.
1840            $oldver = $status->value;
1841
1842            $uploadStatus = $this->recordUpload3(
1843                $oldver,
1844                $comment,
1845                $pageText,
1846                $uploader ?? RequestContext::getMain()->getAuthority(),
1847                $props,
1848                $timestamp,
1849                $tags,
1850                $createDummyRevision,
1851                $revert
1852            );
1853            if ( !$uploadStatus->isOK() ) {
1854                if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1855                    // update filenotfound error with more specific path
1856                    $status->fatal( 'filenotfound', $srcPath );
1857                } else {
1858                    $status->merge( $uploadStatus );
1859                }
1860            }
1861        }
1862
1863        return $status;
1864    }
1865
1866    /**
1867     * Record a file upload in the upload log and the image table (version 3)
1868     * @since 1.35
1869     * @stable to override
1870     * @param string $oldver
1871     * @param string $comment
1872     * @param string $pageText File description page text (only used for new uploads)
1873     * @param Authority $performer
1874     * @param array|false $props
1875     * @param string|false $timestamp Can be in any format accepted by ConvertibleTimestamp
1876     * @param string[] $tags
1877     * @param bool $createDummyRevision Set to false to avoid creation of a dummy revision on file
1878     *   upload, see T193621
1879     * @param bool $revert If this file upload is a revert
1880     * @return Status
1881     */
1882    public function recordUpload3(
1883        string $oldver,
1884        string $comment,
1885        string $pageText,
1886        Authority $performer,
1887        $props = false,
1888        $timestamp = false,
1889        $tags = [],
1890        bool $createDummyRevision = true,
1891        bool $revert = false
1892    ): Status {
1893        $dbw = $this->repo->getPrimaryDB();
1894
1895        # Imports or such might force a certain timestamp; otherwise we generate
1896        # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1897        if ( $timestamp === false ) {
1898            $timestamp = $dbw->timestamp();
1899            $allowTimeKludge = true;
1900        } else {
1901            $allowTimeKludge = false;
1902        }
1903
1904        $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1905        $props['description'] = $comment;
1906        $props['timestamp'] = wfTimestamp( TS::MW, $timestamp ); // DB -> TS::MW
1907        $this->setProps( $props );
1908
1909        # Fail now if the file isn't there
1910        if ( !$this->fileExists ) {
1911            wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1912
1913            return Status::newFatal( 'filenotfound', $this->getRel() );
1914        }
1915
1916        $mimeAnalyzer = MediaWikiServices::getInstance()->getMimeAnalyzer();
1917        if ( !$mimeAnalyzer->isValidMajorMimeType( $this->major_mime ) ) {
1918            $this->major_mime = 'unknown';
1919        }
1920
1921        $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1922
1923        // T391473: File uploads can involve moving a lot of bytes around. Sometimes in
1924        // that time the DB connection can timeout. Normally this is automatically
1925        // reconnected, but reconnection does not work inside atomic sections.
1926        // Ping the DB to ensure it is still there prior to entering the atomic
1927        // section. TODO: Refactor upload jobs to be smarter about implicit transactions.
1928        $dbw->ping();
1929        $dbw->startAtomic( __METHOD__ );
1930
1931        $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1932        $this->user = $performer->getUser();
1933        $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1934
1935        if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
1936            // Test to see if the row exists using INSERT IGNORE
1937            // This avoids race conditions by locking the row until the commit, and also
1938            // doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1939            $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1940            $actorFields = [ 'img_actor' => $actorId ];
1941            $dbw->newInsertQueryBuilder()
1942                ->insertInto( 'image' )
1943                ->ignore()
1944                ->row( [
1945                        'img_name' => $this->getName(),
1946                        'img_size' => $this->size,
1947                        'img_width' => intval( $this->width ),
1948                        'img_height' => intval( $this->height ),
1949                        'img_bits' => $this->bits,
1950                        'img_media_type' => $this->media_type,
1951                        'img_major_mime' => $this->major_mime,
1952                        'img_minor_mime' => $this->minor_mime,
1953                        'img_timestamp' => $dbw->timestamp( $timestamp ),
1954                        'img_metadata' => $this->getMetadataForDb( $dbw ),
1955                        'img_sha1' => $this->sha1
1956                    ] + $commentFields + $actorFields )
1957                ->caller( __METHOD__ )->execute();
1958            $reupload = ( $dbw->affectedRows() == 0 );
1959        } else {
1960            $reupload = $this->getFileIdFromName();
1961        }
1962
1963        if ( $reupload ) {
1964            if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
1965                $row = $dbw->newSelectQueryBuilder()
1966                    ->select( [ 'img_timestamp', 'img_sha1' ] )
1967                    ->from( 'image' )
1968                    ->where( [ 'img_name' => $this->getName() ] )
1969                    ->caller( __METHOD__ )->fetchRow();
1970            } else {
1971                $row = $dbw->newSelectQueryBuilder()
1972                    ->select( [
1973                        'img_timestamp' => 'fr_timestamp',
1974                        'img_sha1' => 'fr_sha1',
1975                    ] )
1976                    ->from( 'file' )
1977                    ->join( 'filerevision', null, 'file_latest = fr_id' )
1978                    ->where( [ 'file_id' => $this->getFileIdFromName() ] )
1979                    ->caller( __METHOD__ )->fetchRow();
1980            }
1981
1982            if ( $row && $row->img_sha1 === $this->sha1 ) {
1983                $dbw->endAtomic( __METHOD__ );
1984                wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1985                $title = Title::newFromText( $this->getName(), NS_FILE );
1986                return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1987            }
1988            if ( $allowTimeKludge ) {
1989                # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1990                $lUnixtime = $row ? (int)wfTimestamp( TS::UNIX, $row->img_timestamp ) : false;
1991                # Avoid a timestamp that is not newer than the last version
1992                # TODO: the image/oldimage tables should be like page/revision with an ID field
1993                if ( $lUnixtime && (int)wfTimestamp( TS::UNIX, $timestamp ) <= $lUnixtime ) {
1994                    sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1995                    $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1996                    $this->timestamp = wfTimestamp( TS::MW, $timestamp ); // DB -> TS::MW
1997                }
1998            }
1999        }
2000        $latestFileRevId = null;
2001        if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
2002            if ( $reupload ) {
2003                $latestFileRevId = $dbw->newSelectQueryBuilder()
2004                    ->select( 'fr_id' )
2005                    ->from( 'filerevision' )
2006                    ->where( [ 'fr_file' => $this->acquireFileIdFromName() ] )
2007                    ->orderBy( 'fr_timestamp', 'DESC' )
2008                    ->caller( __METHOD__ )
2009                    ->fetchField();
2010            }
2011            $commentFieldsNew = $commentStore->insert( $dbw, 'fr_description', $comment );
2012            $dbw->newInsertQueryBuilder()
2013                ->insertInto( 'filerevision' )
2014                ->row( [
2015                        'fr_file' => $this->acquireFileIdFromName(),
2016                        'fr_size' => $this->size,
2017                        'fr_width' => intval( $this->width ),
2018                        'fr_height' => intval( $this->height ),
2019                        'fr_bits' => $this->bits,
2020                        'fr_actor' => $actorId,
2021                        'fr_deleted' => 0,
2022                        'fr_timestamp' => $dbw->timestamp( $timestamp ),
2023                        'fr_metadata' => $this->getMetadataForDb( $dbw ),
2024                        'fr_sha1' => $this->sha1
2025                    ] + $commentFieldsNew )
2026                ->caller( __METHOD__ )->execute();
2027            $dbw->newUpdateQueryBuilder()
2028                ->update( 'file' )
2029                ->set( [ 'file_latest' => $dbw->insertId() ] )
2030                ->where( [ 'file_id' => $this->getFileIdFromName() ] )
2031                ->caller( __METHOD__ )->execute();
2032        }
2033
2034        if ( $reupload ) {
2035            if ( ( $this->migrationStage & SCHEMA_COMPAT_WRITE_NEW ) && $latestFileRevId && $oldver ) {
2036                $dbw->newUpdateQueryBuilder()
2037                    ->update( 'filerevision' )
2038                    ->set( [ 'fr_archive_name' => $oldver ] )
2039                    ->where( [ 'fr_id' => $latestFileRevId ] )
2040                    ->caller( __METHOD__ )->execute();
2041            }
2042
2043            if ( $this->migrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
2044                $tables = [ 'image' ];
2045                $fields = [
2046                    'oi_name' => 'img_name',
2047                    'oi_archive_name' => $dbw->addQuotes( $oldver ),
2048                    'oi_size' => 'img_size',
2049                    'oi_width' => 'img_width',
2050                    'oi_height' => 'img_height',
2051                    'oi_bits' => 'img_bits',
2052                    'oi_description_id' => 'img_description_id',
2053                    'oi_timestamp' => 'img_timestamp',
2054                    'oi_metadata' => 'img_metadata',
2055                    'oi_media_type' => 'img_media_type',
2056                    'oi_major_mime' => 'img_major_mime',
2057                    'oi_minor_mime' => 'img_minor_mime',
2058                    'oi_sha1' => 'img_sha1',
2059                    'oi_actor' => 'img_actor',
2060                ];
2061                $joins = [];
2062                // (T36993) Note: $oldver can be empty here, if the previous
2063                // version of the file was broken. Allow registration of the new
2064                // version to continue anyway, because that's better than having
2065                // an image that's not fixable by user operations.
2066                // Collision, this is an update of a file
2067                // Insert previous contents into oldimage
2068                $dbw->insertSelect( 'oldimage', $tables, $fields,
2069                    [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
2070
2071                // Update the current image row
2072                $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
2073                $actorFields = [ 'img_actor' => $actorId ];
2074                $dbw->newUpdateQueryBuilder()
2075                    ->update( 'image' )
2076                    ->set( [
2077                            'img_size' => $this->size,
2078                            'img_width' => intval( $this->width ),
2079                            'img_height' => intval( $this->height ),
2080                            'img_bits' => $this->bits,
2081                            'img_media_type' => $this->media_type,
2082                            'img_major_mime' => $this->major_mime,
2083                            'img_minor_mime' => $this->minor_mime,
2084                            'img_timestamp' => $dbw->timestamp( $timestamp ),
2085                            'img_metadata' => $this->getMetadataForDb( $dbw ),
2086                            'img_sha1' => $this->sha1
2087                        ] + $commentFields + $actorFields )
2088                    ->where( [ 'img_name' => $this->getName() ] )
2089                    ->caller( __METHOD__ )->execute();
2090            }
2091        }
2092
2093        $descTitle = $this->getTitle();
2094        $descId = $descTitle->getArticleID();
2095        $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
2096        if ( !$wikiPage instanceof WikiFilePage ) {
2097            throw new UnexpectedValueException( 'Cannot obtain instance of WikiFilePage for ' . $this->getName()
2098                . ', got instance of ' . get_class( $wikiPage ) );
2099        }
2100        $wikiPage->setFile( $this );
2101
2102        // Determine log action. If reupload is done by reverting, use a special log_action.
2103        if ( $revert ) {
2104            $logAction = 'revert';
2105        } elseif ( $reupload ) {
2106            $logAction = 'overwrite';
2107        } else {
2108            $logAction = 'upload';
2109        }
2110        // Add the log entry...
2111        $logEntry = new ManualLogEntry( 'upload', $logAction );
2112        $logEntry->setTimestamp( $this->timestamp );
2113        $logEntry->setPerformer( $performer->getUser() );
2114        $logEntry->setComment( $comment );
2115        $logEntry->setTarget( $descTitle );
2116        // Allow people using the api to associate log entries with the upload.
2117        // Log has a timestamp, but sometimes different from upload timestamp.
2118        $logEntry->setParameters(
2119            [
2120                'img_sha1' => $this->sha1,
2121                'img_timestamp' => $timestamp,
2122            ]
2123        );
2124        // Note we keep $logId around since during new image
2125        // creation, page doesn't exist yet, so log_page = 0
2126        // but we want it to point to the page we're making,
2127        // so we later modify the log entry.
2128        // For a similar reason, we avoid making an RC entry
2129        // now and wait until the page exists.
2130        $logId = $logEntry->insert();
2131
2132        if ( $descTitle->exists() ) {
2133            if ( $createDummyRevision ) {
2134                $services = MediaWikiServices::getInstance();
2135                // Use own context to get the action text in content language
2136                $formatter = $services->getLogFormatterFactory()->newFromEntry( $logEntry );
2137                $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
2138                $editSummary = $formatter->getPlainActionText();
2139
2140                $dummyRevRecord = $wikiPage->newPageUpdater( $performer->getUser() )
2141                    ->setCause( PageUpdater::CAUSE_UPLOAD )
2142                    ->saveDummyRevision( $editSummary, EDIT_SILENT );
2143
2144                // Associate dummy revision id
2145                $logEntry->setAssociatedRevId( $dummyRevRecord->getId() );
2146            }
2147
2148            $newPageContent = null;
2149        } else {
2150            // Make the description page and RC log entry post-commit
2151            $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
2152        }
2153
2154        // NOTE: Even after ending this atomic section, we are probably still in the implicit
2155        // transaction started by any prior master query in the request. We cannot yet safely
2156        // schedule jobs, see T263301.
2157        $dbw->endAtomic( __METHOD__ );
2158        $fname = __METHOD__;
2159
2160        # Do some cache purges after final commit so that:
2161        # a) Changes are more likely to be seen post-purge
2162        # b) They won't cause rollback of the log publish/update above
2163        $purgeUpdate = new AutoCommitUpdate(
2164            $dbw,
2165            __METHOD__,
2166            function () use (
2167                $reupload, $wikiPage, $newPageContent, $comment, $performer,
2168                $logEntry, $logId, $descId, $tags, $fname
2169            ) {
2170                # Update memcache after the commit
2171                $this->invalidateCache();
2172
2173                $updateLogPage = false;
2174                if ( $newPageContent ) {
2175                    # New file page; create the description page.
2176                    # There's already a log entry, so don't make a second RC entry
2177                    # CDN and file cache for the description page are purged by doUserEditContent.
2178                    $revRecord = $wikiPage->newPageUpdater( $performer )
2179                        ->setCause( PageUpdater::CAUSE_UPLOAD )
2180                        ->setContent( SlotRecord::MAIN, $newPageContent )
2181                        ->saveRevision( $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
2182
2183                    if ( $revRecord ) {
2184                        // Associate new page revision id
2185                        $logEntry->setAssociatedRevId( $revRecord->getId() );
2186
2187                        // This relies on the resetArticleID() call in WikiPage::insertOn(),
2188                        // which is triggered on $descTitle by doUserEditContent() above.
2189                        $updateLogPage = $revRecord->getPageId();
2190                    }
2191                } else {
2192                    # Existing file page: invalidate description page cache
2193                    $title = $wikiPage->getTitle();
2194                    $title->invalidateCache();
2195                    $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
2196                    $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2197                    # Allow the new file version to be patrolled from the page footer
2198                    Article::purgePatrolFooterCache( $descId );
2199                }
2200
2201                # Update associated rev id. This should be done by $logEntry->insert() earlier,
2202                # but setAssociatedRevId() wasn't called at that point yet...
2203                $logParams = $logEntry->getParameters();
2204                $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2205                $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
2206                if ( $updateLogPage ) {
2207                    # Also log page, in case where we just created it above
2208                    $update['log_page'] = $updateLogPage;
2209                }
2210                $this->getRepo()->getPrimaryDB()->newUpdateQueryBuilder()
2211                    ->update( 'logging' )
2212                    ->set( $update )
2213                    ->where( [ 'log_id' => $logId ] )
2214                    ->caller( $fname )->execute();
2215
2216                $this->getRepo()->getPrimaryDB()->newInsertQueryBuilder()
2217                    ->insertInto( 'log_search' )
2218                    ->row( [
2219                        'ls_field' => 'associated_rev_id',
2220                        'ls_value' => (string)$logEntry->getAssociatedRevId(),
2221                        'ls_log_id' => $logId,
2222                    ] )
2223                    ->caller( $fname )->execute();
2224
2225                # Add change tags, if any
2226                if ( $tags ) {
2227                    $logEntry->addTags( $tags );
2228                }
2229
2230                # Uploads can be patrolled
2231                $logEntry->setIsPatrollable( true );
2232
2233                # Now that the log entry is up-to-date, make an RC entry.
2234                $logEntry->publish( $logId );
2235
2236                # Run hook for other updates (typically more cache purging)
2237                $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2238
2239                if ( $reupload ) {
2240                    # Delete old thumbnails
2241                    $this->purgeThumbnails();
2242                    # Remove the old file from the CDN cache
2243                    $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
2244                    $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2245                } else {
2246                    # Update backlink pages pointing to this title if created
2247                    $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2248                    LinksUpdate::queueRecursiveJobsForTable(
2249                        $this->getTitle(),
2250                        'imagelinks',
2251                        'upload-image',
2252                        $performer->getUser()->getName(),
2253                        $blcFactory->getBacklinkCache( $this->getTitle() )
2254                    );
2255                }
2256
2257                $this->prerenderThumbnails();
2258            }
2259        );
2260
2261        # Invalidate cache for all pages using this file
2262        $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2263            $this->getTitle(),
2264            'imagelinks',
2265            [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2266        );
2267
2268        // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2269        // only schedule jobs after that transaction was committed, so a job queue failure
2270        // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2271        // Jobs or the DeferredUpdates that assume the update is complete until after the
2272        // transaction has been committed and we are sure that the upload was indeed successful.
2273        $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2274            DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2275
2276            if ( !$reupload ) {
2277                // This is a new file, so update the image count
2278                DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2279            }
2280
2281            MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2282        }, __METHOD__ );
2283
2284        return Status::newGood();
2285    }
2286
2287    /**
2288     * Move or copy a file to its public location. If a file exists at the
2289     * destination, move it to an archive. Returns a Status object with
2290     * the archive name in the "value" member on success.
2291     *
2292     * The archive name should be passed through to recordUpload for database
2293     * registration.
2294     *
2295     * @stable to override
2296     * @param string|FSFile $src Local filesystem path or virtual URL to the source image
2297     * @param int $flags A bitwise combination of:
2298     *     File::DELETE_SOURCE    Delete the source file, i.e. move rather than copy
2299     * @param array $options Optional additional parameters
2300     * @return Status On success, the value member contains the
2301     *     archive name, or an empty string if it was a new file.
2302     */
2303    public function publish( $src, $flags = 0, array $options = [] ) {
2304        return $this->publishTo( $src, $this->getRel(), $flags, $options );
2305    }
2306
2307    /**
2308     * Move or copy a file to a specified location. Returns a Status
2309     * object with the archive name in the "value" member on success.
2310     *
2311     * The archive name should be passed through to recordUpload for database
2312     * registration.
2313     *
2314     * @stable to override
2315     * @param string|FSFile $src Local filesystem path or virtual URL to the source image
2316     * @param string $dstRel Target relative path
2317     * @param int $flags A bitwise combination of:
2318     *     File::DELETE_SOURCE    Delete the source file, i.e. move rather than copy
2319     * @param array $options Optional additional parameters
2320     * @return Status On success, the value member contains the
2321     *     archive name, or an empty string if it was a new file.
2322     */
2323    protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2324        $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2325
2326        $repo = $this->getRepo();
2327        if ( $repo->getReadOnlyReason() !== false ) {
2328            return $this->readOnlyFatalStatus();
2329        }
2330
2331        $status = $this->acquireFileLock();
2332        if ( !$status->isOK() ) {
2333            return $status;
2334        }
2335
2336        if ( $this->isOld() ) {
2337            $archiveRel = $dstRel;
2338            $archiveName = basename( $archiveRel );
2339        } else {
2340            $archiveName = ConvertibleTimestamp::now( TS::MW ) . '!' . $this->getName();
2341            $archiveRel = $this->getArchiveRel( $archiveName );
2342        }
2343
2344        if ( $repo->hasSha1Storage() ) {
2345            $sha1 = FileRepo::isVirtualUrl( $srcPath )
2346                ? $repo->getFileSha1( $srcPath )
2347                : FSFile::getSha1Base36FromPath( $srcPath );
2348            /** @var FileBackendDBRepoWrapper $wrapperBackend */
2349            $wrapperBackend = $repo->getBackend();
2350            '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2351            $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2352            $status = $repo->quickImport( $src, $dst );
2353            if ( $flags & File::DELETE_SOURCE ) {
2354                unlink( $srcPath );
2355            }
2356
2357            if ( $this->exists() ) {
2358                $status->value = $archiveName;
2359            }
2360        } else {
2361            $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2362            $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2363
2364            if ( $status->value == 'new' ) {
2365                $status->value = '';
2366            } else {
2367                $status->value = $archiveName;
2368            }
2369        }
2370
2371        $this->releaseFileLock();
2372        return $status;
2373    }
2374
2375    /** getLinksTo inherited */
2376    /** getExifData inherited */
2377    /** isLocal inherited */
2378    /** wasDeleted inherited */
2379
2380    /**
2381     * Move file to the new title
2382     *
2383     * Move current, old version and all thumbnails
2384     * to the new filename. Old file is deleted.
2385     *
2386     * Cache purging is done; checks for validity
2387     * and logging are caller's responsibility
2388     *
2389     * @stable to override
2390     * @param Title $target New file name
2391     * @return Status
2392     */
2393    public function move( $target ) {
2394        $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2395        if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2396            return $this->readOnlyFatalStatus();
2397        }
2398
2399        wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2400        $batch = new LocalFileMoveBatch( $this, $target );
2401
2402        $status = $batch->addCurrent();
2403        if ( !$status->isOK() ) {
2404            return $status;
2405        }
2406        $archiveNames = $batch->addOlds();
2407        $status = $batch->execute();
2408
2409        wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2410
2411        // Purge the source and target files outside the transaction...
2412        $oldTitleFile = $localRepo->newFile( $this->title );
2413        $newTitleFile = $localRepo->newFile( $target );
2414        DeferredUpdates::addUpdate(
2415            new AutoCommitUpdate(
2416                $this->getRepo()->getPrimaryDB(),
2417                __METHOD__,
2418                static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2419                    $oldTitleFile->purgeEverything();
2420                    foreach ( $archiveNames as $archiveName ) {
2421                        /** @var OldLocalFile $oldTitleFile */
2422                        '@phan-var OldLocalFile $oldTitleFile';
2423                        $oldTitleFile->purgeOldThumbnails( $archiveName );
2424                    }
2425                    $newTitleFile->purgeEverything();
2426                }
2427            ),
2428            DeferredUpdates::PRESEND
2429        );
2430
2431        if ( $status->isOK() ) {
2432            // Now switch the object
2433            $this->title = $target;
2434            // Force regeneration of the name and hashpath
2435            $this->name = null;
2436            $this->hashPath = null;
2437        }
2438
2439        return $status;
2440    }
2441
2442    /**
2443     * Delete all versions of the file.
2444     *
2445     * @since 1.35
2446     *
2447     * Moves the files into an archive directory (or deletes them)
2448     * and removes the database rows.
2449     *
2450     * Cache purging is done; logging is caller's responsibility.
2451     * @stable to override
2452     *
2453     * @param string $reason
2454     * @param UserIdentity $user
2455     * @param bool $suppress
2456     * @return Status
2457     */
2458    public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2459        if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2460            return $this->readOnlyFatalStatus();
2461        }
2462
2463        $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2464
2465        $batch->addCurrent();
2466        // Get old version relative paths
2467        $archiveNames = $batch->addOlds();
2468        $status = $batch->execute();
2469
2470        if ( $status->isOK() ) {
2471            DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2472        }
2473
2474        // To avoid slow purges in the transaction, move them outside...
2475        DeferredUpdates::addUpdate(
2476            new AutoCommitUpdate(
2477                $this->getRepo()->getPrimaryDB(),
2478                __METHOD__,
2479                function () use ( $archiveNames ) {
2480                    $this->purgeEverything();
2481                    foreach ( $archiveNames as $archiveName ) {
2482                        $this->purgeOldThumbnails( $archiveName );
2483                    }
2484                }
2485            ),
2486            DeferredUpdates::PRESEND
2487        );
2488
2489        // Purge the CDN
2490        $purgeUrls = [];
2491        foreach ( $archiveNames as $archiveName ) {
2492            $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2493        }
2494
2495        $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
2496        $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2497
2498        return $status;
2499    }
2500
2501    /**
2502     * Delete an old version of the file.
2503     *
2504     * @since 1.35
2505     * @stable to override
2506     *
2507     * Moves the file into an archive directory (or deletes it)
2508     * and removes the database row.
2509     *
2510     * Cache purging is done; logging is caller's responsibility.
2511     *
2512     * @param string $archiveName
2513     * @param string $reason
2514     * @param UserIdentity $user
2515     * @param bool $suppress
2516     * @return Status
2517     */
2518    public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2519        if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2520            return $this->readOnlyFatalStatus();
2521        }
2522
2523        $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2524
2525        $batch->addOld( $archiveName );
2526        $status = $batch->execute();
2527
2528        $this->purgeOldThumbnails( $archiveName );
2529        if ( $status->isOK() ) {
2530            $this->purgeDescription();
2531        }
2532
2533        $url = $this->getArchiveUrl( $archiveName );
2534        $hcu = MediaWikiServices::getInstance()->getHTMLCacheUpdater();
2535        $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2536
2537        return $status;
2538    }
2539
2540    /**
2541     * Restore all or specified deleted revisions to the given file.
2542     * Permissions and logging are left to the caller.
2543     *
2544     * May throw database exceptions on error.
2545     * @stable to override
2546     *
2547     * @param int[] $versions Set of record ids of deleted items to restore,
2548     *   or empty to restore all revisions.
2549     * @param bool $unsuppress
2550     * @return Status
2551     */
2552    public function restore( $versions = [], $unsuppress = false ) {
2553        if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2554            return $this->readOnlyFatalStatus();
2555        }
2556
2557        $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2558
2559        if ( !$versions ) {
2560            $batch->addAll();
2561        } else {
2562            $batch->addIds( $versions );
2563        }
2564        $status = $batch->execute();
2565        if ( $status->isGood() ) {
2566            $cleanupStatus = $batch->cleanup();
2567            $cleanupStatus->successCount = 0;
2568            $cleanupStatus->failCount = 0;
2569            $status->merge( $cleanupStatus );
2570        }
2571
2572        return $status;
2573    }
2574
2575    /** isMultipage inherited */
2576    /** pageCount inherited */
2577    /** scaleHeight inherited */
2578    /** getImageSize inherited */
2579
2580    /**
2581     * Get the URL of the file description page.
2582     * @stable to override
2583     * @return string|false
2584     */
2585    public function getDescriptionUrl() {
2586        // Avoid hard failure when the file does not exist. T221812
2587        return $this->title ? $this->title->getLocalURL() : false;
2588    }
2589
2590    /**
2591     * Get the HTML text of the description page
2592     * This is not used by ImagePage for local files, since (among other things)
2593     * it skips the parser cache.
2594     * @stable to override
2595     *
2596     * @param Language $lang What language to get description in.
2597     * @return string|false
2598     */
2599    public function getDescriptionText( Language $lang ) {
2600        if ( !$this->title ) {
2601            return false; // Avoid hard failure when the file does not exist. T221812
2602        }
2603
2604        $services = MediaWikiServices::getInstance();
2605        $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2606        if ( !$page ) {
2607            return false;
2608        }
2609
2610        $parserOptions = ParserOptions::newFromUserAndLang(
2611            RequestContext::getMain()->getUser(),
2612            $lang
2613        );
2614        $parseStatus = $services->getParserOutputAccess()
2615            ->getParserOutput( $page, $parserOptions );
2616
2617        if ( !$parseStatus->isGood() ) {
2618            // Rendering failed.
2619            return false;
2620        }
2621        // TODO T371004 move runOutputPipeline out of $parserOutput
2622        return $parseStatus->getValue()->runOutputPipeline( $parserOptions, [] )->getContentHolderText();
2623    }
2624
2625    /**
2626     * @since 1.37
2627     * @stable to override
2628     * @param int $audience
2629     * @param Authority|null $performer
2630     * @return UserIdentity|null
2631     */
2632    public function getUploader( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): ?UserIdentity {
2633        $this->load();
2634        if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2635            return null;
2636        } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2637            return null;
2638        } else {
2639            return $this->user;
2640        }
2641    }
2642
2643    /**
2644     * @stable to override
2645     * @param int $audience
2646     * @param Authority|null $performer
2647     * @return string
2648     */
2649    public function getDescription( $audience = self::FOR_PUBLIC, ?Authority $performer = null ) {
2650        $this->load();
2651        if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2652            return '';
2653        } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2654            return '';
2655        } else {
2656            return $this->description;
2657        }
2658    }
2659
2660    /**
2661     * @stable to override
2662     * @return string|false TS::MW timestamp, a string with 14 digits
2663     */
2664    public function getTimestamp() {
2665        $this->load();
2666
2667        return $this->timestamp;
2668    }
2669
2670    /**
2671     * @stable to override
2672     * @return string|false
2673     */
2674    public function getDescriptionTouched() {
2675        if ( !$this->exists() ) {
2676            return false; // Avoid hard failure when the file does not exist. T221812
2677        }
2678
2679        // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2680        // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2681        // need to differentiate between null (uninitialized) and false (failed to load).
2682        if ( $this->descriptionTouched === null ) {
2683            $touched = $this->repo->getReplicaDB()->newSelectQueryBuilder()
2684                ->select( 'page_touched' )
2685                ->from( 'page' )
2686                ->where( [ 'page_namespace' => $this->title->getNamespace() ] )
2687                ->andWhere( [ 'page_title' => $this->title->getDBkey() ] )
2688                ->caller( __METHOD__ )->fetchField();
2689            $this->descriptionTouched = $touched ? wfTimestamp( TS::MW, $touched ) : false;
2690        }
2691
2692        return $this->descriptionTouched;
2693    }
2694
2695    /**
2696     * @stable to override
2697     * @return string|false
2698     */
2699    public function getSha1() {
2700        $this->load();
2701        return $this->sha1;
2702    }
2703
2704    /**
2705     * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2706     */
2707    public function isCacheable() {
2708        $this->load();
2709
2710        // If extra data (metadata) was not loaded then it must have been large
2711        return $this->extraDataLoaded
2712            && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2713    }
2714
2715    /**
2716     * Acquire an exclusive lock on the file, indicating an intention to write
2717     * to the file backend.
2718     *
2719     * @param float|int $timeout The timeout in seconds
2720     * @return Status
2721     * @since 1.28
2722     */
2723    public function acquireFileLock( $timeout = 0 ) {
2724        return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2725            [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2726        ) );
2727    }
2728
2729    /**
2730     * Release a lock acquired with acquireFileLock().
2731     *
2732     * @return Status
2733     * @since 1.28
2734     */
2735    public function releaseFileLock() {
2736        return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2737            [ $this->getPath() ], LockManager::LOCK_EX
2738        ) );
2739    }
2740
2741    /**
2742     * Start an atomic DB section and lock the image for update
2743     * or increments a reference counter if the lock is already held
2744     *
2745     * This method should not be used outside of LocalFile/LocalFile*Batch
2746     *
2747     * @deprecated since 1.38 Use acquireFileLock()
2748     * @throws LocalFileLockError Throws an error if the lock was not acquired
2749     * @return bool Whether the file lock owns/spawned the DB transaction
2750     */
2751    public function lock() {
2752        if ( !$this->locked ) {
2753            $logger = LoggerFactory::getInstance( 'LocalFile' );
2754
2755            $dbw = $this->repo->getPrimaryDB();
2756            $makesTransaction = !$dbw->trxLevel();
2757            $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2758            // T56736: use simple lock to handle when the file does not exist.
2759            // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2760            // Also, that would cause contention on INSERT of similarly named rows.
2761            $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2762            if ( !$status->isGood() ) {
2763                $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2764                $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2765
2766                throw new LocalFileLockError( $status );
2767            }
2768            // Release the lock *after* commit to avoid row-level contention.
2769            // Make sure it triggers on rollback() as well as commit() (T132921).
2770            $dbw->onTransactionResolution(
2771                function () use ( $logger ) {
2772                    $status = $this->releaseFileLock();
2773                    if ( !$status->isGood() ) {
2774                        $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2775                    }
2776                },
2777                __METHOD__
2778            );
2779            // Callers might care if the SELECT snapshot is safely fresh
2780            $this->lockedOwnTrx = $makesTransaction;
2781        }
2782
2783        $this->locked++;
2784
2785        return $this->lockedOwnTrx;
2786    }
2787
2788    /**
2789     * Decrement the lock reference count and end the atomic section if it reaches zero
2790     *
2791     * This method should not be used outside of LocalFile/LocalFile*Batch
2792     *
2793     * The commit and lock release will happen when no atomic sections are active, which
2794     * may happen immediately or at some point after calling this
2795     *
2796     * @deprecated since 1.38 Use releaseFileLock()
2797     */
2798    public function unlock() {
2799        if ( $this->locked ) {
2800            --$this->locked;
2801            if ( !$this->locked ) {
2802                $dbw = $this->repo->getPrimaryDB();
2803                $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2804                $this->lockedOwnTrx = false;
2805            }
2806        }
2807    }
2808
2809    /**
2810     * @return Status
2811     */
2812    protected function readOnlyFatalStatus() {
2813        return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2814            $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2815    }
2816
2817    /**
2818     * Clean up any dangling locks
2819     */
2820    public function __destruct() {
2821        $this->unlock();
2822    }
2823}
2824
2825/** @deprecated class alias since 1.44 */
2826class_alias( LocalFile::class, 'LocalFile' );