3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\CommentStore\CommentStoreComment
;
22 use MediaWiki\Content\ContentHandler
;
23 use MediaWiki\Context\RequestContext
;
24 use MediaWiki\Deferred\AutoCommitUpdate
;
25 use MediaWiki\Deferred\DeferredUpdates
;
26 use MediaWiki\Deferred\LinksUpdate\LinksUpdate
;
27 use MediaWiki\Deferred\SiteStatsUpdate
;
28 use MediaWiki\FileRepo\File\FileSelectQueryBuilder
;
29 use MediaWiki\Language\Language
;
30 use MediaWiki\Logger\LoggerFactory
;
31 use MediaWiki\MainConfigNames
;
32 use MediaWiki\MediaWikiServices
;
33 use MediaWiki\Parser\ParserOptions
;
34 use MediaWiki\Permissions\Authority
;
35 use MediaWiki\Status\Status
;
36 use MediaWiki\Title\Title
;
37 use MediaWiki\User\UserIdentity
;
38 use MediaWiki\User\UserIdentityValue
;
39 use Wikimedia\FileBackend\FileBackend
;
40 use Wikimedia\FileBackend\FileBackendError
;
41 use Wikimedia\FileBackend\FSFile\FSFile
;
42 use Wikimedia\Rdbms\Blob
;
43 use Wikimedia\Rdbms\Database
;
44 use Wikimedia\Rdbms\IDBAccessObject
;
45 use Wikimedia\Rdbms\IReadableDatabase
;
46 use Wikimedia\Rdbms\IResultWrapper
;
47 use Wikimedia\Rdbms\SelectQueryBuilder
;
50 * Local file in the wiki's own database.
52 * Provides methods to retrieve paths (physical, logical, URL),
53 * to generate image thumbnails or for uploading.
55 * Note that only the repo object knows what its file class is called. You should
56 * never name a file class explicitly outside of the repo class. Instead use the
57 * repo's factory functions to generate file objects, for example:
59 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
61 * Consider the services container below;
63 * $services = MediaWikiServices::getInstance();
65 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
66 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
68 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
69 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
70 * and $this->repoGroup->getLocalRepo()->newFile().
73 * @ingroup FileAbstraction
75 class LocalFile
extends File
{
76 private const VERSION
= 13; // cache version
78 private const CACHE_FIELD_MAX_LEN
= 1000;
80 /** @var string Metadata serialization: empty string. This is a compact non-legacy format. */
81 private const MDS_EMPTY
= 'empty';
83 /** @var string Metadata serialization: some other string */
84 private const MDS_LEGACY
= 'legacy';
86 /** @var string Metadata serialization: PHP serialize() */
87 private const MDS_PHP
= 'php';
89 /** @var string Metadata serialization: JSON */
90 private const MDS_JSON
= 'json';
92 /** @var int Maximum number of pages for which to trigger render jobs */
93 private const MAX_PAGE_RENDER_JOBS
= 50;
95 /** @var bool Does the file exist on disk? (loadFromXxx) */
96 protected $fileExists;
98 /** @var int Id of the file */
101 /** @var int Id of the file type */
104 /** @var int Image width */
107 /** @var int Image height */
110 /** @var int Returned by getimagesize (loadFromXxx) */
113 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
114 protected $media_type;
116 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
119 /** @var int Size in bytes (loadFromXxx) */
122 /** @var array Unserialized metadata */
123 protected $metadataArray = [];
126 * One of the MDS_* constants, giving the format of the metadata as stored
127 * in the DB, or null if the data was not loaded from the DB.
131 protected $metadataSerializationFormat;
133 /** @var string[] Map of metadata item name to blob address */
134 protected $metadataBlobs = [];
137 * Map of metadata item name to blob address for items that exist but
138 * have not yet been loaded into $this->metadataArray
142 protected $unloadedMetadataBlobs = [];
144 /** @var string SHA-1 base 36 content hash */
147 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
148 protected $dataLoaded = false;
150 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
151 protected $extraDataLoaded = false;
153 /** @var int Bitfield akin to rev_deleted */
156 /** @var int id in file table, null on read old */
159 /** @var int id in filerevision table, null on read old */
160 protected $filerevision_id;
163 protected $repoClass = LocalRepo
::class;
165 /** @var int Number of line to return by nextHistoryLine() (constructor) */
166 private $historyLine = 0;
168 /** @var IResultWrapper|null Result of the query for the file's history (nextHistoryLine) */
169 private $historyRes = null;
171 /** @var string Major MIME type */
174 /** @var string Minor MIME type */
177 /** @var string Upload timestamp */
180 /** @var UserIdentity|null Uploader */
183 /** @var string Description of current revision of the file */
184 private $description;
186 /** @var string TS_MW timestamp of the last change of the file description */
187 private $descriptionTouched;
189 /** @var bool Whether the row was upgraded on load */
192 /** @var bool Whether the row was scheduled to upgrade on load */
195 /** @var int If >= 1 the image row is locked */
198 /** @var bool True if the image row is locked with a lock initiated transaction */
199 private $lockedOwnTrx;
201 /** @var bool True if file is not present in file system. Not to be cached in memcached */
204 /** @var MetadataStorageHelper */
205 private $metadataStorageHelper;
208 private $migrationStage = SCHEMA_COMPAT_OLD
;
210 // @note: higher than IDBAccessObject constants
211 private const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
213 private const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
216 * Create a LocalFile from a title
217 * Do not call this except from inside a repo class.
219 * Note: $unused param is only here to avoid an E_STRICT
221 * @stable to override
223 * @param Title $title
224 * @param LocalRepo $repo
225 * @param null $unused
229 public static function newFromTitle( $title, $repo, $unused = null ) {
230 return new static( $title, $repo );
234 * Create a LocalFile from a title
235 * Do not call this except from inside a repo class.
237 * @stable to override
239 * @param stdClass $row
240 * @param LocalRepo $repo
244 public static function newFromRow( $row, $repo ) {
245 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
246 $file = new static( $title, $repo );
247 $file->loadFromRow( $row );
253 * Create a LocalFile from a SHA-1 key
254 * Do not call this except from inside a repo class.
256 * @stable to override
258 * @param string $sha1 Base-36 SHA-1
259 * @param LocalRepo $repo
260 * @param string|false $timestamp MW_timestamp (optional)
261 * @return static|false
263 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
264 $dbr = $repo->getReplicaDB();
265 $queryBuilder = FileSelectQueryBuilder
::newForFile( $dbr );
267 $queryBuilder->where( [ 'img_sha1' => $sha1 ] );
270 $queryBuilder->andWhere( [ 'img_timestamp' => $dbr->timestamp( $timestamp ) ] );
273 $row = $queryBuilder->caller( __METHOD__
)->fetchRow();
275 return static::newFromRow( $row, $repo );
282 * Return the tables, fields, and join conditions to be selected to create
283 * a new localfile object.
285 * Since 1.34, img_user and img_user_text have not been present in the
286 * database, but they continue to be available in query results as
290 * @stable to override
292 * @deprecated since 1.41 use FileSelectQueryBuilder instead
293 * @param string[] $options
294 * - omit-lazy: Omit fields that are lazily cached.
295 * @return array[] With three keys:
296 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
297 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
298 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
299 * @phan-return array{tables:string[],fields:string[],joins:array}
301 public static function getQueryInfo( array $options = [] ) {
302 $dbr = MediaWikiServices
::getInstance()->getConnectionProvider()->getReplicaDatabase();
303 $queryInfo = FileSelectQueryBuilder
::newForFile( $dbr, $options )->getQueryInfo();
304 // needs remapping...
306 'tables' => $queryInfo['tables'],
307 'fields' => $queryInfo['fields'],
308 'joins' => $queryInfo['join_conds'],
313 * Do not call this except from inside a repo class.
316 * @param Title $title
317 * @param LocalRepo $repo
319 public function __construct( $title, $repo ) {
320 parent
::__construct( $title, $repo );
321 $this->metadataStorageHelper
= new MetadataStorageHelper( $repo );
322 $this->migrationStage
= MediaWikiServices
::getInstance()->getMainConfig()->get(
323 MainConfigNames
::FileSchemaMigrationStage
326 $this->assertRepoDefined();
327 $this->assertTitleDefined();
331 * @return LocalRepo|false
333 public function getRepo() {
338 * Get the memcached key for the main data for this file, or false if
339 * there is no access to the shared cache.
340 * @stable to override
341 * @return string|false
343 protected function getCacheKey() {
344 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
348 * Try to load file metadata from memcached, falling back to the database
350 private function loadFromCache() {
351 $this->dataLoaded
= false;
352 $this->extraDataLoaded
= false;
354 $key = $this->getCacheKey();
356 $this->loadFromDB( IDBAccessObject
::READ_NORMAL
);
361 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
362 $cachedValues = $cache->getWithSetCallback(
365 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
366 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
368 $this->loadFromDB( IDBAccessObject
::READ_NORMAL
);
370 $fields = $this->getCacheFields( '' );
372 $cacheVal['fileExists'] = $this->fileExists
;
373 if ( $this->fileExists
) {
374 foreach ( $fields as $field ) {
375 $cacheVal[$field] = $this->$field;
379 $cacheVal['user'] = $this->user
->getId();
380 $cacheVal['user_text'] = $this->user
->getName();
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
;
390 $cacheVal['metadata'] = $this->metadataArray
;
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
400 unset( $cacheVal[$field] ); // don't let the value get too big
401 if ( $field === 'metadata' ) {
402 unset( $cacheVal['metadataBlobs'] );
407 if ( $this->fileExists
) {
408 $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
410 $ttl = $cache::TTL_DAY
;
415 [ 'version' => self
::VERSION
]
418 $this->fileExists
= $cachedValues['fileExists'];
419 if ( $this->fileExists
) {
420 $this->setProps( $cachedValues );
423 $this->dataLoaded
= true;
424 $this->extraDataLoaded
= true;
425 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
426 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
431 * Purge the file object/metadata cache
433 public function invalidateCache() {
434 $key = $this->getCacheKey();
439 $this->repo
->getPrimaryDB()->onTransactionPreCommitOrIdle(
440 static function () use ( $key ) {
441 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
448 * Load metadata from the file itself
451 * @param string|null $path The path or virtual URL to load from, or null
452 * to use the previously stored file.
454 public function loadFromFile( $path = null ) {
455 $props = $this->repo
->getFileProps( $path ??
$this->getVirtualUrl() );
456 $this->setProps( $props );
460 * Returns the list of object properties that are included as-is in the cache.
461 * @stable to override
462 * @param string $prefix Must be the empty string
464 * @since 1.31 No longer accepts a non-empty $prefix
466 protected function getCacheFields( $prefix = 'img_' ) {
467 if ( $prefix !== '' ) {
468 throw new InvalidArgumentException(
469 __METHOD__
. ' with a non-empty prefix is no longer supported.'
473 // See self::getQueryInfo() for the fetching of the data from the DB,
474 // self::loadFromRow() for the loading of the object from the DB row,
475 // and self::loadFromCache() for the caching, and self::setProps() for
476 // populating the object from an array of data.
477 return [ 'size', 'width', 'height', 'bits', 'media_type',
478 'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
482 * Returns the list of object properties that are included as-is in the
483 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
484 * @param string $prefix Must be the empty string
486 * @since 1.31 No longer accepts a non-empty $prefix
488 protected function getLazyCacheFields( $prefix = 'img_' ) {
489 if ( $prefix !== '' ) {
490 throw new InvalidArgumentException(
491 __METHOD__
. ' with a non-empty prefix is no longer supported.'
495 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
496 return [ 'metadata' ];
500 * Load file metadata from the DB
501 * @stable to override
504 protected function loadFromDB( $flags = 0 ) {
505 $fname = static::class . '::' . __FUNCTION__
;
507 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
508 $this->dataLoaded
= true;
509 $this->extraDataLoaded
= true;
511 $dbr = ( $flags & IDBAccessObject
::READ_LATEST
)
512 ?
$this->repo
->getPrimaryDB()
513 : $this->repo
->getReplicaDB();
514 $queryBuilder = FileSelectQueryBuilder
::newForFile( $dbr );
516 $queryBuilder->where( [ 'img_name' => $this->getName() ] );
517 $row = $queryBuilder->caller( $fname )->fetchRow();
520 $this->loadFromRow( $row );
522 $this->fileExists
= false;
527 * Load lazy file metadata from the DB.
528 * This covers fields that are sometimes not cached.
529 * @stable to override
531 protected function loadExtraFromDB() {
532 if ( !$this->title
) {
533 return; // Avoid hard failure when the file does not exist. T221812
536 $fname = static::class . '::' . __FUNCTION__
;
538 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
539 $this->extraDataLoaded
= true;
541 $db = $this->repo
->getReplicaDB();
542 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
544 $db = $this->repo
->getPrimaryDB();
545 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
549 if ( isset( $fieldMap['metadata'] ) ) {
550 $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
553 throw new RuntimeException( "Could not find data for image '{$this->getName()}'." );
558 * @param IReadableDatabase $dbr
559 * @param string $fname
560 * @return string[]|false
562 private function loadExtraFieldsWithTimestamp( IReadableDatabase
$dbr, $fname ) {
565 $queryBuilder = FileSelectQueryBuilder
::newForFile( $dbr, [ 'omit-nonlazy' ] );
566 $queryBuilder->where( [ 'img_name' => $this->getName() ] )
567 ->andWhere( [ 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] );
568 $row = $queryBuilder->caller( $fname )->fetchRow();
570 $fieldMap = $this->unprefixRow( $row, 'img_' );
572 # File may have been uploaded over in the meantime; check the old versions
573 $queryBuilder = FileSelectQueryBuilder
::newForOldFile( $dbr, [ 'omit-nonlazy' ] );
574 $row = $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
575 ->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] )
576 ->caller( __METHOD__
)->fetchRow();
578 $fieldMap = $this->unprefixRow( $row, 'oi_' );
586 * @param array|stdClass $row
587 * @param string $prefix
590 protected function unprefixRow( $row, $prefix = 'img_' ) {
591 $array = (array)$row;
592 $prefixLength = strlen( $prefix );
594 // Double check prefix once
595 if ( substr( array_key_first( $array ), 0, $prefixLength ) !== $prefix ) {
596 throw new InvalidArgumentException( __METHOD__
. ': incorrect $prefix parameter' );
600 foreach ( $array as $name => $value ) {
601 $decoded[substr( $name, $prefixLength )] = $value;
608 * Load file metadata from a DB result row
609 * @stable to override
611 * Passing arbitrary fields in the row and expecting them to be translated
612 * to property names on $this is deprecated since 1.37. Instead, override
613 * loadFromRow(), and clone and unset the extra fields before passing them
616 * After the deprecation period has passed, extra fields will be ignored,
617 * and the deprecation warning will be removed.
619 * @param stdClass $row
620 * @param string $prefix
622 public function loadFromRow( $row, $prefix = 'img_' ) {
623 $this->dataLoaded
= true;
625 $unprefixed = $this->unprefixRow( $row, $prefix );
627 $this->name
= $unprefixed['name'];
628 $this->media_type
= $unprefixed['media_type'];
630 $services = MediaWikiServices
::getInstance();
631 $this->description
= $services->getCommentStore()
632 ->getComment( "{$prefix}description", $row )->text
;
634 $this->user
= $services->getUserFactory()->newFromAnyId(
635 $unprefixed['user'] ??
null,
636 $unprefixed['user_text'] ??
null,
637 $unprefixed['actor'] ??
null
640 $this->timestamp
= wfTimestamp( TS_MW
, $unprefixed['timestamp'] );
642 $this->loadMetadataFromDbFieldValue(
643 $this->repo
->getReplicaDB(), $unprefixed['metadata'] );
645 if ( empty( $unprefixed['major_mime'] ) ) {
646 $this->major_mime
= 'unknown';
647 $this->minor_mime
= 'unknown';
648 $this->mime
= 'unknown/unknown';
650 if ( !$unprefixed['minor_mime'] ) {
651 $unprefixed['minor_mime'] = 'unknown';
653 $this->major_mime
= $unprefixed['major_mime'];
654 $this->minor_mime
= $unprefixed['minor_mime'];
655 $this->mime
= $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
658 // Trim zero padding from char/binary field
659 $this->sha1
= rtrim( $unprefixed['sha1'], "\0" );
661 // Normalize some fields to integer type, per their database definition.
662 // Use unary + so that overflows will be upgraded to double instead of
663 // being truncated as with intval(). This is important to allow > 2 GiB
664 // files on 32-bit systems.
665 $this->size
= +
$unprefixed['size'];
666 $this->width
= +
$unprefixed['width'];
667 $this->height
= +
$unprefixed['height'];
668 $this->bits
= +
$unprefixed['bits'];
670 // Check for extra fields (deprecated since MW 1.37)
671 $extraFields = array_diff(
672 array_keys( $unprefixed ),
674 'name', 'media_type', 'description_text', 'description_data',
675 'description_cid', 'user', 'user_text', 'actor', 'timestamp',
676 'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
677 'height', 'bits', 'file_id', 'filerevision_id'
680 if ( $extraFields ) {
682 'Passing extra fields (' .
683 implode( ', ', $extraFields )
684 . ') to ' . __METHOD__
. ' was deprecated in MediaWiki 1.37. ' .
685 'Property assignment will be removed in a later version.',
687 foreach ( $extraFields as $field ) {
688 $this->$field = $unprefixed[$field];
692 $this->fileExists
= true;
696 * Load file metadata from cache or DB, unless already loaded
697 * @stable to override
700 public function load( $flags = 0 ) {
701 if ( !$this->dataLoaded
) {
702 if ( $flags & IDBAccessObject
::READ_LATEST
) {
703 $this->loadFromDB( $flags );
705 $this->loadFromCache();
709 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
710 // @note: loads on name/timestamp to reduce race condition problems
711 $this->loadExtraFromDB();
716 * Upgrade a row if it needs it
719 public function maybeUpgradeRow() {
720 if ( MediaWikiServices
::getInstance()->getReadOnlyMode()->isReadOnly() ||
$this->upgrading
) {
725 $reserialize = false;
726 if ( $this->media_type
=== null ||
$this->mime
== 'image/svg' ) {
729 $handler = $this->getHandler();
731 $validity = $handler->isFileMetadataValid( $this );
732 if ( $validity === MediaHandler
::METADATA_BAD
) {
734 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
735 && $this->repo
->isMetadataUpdateEnabled()
738 } elseif ( $this->repo
->isJsonMetadataEnabled()
739 && $this->repo
->isMetadataReserializeEnabled()
741 if ( $this->repo
->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
743 } elseif ( $this->metadataSerializationFormat
!== self
::MDS_EMPTY
&&
744 $this->metadataSerializationFormat
!== self
::MDS_JSON
) {
751 if ( $upgrade ||
$reserialize ) {
752 $this->upgrading
= true;
753 // Defer updates unless in auto-commit CLI mode
754 DeferredUpdates
::addCallableUpdate( function () use ( $upgrade ) {
755 $this->upgrading
= false; // avoid duplicate updates
760 $this->reserializeMetadata();
762 } catch ( LocalFileLockError
$e ) {
763 // let the other process handle it (or do it next time)
770 * @return bool Whether upgradeRow() ran for this object
772 public function getUpgraded() {
773 return $this->upgraded
;
777 * This is mostly for the migration period.
782 public function getFileIdFromName() {
783 if ( !$this->fileId
) {
784 $dbw = $this->repo
->getPrimaryDB();
785 $id = $dbw->newSelectQueryBuilder()
786 ->select( 'file_id' )
789 'file_name' => $this->getName(),
796 return $this->fileId
;
800 * This is mostly for the migration period.
805 public function acquireFileIdFromName() {
806 $dbw = $this->repo
->getPrimaryDB();
807 $id = $this->getFileIdFromName();
811 $id = $dbw->newSelectQueryBuilder()
812 ->select( 'file_id' )
815 'file_name' => $this->getName(),
819 $dbw->newInsertQueryBuilder()
820 ->insertInto( 'file' )
822 'file_name' => $this->getName(),
823 // The value will be updated later
826 'file_type' => $this->getFileTypeId(),
828 ->caller( __METHOD__
)->execute();
829 $insertId = $dbw->insertId();
831 throw new RuntimeException( 'File entry could not be inserted' );
836 $dbw->newUpdateQueryBuilder()
838 ->set( [ 'file_deleted' => 0 ] )
839 ->where( [ 'file_id' => $id ] )
840 ->caller( __METHOD__
)->execute();
845 protected function getFileTypeId() {
846 if ( $this->fileTypeId
) {
847 return $this->fileTypeId
;
849 [ $major, $minor ] = self
::splitMime( $this->mime
);
850 $dbw = $this->repo
->getPrimaryDB();
851 $id = $dbw->newSelectQueryBuilder()
853 ->from( 'filetypes' )
855 'ft_media_type' => $this->getMediaType(),
856 'ft_major_mime' => $major,
857 'ft_minor_mime' => $minor,
861 $this->fileTypeId
= $id;
864 $dbw->newInsertQueryBuilder()
865 ->insertInto( 'filetypes' )
867 'ft_media_type' => $this->getMediaType(),
868 'ft_major_mime' => $major,
869 'ft_minor_mime' => $minor,
871 ->caller( __METHOD__
)->execute();
873 $id = $dbw->insertId();
875 throw new RuntimeException( 'File entry could not be inserted' );
878 $this->fileTypeId
= $id;
883 * Fix assorted version-related problems with the image row by reloading it from the file
884 * @stable to override
886 public function upgradeRow() {
887 $dbw = $this->repo
->getPrimaryDB();
889 // Make a DB query condition that will fail to match the image row if the
890 // image was reuploaded while the upgrade was in process.
891 $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
893 $this->loadFromFile();
895 # Don't destroy file info of missing files
896 if ( !$this->fileExists
) {
897 wfDebug( __METHOD__
. ": file does not exist, aborting" );
902 [ $major, $minor ] = self
::splitMime( $this->mime
);
904 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema" );
906 $metadata = $this->getMetadataForDb( $dbw );
907 $dbw->newUpdateQueryBuilder()
910 'img_size' => $this->size
,
911 'img_width' => $this->width
,
912 'img_height' => $this->height
,
913 'img_bits' => $this->bits
,
914 'img_media_type' => $this->media_type
,
915 'img_major_mime' => $major,
916 'img_minor_mime' => $minor,
917 'img_metadata' => $metadata,
918 'img_sha1' => $this->sha1
,
920 ->where( [ 'img_name' => $this->getName() ] )
921 ->andWhere( $freshnessCondition )
922 ->caller( __METHOD__
)->execute();
924 if ( $this->migrationStage
& SCHEMA_COMPAT_WRITE_NEW
) {
925 $dbw->newUpdateQueryBuilder()
926 ->update( 'filerevision' )
928 'fr_size' => $this->size
,
929 'fr_width' => $this->width
,
930 'fr_height' => $this->height
,
931 'fr_bits' => $this->bits
,
932 'fr_metadata' => $metadata,
933 'fr_sha1' => $this->sha1
,
935 ->where( [ 'fr_file' => $this->acquireFileIdFromName() ] )
936 ->andWhere( [ 'fr_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ] )
937 ->caller( __METHOD__
)->execute();
940 $this->invalidateCache();
942 $this->upgraded
= true; // avoid rework/retries
946 * Write the metadata back to the database with the current serialization
949 protected function reserializeMetadata() {
950 if ( MediaWikiServices
::getInstance()->getReadOnlyMode()->isReadOnly() ) {
953 $dbw = $this->repo
->getPrimaryDB();
954 $metadata = $this->getMetadataForDb( $dbw );
955 $dbw->newUpdateQueryBuilder()
957 ->set( [ 'img_metadata' => $metadata ] )
959 'img_name' => $this->name
,
960 'img_timestamp' => $dbw->timestamp( $this->timestamp
),
962 ->caller( __METHOD__
)->execute();
963 if ( $this->migrationStage
& SCHEMA_COMPAT_WRITE_NEW
) {
964 $dbw->newUpdateQueryBuilder()
965 ->update( 'filerevision' )
966 ->set( [ 'fr_metadata' => $metadata ] )
967 ->where( [ 'fr_file' => $this->acquireFileIdFromName() ] )
968 ->andWhere( [ 'fr_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ] )
969 ->caller( __METHOD__
)->execute();
971 $this->upgraded
= true;
975 * Set properties in this object to be equal to those given in the
976 * associative array $info. Only cacheable fields can be set.
977 * All fields *must* be set in $info except for getLazyCacheFields().
979 * If 'mime' is given, it will be split into major_mime/minor_mime.
980 * If major_mime/minor_mime are given, $this->mime will also be set.
982 * @stable to override
986 public function setProps( $info ) {
987 $this->dataLoaded
= true;
988 $fields = $this->getCacheFields( '' );
989 $fields[] = 'fileExists';
991 foreach ( $fields as $field ) {
992 if ( isset( $info[$field] ) ) {
993 $this->$field = $info[$field];
997 // Only our own cache sets these properties, so they both should be present.
998 if ( isset( $info['user'] ) &&
999 isset( $info['user_text'] ) &&
1000 $info['user_text'] !== ''
1002 $this->user
= new UserIdentityValue( $info['user'], $info['user_text'] );
1005 // Fix up mime fields
1006 if ( isset( $info['major_mime'] ) ) {
1007 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
1008 } elseif ( isset( $info['mime'] ) ) {
1009 $this->mime
= $info['mime'];
1010 [ $this->major_mime
, $this->minor_mime
] = self
::splitMime( $this->mime
);
1013 if ( isset( $info['metadata'] ) ) {
1014 if ( is_string( $info['metadata'] ) ) {
1015 $this->loadMetadataFromString( $info['metadata'] );
1016 } elseif ( is_array( $info['metadata'] ) ) {
1017 $this->metadataArray
= $info['metadata'];
1018 if ( isset( $info['metadataBlobs'] ) ) {
1019 $this->metadataBlobs
= $info['metadataBlobs'];
1020 $this->unloadedMetadataBlobs
= array_diff_key(
1021 $this->metadataBlobs
,
1022 $this->metadataArray
1025 $this->metadataBlobs
= [];
1026 $this->unloadedMetadataBlobs
= [];
1029 $logger = LoggerFactory
::getInstance( 'LocalFile' );
1030 $logger->warning( __METHOD__
. ' given invalid metadata of type ' .
1031 get_debug_type( $info['metadata'] ) );
1032 $this->metadataArray
= [];
1034 $this->extraDataLoaded
= true;
1038 /** splitMime inherited */
1039 /** getName inherited */
1040 /** getTitle inherited */
1041 /** getURL inherited */
1042 /** getViewURL inherited */
1043 /** getPath inherited */
1044 /** isVisible inherited */
1047 * Checks if this file exists in its parent repo, as referenced by its
1049 * @stable to override
1053 public function isMissing() {
1054 if ( $this->missing
=== null ) {
1055 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
1056 $this->missing
= !$fileExists;
1059 return $this->missing
;
1063 * Return the width of the image
1064 * @stable to override
1069 public function getWidth( $page = 1 ) {
1077 if ( $this->isMultipage() ) {
1078 $handler = $this->getHandler();
1082 $dim = $handler->getPageDimensions( $this, $page );
1084 return $dim['width'];
1086 // For non-paged media, the false goes through an
1087 // intval, turning failure into 0, so do same here.
1091 return $this->width
;
1096 * Return the height of the image
1097 * @stable to override
1102 public function getHeight( $page = 1 ) {
1110 if ( $this->isMultipage() ) {
1111 $handler = $this->getHandler();
1115 $dim = $handler->getPageDimensions( $this, $page );
1117 return $dim['height'];
1119 // For non-paged media, the false goes through an
1120 // intval, turning failure into 0, so do same here.
1124 return $this->height
;
1129 * Get short description URL for a file based on the page ID.
1130 * @stable to override
1132 * @return string|null
1135 public function getDescriptionShortUrl() {
1136 if ( !$this->title
) {
1137 return null; // Avoid hard failure when the file does not exist. T221812
1140 $pageId = $this->title
->getArticleID();
1143 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
1144 if ( $url !== false ) {
1152 * Get handler-specific metadata as a serialized string
1154 * @deprecated since 1.37 use getMetadataArray() or getMetadataItem()
1157 public function getMetadata() {
1158 $data = $this->getMetadataArray();
1161 } elseif ( array_keys( $data ) === [ '_error' ] ) {
1162 // Legacy error encoding
1163 return $data['_error'];
1165 return serialize( $this->getMetadataArray() );
1170 * Get unserialized handler-specific metadata
1175 public function getMetadataArray(): array {
1176 $this->load( self
::LOAD_ALL
);
1177 if ( $this->unloadedMetadataBlobs
) {
1178 return $this->getMetadataItems(
1179 array_unique( array_merge(
1180 array_keys( $this->metadataArray
),
1181 array_keys( $this->unloadedMetadataBlobs
)
1185 return $this->metadataArray
;
1188 public function getMetadataItems( array $itemNames ): array {
1189 $this->load( self
::LOAD_ALL
);
1192 foreach ( $itemNames as $itemName ) {
1193 if ( array_key_exists( $itemName, $this->metadataArray
) ) {
1194 $result[$itemName] = $this->metadataArray
[$itemName];
1195 } elseif ( isset( $this->unloadedMetadataBlobs
[$itemName] ) ) {
1196 $addresses[$itemName] = $this->unloadedMetadataBlobs
[$itemName];
1201 $resultFromBlob = $this->metadataStorageHelper
->getMetadataFromBlobStore( $addresses );
1202 foreach ( $addresses as $itemName => $address ) {
1203 unset( $this->unloadedMetadataBlobs
[$itemName] );
1204 $value = $resultFromBlob[$itemName] ??
null;
1205 if ( $value !== null ) {
1206 $result[$itemName] = $value;
1207 $this->metadataArray
[$itemName] = $value;
1215 * Serialize the metadata array for insertion into img_metadata, oi_metadata
1218 * If metadata splitting is enabled, this may write blobs to the database,
1219 * returning their addresses.
1222 * @param IReadableDatabase $db
1223 * @return string|Blob
1225 public function getMetadataForDb( IReadableDatabase
$db ) {
1226 $this->load( self
::LOAD_ALL
);
1227 if ( !$this->metadataArray
&& !$this->metadataBlobs
) {
1229 } elseif ( $this->repo
->isJsonMetadataEnabled() ) {
1230 $s = $this->getJsonMetadata();
1232 $s = serialize( $this->getMetadataArray() );
1234 if ( !is_string( $s ) ) {
1235 throw new RuntimeException( 'Could not serialize image metadata value for DB' );
1237 return $db->encodeBlob( $s );
1241 * Get metadata in JSON format ready for DB insertion, optionally splitting
1242 * items out to BlobStore.
1246 private function getJsonMetadata() {
1247 // Directly store data that is not already in BlobStore
1249 'data' => array_diff_key( $this->metadataArray
, $this->metadataBlobs
)
1252 // Also store the blob addresses
1253 if ( $this->metadataBlobs
) {
1254 $envelope['blobs'] = $this->metadataBlobs
;
1257 [ $s, $blobAddresses ] = $this->metadataStorageHelper
->getJsonMetadata( $this, $envelope );
1259 // Repeated calls to this function should not keep inserting more blobs
1260 $this->metadataBlobs +
= $blobAddresses;
1266 * Determine whether the loaded metadata may be a candidate for splitting, by measuring its
1267 * serialized size. Helper for maybeUpgradeRow().
1271 private function isMetadataOversize() {
1272 if ( !$this->repo
->isSplitMetadataEnabled() ) {
1275 $threshold = $this->repo
->getSplitMetadataThreshold();
1276 $directItems = array_diff_key( $this->metadataArray
, $this->metadataBlobs
);
1277 foreach ( $directItems as $value ) {
1278 if ( strlen( $this->metadataStorageHelper
->jsonEncode( $value ) ) > $threshold ) {
1286 * Unserialize a metadata blob which came from the database and store it
1290 * @param IReadableDatabase $db
1291 * @param string|Blob $metadataBlob
1293 protected function loadMetadataFromDbFieldValue( IReadableDatabase
$db, $metadataBlob ) {
1294 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1298 * Unserialize a metadata string which came from some non-DB source, or is
1299 * the return value of IReadableDatabase::decodeBlob().
1302 * @param string $metadataString
1304 protected function loadMetadataFromString( $metadataString ) {
1305 $this->extraDataLoaded
= true;
1306 $this->metadataArray
= [];
1307 $this->metadataBlobs
= [];
1308 $this->unloadedMetadataBlobs
= [];
1309 $metadataString = (string)$metadataString;
1310 if ( $metadataString === '' ) {
1311 $this->metadataSerializationFormat
= self
::MDS_EMPTY
;
1314 if ( $metadataString[0] === '{' ) {
1315 $envelope = $this->metadataStorageHelper
->jsonDecode( $metadataString );
1317 // Legacy error encoding
1318 $this->metadataArray
= [ '_error' => $metadataString ];
1319 $this->metadataSerializationFormat
= self
::MDS_LEGACY
;
1321 $this->metadataSerializationFormat
= self
::MDS_JSON
;
1322 if ( isset( $envelope['data'] ) ) {
1323 $this->metadataArray
= $envelope['data'];
1325 if ( isset( $envelope['blobs'] ) ) {
1326 $this->metadataBlobs
= $this->unloadedMetadataBlobs
= $envelope['blobs'];
1330 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1331 $data = @unserialize
( $metadataString );
1332 if ( !is_array( $data ) ) {
1333 // Legacy error encoding
1334 $data = [ '_error' => $metadataString ];
1335 $this->metadataSerializationFormat
= self
::MDS_LEGACY
;
1337 $this->metadataSerializationFormat
= self
::MDS_PHP
;
1339 $this->metadataArray
= $data;
1344 * @stable to override
1347 public function getBitDepth() {
1350 return (int)$this->bits
;
1354 * Returns the size of the image file, in bytes
1355 * @stable to override
1358 public function getSize() {
1365 * Returns the MIME type of the file.
1366 * @stable to override
1369 public function getMimeType() {
1376 * Returns the type of the media in the file.
1377 * Use the value returned by this function with the MEDIATYPE_xxx constants.
1378 * @stable to override
1381 public function getMediaType() {
1384 return $this->media_type
;
1387 /** canRender inherited */
1388 /** mustRender inherited */
1389 /** allowInlineDisplay inherited */
1390 /** isSafeFile inherited */
1391 /** isTrustedFile inherited */
1394 * Returns true if the file exists on disk.
1395 * @stable to override
1396 * @return bool Whether file exist on disk.
1398 public function exists() {
1401 return $this->fileExists
;
1404 /** getTransformScript inherited */
1405 /** getUnscaledThumb inherited */
1406 /** thumbName inherited */
1407 /** createThumb inherited */
1408 /** transform inherited */
1410 /** getHandler inherited */
1411 /** iconThumb inherited */
1412 /** getLastError inherited */
1415 * Get all thumbnail names previously generated for this file.
1417 * This should be called during POST requests only (and other db-writing
1418 * contexts) as it may involve connections across multiple data centers
1419 * (e.g. both backends of a FileBackendMultiWrite setup).
1421 * @stable to override
1422 * @param string|false $archiveName Name of an archive file, default false
1423 * @return array First element is the base dir, then files in that base dir.
1425 protected function getThumbnails( $archiveName = false ) {
1426 if ( $archiveName ) {
1427 $dir = $this->getArchiveThumbPath( $archiveName );
1429 $dir = $this->getThumbPath();
1432 $backend = $this->repo
->getBackend();
1435 $iterator = $backend->getFileList( [ 'dir' => $dir, 'forWrite' => true ] );
1436 if ( $iterator !== null ) {
1437 foreach ( $iterator as $file ) {
1441 } catch ( FileBackendError
$e ) {
1442 } // suppress (T56674)
1448 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1449 * @stable to override
1451 * @param array $options An array potentially with the key forThumbRefresh.
1453 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1455 public function purgeCache( $options = [] ) {
1456 // Refresh metadata in memcached, but don't touch thumbnails or CDN
1457 $this->maybeUpgradeRow();
1458 $this->invalidateCache();
1460 // Delete thumbnails
1461 $this->purgeThumbnails( $options );
1463 // Purge CDN cache for this file
1464 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
1467 !empty( $options['forThumbRefresh'] )
1468 ?
$hcu::PURGE_PRESEND
// just a manual purge
1469 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1474 * Delete cached transformed files for an archived version only.
1475 * @stable to override
1476 * @param string $archiveName Name of the archived file
1478 public function purgeOldThumbnails( $archiveName ) {
1479 // Get a list of old thumbnails
1480 $thumbs = $this->getThumbnails( $archiveName );
1482 // Delete thumbnails from storage, and prevent the directory itself from being purged
1483 $dir = array_shift( $thumbs );
1484 $this->purgeThumbList( $dir, $thumbs );
1487 foreach ( $thumbs as $thumb ) {
1488 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1491 // Purge any custom thumbnail caches
1492 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1495 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
1496 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND
);
1500 * Delete cached transformed files for the current version only.
1501 * @stable to override
1502 * @param array $options
1503 * @phan-param array{forThumbRefresh?:bool} $options
1505 public function purgeThumbnails( $options = [] ) {
1506 $thumbs = $this->getThumbnails();
1508 // Delete thumbnails from storage, and prevent the directory itself from being purged
1509 $dir = array_shift( $thumbs );
1510 $this->purgeThumbList( $dir, $thumbs );
1512 // Always purge all files from CDN regardless of handler filters
1514 foreach ( $thumbs as $thumb ) {
1515 $urls[] = $this->getThumbUrl( $thumb );
1518 // Give the media handler a chance to filter the file purge list
1519 if ( !empty( $options['forThumbRefresh'] ) ) {
1520 $handler = $this->getHandler();
1522 $handler->filterThumbnailPurgeList( $thumbs, $options );
1526 // Purge any custom thumbnail caches
1527 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1530 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
1533 !empty( $options['forThumbRefresh'] )
1534 ?
$hcu::PURGE_PRESEND
// just a manual purge
1535 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1540 * Prerenders a configurable set of thumbnails
1541 * @stable to override
1545 public function prerenderThumbnails() {
1546 $uploadThumbnailRenderMap = MediaWikiServices
::getInstance()
1547 ->getMainConfig()->get( MainConfigNames
::UploadThumbnailRenderMap
);
1551 $sizes = $uploadThumbnailRenderMap;
1554 foreach ( $sizes as $size ) {
1555 if ( $this->isMultipage() ) {
1556 // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1557 // a flood of jobs for huge files.
1558 $pageLimit = min( $this->pageCount(), self
::MAX_PAGE_RENDER_JOBS
);
1560 $jobs[] = new ThumbnailRenderJob(
1563 'transformParams' => [ 'width' => $size, 'page' => 1 ],
1564 'enqueueNextPage' => true,
1565 'pageLimit' => $pageLimit
1568 } elseif ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1569 $jobs[] = new ThumbnailRenderJob(
1571 [ 'transformParams' => [ 'width' => $size ] ]
1577 MediaWikiServices
::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1582 * Delete a list of thumbnails visible at urls
1583 * @stable to override
1584 * @param string $dir Base dir of the files.
1585 * @param array $files Array of strings: relative filenames (to $dir)
1587 protected function purgeThumbList( $dir, $files ) {
1588 $fileListDebug = strtr(
1589 var_export( $files, true ),
1592 wfDebug( __METHOD__
. ": $fileListDebug" );
1594 if ( $this->repo
->supportsSha1URLs() ) {
1595 $reference = $this->getSha1();
1597 $reference = $this->getName();
1601 foreach ( $files as $file ) {
1602 # Check that the reference (filename or sha1) is part of the thumb name
1603 # This is a basic check to avoid erasing unrelated directories
1604 if ( str_contains( $file, $reference )
1605 ||
str_contains( $file, "-thumbnail" ) // "short" thumb name
1607 $purgeList[] = "{$dir}/{$file}";
1611 # Delete the thumbnails
1612 $this->repo
->quickPurgeBatch( $purgeList );
1613 # Clear out the thumbnail directory if empty
1614 $this->repo
->quickCleanDir( $dir );
1617 /** purgeDescription inherited */
1618 /** purgeEverything inherited */
1621 * @stable to override
1622 * @param int|null $limit Optional: Limit to number of results
1623 * @param string|int|null $start Optional: Timestamp, start from
1624 * @param string|int|null $end Optional: Timestamp, end at
1626 * @return OldLocalFile[] Guaranteed to be in descending order
1628 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1629 if ( !$this->exists() ) {
1630 return []; // Avoid hard failure when the file does not exist. T221812
1633 $dbr = $this->repo
->getReplicaDB();
1634 $oldFileQuery = OldLocalFile
::getQueryInfo();
1636 $tables = $oldFileQuery['tables'];
1637 $fields = $oldFileQuery['fields'];
1638 $join_conds = $oldFileQuery['joins'];
1639 $conds = $opts = [];
1640 $eq = $inc ?
'=' : '';
1641 $conds[] = $dbr->expr( 'oi_name', '=', $this->title
->getDBkey() );
1644 $conds[] = $dbr->expr( 'oi_timestamp', "<$eq", $dbr->timestamp( $start ) );
1648 $conds[] = $dbr->expr( 'oi_timestamp', ">$eq", $dbr->timestamp( $end ) );
1652 $opts['LIMIT'] = $limit;
1655 // Search backwards for time > x queries
1656 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1657 $opts['ORDER BY'] = "oi_timestamp $order";
1658 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1660 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1661 $conds, $opts, $join_conds );
1663 $res = $dbr->newSelectQueryBuilder()
1667 ->caller( __METHOD__
)
1669 ->joinConds( $join_conds )
1673 foreach ( $res as $row ) {
1674 $r[] = $this->repo
->newFileFromRow( $row );
1677 if ( $order == 'ASC' ) {
1678 $r = array_reverse( $r ); // make sure it ends up descending
1685 * Returns the history of this file, line by line.
1686 * starts with current version, then old versions.
1687 * uses $this->historyLine to check which line to return:
1688 * 0 return line for current version
1689 * 1 query for old versions, return first one
1690 * 2, ... return next old version from above query
1691 * @stable to override
1692 * @return stdClass|false
1694 public function nextHistoryLine() {
1695 if ( !$this->exists() ) {
1696 return false; // Avoid hard failure when the file does not exist. T221812
1699 # Polymorphic function name to distinguish foreign and local fetches
1700 $fname = static::class . '::' . __FUNCTION__
;
1702 $dbr = $this->repo
->getReplicaDB();
1704 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1705 $queryBuilder = FileSelectQueryBuilder
::newForFile( $dbr );
1707 $queryBuilder->fields( [ 'oi_archive_name' => $dbr->addQuotes( '' ), 'oi_deleted' => '0' ] )
1708 ->where( [ 'img_name' => $this->title
->getDBkey() ] );
1709 $this->historyRes
= $queryBuilder->caller( $fname )->fetchResultSet();
1711 if ( $this->historyRes
->numRows() == 0 ) {
1712 $this->historyRes
= null;
1716 } elseif ( $this->historyLine
== 1 ) {
1717 $queryBuilder = FileSelectQueryBuilder
::newForOldFile( $dbr );
1719 $this->historyRes
= $queryBuilder->where( [ 'oi_name' => $this->title
->getDBkey() ] )
1720 ->orderBy( 'oi_timestamp', SelectQueryBuilder
::SORT_DESC
)
1721 ->caller( $fname )->fetchResultSet();
1723 $this->historyLine++
;
1725 return $this->historyRes
->fetchObject();
1729 * Reset the history pointer to the first element of the history
1730 * @stable to override
1732 public function resetHistory() {
1733 $this->historyLine
= 0;
1735 if ( $this->historyRes
!== null ) {
1736 $this->historyRes
= null;
1740 /** getHashPath inherited */
1741 /** getRel inherited */
1742 /** getUrlRel inherited */
1743 /** getArchiveRel inherited */
1744 /** getArchivePath inherited */
1745 /** getThumbPath inherited */
1746 /** getArchiveUrl inherited */
1747 /** getThumbUrl inherited */
1748 /** getArchiveVirtualUrl inherited */
1749 /** getThumbVirtualUrl inherited */
1750 /** isHashed inherited */
1753 * Upload a file and record it in the DB
1754 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1755 * @param string $comment Upload description
1756 * @param string $pageText Text to use for the new description page,
1757 * if a new description page is created
1758 * @param int $flags Flags for publish()
1759 * @param array|false $props File properties, if known. This can be used to
1760 * reduce the upload time when uploading virtual URLs for which the file
1761 * info is already known
1762 * @param string|false $timestamp Timestamp for img_timestamp, or false to use the
1763 * current time. Can be in any format accepted by ConvertibleTimestamp.
1764 * @param Authority|null $uploader object or null to use the context authority
1765 * @param string[] $tags Change tags to add to the log entry and page revision.
1766 * (This doesn't check $uploader's permissions.)
1767 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1768 * upload, see T193621
1769 * @param bool $revert If this file upload is a revert
1770 * @return Status On success, the value member contains the
1771 * archive name, or an empty string if it was a new file.
1773 public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1774 $timestamp = false, ?Authority
$uploader = null, $tags = [],
1775 $createNullRevision = true, $revert = false
1777 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1778 return $this->readOnlyFatalStatus();
1779 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1780 // Check this in advance to avoid writing to FileBackend and the file tables,
1781 // only to fail on insert the revision due to the text store being unavailable.
1782 return $this->readOnlyFatalStatus();
1785 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1787 if ( FileRepo
::isVirtualUrl( $srcPath )
1788 || FileBackend
::isStoragePath( $srcPath )
1790 $props = $this->repo
->getFileProps( $srcPath );
1792 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1793 $props = $mwProps->getPropsFromPath( $srcPath, true );
1798 $handler = MediaHandler
::getHandler( $props['mime'] );
1800 if ( is_string( $props['metadata'] ) ) {
1801 // This supports callers directly fabricating a metadata
1802 // property using serialize(). Normally the metadata property
1803 // comes from MWFileProps, in which case it won't be a string.
1804 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1805 $metadata = @unserialize
( $props['metadata'] );
1807 $metadata = $props['metadata'];
1810 if ( is_array( $metadata ) ) {
1811 $options['headers'] = $handler->getContentHeaders( $metadata );
1814 $options['headers'] = [];
1817 // Trim spaces on user supplied text
1818 $comment = trim( $comment );
1820 $status = $this->publish( $src, $flags, $options );
1822 if ( $status->successCount
>= 2 ) {
1823 // There will be a copy+(one of move,copy,store).
1824 // The first succeeding does not commit us to updating the DB
1825 // since it simply copied the current version to a timestamped file name.
1826 // It is only *preferable* to avoid leaving such files orphaned.
1827 // Once the second operation goes through, then the current version was
1828 // updated and we must therefore update the DB too.
1829 $oldver = $status->value
;
1831 $uploadStatus = $this->recordUpload3(
1835 $uploader ?? RequestContext
::getMain()->getAuthority(),
1839 $createNullRevision,
1842 if ( !$uploadStatus->isOK() ) {
1843 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1844 // update filenotfound error with more specific path
1845 $status->fatal( 'filenotfound', $srcPath );
1847 $status->merge( $uploadStatus );
1856 * Record a file upload in the upload log and the image table (version 3)
1858 * @stable to override
1859 * @param string $oldver
1860 * @param string $comment
1861 * @param string $pageText File description page text (only used for new uploads)
1862 * @param Authority $performer
1863 * @param array|false $props
1864 * @param string|false $timestamp Can be in any format accepted by ConvertibleTimestamp
1865 * @param string[] $tags
1866 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1867 * upload, see T193621
1868 * @param bool $revert If this file upload is a revert
1871 public function recordUpload3(
1875 Authority
$performer,
1879 bool $createNullRevision = true,
1880 bool $revert = false
1882 $dbw = $this->repo
->getPrimaryDB();
1884 # Imports or such might force a certain timestamp; otherwise we generate
1885 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1886 if ( $timestamp === false ) {
1887 $timestamp = $dbw->timestamp();
1888 $allowTimeKludge = true;
1890 $allowTimeKludge = false;
1893 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1894 $props['description'] = $comment;
1895 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1896 $this->setProps( $props );
1898 # Fail now if the file isn't there
1899 if ( !$this->fileExists
) {
1900 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!" );
1902 return Status
::newFatal( 'filenotfound', $this->getRel() );
1905 $mimeAnalyzer = MediaWikiServices
::getInstance()->getMimeAnalyzer();
1906 if ( !$mimeAnalyzer->isValidMajorMimeType( $this->major_mime
) ) {
1907 $this->major_mime
= 'unknown';
1910 $actorNormalizaton = MediaWikiServices
::getInstance()->getActorNormalization();
1912 $dbw->startAtomic( __METHOD__
);
1914 $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1915 $this->user
= $performer->getUser();
1917 # Test to see if the row exists using INSERT IGNORE
1918 # This avoids race conditions by locking the row until the commit, and also
1919 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1920 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1921 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1922 $actorFields = [ 'img_actor' => $actorId ];
1923 $dbw->newInsertQueryBuilder()
1924 ->insertInto( 'image' )
1927 'img_name' => $this->getName(),
1928 'img_size' => $this->size
,
1929 'img_width' => intval( $this->width
),
1930 'img_height' => intval( $this->height
),
1931 'img_bits' => $this->bits
,
1932 'img_media_type' => $this->media_type
,
1933 'img_major_mime' => $this->major_mime
,
1934 'img_minor_mime' => $this->minor_mime
,
1935 'img_timestamp' => $dbw->timestamp( $timestamp ),
1936 'img_metadata' => $this->getMetadataForDb( $dbw ),
1937 'img_sha1' => $this->sha1
1938 ] +
$commentFields +
$actorFields )
1939 ->caller( __METHOD__
)->execute();
1940 $reupload = ( $dbw->affectedRows() == 0 );
1942 $latestFileRevId = null;
1943 if ( $this->migrationStage
& SCHEMA_COMPAT_WRITE_NEW
) {
1945 $latestFileRevId = $dbw->newSelectQueryBuilder()
1947 ->from( 'filerevision' )
1948 ->where( [ 'fr_file' => $this->acquireFileIdFromName() ] )
1949 ->orderBy( 'fr_timestamp', 'DESC' )
1952 $commentFieldsNew = $commentStore->insert( $dbw, 'fr_description', $comment );
1953 $dbw->newInsertQueryBuilder()
1954 ->insertInto( 'filerevision' )
1956 'fr_file' => $this->acquireFileIdFromName(),
1957 'fr_size' => $this->size
,
1958 'fr_width' => intval( $this->width
),
1959 'fr_height' => intval( $this->height
),
1960 'fr_bits' => $this->bits
,
1961 'fr_actor' => $actorId,
1963 'fr_timestamp' => $dbw->timestamp( $timestamp ),
1964 'fr_metadata' => $this->getMetadataForDb( $dbw ),
1965 'fr_sha1' => $this->sha1
1966 ] +
$commentFieldsNew )
1967 ->caller( __METHOD__
)->execute();
1968 $dbw->newUpdateQueryBuilder()
1970 ->set( [ 'file_latest' => $dbw->insertId() ] )
1971 ->where( [ 'file_id' => $this->getFileIdFromName() ] )
1972 ->caller( __METHOD__
)->execute();
1976 $row = $dbw->newSelectQueryBuilder()
1977 ->select( [ 'img_timestamp', 'img_sha1' ] )
1979 ->where( [ 'img_name' => $this->getName() ] )
1980 ->caller( __METHOD__
)->fetchRow();
1982 if ( $row && $row->img_sha1
=== $this->sha1
) {
1983 $dbw->endAtomic( __METHOD__
);
1984 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!" );
1985 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1986 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1989 if ( $allowTimeKludge ) {
1990 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1991 $lUnixtime = $row ?
(int)wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1992 # Avoid a timestamp that is not newer than the last version
1993 # TODO: the image/oldimage tables should be like page/revision with an ID field
1994 if ( $lUnixtime && (int)wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1995 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1996 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1997 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
2001 $tables = [ 'image' ];
2003 'oi_name' => 'img_name',
2004 'oi_archive_name' => $dbw->addQuotes( $oldver ),
2005 'oi_size' => 'img_size',
2006 'oi_width' => 'img_width',
2007 'oi_height' => 'img_height',
2008 'oi_bits' => 'img_bits',
2009 'oi_description_id' => 'img_description_id',
2010 'oi_timestamp' => 'img_timestamp',
2011 'oi_metadata' => 'img_metadata',
2012 'oi_media_type' => 'img_media_type',
2013 'oi_major_mime' => 'img_major_mime',
2014 'oi_minor_mime' => 'img_minor_mime',
2015 'oi_sha1' => 'img_sha1',
2016 'oi_actor' => 'img_actor',
2019 if ( ( $this->migrationStage
& SCHEMA_COMPAT_WRITE_NEW
) && $latestFileRevId && $oldver ) {
2020 $dbw->newUpdateQueryBuilder()
2021 ->update( 'filerevision' )
2022 ->set( [ 'fr_archive_name' => $oldver ] )
2023 ->where( [ 'fr_id' => $latestFileRevId ] )
2024 ->caller( __METHOD__
)->execute();
2028 # (T36993) Note: $oldver can be empty here, if the previous
2029 # version of the file was broken. Allow registration of the new
2030 # version to continue anyway, because that's better than having
2031 # an image that's not fixable by user operations.
2032 # Collision, this is an update of a file
2033 # Insert previous contents into oldimage
2034 $dbw->insertSelect( 'oldimage', $tables, $fields,
2035 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
2037 # Update the current image row
2038 $dbw->newUpdateQueryBuilder()
2041 'img_size' => $this->size
,
2042 'img_width' => intval( $this->width
),
2043 'img_height' => intval( $this->height
),
2044 'img_bits' => $this->bits
,
2045 'img_media_type' => $this->media_type
,
2046 'img_major_mime' => $this->major_mime
,
2047 'img_minor_mime' => $this->minor_mime
,
2048 'img_timestamp' => $dbw->timestamp( $timestamp ),
2049 'img_metadata' => $this->getMetadataForDb( $dbw ),
2050 'img_sha1' => $this->sha1
2051 ] +
$commentFields +
$actorFields )
2052 ->where( [ 'img_name' => $this->getName() ] )
2053 ->caller( __METHOD__
)->execute();
2056 $descTitle = $this->getTitle();
2057 $descId = $descTitle->getArticleID();
2058 $wikiPage = MediaWikiServices
::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
2059 if ( !$wikiPage instanceof WikiFilePage
) {
2060 throw new UnexpectedValueException( 'Cannot obtain instance of WikiFilePage for ' . $this->getName()
2061 . ', got instance of ' . get_class( $wikiPage ) );
2063 $wikiPage->setFile( $this );
2065 // Determine log action. If reupload is done by reverting, use a special log_action.
2067 $logAction = 'revert';
2068 } elseif ( $reupload ) {
2069 $logAction = 'overwrite';
2071 $logAction = 'upload';
2073 // Add the log entry...
2074 $logEntry = new ManualLogEntry( 'upload', $logAction );
2075 $logEntry->setTimestamp( $this->timestamp
);
2076 $logEntry->setPerformer( $performer->getUser() );
2077 $logEntry->setComment( $comment );
2078 $logEntry->setTarget( $descTitle );
2079 // Allow people using the api to associate log entries with the upload.
2080 // Log has a timestamp, but sometimes different from upload timestamp.
2081 $logEntry->setParameters(
2083 'img_sha1' => $this->sha1
,
2084 'img_timestamp' => $timestamp,
2087 // Note we keep $logId around since during new image
2088 // creation, page doesn't exist yet, so log_page = 0
2089 // but we want it to point to the page we're making,
2090 // so we later modify the log entry.
2091 // For a similar reason, we avoid making an RC entry
2092 // now and wait until the page exists.
2093 $logId = $logEntry->insert();
2095 if ( $descTitle->exists() ) {
2096 if ( $createNullRevision ) {
2097 $services = MediaWikiServices
::getInstance();
2098 $revStore = $services->getRevisionStore();
2099 // Use own context to get the action text in content language
2100 $formatter = $services->getLogFormatterFactory()->newFromEntry( $logEntry );
2101 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
2102 $editSummary = $formatter->getPlainActionText();
2103 $summary = CommentStoreComment
::newUnsavedComment( $editSummary );
2104 $nullRevRecord = $revStore->newNullRevision(
2109 $performer->getUser()
2112 if ( $nullRevRecord ) {
2113 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
2115 $this->getHookRunner()->onRevisionFromEditComplete(
2118 $inserted->getParentId(),
2119 $performer->getUser(),
2123 $wikiPage->updateRevisionOn( $dbw, $inserted );
2124 // Associate null revision id
2125 $logEntry->setAssociatedRevId( $inserted->getId() );
2129 $newPageContent = null;
2131 // Make the description page and RC log entry post-commit
2132 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
2135 // NOTE: Even after ending this atomic section, we are probably still in the implicit
2136 // transaction started by any prior master query in the request. We cannot yet safely
2137 // schedule jobs, see T263301.
2138 $dbw->endAtomic( __METHOD__
);
2139 $fname = __METHOD__
;
2141 # Do some cache purges after final commit so that:
2142 # a) Changes are more likely to be seen post-purge
2143 # b) They won't cause rollback of the log publish/update above
2144 $purgeUpdate = new AutoCommitUpdate(
2148 $reupload, $wikiPage, $newPageContent, $comment, $performer,
2149 $logEntry, $logId, $descId, $tags, $fname
2151 # Update memcache after the commit
2152 $this->invalidateCache();
2154 $updateLogPage = false;
2155 if ( $newPageContent ) {
2156 # New file page; create the description page.
2157 # There's already a log entry, so don't make a second RC entry
2158 # CDN and file cache for the description page are purged by doUserEditContent.
2159 $status = $wikiPage->doUserEditContent(
2163 EDIT_NEW | EDIT_SUPPRESS_RC
2166 $revRecord = $status->getNewRevision();
2168 // Associate new page revision id
2169 $logEntry->setAssociatedRevId( $revRecord->getId() );
2171 // This relies on the resetArticleID() call in WikiPage::insertOn(),
2172 // which is triggered on $descTitle by doUserEditContent() above.
2173 $updateLogPage = $revRecord->getPageId();
2176 # Existing file page: invalidate description page cache
2177 $title = $wikiPage->getTitle();
2178 $title->invalidateCache();
2179 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
2180 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED
);
2181 # Allow the new file version to be patrolled from the page footer
2182 Article
::purgePatrolFooterCache( $descId );
2185 # Update associated rev id. This should be done by $logEntry->insert() earlier,
2186 # but setAssociatedRevId() wasn't called at that point yet...
2187 $logParams = $logEntry->getParameters();
2188 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2189 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
2190 if ( $updateLogPage ) {
2191 # Also log page, in case where we just created it above
2192 $update['log_page'] = $updateLogPage;
2194 $this->getRepo()->getPrimaryDB()->newUpdateQueryBuilder()
2195 ->update( 'logging' )
2197 ->where( [ 'log_id' => $logId ] )
2198 ->caller( $fname )->execute();
2200 $this->getRepo()->getPrimaryDB()->newInsertQueryBuilder()
2201 ->insertInto( 'log_search' )
2203 'ls_field' => 'associated_rev_id',
2204 'ls_value' => (string)$logEntry->getAssociatedRevId(),
2205 'ls_log_id' => $logId,
2207 ->caller( $fname )->execute();
2209 # Add change tags, if any
2211 $logEntry->addTags( $tags );
2214 # Uploads can be patrolled
2215 $logEntry->setIsPatrollable( true );
2217 # Now that the log entry is up-to-date, make an RC entry.
2218 $logEntry->publish( $logId );
2220 # Run hook for other updates (typically more cache purging)
2221 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2224 # Delete old thumbnails
2225 $this->purgeThumbnails();
2226 # Remove the old file from the CDN cache
2227 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
2228 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED
);
2230 # Update backlink pages pointing to this title if created
2231 $blcFactory = MediaWikiServices
::getInstance()->getBacklinkCacheFactory();
2232 LinksUpdate
::queueRecursiveJobsForTable(
2236 $performer->getUser()->getName(),
2237 $blcFactory->getBacklinkCache( $this->getTitle() )
2241 $this->prerenderThumbnails();
2245 # Invalidate cache for all pages using this file
2246 $cacheUpdateJob = HTMLCacheUpdateJob
::newForBacklinks(
2249 [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2252 // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2253 // only schedule jobs after that transaction was committed, so a job queue failure
2254 // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2255 // Jobs or the DeferredUpdates that assume the update is complete until after the
2256 // transaction has been committed and we are sure that the upload was indeed successful.
2257 $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2258 DeferredUpdates
::addUpdate( $purgeUpdate, DeferredUpdates
::PRESEND
);
2261 // This is a new file, so update the image count
2262 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2265 MediaWikiServices
::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2268 return Status
::newGood();
2272 * Move or copy a file to its public location. If a file exists at the
2273 * destination, move it to an archive. Returns a Status object with
2274 * the archive name in the "value" member on success.
2276 * The archive name should be passed through to recordUpload for database
2279 * @stable to override
2280 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
2281 * @param int $flags A bitwise combination of:
2282 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
2283 * @param array $options Optional additional parameters
2284 * @return Status On success, the value member contains the
2285 * archive name, or an empty string if it was a new file.
2287 public function publish( $src, $flags = 0, array $options = [] ) {
2288 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2292 * Move or copy a file to a specified location. Returns a Status
2293 * object with the archive name in the "value" member on success.
2295 * The archive name should be passed through to recordUpload for database
2298 * @stable to override
2299 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
2300 * @param string $dstRel Target relative path
2301 * @param int $flags A bitwise combination of:
2302 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
2303 * @param array $options Optional additional parameters
2304 * @return Status On success, the value member contains the
2305 * archive name, or an empty string if it was a new file.
2307 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2308 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
2310 $repo = $this->getRepo();
2311 if ( $repo->getReadOnlyReason() !== false ) {
2312 return $this->readOnlyFatalStatus();
2315 $status = $this->acquireFileLock();
2316 if ( !$status->isOK() ) {
2320 if ( $this->isOld() ) {
2321 $archiveRel = $dstRel;
2322 $archiveName = basename( $archiveRel );
2324 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
2325 $archiveRel = $this->getArchiveRel( $archiveName );
2328 if ( $repo->hasSha1Storage() ) {
2329 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
2330 ?
$repo->getFileSha1( $srcPath )
2331 : FSFile
::getSha1Base36FromPath( $srcPath );
2332 /** @var FileBackendDBRepoWrapper $wrapperBackend */
2333 $wrapperBackend = $repo->getBackend();
2334 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2335 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2336 $status = $repo->quickImport( $src, $dst );
2337 if ( $flags & File
::DELETE_SOURCE
) {
2341 if ( $this->exists() ) {
2342 $status->value
= $archiveName;
2345 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
2346 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2348 if ( $status->value
== 'new' ) {
2349 $status->value
= '';
2351 $status->value
= $archiveName;
2355 $this->releaseFileLock();
2359 /** getLinksTo inherited */
2360 /** getExifData inherited */
2361 /** isLocal inherited */
2362 /** wasDeleted inherited */
2365 * Move file to the new title
2367 * Move current, old version and all thumbnails
2368 * to the new filename. Old file is deleted.
2370 * Cache purging is done; checks for validity
2371 * and logging are caller's responsibility
2373 * @stable to override
2374 * @param Title $target New file name
2377 public function move( $target ) {
2378 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
2379 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2380 return $this->readOnlyFatalStatus();
2383 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2384 $batch = new LocalFileMoveBatch( $this, $target );
2386 $status = $batch->addCurrent();
2387 if ( !$status->isOK() ) {
2390 $archiveNames = $batch->addOlds();
2391 $status = $batch->execute();
2393 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2395 // Purge the source and target files outside the transaction...
2396 $oldTitleFile = $localRepo->newFile( $this->title
);
2397 $newTitleFile = $localRepo->newFile( $target );
2398 DeferredUpdates
::addUpdate(
2399 new AutoCommitUpdate(
2400 $this->getRepo()->getPrimaryDB(),
2402 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2403 $oldTitleFile->purgeEverything();
2404 foreach ( $archiveNames as $archiveName ) {
2405 /** @var OldLocalFile $oldTitleFile */
2406 '@phan-var OldLocalFile $oldTitleFile';
2407 $oldTitleFile->purgeOldThumbnails( $archiveName );
2409 $newTitleFile->purgeEverything();
2412 DeferredUpdates
::PRESEND
2415 if ( $status->isOK() ) {
2416 // Now switch the object
2417 $this->title
= $target;
2418 // Force regeneration of the name and hashpath
2420 $this->hashPath
= null;
2427 * Delete all versions of the file.
2431 * Moves the files into an archive directory (or deletes them)
2432 * and removes the database rows.
2434 * Cache purging is done; logging is caller's responsibility.
2435 * @stable to override
2437 * @param string $reason
2438 * @param UserIdentity $user
2439 * @param bool $suppress
2442 public function deleteFile( $reason, UserIdentity
$user, $suppress = false ) {
2443 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2444 return $this->readOnlyFatalStatus();
2447 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2449 $batch->addCurrent();
2450 // Get old version relative paths
2451 $archiveNames = $batch->addOlds();
2452 $status = $batch->execute();
2454 if ( $status->isOK() ) {
2455 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
2458 // To avoid slow purges in the transaction, move them outside...
2459 DeferredUpdates
::addUpdate(
2460 new AutoCommitUpdate(
2461 $this->getRepo()->getPrimaryDB(),
2463 function () use ( $archiveNames ) {
2464 $this->purgeEverything();
2465 foreach ( $archiveNames as $archiveName ) {
2466 $this->purgeOldThumbnails( $archiveName );
2470 DeferredUpdates
::PRESEND
2475 foreach ( $archiveNames as $archiveName ) {
2476 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2479 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
2480 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED
);
2486 * Delete an old version of the file.
2489 * @stable to override
2491 * Moves the file into an archive directory (or deletes it)
2492 * and removes the database row.
2494 * Cache purging is done; logging is caller's responsibility.
2496 * @param string $archiveName
2497 * @param string $reason
2498 * @param UserIdentity $user
2499 * @param bool $suppress
2502 public function deleteOldFile( $archiveName, $reason, UserIdentity
$user, $suppress = false ) {
2503 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2504 return $this->readOnlyFatalStatus();
2507 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2509 $batch->addOld( $archiveName );
2510 $status = $batch->execute();
2512 $this->purgeOldThumbnails( $archiveName );
2513 if ( $status->isOK() ) {
2514 $this->purgeDescription();
2517 $url = $this->getArchiveUrl( $archiveName );
2518 $hcu = MediaWikiServices
::getInstance()->getHtmlCacheUpdater();
2519 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED
);
2525 * Restore all or specified deleted revisions to the given file.
2526 * Permissions and logging are left to the caller.
2528 * May throw database exceptions on error.
2529 * @stable to override
2531 * @param int[] $versions Set of record ids of deleted items to restore,
2532 * or empty to restore all revisions.
2533 * @param bool $unsuppress
2536 public function restore( $versions = [], $unsuppress = false ) {
2537 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2538 return $this->readOnlyFatalStatus();
2541 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2546 $batch->addIds( $versions );
2548 $status = $batch->execute();
2549 if ( $status->isGood() ) {
2550 $cleanupStatus = $batch->cleanup();
2551 $cleanupStatus->successCount
= 0;
2552 $cleanupStatus->failCount
= 0;
2553 $status->merge( $cleanupStatus );
2559 /** isMultipage inherited */
2560 /** pageCount inherited */
2561 /** scaleHeight inherited */
2562 /** getImageSize inherited */
2565 * Get the URL of the file description page.
2566 * @stable to override
2567 * @return string|false
2569 public function getDescriptionUrl() {
2570 // Avoid hard failure when the file does not exist. T221812
2571 return $this->title ?
$this->title
->getLocalURL() : false;
2575 * Get the HTML text of the description page
2576 * This is not used by ImagePage for local files, since (among other things)
2577 * it skips the parser cache.
2578 * @stable to override
2580 * @param Language|null $lang What language to get description in (Optional)
2581 * @return string|false
2583 public function getDescriptionText( ?Language
$lang = null ) {
2584 if ( !$this->title
) {
2585 return false; // Avoid hard failure when the file does not exist. T221812
2588 $services = MediaWikiServices
::getInstance();
2589 $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2595 $parserOptions = ParserOptions
::newFromUserAndLang(
2596 RequestContext
::getMain()->getUser(),
2600 $parserOptions = ParserOptions
::newFromContext( RequestContext
::getMain() );
2603 $parseStatus = $services->getParserOutputAccess()
2604 ->getParserOutput( $page, $parserOptions );
2606 if ( !$parseStatus->isGood() ) {
2607 // Rendering failed.
2610 return $parseStatus->getValue()->getText();
2615 * @stable to override
2616 * @param int $audience
2617 * @param Authority|null $performer
2618 * @return UserIdentity|null
2620 public function getUploader( int $audience = self
::FOR_PUBLIC
, ?Authority
$performer = null ): ?UserIdentity
{
2622 if ( $audience === self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_USER
) ) {
2624 } elseif ( $audience === self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_USER
, $performer ) ) {
2632 * @stable to override
2633 * @param int $audience
2634 * @param Authority|null $performer
2637 public function getDescription( $audience = self
::FOR_PUBLIC
, ?Authority
$performer = null ) {
2639 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2641 } elseif ( $audience == self
::FOR_THIS_USER
&& !$this->userCan( self
::DELETED_COMMENT
, $performer ) ) {
2644 return $this->description
;
2649 * @stable to override
2650 * @return string|false TS_MW timestamp, a string with 14 digits
2652 public function getTimestamp() {
2655 return $this->timestamp
;
2659 * @stable to override
2660 * @return string|false
2662 public function getDescriptionTouched() {
2663 if ( !$this->exists() ) {
2664 return false; // Avoid hard failure when the file does not exist. T221812
2667 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2668 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2669 // need to differentiate between null (uninitialized) and false (failed to load).
2670 if ( $this->descriptionTouched
=== null ) {
2671 $touched = $this->repo
->getReplicaDB()->newSelectQueryBuilder()
2672 ->select( 'page_touched' )
2674 ->where( [ 'page_namespace' => $this->title
->getNamespace() ] )
2675 ->andWhere( [ 'page_title' => $this->title
->getDBkey() ] )
2676 ->caller( __METHOD__
)->fetchField();
2677 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2680 return $this->descriptionTouched
;
2684 * @stable to override
2685 * @return string|false
2687 public function getSha1() {
2693 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2695 public function isCacheable() {
2698 // If extra data (metadata) was not loaded then it must have been large
2699 return $this->extraDataLoaded
2700 && strlen( serialize( $this->metadataArray
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2704 * Acquire an exclusive lock on the file, indicating an intention to write
2705 * to the file backend.
2707 * @param float|int $timeout The timeout in seconds
2711 public function acquireFileLock( $timeout = 0 ) {
2712 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2713 [ $this->getPath() ], LockManager
::LOCK_EX
, $timeout
2718 * Release a lock acquired with acquireFileLock().
2723 public function releaseFileLock() {
2724 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2725 [ $this->getPath() ], LockManager
::LOCK_EX
2730 * Start an atomic DB section and lock the image for update
2731 * or increments a reference counter if the lock is already held
2733 * This method should not be used outside of LocalFile/LocalFile*Batch
2735 * @deprecated since 1.38 Use acquireFileLock()
2736 * @throws LocalFileLockError Throws an error if the lock was not acquired
2737 * @return bool Whether the file lock owns/spawned the DB transaction
2739 public function lock() {
2740 if ( !$this->locked
) {
2741 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2743 $dbw = $this->repo
->getPrimaryDB();
2744 $makesTransaction = !$dbw->trxLevel();
2745 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2746 // T56736: use simple lock to handle when the file does not exist.
2747 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2748 // Also, that would cause contention on INSERT of similarly named rows.
2749 $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2750 if ( !$status->isGood() ) {
2751 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2752 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2754 throw new LocalFileLockError( $status );
2756 // Release the lock *after* commit to avoid row-level contention.
2757 // Make sure it triggers on rollback() as well as commit() (T132921).
2758 $dbw->onTransactionResolution(
2759 function () use ( $logger ) {
2760 $status = $this->releaseFileLock();
2761 if ( !$status->isGood() ) {
2762 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2767 // Callers might care if the SELECT snapshot is safely fresh
2768 $this->lockedOwnTrx
= $makesTransaction;
2773 return $this->lockedOwnTrx
;
2777 * Decrement the lock reference count and end the atomic section if it reaches zero
2779 * This method should not be used outside of LocalFile/LocalFile*Batch
2781 * The commit and lock release will happen when no atomic sections are active, which
2782 * may happen immediately or at some point after calling this
2784 * @deprecated since 1.38 Use releaseFileLock()
2786 public function unlock() {
2787 if ( $this->locked
) {
2789 if ( !$this->locked
) {
2790 $dbw = $this->repo
->getPrimaryDB();
2791 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2792 $this->lockedOwnTrx
= false;
2800 protected function readOnlyFatalStatus() {
2801 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2802 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2806 * Clean up any dangling locks
2808 public function __destruct() {