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