3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use Wikimedia\AtEase\AtEase
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\IResultWrapper
;
29 use MediaWiki\MediaWikiServices
;
32 * Class to represent a local file in the wiki's own database
34 * Provides methods to retrieve paths (physical, logical, URL),
35 * to generate image thumbnails or for uploading.
37 * Note that only the repo object knows what its file class is called. You should
38 * never name a file class explictly outside of the repo class. Instead use the
39 * repo's factory functions to generate file objects, for example:
41 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
43 * Consider the services container below;
45 * $services = MediaWikiServices::getInstance();
47 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
48 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
50 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
51 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
52 * and $this->repoGroup->getLocalRepo()->newFile().
54 * @ingroup FileAbstraction
56 class LocalFile
extends File
{
57 const VERSION
= 11; // cache version
59 const CACHE_FIELD_MAX_LEN
= 1000;
61 /** @var bool Does the file exist on disk? (loadFromXxx) */
62 protected $fileExists;
64 /** @var int Image width */
67 /** @var int Image height */
70 /** @var int Returned by getimagesize (loadFromXxx) */
73 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
74 protected $media_type;
76 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
79 /** @var int Size in bytes (loadFromXxx) */
82 /** @var string Handler-specific metadata */
85 /** @var string SHA-1 base 36 content hash */
88 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
89 protected $dataLoaded;
91 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
92 protected $extraDataLoaded;
94 /** @var int Bitfield akin to rev_deleted */
98 protected $repoClass = LocalRepo
::class;
100 /** @var int Number of line to return by nextHistoryLine() (constructor) */
101 private $historyLine;
103 /** @var IResultWrapper|null Result of the query for the file's history (nextHistoryLine) */
106 /** @var string Major MIME type */
109 /** @var string Minor MIME type */
112 /** @var string Upload timestamp */
115 /** @var User Uploader */
118 /** @var string Description of current revision of the file */
119 private $description;
121 /** @var string TS_MW timestamp of the last change of the file description */
122 private $descriptionTouched;
124 /** @var bool Whether the row was upgraded on load */
127 /** @var bool Whether the row was scheduled to upgrade on load */
130 /** @var bool True if the image row is locked */
133 /** @var bool True if the image row is locked with a lock initiated transaction */
134 private $lockedOwnTrx;
136 /** @var bool True if file is not present in file system. Not to be cached in memcached */
139 // @note: higher than IDBAccessObject constants
140 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
142 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
145 * Create a LocalFile from a title
146 * Do not call this except from inside a repo class.
148 * Note: $unused param is only here to avoid an E_STRICT
150 * @param Title $title
151 * @param FileRepo $repo
152 * @param null $unused
156 static function newFromTitle( $title, $repo, $unused = null ) {
157 return new static( $title, $repo );
161 * Create a LocalFile from a title
162 * Do not call this except from inside a repo class.
164 * @param stdClass $row
165 * @param FileRepo $repo
169 static function newFromRow( $row, $repo ) {
170 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
171 $file = new static( $title, $repo );
172 $file->loadFromRow( $row );
178 * Create a LocalFile from a SHA-1 key
179 * Do not call this except from inside a repo class.
181 * @param string $sha1 Base-36 SHA-1
182 * @param LocalRepo $repo
183 * @param string|bool $timestamp MW_timestamp (optional)
184 * @return bool|LocalFile
186 static function newFromKey( $sha1, $repo, $timestamp = false ) {
187 $dbr = $repo->getReplicaDB();
189 $conds = [ 'img_sha1' => $sha1 ];
191 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
194 $fileQuery = static::getQueryInfo();
195 $row = $dbr->selectRow(
196 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
199 return static::newFromRow( $row, $repo );
206 * Return the tables, fields, and join conditions to be selected to create
207 * a new localfile object.
209 * @param string[] $options
210 * - omit-lazy: Omit fields that are lazily cached.
211 * @return array[] With three keys:
212 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
213 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
214 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
216 public static function getQueryInfo( array $options = [] ) {
217 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
218 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
220 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
233 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
234 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
237 if ( in_array( 'omit-nonlazy', $options, true ) ) {
238 // Internal use only for getting only the lazy fields
241 if ( !in_array( 'omit-lazy', $options, true ) ) {
242 // Note: Keep this in sync with self::getLazyCacheFields()
243 $ret['fields'][] = 'img_metadata';
250 * Do not call this except from inside a repo class.
251 * @param Title $title
252 * @param FileRepo $repo
254 function __construct( $title, $repo ) {
255 parent
::__construct( $title, $repo );
257 $this->metadata
= '';
258 $this->historyLine
= 0;
259 $this->historyRes
= null;
260 $this->dataLoaded
= false;
261 $this->extraDataLoaded
= false;
263 $this->assertRepoDefined();
264 $this->assertTitleDefined();
268 * Get the memcached key for the main data for this file, or false if
269 * there is no access to the shared cache.
270 * @return string|bool
272 function getCacheKey() {
273 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
277 * @param WANObjectCache $cache
281 public function getMutableCacheKeys( WANObjectCache
$cache ) {
282 return [ $this->getCacheKey() ];
286 * Try to load file metadata from memcached, falling back to the database
288 private function loadFromCache() {
289 $this->dataLoaded
= false;
290 $this->extraDataLoaded
= false;
292 $key = $this->getCacheKey();
294 $this->loadFromDB( self
::READ_NORMAL
);
299 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
300 $cachedValues = $cache->getWithSetCallback(
303 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
304 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
306 $this->loadFromDB( self
::READ_NORMAL
);
308 $fields = $this->getCacheFields( '' );
310 $cacheVal['fileExists'] = $this->fileExists
;
311 if ( $this->fileExists
) {
312 foreach ( $fields as $field ) {
313 $cacheVal[$field] = $this->$field;
316 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
317 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
318 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
320 // Strip off excessive entries from the subset of fields that can become large.
321 // If the cache value gets to large it will not fit in memcached and nothing will
322 // get cached at all, causing master queries for any file access.
323 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
324 if ( isset( $cacheVal[$field] )
325 && strlen( $cacheVal[$field] ) > 100 * 1024
327 unset( $cacheVal[$field] ); // don't let the value get too big
331 if ( $this->fileExists
) {
332 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
334 $ttl = $cache::TTL_DAY
;
339 [ 'version' => self
::VERSION
]
342 $this->fileExists
= $cachedValues['fileExists'];
343 if ( $this->fileExists
) {
344 $this->setProps( $cachedValues );
347 $this->dataLoaded
= true;
348 $this->extraDataLoaded
= true;
349 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
350 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
355 * Purge the file object/metadata cache
357 public function invalidateCache() {
358 $key = $this->getCacheKey();
363 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
364 function () use ( $key ) {
365 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
372 * Load metadata from the file itself
374 function loadFromFile() {
375 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
376 $this->setProps( $props );
380 * Returns the list of object properties that are included as-is in the cache.
381 * @param string $prefix Must be the empty string
383 * @since 1.31 No longer accepts a non-empty $prefix
385 protected function getCacheFields( $prefix = 'img_' ) {
386 if ( $prefix !== '' ) {
387 throw new InvalidArgumentException(
388 __METHOD__
. ' with a non-empty prefix is no longer supported.'
392 // See self::getQueryInfo() for the fetching of the data from the DB,
393 // self::loadFromRow() for the loading of the object from the DB row,
394 // and self::loadFromCache() for the caching, and self::setProps() for
395 // populating the object from an array of data.
396 return [ 'size', 'width', 'height', 'bits', 'media_type',
397 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
401 * Returns the list of object properties that are included as-is in the
402 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
403 * @param string $prefix Must be the empty string
405 * @since 1.31 No longer accepts a non-empty $prefix
407 protected function getLazyCacheFields( $prefix = 'img_' ) {
408 if ( $prefix !== '' ) {
409 throw new InvalidArgumentException(
410 __METHOD__
. ' with a non-empty prefix is no longer supported.'
414 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
415 return [ 'metadata' ];
419 * Load file metadata from the DB
422 function loadFromDB( $flags = 0 ) {
423 $fname = static::class . '::' . __FUNCTION__
;
425 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
426 $this->dataLoaded
= true;
427 $this->extraDataLoaded
= true;
429 $dbr = ( $flags & self
::READ_LATEST
)
430 ?
$this->repo
->getMasterDB()
431 : $this->repo
->getReplicaDB();
433 $fileQuery = static::getQueryInfo();
434 $row = $dbr->selectRow(
435 $fileQuery['tables'],
436 $fileQuery['fields'],
437 [ 'img_name' => $this->getName() ],
444 $this->loadFromRow( $row );
446 $this->fileExists
= false;
451 * Load lazy file metadata from the DB.
452 * This covers fields that are sometimes not cached.
454 protected function loadExtraFromDB() {
455 if ( !$this->title
) {
456 return; // Avoid hard failure when the file does not exist. T221812
459 $fname = static::class . '::' . __FUNCTION__
;
461 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
462 $this->extraDataLoaded
= true;
464 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
466 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
470 foreach ( $fieldMap as $name => $value ) {
471 $this->$name = $value;
474 throw new MWException( "Could not find data for image '{$this->getName()}'." );
479 * @param IDatabase $dbr
480 * @param string $fname
481 * @return string[]|bool
483 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
486 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
487 $row = $dbr->selectRow(
488 $fileQuery['tables'],
489 $fileQuery['fields'],
491 'img_name' => $this->getName(),
492 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
499 $fieldMap = $this->unprefixRow( $row, 'img_' );
501 # File may have been uploaded over in the meantime; check the old versions
502 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
503 $row = $dbr->selectRow(
504 $fileQuery['tables'],
505 $fileQuery['fields'],
507 'oi_name' => $this->getName(),
508 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
515 $fieldMap = $this->unprefixRow( $row, 'oi_' );
519 if ( isset( $fieldMap['metadata'] ) ) {
520 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
527 * @param array|object $row
528 * @param string $prefix
529 * @throws MWException
532 protected function unprefixRow( $row, $prefix = 'img_' ) {
533 $array = (array)$row;
534 $prefixLength = strlen( $prefix );
536 // Sanity check prefix once
537 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
538 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
542 foreach ( $array as $name => $value ) {
543 $decoded[substr( $name, $prefixLength )] = $value;
550 * Decode a row from the database (either object or array) to an array
551 * with timestamps and MIME types decoded, and the field prefix removed.
553 * @param string $prefix
554 * @throws MWException
557 function decodeRow( $row, $prefix = 'img_' ) {
558 $decoded = $this->unprefixRow( $row, $prefix );
560 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
561 ->getComment( 'description', (object)$decoded )->text
;
563 $decoded['user'] = User
::newFromAnyId(
564 $decoded['user'] ??
null,
565 $decoded['user_text'] ??
null,
566 $decoded['actor'] ??
null
568 unset( $decoded['user_text'], $decoded['actor'] );
570 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
572 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
574 if ( empty( $decoded['major_mime'] ) ) {
575 $decoded['mime'] = 'unknown/unknown';
577 if ( !$decoded['minor_mime'] ) {
578 $decoded['minor_mime'] = 'unknown';
580 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
583 // Trim zero padding from char/binary field
584 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
586 // Normalize some fields to integer type, per their database definition.
587 // Use unary + so that overflows will be upgraded to double instead of
588 // being trucated as with intval(). This is important to allow >2GB
589 // files on 32-bit systems.
590 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
591 $decoded[$field] = +
$decoded[$field];
598 * Load file metadata from a DB result row
601 * @param string $prefix
603 function loadFromRow( $row, $prefix = 'img_' ) {
604 $this->dataLoaded
= true;
605 $this->extraDataLoaded
= true;
607 $array = $this->decodeRow( $row, $prefix );
609 foreach ( $array as $name => $value ) {
610 $this->$name = $value;
613 $this->fileExists
= true;
617 * Load file metadata from cache or DB, unless already loaded
620 function load( $flags = 0 ) {
621 if ( !$this->dataLoaded
) {
622 if ( $flags & self
::READ_LATEST
) {
623 $this->loadFromDB( $flags );
625 $this->loadFromCache();
629 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
630 // @note: loads on name/timestamp to reduce race condition problems
631 $this->loadExtraFromDB();
636 * Upgrade a row if it needs it
638 protected function maybeUpgradeRow() {
639 global $wgUpdateCompatibleMetadata;
641 if ( wfReadOnly() ||
$this->upgrading
) {
646 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
649 $handler = $this->getHandler();
651 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
652 if ( $validity === MediaHandler
::METADATA_BAD
) {
654 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
655 $upgrade = $wgUpdateCompatibleMetadata;
661 $this->upgrading
= true;
662 // Defer updates unless in auto-commit CLI mode
663 DeferredUpdates
::addCallableUpdate( function () {
664 $this->upgrading
= false; // avoid duplicate updates
667 } catch ( LocalFileLockError
$e ) {
668 // let the other process handle it (or do it next time)
675 * @return bool Whether upgradeRow() ran for this object
677 function getUpgraded() {
678 return $this->upgraded
;
682 * Fix assorted version-related problems with the image row by reloading it from the file
684 function upgradeRow() {
687 $this->loadFromFile();
689 # Don't destroy file info of missing files
690 if ( !$this->fileExists
) {
692 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
697 $dbw = $this->repo
->getMasterDB();
698 list( $major, $minor ) = self
::splitMime( $this->mime
);
700 if ( wfReadOnly() ) {
705 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
707 $dbw->update( 'image',
709 'img_size' => $this->size
, // sanity
710 'img_width' => $this->width
,
711 'img_height' => $this->height
,
712 'img_bits' => $this->bits
,
713 'img_media_type' => $this->media_type
,
714 'img_major_mime' => $major,
715 'img_minor_mime' => $minor,
716 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
717 'img_sha1' => $this->sha1
,
719 [ 'img_name' => $this->getName() ],
723 $this->invalidateCache();
726 $this->upgraded
= true; // avoid rework/retries
730 * Set properties in this object to be equal to those given in the
731 * associative array $info. Only cacheable fields can be set.
732 * All fields *must* be set in $info except for getLazyCacheFields().
734 * If 'mime' is given, it will be split into major_mime/minor_mime.
735 * If major_mime/minor_mime are given, $this->mime will also be set.
739 function setProps( $info ) {
740 $this->dataLoaded
= true;
741 $fields = $this->getCacheFields( '' );
742 $fields[] = 'fileExists';
744 foreach ( $fields as $field ) {
745 if ( isset( $info[$field] ) ) {
746 $this->$field = $info[$field];
750 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
751 $this->user
= User
::newFromAnyId(
752 $info['user'] ??
null,
753 $info['user_text'] ??
null,
754 $info['actor'] ??
null
758 // Fix up mime fields
759 if ( isset( $info['major_mime'] ) ) {
760 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
761 } elseif ( isset( $info['mime'] ) ) {
762 $this->mime
= $info['mime'];
763 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
767 /** splitMime inherited */
768 /** getName inherited */
769 /** getTitle inherited */
770 /** getURL inherited */
771 /** getViewURL inherited */
772 /** getPath inherited */
773 /** isVisible inherited */
776 * Checks if this file exists in its parent repo, as referenced by its
781 function isMissing() {
782 if ( $this->missing
=== null ) {
783 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
784 $this->missing
= !$fileExists;
787 return $this->missing
;
791 * Return the width of the image
796 public function getWidth( $page = 1 ) {
804 if ( $this->isMultipage() ) {
805 $handler = $this->getHandler();
809 $dim = $handler->getPageDimensions( $this, $page );
811 return $dim['width'];
813 // For non-paged media, the false goes through an
814 // intval, turning failure into 0, so do same here.
823 * Return the height of the image
828 public function getHeight( $page = 1 ) {
836 if ( $this->isMultipage() ) {
837 $handler = $this->getHandler();
841 $dim = $handler->getPageDimensions( $this, $page );
843 return $dim['height'];
845 // For non-paged media, the false goes through an
846 // intval, turning failure into 0, so do same here.
850 return $this->height
;
855 * Returns user who uploaded the file
857 * @param string $type 'text', 'id', or 'object'
858 * @return int|string|User
859 * @since 1.31 Added 'object'
861 function getUser( $type = 'text' ) {
864 if ( !$this->user
) {
865 // If the file does not exist, $this->user will be null, see T221812.
866 // Note: 'Unknown user' this is a reserved user name.
867 if ( $type === 'object' ) {
868 return User
::newFromName( 'Unknown user', false );
869 } elseif ( $type === 'text' ) {
870 return 'Unknown user';
871 } elseif ( $type === 'id' ) {
875 if ( $type === 'object' ) {
877 } elseif ( $type === 'text' ) {
878 return $this->user
->getName();
879 } elseif ( $type === 'id' ) {
880 return $this->user
->getId();
884 throw new MWException( "Unknown type '$type'." );
888 * Get short description URL for a file based on the page ID.
890 * @return string|null
891 * @throws MWException
894 public function getDescriptionShortUrl() {
895 if ( !$this->title
) {
896 return null; // Avoid hard failure when the file does not exist. T221812
899 $pageId = $this->title
->getArticleID();
902 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
903 if ( $url !== false ) {
911 * Get handler-specific metadata
914 function getMetadata() {
915 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
916 return $this->metadata
;
922 function getBitDepth() {
925 return (int)$this->bits
;
929 * Returns the size of the image file, in bytes
932 public function getSize() {
939 * Returns the MIME type of the file.
942 function getMimeType() {
949 * Returns the type of the media in the file.
950 * Use the value returned by this function with the MEDIATYPE_xxx constants.
953 function getMediaType() {
956 return $this->media_type
;
959 /** canRender inherited */
960 /** mustRender inherited */
961 /** allowInlineDisplay inherited */
962 /** isSafeFile inherited */
963 /** isTrustedFile inherited */
966 * Returns true if the file exists on disk.
967 * @return bool Whether file exist on disk.
969 public function exists() {
972 return $this->fileExists
;
975 /** getTransformScript inherited */
976 /** getUnscaledThumb inherited */
977 /** thumbName inherited */
978 /** createThumb inherited */
979 /** transform inherited */
981 /** getHandler inherited */
982 /** iconThumb inherited */
983 /** getLastError inherited */
986 * Get all thumbnail names previously generated for this file
987 * @param string|bool $archiveName Name of an archive file, default false
988 * @return array First element is the base dir, then files in that base dir.
990 function getThumbnails( $archiveName = false ) {
991 if ( $archiveName ) {
992 $dir = $this->getArchiveThumbPath( $archiveName );
994 $dir = $this->getThumbPath();
997 $backend = $this->repo
->getBackend();
1000 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1001 foreach ( $iterator as $file ) {
1004 } catch ( FileBackendError
$e ) {
1005 } // suppress (T56674)
1011 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1013 function purgeMetadataCache() {
1014 $this->invalidateCache();
1018 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1020 * @param array $options An array potentially with the key forThumbRefresh.
1022 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1024 function purgeCache( $options = [] ) {
1025 // Refresh metadata cache
1026 $this->maybeUpgradeRow();
1027 $this->purgeMetadataCache();
1029 // Delete thumbnails
1030 $this->purgeThumbnails( $options );
1032 // Purge CDN cache for this file
1033 DeferredUpdates
::addUpdate(
1034 new CdnCacheUpdate( [ $this->getUrl() ] ),
1035 DeferredUpdates
::PRESEND
1040 * Delete cached transformed files for an archived version only.
1041 * @param string $archiveName Name of the archived file
1043 function purgeOldThumbnails( $archiveName ) {
1044 // Get a list of old thumbnails and URLs
1045 $files = $this->getThumbnails( $archiveName );
1047 // Purge any custom thumbnail caches
1048 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1050 // Delete thumbnails
1051 $dir = array_shift( $files );
1052 $this->purgeThumbList( $dir, $files );
1056 foreach ( $files as $file ) {
1057 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1059 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1063 * Delete cached transformed files for the current version only.
1064 * @param array $options
1065 * @phan-param array{forThumbRefresh?:bool} $options
1067 public function purgeThumbnails( $options = [] ) {
1068 $files = $this->getThumbnails();
1069 // Always purge all files from CDN regardless of handler filters
1071 foreach ( $files as $file ) {
1072 $urls[] = $this->getThumbUrl( $file );
1074 array_shift( $urls ); // don't purge directory
1076 // Give media handler a chance to filter the file purge list
1077 if ( !empty( $options['forThumbRefresh'] ) ) {
1078 $handler = $this->getHandler();
1080 $handler->filterThumbnailPurgeList( $files, $options );
1084 // Purge any custom thumbnail caches
1085 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1087 // Delete thumbnails
1088 $dir = array_shift( $files );
1089 $this->purgeThumbList( $dir, $files );
1092 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1096 * Prerenders a configurable set of thumbnails
1100 public function prerenderThumbnails() {
1101 global $wgUploadThumbnailRenderMap;
1105 $sizes = $wgUploadThumbnailRenderMap;
1108 foreach ( $sizes as $size ) {
1109 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1110 $jobs[] = new ThumbnailRenderJob(
1112 [ 'transformParams' => [ 'width' => $size ] ]
1118 JobQueueGroup
::singleton()->lazyPush( $jobs );
1123 * Delete a list of thumbnails visible at urls
1124 * @param string $dir Base dir of the files.
1125 * @param array $files Array of strings: relative filenames (to $dir)
1127 protected function purgeThumbList( $dir, $files ) {
1128 $fileListDebug = strtr(
1129 var_export( $files, true ),
1132 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1135 foreach ( $files as $file ) {
1136 if ( $this->repo
->supportsSha1URLs() ) {
1137 $reference = $this->getSha1();
1139 $reference = $this->getName();
1142 # Check that the reference (filename or sha1) is part of the thumb name
1143 # This is a basic sanity check to avoid erasing unrelated directories
1144 if ( strpos( $file, $reference ) !== false
1145 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1147 $purgeList[] = "{$dir}/{$file}";
1151 # Delete the thumbnails
1152 $this->repo
->quickPurgeBatch( $purgeList );
1153 # Clear out the thumbnail directory if empty
1154 $this->repo
->quickCleanDir( $dir );
1157 /** purgeDescription inherited */
1158 /** purgeEverything inherited */
1161 * @param int|null $limit Optional: Limit to number of results
1162 * @param string|int|null $start Optional: Timestamp, start from
1163 * @param string|int|null $end Optional: Timestamp, end at
1165 * @return OldLocalFile[]
1167 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1168 if ( !$this->exists() ) {
1169 return []; // Avoid hard failure when the file does not exist. T221812
1172 $dbr = $this->repo
->getReplicaDB();
1173 $oldFileQuery = OldLocalFile
::getQueryInfo();
1175 $tables = $oldFileQuery['tables'];
1176 $fields = $oldFileQuery['fields'];
1177 $join_conds = $oldFileQuery['joins'];
1178 $conds = $opts = [];
1179 $eq = $inc ?
'=' : '';
1180 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1183 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1187 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1191 $opts['LIMIT'] = $limit;
1194 // Search backwards for time > x queries
1195 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1196 $opts['ORDER BY'] = "oi_timestamp $order";
1197 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1199 // Avoid PHP 7.1 warning from passing $this by reference
1201 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1202 &$conds, &$opts, &$join_conds ] );
1204 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1207 foreach ( $res as $row ) {
1208 $r[] = $this->repo
->newFileFromRow( $row );
1211 if ( $order == 'ASC' ) {
1212 $r = array_reverse( $r ); // make sure it ends up descending
1219 * Returns the history of this file, line by line.
1220 * starts with current version, then old versions.
1221 * uses $this->historyLine to check which line to return:
1222 * 0 return line for current version
1223 * 1 query for old versions, return first one
1224 * 2, ... return next old version from above query
1225 * @return stdClass|bool
1227 public function nextHistoryLine() {
1228 if ( !$this->exists() ) {
1229 return false; // Avoid hard failure when the file does not exist. T221812
1232 # Polymorphic function name to distinguish foreign and local fetches
1233 $fname = static::class . '::' . __FUNCTION__
;
1235 $dbr = $this->repo
->getReplicaDB();
1237 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1238 $fileQuery = self
::getQueryInfo();
1239 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1240 $fileQuery['fields'] +
[
1241 'oi_archive_name' => $dbr->addQuotes( '' ),
1244 [ 'img_name' => $this->title
->getDBkey() ],
1250 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1251 $this->historyRes
= null;
1255 } elseif ( $this->historyLine
== 1 ) {
1256 $fileQuery = OldLocalFile
::getQueryInfo();
1257 $this->historyRes
= $dbr->select(
1258 $fileQuery['tables'],
1259 $fileQuery['fields'],
1260 [ 'oi_name' => $this->title
->getDBkey() ],
1262 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1266 $this->historyLine++
;
1268 return $dbr->fetchObject( $this->historyRes
);
1272 * Reset the history pointer to the first element of the history
1274 public function resetHistory() {
1275 $this->historyLine
= 0;
1277 if ( !is_null( $this->historyRes
) ) {
1278 $this->historyRes
= null;
1282 /** getHashPath inherited */
1283 /** getRel inherited */
1284 /** getUrlRel inherited */
1285 /** getArchiveRel inherited */
1286 /** getArchivePath inherited */
1287 /** getThumbPath inherited */
1288 /** getArchiveUrl inherited */
1289 /** getThumbUrl inherited */
1290 /** getArchiveVirtualUrl inherited */
1291 /** getThumbVirtualUrl inherited */
1292 /** isHashed inherited */
1295 * Upload a file and record it in the DB
1296 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1297 * @param string $comment Upload description
1298 * @param string $pageText Text to use for the new description page,
1299 * if a new description page is created
1300 * @param int|bool $flags Flags for publish()
1301 * @param array|bool $props File properties, if known. This can be used to
1302 * reduce the upload time when uploading virtual URLs for which the file
1303 * info is already known
1304 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1306 * @param User|null $user User object or null to use $wgUser
1307 * @param string[] $tags Change tags to add to the log entry and page revision.
1308 * (This doesn't check $user's permissions.)
1309 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1310 * upload, see T193621
1311 * @param bool $revert If this file upload is a revert
1312 * @return Status On success, the value member contains the
1313 * archive name, or an empty string if it was a new file.
1315 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1316 $timestamp = false, $user = null, $tags = [],
1317 $createNullRevision = true, $revert = false
1319 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1320 return $this->readOnlyFatalStatus();
1321 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1322 // Check this in advance to avoid writing to FileBackend and the file tables,
1323 // only to fail on insert the revision due to the text store being unavailable.
1324 return $this->readOnlyFatalStatus();
1327 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1329 if ( FileRepo
::isVirtualUrl( $srcPath )
1330 || FileBackend
::isStoragePath( $srcPath )
1332 $props = $this->repo
->getFileProps( $srcPath );
1334 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1335 $props = $mwProps->getPropsFromPath( $srcPath, true );
1340 $handler = MediaHandler
::getHandler( $props['mime'] );
1342 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1344 if ( !is_array( $metadata ) ) {
1348 $options['headers'] = $handler->getContentHeaders( $metadata );
1350 $options['headers'] = [];
1353 // Trim spaces on user supplied text
1354 $comment = trim( $comment );
1357 $status = $this->publish( $src, $flags, $options );
1359 if ( $status->successCount
>= 2 ) {
1360 // There will be a copy+(one of move,copy,store).
1361 // The first succeeding does not commit us to updating the DB
1362 // since it simply copied the current version to a timestamped file name.
1363 // It is only *preferable* to avoid leaving such files orphaned.
1364 // Once the second operation goes through, then the current version was
1365 // updated and we must therefore update the DB too.
1366 $oldver = $status->value
;
1367 $uploadStatus = $this->recordUpload2(
1375 $createNullRevision,
1378 if ( !$uploadStatus->isOK() ) {
1379 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1380 // update filenotfound error with more specific path
1381 $status->fatal( 'filenotfound', $srcPath );
1383 $status->merge( $uploadStatus );
1393 * Record a file upload in the upload log and the image table
1394 * @param string $oldver
1395 * @param string $desc
1396 * @param string $license
1397 * @param string $copyStatus
1398 * @param string $source
1399 * @param bool $watch
1400 * @param string|bool $timestamp
1401 * @param User|null $user User object or null to use $wgUser
1404 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1405 $watch = false, $timestamp = false, User
$user = null ) {
1411 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1413 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1418 $user->addWatch( $this->getTitle() );
1425 * Record a file upload in the upload log and the image table
1426 * @param string $oldver
1427 * @param string $comment
1428 * @param string $pageText
1429 * @param bool|array $props
1430 * @param string|bool $timestamp
1431 * @param null|User $user
1432 * @param string[] $tags
1433 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1434 * upload, see T193621
1435 * @param bool $revert If this file upload is a revert
1438 function recordUpload2(
1439 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1440 $createNullRevision = true, $revert = false
1442 if ( is_null( $user ) ) {
1447 $dbw = $this->repo
->getMasterDB();
1449 # Imports or such might force a certain timestamp; otherwise we generate
1450 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1451 if ( $timestamp === false ) {
1452 $timestamp = $dbw->timestamp();
1453 $allowTimeKludge = true;
1455 $allowTimeKludge = false;
1458 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1459 $props['description'] = $comment;
1460 $props['user'] = $user->getId();
1461 $props['user_text'] = $user->getName();
1462 $props['actor'] = $user->getActorId( $dbw );
1463 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1464 $this->setProps( $props );
1466 # Fail now if the file isn't there
1467 if ( !$this->fileExists
) {
1468 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1470 return Status
::newFatal( 'filenotfound', $this->getRel() );
1473 $dbw->startAtomic( __METHOD__
);
1475 # Test to see if the row exists using INSERT IGNORE
1476 # This avoids race conditions by locking the row until the commit, and also
1477 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1478 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1479 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1480 $actorMigration = ActorMigration
::newMigration();
1481 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1482 $dbw->insert( 'image',
1484 'img_name' => $this->getName(),
1485 'img_size' => $this->size
,
1486 'img_width' => intval( $this->width
),
1487 'img_height' => intval( $this->height
),
1488 'img_bits' => $this->bits
,
1489 'img_media_type' => $this->media_type
,
1490 'img_major_mime' => $this->major_mime
,
1491 'img_minor_mime' => $this->minor_mime
,
1492 'img_timestamp' => $timestamp,
1493 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1494 'img_sha1' => $this->sha1
1495 ] +
$commentFields +
$actorFields,
1499 $reupload = ( $dbw->affectedRows() == 0 );
1502 $row = $dbw->selectRow(
1504 [ 'img_timestamp', 'img_sha1' ],
1505 [ 'img_name' => $this->getName() ],
1507 [ 'LOCK IN SHARE MODE' ]
1510 if ( $row && $row->img_sha1
=== $this->sha1
) {
1511 $dbw->endAtomic( __METHOD__
);
1512 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1513 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1514 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1517 if ( $allowTimeKludge ) {
1518 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1519 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1520 # Avoid a timestamp that is not newer than the last version
1521 # TODO: the image/oldimage tables should be like page/revision with an ID field
1522 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1523 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1524 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1525 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1529 $tables = [ 'image' ];
1531 'oi_name' => 'img_name',
1532 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1533 'oi_size' => 'img_size',
1534 'oi_width' => 'img_width',
1535 'oi_height' => 'img_height',
1536 'oi_bits' => 'img_bits',
1537 'oi_description_id' => 'img_description_id',
1538 'oi_timestamp' => 'img_timestamp',
1539 'oi_metadata' => 'img_metadata',
1540 'oi_media_type' => 'img_media_type',
1541 'oi_major_mime' => 'img_major_mime',
1542 'oi_minor_mime' => 'img_minor_mime',
1543 'oi_sha1' => 'img_sha1',
1544 'oi_actor' => 'img_actor',
1548 # (T36993) Note: $oldver can be empty here, if the previous
1549 # version of the file was broken. Allow registration of the new
1550 # version to continue anyway, because that's better than having
1551 # an image that's not fixable by user operations.
1552 # Collision, this is an update of a file
1553 # Insert previous contents into oldimage
1554 $dbw->insertSelect( 'oldimage', $tables, $fields,
1555 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1557 # Update the current image row
1558 $dbw->update( 'image',
1560 'img_size' => $this->size
,
1561 'img_width' => intval( $this->width
),
1562 'img_height' => intval( $this->height
),
1563 'img_bits' => $this->bits
,
1564 'img_media_type' => $this->media_type
,
1565 'img_major_mime' => $this->major_mime
,
1566 'img_minor_mime' => $this->minor_mime
,
1567 'img_timestamp' => $timestamp,
1568 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1569 'img_sha1' => $this->sha1
1570 ] +
$commentFields +
$actorFields,
1571 [ 'img_name' => $this->getName() ],
1576 $descTitle = $this->getTitle();
1577 $descId = $descTitle->getArticleID();
1578 $wikiPage = new WikiFilePage( $descTitle );
1579 $wikiPage->setFile( $this );
1581 // Determine log action. If reupload is done by reverting, use a special log_action.
1582 if ( $revert === true ) {
1583 $logAction = 'revert';
1584 } elseif ( $reupload === true ) {
1585 $logAction = 'overwrite';
1587 $logAction = 'upload';
1589 // Add the log entry...
1590 $logEntry = new ManualLogEntry( 'upload', $logAction );
1591 $logEntry->setTimestamp( $this->timestamp
);
1592 $logEntry->setPerformer( $user );
1593 $logEntry->setComment( $comment );
1594 $logEntry->setTarget( $descTitle );
1595 // Allow people using the api to associate log entries with the upload.
1596 // Log has a timestamp, but sometimes different from upload timestamp.
1597 $logEntry->setParameters(
1599 'img_sha1' => $this->sha1
,
1600 'img_timestamp' => $timestamp,
1603 // Note we keep $logId around since during new image
1604 // creation, page doesn't exist yet, so log_page = 0
1605 // but we want it to point to the page we're making,
1606 // so we later modify the log entry.
1607 // For a similar reason, we avoid making an RC entry
1608 // now and wait until the page exists.
1609 $logId = $logEntry->insert();
1611 if ( $descTitle->exists() ) {
1612 // Use own context to get the action text in content language
1613 $formatter = LogFormatter
::newFromEntry( $logEntry );
1614 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1615 $editSummary = $formatter->getPlainActionText();
1617 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1624 if ( $nullRevision ) {
1625 $nullRevision->insertOn( $dbw );
1627 'NewRevisionFromEditComplete',
1628 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1630 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1631 // Associate null revision id
1632 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1635 $newPageContent = null;
1637 // Make the description page and RC log entry post-commit
1638 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1641 # Defer purges, page creation, and link updates in case they error out.
1642 # The most important thing is that files and the DB registry stay synced.
1643 $dbw->endAtomic( __METHOD__
);
1644 $fname = __METHOD__
;
1646 # Do some cache purges after final commit so that:
1647 # a) Changes are more likely to be seen post-purge
1648 # b) They won't cause rollback of the log publish/update above
1649 DeferredUpdates
::addUpdate(
1650 new AutoCommitUpdate(
1654 $reupload, $wikiPage, $newPageContent, $comment, $user,
1655 $logEntry, $logId, $descId, $tags, $fname
1657 # Update memcache after the commit
1658 $this->invalidateCache();
1660 $updateLogPage = false;
1661 if ( $newPageContent ) {
1662 # New file page; create the description page.
1663 # There's already a log entry, so don't make a second RC entry
1664 # CDN and file cache for the description page are purged by doEditContent.
1665 $status = $wikiPage->doEditContent(
1668 EDIT_NEW | EDIT_SUPPRESS_RC
,
1673 if ( isset( $status->value
['revision'] ) ) {
1674 /** @var Revision $rev */
1675 $rev = $status->value
['revision'];
1676 // Associate new page revision id
1677 $logEntry->setAssociatedRevId( $rev->getId() );
1679 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1680 // which is triggered on $descTitle by doEditContent() above.
1681 if ( isset( $status->value
['revision'] ) ) {
1682 /** @var Revision $rev */
1683 $rev = $status->value
['revision'];
1684 $updateLogPage = $rev->getPage();
1687 # Existing file page: invalidate description page cache
1688 $wikiPage->getTitle()->invalidateCache();
1689 $wikiPage->getTitle()->purgeSquid();
1690 # Allow the new file version to be patrolled from the page footer
1691 Article
::purgePatrolFooterCache( $descId );
1694 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1695 # but setAssociatedRevId() wasn't called at that point yet...
1696 $logParams = $logEntry->getParameters();
1697 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1698 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1699 if ( $updateLogPage ) {
1700 # Also log page, in case where we just created it above
1701 $update['log_page'] = $updateLogPage;
1703 $this->getRepo()->getMasterDB()->update(
1706 [ 'log_id' => $logId ],
1709 $this->getRepo()->getMasterDB()->insert(
1712 'ls_field' => 'associated_rev_id',
1713 'ls_value' => $logEntry->getAssociatedRevId(),
1714 'ls_log_id' => $logId,
1719 # Add change tags, if any
1721 $logEntry->addTags( $tags );
1724 # Uploads can be patrolled
1725 $logEntry->setIsPatrollable( true );
1727 # Now that the log entry is up-to-date, make an RC entry.
1728 $logEntry->publish( $logId );
1730 # Run hook for other updates (typically more cache purging)
1731 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1734 # Delete old thumbnails
1735 $this->purgeThumbnails();
1736 # Remove the old file from the CDN cache
1737 DeferredUpdates
::addUpdate(
1738 new CdnCacheUpdate( [ $this->getUrl() ] ),
1739 DeferredUpdates
::PRESEND
1742 # Update backlink pages pointing to this title if created
1743 LinksUpdate
::queueRecursiveJobsForTable(
1751 $this->prerenderThumbnails();
1754 DeferredUpdates
::PRESEND
1758 # This is a new file, so update the image count
1759 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1762 # Invalidate cache for all pages using this file
1763 DeferredUpdates
::addUpdate(
1764 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1767 return Status
::newGood();
1771 * Move or copy a file to its public location. If a file exists at the
1772 * destination, move it to an archive. Returns a Status object with
1773 * the archive name in the "value" member on success.
1775 * The archive name should be passed through to recordUpload for database
1778 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1779 * @param int $flags A bitwise combination of:
1780 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1781 * @param array $options Optional additional parameters
1782 * @return Status On success, the value member contains the
1783 * archive name, or an empty string if it was a new file.
1785 function publish( $src, $flags = 0, array $options = [] ) {
1786 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1790 * Move or copy a file to a specified location. Returns a Status
1791 * object with the archive name in the "value" member on success.
1793 * The archive name should be passed through to recordUpload for database
1796 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1797 * @param string $dstRel Target relative path
1798 * @param int $flags A bitwise combination of:
1799 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1800 * @param array $options Optional additional parameters
1801 * @return Status On success, the value member contains the
1802 * archive name, or an empty string if it was a new file.
1804 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1805 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1807 $repo = $this->getRepo();
1808 if ( $repo->getReadOnlyReason() !== false ) {
1809 return $this->readOnlyFatalStatus();
1814 if ( $this->isOld() ) {
1815 $archiveRel = $dstRel;
1816 $archiveName = basename( $archiveRel );
1818 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1819 $archiveRel = $this->getArchiveRel( $archiveName );
1822 if ( $repo->hasSha1Storage() ) {
1823 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1824 ?
$repo->getFileSha1( $srcPath )
1825 : FSFile
::getSha1Base36FromPath( $srcPath );
1826 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1827 $wrapperBackend = $repo->getBackend();
1828 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1829 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1830 $status = $repo->quickImport( $src, $dst );
1831 if ( $flags & File
::DELETE_SOURCE
) {
1835 if ( $this->exists() ) {
1836 $status->value
= $archiveName;
1839 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1840 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1842 if ( $status->value
== 'new' ) {
1843 $status->value
= '';
1845 $status->value
= $archiveName;
1853 /** getLinksTo inherited */
1854 /** getExifData inherited */
1855 /** isLocal inherited */
1856 /** wasDeleted inherited */
1859 * Move file to the new title
1861 * Move current, old version and all thumbnails
1862 * to the new filename. Old file is deleted.
1864 * Cache purging is done; checks for validity
1865 * and logging are caller's responsibility
1867 * @param Title $target New file name
1870 function move( $target ) {
1871 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1872 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1873 return $this->readOnlyFatalStatus();
1876 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1877 $batch = new LocalFileMoveBatch( $this, $target );
1880 $batch->addCurrent();
1881 $archiveNames = $batch->addOlds();
1882 $status = $batch->execute();
1885 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1887 // Purge the source and target files outside the transaction...
1888 $oldTitleFile = $localRepo->newFile( $this->title
);
1889 $newTitleFile = $localRepo->newFile( $target );
1890 DeferredUpdates
::addUpdate(
1891 new AutoCommitUpdate(
1892 $this->getRepo()->getMasterDB(),
1894 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1895 $oldTitleFile->purgeEverything();
1896 foreach ( $archiveNames as $archiveName ) {
1897 /** @var OldLocalFile $oldTitleFile */
1898 '@phan-var OldLocalFile $oldTitleFile';
1899 $oldTitleFile->purgeOldThumbnails( $archiveName );
1901 $newTitleFile->purgeEverything();
1904 DeferredUpdates
::PRESEND
1907 if ( $status->isOK() ) {
1908 // Now switch the object
1909 $this->title
= $target;
1910 // Force regeneration of the name and hashpath
1912 $this->hashPath
= null;
1919 * Delete all versions of the file.
1921 * Moves the files into an archive directory (or deletes them)
1922 * and removes the database rows.
1924 * Cache purging is done; logging is caller's responsibility.
1926 * @param string $reason
1927 * @param bool $suppress
1928 * @param User|null $user
1931 function delete( $reason, $suppress = false, $user = null ) {
1932 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1933 return $this->readOnlyFatalStatus();
1936 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1939 $batch->addCurrent();
1940 // Get old version relative paths
1941 $archiveNames = $batch->addOlds();
1942 $status = $batch->execute();
1945 if ( $status->isOK() ) {
1946 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1949 // To avoid slow purges in the transaction, move them outside...
1950 DeferredUpdates
::addUpdate(
1951 new AutoCommitUpdate(
1952 $this->getRepo()->getMasterDB(),
1954 function () use ( $archiveNames ) {
1955 $this->purgeEverything();
1956 foreach ( $archiveNames as $archiveName ) {
1957 $this->purgeOldThumbnails( $archiveName );
1961 DeferredUpdates
::PRESEND
1966 foreach ( $archiveNames as $archiveName ) {
1967 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1969 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1975 * Delete an old version of the file.
1977 * Moves the file into an archive directory (or deletes it)
1978 * and removes the database row.
1980 * Cache purging is done; logging is caller's responsibility.
1982 * @param string $archiveName
1983 * @param string $reason
1984 * @param bool $suppress
1985 * @param User|null $user
1986 * @throws MWException Exception on database or file store failure
1989 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1990 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1991 return $this->readOnlyFatalStatus();
1994 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1997 $batch->addOld( $archiveName );
1998 $status = $batch->execute();
2001 $this->purgeOldThumbnails( $archiveName );
2002 if ( $status->isOK() ) {
2003 $this->purgeDescription();
2006 DeferredUpdates
::addUpdate(
2007 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2008 DeferredUpdates
::PRESEND
2015 * Restore all or specified deleted revisions to the given file.
2016 * Permissions and logging are left to the caller.
2018 * May throw database exceptions on error.
2020 * @param array $versions Set of record ids of deleted items to restore,
2021 * or empty to restore all revisions.
2022 * @param bool $unsuppress
2025 function restore( $versions = [], $unsuppress = false ) {
2026 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2027 return $this->readOnlyFatalStatus();
2030 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2036 $batch->addIds( $versions );
2038 $status = $batch->execute();
2039 if ( $status->isGood() ) {
2040 $cleanupStatus = $batch->cleanup();
2041 $cleanupStatus->successCount
= 0;
2042 $cleanupStatus->failCount
= 0;
2043 $status->merge( $cleanupStatus );
2050 /** isMultipage inherited */
2051 /** pageCount inherited */
2052 /** scaleHeight inherited */
2053 /** getImageSize inherited */
2056 * Get the URL of the file description page.
2057 * @return string|bool
2059 function getDescriptionUrl() {
2060 if ( !$this->title
) {
2061 return false; // Avoid hard failure when the file does not exist. T221812
2064 return $this->title
->getLocalURL();
2068 * Get the HTML text of the description page
2069 * This is not used by ImagePage for local files, since (among other things)
2070 * it skips the parser cache.
2072 * @param Language|null $lang What language to get description in (Optional)
2073 * @return string|false
2075 function getDescriptionText( Language
$lang = null ) {
2076 if ( !$this->title
) {
2077 return false; // Avoid hard failure when the file does not exist. T221812
2080 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2081 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2086 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2087 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2090 // audience check failed
2094 $pout = $rendered->getRevisionParserOutput();
2095 return $pout->getText();
2099 * @param int $audience
2100 * @param User|null $user
2103 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2105 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2107 } elseif ( $audience == self
::FOR_THIS_USER
2108 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2112 return $this->description
;
2117 * @return bool|string
2119 function getTimestamp() {
2122 return $this->timestamp
;
2126 * @return bool|string
2128 public function getDescriptionTouched() {
2129 if ( !$this->exists() ) {
2130 return false; // Avoid hard failure when the file does not exist. T221812
2133 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2134 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2135 // need to differentiate between null (uninitialized) and false (failed to load).
2136 if ( $this->descriptionTouched
=== null ) {
2138 'page_namespace' => $this->title
->getNamespace(),
2139 'page_title' => $this->title
->getDBkey()
2141 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2142 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2145 return $this->descriptionTouched
;
2151 function getSha1() {
2153 // Initialise now if necessary
2154 if ( $this->sha1
== '' && $this->fileExists
) {
2157 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2158 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2159 $dbw = $this->repo
->getMasterDB();
2160 $dbw->update( 'image',
2161 [ 'img_sha1' => $this->sha1
],
2162 [ 'img_name' => $this->getName() ],
2164 $this->invalidateCache();
2174 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2176 function isCacheable() {
2179 // If extra data (metadata) was not loaded then it must have been large
2180 return $this->extraDataLoaded
2181 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2188 public function acquireFileLock() {
2189 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2190 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2198 public function releaseFileLock() {
2199 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2200 [ $this->getPath() ], LockManager
::LOCK_EX
2205 * Start an atomic DB section and lock the image for update
2206 * or increments a reference counter if the lock is already held
2208 * This method should not be used outside of LocalFile/LocalFile*Batch
2210 * @throws LocalFileLockError Throws an error if the lock was not acquired
2211 * @return bool Whether the file lock owns/spawned the DB transaction
2213 public function lock() {
2214 if ( !$this->locked
) {
2215 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2217 $dbw = $this->repo
->getMasterDB();
2218 $makesTransaction = !$dbw->trxLevel();
2219 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2220 // T56736: use simple lock to handle when the file does not exist.
2221 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2222 // Also, that would cause contention on INSERT of similarly named rows.
2223 $status = $this->acquireFileLock(); // represents all versions of the file
2224 if ( !$status->isGood() ) {
2225 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2226 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2228 throw new LocalFileLockError( $status );
2230 // Release the lock *after* commit to avoid row-level contention.
2231 // Make sure it triggers on rollback() as well as commit() (T132921).
2232 $dbw->onTransactionResolution(
2233 function () use ( $logger ) {
2234 $status = $this->releaseFileLock();
2235 if ( !$status->isGood() ) {
2236 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2241 // Callers might care if the SELECT snapshot is safely fresh
2242 $this->lockedOwnTrx
= $makesTransaction;
2247 return $this->lockedOwnTrx
;
2251 * Decrement the lock reference count and end the atomic section if it reaches zero
2253 * This method should not be used outside of LocalFile/LocalFile*Batch
2255 * The commit and loc release will happen when no atomic sections are active, which
2256 * may happen immediately or at some point after calling this
2258 public function unlock() {
2259 if ( $this->locked
) {
2261 if ( !$this->locked
) {
2262 $dbw = $this->repo
->getMasterDB();
2263 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2264 $this->lockedOwnTrx
= false;
2272 protected function readOnlyFatalStatus() {
2273 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2274 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2278 * Clean up any dangling locks
2280 function __destruct() {