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