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 MediaWiki\MediaWikiServices
;
31 * Class to represent a local file in the wiki's own database
33 * Provides methods to retrieve paths (physical, logical, URL),
34 * to generate image thumbnails or for uploading.
36 * Note that only the repo object knows what its file class is called. You should
37 * never name a file class explictly outside of the repo class. Instead use the
38 * repo's factory functions to generate file objects, for example:
40 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
42 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
45 * @ingroup FileAbstraction
47 class LocalFile
extends File
{
48 const VERSION
= 11; // cache version
50 const CACHE_FIELD_MAX_LEN
= 1000;
52 /** @var bool Does the file exist on disk? (loadFromXxx) */
53 protected $fileExists;
55 /** @var int Image width */
58 /** @var int Image height */
61 /** @var int Returned by getimagesize (loadFromXxx) */
64 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
65 protected $media_type;
67 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
70 /** @var int Size in bytes (loadFromXxx) */
73 /** @var string Handler-specific metadata */
76 /** @var string SHA-1 base 36 content hash */
79 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
80 protected $dataLoaded;
82 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
83 protected $extraDataLoaded;
85 /** @var int Bitfield akin to rev_deleted */
89 protected $repoClass = LocalRepo
::class;
91 /** @var int Number of line to return by nextHistoryLine() (constructor) */
94 /** @var int Result of the query for the file's history (nextHistoryLine) */
97 /** @var string Major MIME type */
100 /** @var string Minor MIME type */
103 /** @var string Upload timestamp */
106 /** @var User Uploader */
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var string TS_MW timestamp of the last change of the file description */
113 private $descriptionTouched;
115 /** @var bool Whether the row was upgraded on load */
118 /** @var bool Whether the row was scheduled to upgrade on load */
121 /** @var bool True if the image row is locked */
124 /** @var bool True if the image row is locked with a lock initiated transaction */
125 private $lockedOwnTrx;
127 /** @var bool True if file is not present in file system. Not to be cached in memcached */
130 // @note: higher than IDBAccessObject constants
131 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
133 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
136 * Create a LocalFile from a title
137 * Do not call this except from inside a repo class.
139 * Note: $unused param is only here to avoid an E_STRICT
141 * @param Title $title
142 * @param FileRepo $repo
143 * @param null $unused
147 static function newFromTitle( $title, $repo, $unused = null ) {
148 return new self( $title, $repo );
152 * Create a LocalFile from a title
153 * Do not call this except from inside a repo class.
155 * @param stdClass $row
156 * @param FileRepo $repo
160 static function newFromRow( $row, $repo ) {
161 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
162 $file = new self( $title, $repo );
163 $file->loadFromRow( $row );
169 * Create a LocalFile from a SHA-1 key
170 * Do not call this except from inside a repo class.
172 * @param string $sha1 Base-36 SHA-1
173 * @param LocalRepo $repo
174 * @param string|bool $timestamp MW_timestamp (optional)
175 * @return bool|LocalFile
177 static function newFromKey( $sha1, $repo, $timestamp = false ) {
178 $dbr = $repo->getReplicaDB();
180 $conds = [ 'img_sha1' => $sha1 ];
182 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
185 $fileQuery = self
::getQueryInfo();
186 $row = $dbr->selectRow(
187 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
190 return self
::newFromRow( $row, $repo );
197 * Fields in the image table
198 * @deprecated since 1.31, use self::getQueryInfo() instead.
201 static function selectFields() {
202 global $wgActorTableSchemaMigrationStage;
204 wfDeprecated( __METHOD__
, '1.31' );
205 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
206 // If code is using this instead of self::getQueryInfo(), there's a
207 // decent chance it's going to try to directly access
208 // $row->img_user or $row->img_user_text and we can't give it
209 // useful values here once those aren't being used anymore.
210 throw new BadMethodCallException(
211 'Cannot use ' . __METHOD__
212 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
228 'img_actor' => 'NULL',
231 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
235 * Return the tables, fields, and join conditions to be selected to create
236 * a new localfile object.
238 * @param string[] $options
239 * - omit-lazy: Omit fields that are lazily cached.
240 * @return array[] With three keys:
241 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
242 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
243 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
245 public static function getQueryInfo( array $options = [] ) {
246 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
247 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
249 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
262 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
263 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
266 if ( in_array( 'omit-nonlazy', $options, true ) ) {
267 // Internal use only for getting only the lazy fields
270 if ( !in_array( 'omit-lazy', $options, true ) ) {
271 // Note: Keep this in sync with self::getLazyCacheFields()
272 $ret['fields'][] = 'img_metadata';
279 * Do not call this except from inside a repo class.
280 * @param Title $title
281 * @param FileRepo $repo
283 function __construct( $title, $repo ) {
284 parent
::__construct( $title, $repo );
286 $this->metadata
= '';
287 $this->historyLine
= 0;
288 $this->historyRes
= null;
289 $this->dataLoaded
= false;
290 $this->extraDataLoaded
= false;
292 $this->assertRepoDefined();
293 $this->assertTitleDefined();
297 * Get the memcached key for the main data for this file, or false if
298 * there is no access to the shared cache.
299 * @return string|bool
301 function getCacheKey() {
302 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
306 * @param WANObjectCache $cache
310 public function getMutableCacheKeys( WANObjectCache
$cache ) {
311 return [ $this->getCacheKey() ];
315 * Try to load file metadata from memcached, falling back to the database
317 private function loadFromCache() {
318 $this->dataLoaded
= false;
319 $this->extraDataLoaded
= false;
321 $key = $this->getCacheKey();
323 $this->loadFromDB( self
::READ_NORMAL
);
328 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
329 $cachedValues = $cache->getWithSetCallback(
332 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
333 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
335 $this->loadFromDB( self
::READ_NORMAL
);
337 $fields = $this->getCacheFields( '' );
338 $cacheVal['fileExists'] = $this->fileExists
;
339 if ( $this->fileExists
) {
340 foreach ( $fields as $field ) {
341 $cacheVal[$field] = $this->$field;
344 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
345 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
346 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
348 // Strip off excessive entries from the subset of fields that can become large.
349 // If the cache value gets to large it will not fit in memcached and nothing will
350 // get cached at all, causing master queries for any file access.
351 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
352 if ( isset( $cacheVal[$field] )
353 && strlen( $cacheVal[$field] ) > 100 * 1024
355 unset( $cacheVal[$field] ); // don't let the value get too big
359 if ( $this->fileExists
) {
360 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
362 $ttl = $cache::TTL_DAY
;
367 [ 'version' => self
::VERSION
]
370 $this->fileExists
= $cachedValues['fileExists'];
371 if ( $this->fileExists
) {
372 $this->setProps( $cachedValues );
375 $this->dataLoaded
= true;
376 $this->extraDataLoaded
= true;
377 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
378 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
383 * Purge the file object/metadata cache
385 public function invalidateCache() {
386 $key = $this->getCacheKey();
391 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
392 function () use ( $key ) {
393 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
400 * Load metadata from the file itself
402 function loadFromFile() {
403 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
404 $this->setProps( $props );
408 * Returns the list of object properties that are included as-is in the cache.
409 * @param string $prefix Must be the empty string
411 * @since 1.31 No longer accepts a non-empty $prefix
413 protected function getCacheFields( $prefix = 'img_' ) {
414 if ( $prefix !== '' ) {
415 throw new InvalidArgumentException(
416 __METHOD__
. ' with a non-empty prefix is no longer supported.'
420 // See self::getQueryInfo() for the fetching of the data from the DB,
421 // self::loadFromRow() for the loading of the object from the DB row,
422 // and self::loadFromCache() for the caching, and self::setProps() for
423 // populating the object from an array of data.
424 return [ 'size', 'width', 'height', 'bits', 'media_type',
425 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
429 * Returns the list of object properties that are included as-is in the
430 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
431 * @param string $prefix Must be the empty string
433 * @since 1.31 No longer accepts a non-empty $prefix
435 protected function getLazyCacheFields( $prefix = 'img_' ) {
436 if ( $prefix !== '' ) {
437 throw new InvalidArgumentException(
438 __METHOD__
. ' with a non-empty prefix is no longer supported.'
442 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
443 return [ 'metadata' ];
447 * Load file metadata from the DB
450 function loadFromDB( $flags = 0 ) {
451 $fname = static::class . '::' . __FUNCTION__
;
453 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
454 $this->dataLoaded
= true;
455 $this->extraDataLoaded
= true;
457 $dbr = ( $flags & self
::READ_LATEST
)
458 ?
$this->repo
->getMasterDB()
459 : $this->repo
->getReplicaDB();
461 $fileQuery = static::getQueryInfo();
462 $row = $dbr->selectRow(
463 $fileQuery['tables'],
464 $fileQuery['fields'],
465 [ 'img_name' => $this->getName() ],
472 $this->loadFromRow( $row );
474 $this->fileExists
= false;
479 * Load lazy file metadata from the DB.
480 * This covers fields that are sometimes not cached.
482 protected function loadExtraFromDB() {
483 $fname = static::class . '::' . __FUNCTION__
;
485 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
486 $this->extraDataLoaded
= true;
488 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
490 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
494 foreach ( $fieldMap as $name => $value ) {
495 $this->$name = $value;
498 throw new MWException( "Could not find data for image '{$this->getName()}'." );
503 * @param IDatabase $dbr
504 * @param string $fname
505 * @return string[]|bool
507 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
510 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
511 $row = $dbr->selectRow(
512 $fileQuery['tables'],
513 $fileQuery['fields'],
515 'img_name' => $this->getName(),
516 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
523 $fieldMap = $this->unprefixRow( $row, 'img_' );
525 # File may have been uploaded over in the meantime; check the old versions
526 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
527 $row = $dbr->selectRow(
528 $fileQuery['tables'],
529 $fileQuery['fields'],
531 'oi_name' => $this->getName(),
532 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
539 $fieldMap = $this->unprefixRow( $row, 'oi_' );
543 if ( isset( $fieldMap['metadata'] ) ) {
544 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
551 * @param array|object $row
552 * @param string $prefix
553 * @throws MWException
556 protected function unprefixRow( $row, $prefix = 'img_' ) {
557 $array = (array)$row;
558 $prefixLength = strlen( $prefix );
560 // Sanity check prefix once
561 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
562 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
566 foreach ( $array as $name => $value ) {
567 $decoded[substr( $name, $prefixLength )] = $value;
574 * Decode a row from the database (either object or array) to an array
575 * with timestamps and MIME types decoded, and the field prefix removed.
577 * @param string $prefix
578 * @throws MWException
581 function decodeRow( $row, $prefix = 'img_' ) {
582 $decoded = $this->unprefixRow( $row, $prefix );
584 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
585 ->getComment( 'description', (object)$decoded )->text
;
587 $decoded['user'] = User
::newFromAnyId(
588 $decoded['user'] ??
null,
589 $decoded['user_text'] ??
null,
590 $decoded['actor'] ??
null
592 unset( $decoded['user_text'], $decoded['actor'] );
594 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
596 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
598 if ( empty( $decoded['major_mime'] ) ) {
599 $decoded['mime'] = 'unknown/unknown';
601 if ( !$decoded['minor_mime'] ) {
602 $decoded['minor_mime'] = 'unknown';
604 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
607 // Trim zero padding from char/binary field
608 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
610 // Normalize some fields to integer type, per their database definition.
611 // Use unary + so that overflows will be upgraded to double instead of
612 // being trucated as with intval(). This is important to allow >2GB
613 // files on 32-bit systems.
614 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
615 $decoded[$field] = +
$decoded[$field];
622 * Load file metadata from a DB result row
625 * @param string $prefix
627 function loadFromRow( $row, $prefix = 'img_' ) {
628 $this->dataLoaded
= true;
629 $this->extraDataLoaded
= true;
631 $array = $this->decodeRow( $row, $prefix );
633 foreach ( $array as $name => $value ) {
634 $this->$name = $value;
637 $this->fileExists
= true;
641 * Load file metadata from cache or DB, unless already loaded
644 function load( $flags = 0 ) {
645 if ( !$this->dataLoaded
) {
646 if ( $flags & self
::READ_LATEST
) {
647 $this->loadFromDB( $flags );
649 $this->loadFromCache();
653 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
654 // @note: loads on name/timestamp to reduce race condition problems
655 $this->loadExtraFromDB();
660 * Upgrade a row if it needs it
662 protected function maybeUpgradeRow() {
663 global $wgUpdateCompatibleMetadata;
665 if ( wfReadOnly() ||
$this->upgrading
) {
670 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
673 $handler = $this->getHandler();
675 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
676 if ( $validity === MediaHandler
::METADATA_BAD
) {
678 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
679 $upgrade = $wgUpdateCompatibleMetadata;
685 $this->upgrading
= true;
686 // Defer updates unless in auto-commit CLI mode
687 DeferredUpdates
::addCallableUpdate( function () {
688 $this->upgrading
= false; // avoid duplicate updates
691 } catch ( LocalFileLockError
$e ) {
692 // let the other process handle it (or do it next time)
699 * @return bool Whether upgradeRow() ran for this object
701 function getUpgraded() {
702 return $this->upgraded
;
706 * Fix assorted version-related problems with the image row by reloading it from the file
708 function upgradeRow() {
711 $this->loadFromFile();
713 # Don't destroy file info of missing files
714 if ( !$this->fileExists
) {
716 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
721 $dbw = $this->repo
->getMasterDB();
722 list( $major, $minor ) = self
::splitMime( $this->mime
);
724 if ( wfReadOnly() ) {
729 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
731 $dbw->update( 'image',
733 'img_size' => $this->size
, // sanity
734 'img_width' => $this->width
,
735 'img_height' => $this->height
,
736 'img_bits' => $this->bits
,
737 'img_media_type' => $this->media_type
,
738 'img_major_mime' => $major,
739 'img_minor_mime' => $minor,
740 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
741 'img_sha1' => $this->sha1
,
743 [ 'img_name' => $this->getName() ],
747 $this->invalidateCache();
750 $this->upgraded
= true; // avoid rework/retries
754 * Set properties in this object to be equal to those given in the
755 * associative array $info. Only cacheable fields can be set.
756 * All fields *must* be set in $info except for getLazyCacheFields().
758 * If 'mime' is given, it will be split into major_mime/minor_mime.
759 * If major_mime/minor_mime are given, $this->mime will also be set.
763 function setProps( $info ) {
764 $this->dataLoaded
= true;
765 $fields = $this->getCacheFields( '' );
766 $fields[] = 'fileExists';
768 foreach ( $fields as $field ) {
769 if ( isset( $info[$field] ) ) {
770 $this->$field = $info[$field];
774 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
775 $this->user
= User
::newFromAnyId(
776 $info['user'] ??
null,
777 $info['user_text'] ??
null,
778 $info['actor'] ??
null
782 // Fix up mime fields
783 if ( isset( $info['major_mime'] ) ) {
784 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
785 } elseif ( isset( $info['mime'] ) ) {
786 $this->mime
= $info['mime'];
787 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
791 /** splitMime inherited */
792 /** getName inherited */
793 /** getTitle inherited */
794 /** getURL inherited */
795 /** getViewURL inherited */
796 /** getPath inherited */
797 /** isVisible inherited */
800 * Checks if this file exists in its parent repo, as referenced by its
805 function isMissing() {
806 if ( $this->missing
=== null ) {
807 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
808 $this->missing
= !$fileExists;
811 return $this->missing
;
815 * Return the width of the image
820 public function getWidth( $page = 1 ) {
828 if ( $this->isMultipage() ) {
829 $handler = $this->getHandler();
833 $dim = $handler->getPageDimensions( $this, $page );
835 return $dim['width'];
837 // For non-paged media, the false goes through an
838 // intval, turning failure into 0, so do same here.
847 * Return the height of the image
852 public function getHeight( $page = 1 ) {
860 if ( $this->isMultipage() ) {
861 $handler = $this->getHandler();
865 $dim = $handler->getPageDimensions( $this, $page );
867 return $dim['height'];
869 // For non-paged media, the false goes through an
870 // intval, turning failure into 0, so do same here.
874 return $this->height
;
879 * Returns user who uploaded the file
881 * @param string $type 'text', 'id', or 'object'
882 * @return int|string|User
883 * @since 1.31 Added 'object'
885 function getUser( $type = 'text' ) {
888 if ( $type === 'object' ) {
890 } elseif ( $type === 'text' ) {
891 return $this->user
->getName();
892 } elseif ( $type === 'id' ) {
893 return $this->user
->getId();
896 throw new MWException( "Unknown type '$type'." );
900 * Get short description URL for a file based on the page ID.
902 * @return string|null
903 * @throws MWException
906 public function getDescriptionShortUrl() {
907 $pageId = $this->title
->getArticleID();
909 if ( $pageId !== null ) {
910 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
911 if ( $url !== false ) {
919 * Get handler-specific metadata
922 function getMetadata() {
923 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
924 return $this->metadata
;
930 function getBitDepth() {
933 return (int)$this->bits
;
937 * Returns the size of the image file, in bytes
940 public function getSize() {
947 * Returns the MIME type of the file.
950 function getMimeType() {
957 * Returns the type of the media in the file.
958 * Use the value returned by this function with the MEDIATYPE_xxx constants.
961 function getMediaType() {
964 return $this->media_type
;
967 /** canRender inherited */
968 /** mustRender inherited */
969 /** allowInlineDisplay inherited */
970 /** isSafeFile inherited */
971 /** isTrustedFile inherited */
974 * Returns true if the file exists on disk.
975 * @return bool Whether file exist on disk.
977 public function exists() {
980 return $this->fileExists
;
983 /** getTransformScript inherited */
984 /** getUnscaledThumb inherited */
985 /** thumbName inherited */
986 /** createThumb inherited */
987 /** transform inherited */
989 /** getHandler inherited */
990 /** iconThumb inherited */
991 /** getLastError inherited */
994 * Get all thumbnail names previously generated for this file
995 * @param string|bool $archiveName Name of an archive file, default false
996 * @return array First element is the base dir, then files in that base dir.
998 function getThumbnails( $archiveName = false ) {
999 if ( $archiveName ) {
1000 $dir = $this->getArchiveThumbPath( $archiveName );
1002 $dir = $this->getThumbPath();
1005 $backend = $this->repo
->getBackend();
1008 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1009 foreach ( $iterator as $file ) {
1012 } catch ( FileBackendError
$e ) {
1013 } // suppress (T56674)
1019 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1021 function purgeMetadataCache() {
1022 $this->invalidateCache();
1026 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1028 * @param array $options An array potentially with the key forThumbRefresh.
1030 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1032 function purgeCache( $options = [] ) {
1033 // Refresh metadata cache
1034 $this->maybeUpgradeRow();
1035 $this->purgeMetadataCache();
1037 // Delete thumbnails
1038 $this->purgeThumbnails( $options );
1040 // Purge CDN cache for this file
1041 DeferredUpdates
::addUpdate(
1042 new CdnCacheUpdate( [ $this->getUrl() ] ),
1043 DeferredUpdates
::PRESEND
1048 * Delete cached transformed files for an archived version only.
1049 * @param string $archiveName Name of the archived file
1051 function purgeOldThumbnails( $archiveName ) {
1052 // Get a list of old thumbnails and URLs
1053 $files = $this->getThumbnails( $archiveName );
1055 // Purge any custom thumbnail caches
1056 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1058 // Delete thumbnails
1059 $dir = array_shift( $files );
1060 $this->purgeThumbList( $dir, $files );
1064 foreach ( $files as $file ) {
1065 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1067 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1071 * Delete cached transformed files for the current version only.
1072 * @param array $options
1074 public function purgeThumbnails( $options = [] ) {
1075 $files = $this->getThumbnails();
1076 // Always purge all files from CDN regardless of handler filters
1078 foreach ( $files as $file ) {
1079 $urls[] = $this->getThumbUrl( $file );
1081 array_shift( $urls ); // don't purge directory
1083 // Give media handler a chance to filter the file purge list
1084 if ( !empty( $options['forThumbRefresh'] ) ) {
1085 $handler = $this->getHandler();
1087 $handler->filterThumbnailPurgeList( $files, $options );
1091 // Purge any custom thumbnail caches
1092 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1094 // Delete thumbnails
1095 $dir = array_shift( $files );
1096 $this->purgeThumbList( $dir, $files );
1099 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1103 * Prerenders a configurable set of thumbnails
1107 public function prerenderThumbnails() {
1108 global $wgUploadThumbnailRenderMap;
1112 $sizes = $wgUploadThumbnailRenderMap;
1115 foreach ( $sizes as $size ) {
1116 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1117 $jobs[] = new ThumbnailRenderJob(
1119 [ 'transformParams' => [ 'width' => $size ] ]
1125 JobQueueGroup
::singleton()->lazyPush( $jobs );
1130 * Delete a list of thumbnails visible at urls
1131 * @param string $dir Base dir of the files.
1132 * @param array $files Array of strings: relative filenames (to $dir)
1134 protected function purgeThumbList( $dir, $files ) {
1135 $fileListDebug = strtr(
1136 var_export( $files, true ),
1139 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1142 foreach ( $files as $file ) {
1143 if ( $this->repo
->supportsSha1URLs() ) {
1144 $reference = $this->getSha1();
1146 $reference = $this->getName();
1149 # Check that the reference (filename or sha1) is part of the thumb name
1150 # This is a basic sanity check to avoid erasing unrelated directories
1151 if ( strpos( $file, $reference ) !== false
1152 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1154 $purgeList[] = "{$dir}/{$file}";
1158 # Delete the thumbnails
1159 $this->repo
->quickPurgeBatch( $purgeList );
1160 # Clear out the thumbnail directory if empty
1161 $this->repo
->quickCleanDir( $dir );
1164 /** purgeDescription inherited */
1165 /** purgeEverything inherited */
1168 * @param int|null $limit Optional: Limit to number of results
1169 * @param string|int|null $start Optional: Timestamp, start from
1170 * @param string|int|null $end Optional: Timestamp, end at
1172 * @return OldLocalFile[]
1174 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1175 $dbr = $this->repo
->getReplicaDB();
1176 $oldFileQuery = OldLocalFile
::getQueryInfo();
1178 $tables = $oldFileQuery['tables'];
1179 $fields = $oldFileQuery['fields'];
1180 $join_conds = $oldFileQuery['joins'];
1181 $conds = $opts = [];
1182 $eq = $inc ?
'=' : '';
1183 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1186 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1190 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1194 $opts['LIMIT'] = $limit;
1197 // Search backwards for time > x queries
1198 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1199 $opts['ORDER BY'] = "oi_timestamp $order";
1200 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1202 // Avoid PHP 7.1 warning from passing $this by reference
1204 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1205 &$conds, &$opts, &$join_conds ] );
1207 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1210 foreach ( $res as $row ) {
1211 $r[] = $this->repo
->newFileFromRow( $row );
1214 if ( $order == 'ASC' ) {
1215 $r = array_reverse( $r ); // make sure it ends up descending
1222 * Returns the history of this file, line by line.
1223 * starts with current version, then old versions.
1224 * uses $this->historyLine to check which line to return:
1225 * 0 return line for current version
1226 * 1 query for old versions, return first one
1227 * 2, ... return next old version from above query
1230 public function nextHistoryLine() {
1231 # Polymorphic function name to distinguish foreign and local fetches
1232 $fname = static::class . '::' . __FUNCTION__
;
1234 $dbr = $this->repo
->getReplicaDB();
1236 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1237 $fileQuery = self
::getQueryInfo();
1238 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1239 $fileQuery['fields'] +
[
1240 'oi_archive_name' => $dbr->addQuotes( '' ),
1243 [ 'img_name' => $this->title
->getDBkey() ],
1249 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1250 $this->historyRes
= null;
1254 } elseif ( $this->historyLine
== 1 ) {
1255 $fileQuery = OldLocalFile
::getQueryInfo();
1256 $this->historyRes
= $dbr->select(
1257 $fileQuery['tables'],
1258 $fileQuery['fields'],
1259 [ 'oi_name' => $this->title
->getDBkey() ],
1261 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1265 $this->historyLine++
;
1267 return $dbr->fetchObject( $this->historyRes
);
1271 * Reset the history pointer to the first element of the history
1273 public function resetHistory() {
1274 $this->historyLine
= 0;
1276 if ( !is_null( $this->historyRes
) ) {
1277 $this->historyRes
= null;
1281 /** getHashPath inherited */
1282 /** getRel inherited */
1283 /** getUrlRel inherited */
1284 /** getArchiveRel inherited */
1285 /** getArchivePath inherited */
1286 /** getThumbPath inherited */
1287 /** getArchiveUrl inherited */
1288 /** getThumbUrl inherited */
1289 /** getArchiveVirtualUrl inherited */
1290 /** getThumbVirtualUrl inherited */
1291 /** isHashed inherited */
1294 * Upload a file and record it in the DB
1295 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1296 * @param string $comment Upload description
1297 * @param string $pageText Text to use for the new description page,
1298 * if a new description page is created
1299 * @param int|bool $flags Flags for publish()
1300 * @param array|bool $props File properties, if known. This can be used to
1301 * reduce the upload time when uploading virtual URLs for which the file
1302 * info is already known
1303 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1305 * @param User|null $user User object or null to use $wgUser
1306 * @param string[] $tags Change tags to add to the log entry and page revision.
1307 * (This doesn't check $user's permissions.)
1308 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1309 * upload, see T193621
1310 * @param bool $revert If this file upload is a revert
1311 * @return Status On success, the value member contains the
1312 * archive name, or an empty string if it was a new file.
1314 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1315 $timestamp = false, $user = null, $tags = [],
1316 $createNullRevision = true, $revert = false
1318 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1319 return $this->readOnlyFatalStatus();
1320 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1321 // Check this in advance to avoid writing to FileBackend and the file tables,
1322 // only to fail on insert the revision due to the text store being unavailable.
1323 return $this->readOnlyFatalStatus();
1326 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1328 if ( FileRepo
::isVirtualUrl( $srcPath )
1329 || FileBackend
::isStoragePath( $srcPath )
1331 $props = $this->repo
->getFileProps( $srcPath );
1333 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1334 $props = $mwProps->getPropsFromPath( $srcPath, true );
1339 $handler = MediaHandler
::getHandler( $props['mime'] );
1341 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1343 if ( !is_array( $metadata ) ) {
1347 $options['headers'] = $handler->getContentHeaders( $metadata );
1349 $options['headers'] = [];
1352 // Trim spaces on user supplied text
1353 $comment = trim( $comment );
1356 $status = $this->publish( $src, $flags, $options );
1358 if ( $status->successCount
>= 2 ) {
1359 // There will be a copy+(one of move,copy,store).
1360 // The first succeeding does not commit us to updating the DB
1361 // since it simply copied the current version to a timestamped file name.
1362 // It is only *preferable* to avoid leaving such files orphaned.
1363 // Once the second operation goes through, then the current version was
1364 // updated and we must therefore update the DB too.
1365 $oldver = $status->value
;
1366 $uploadStatus = $this->recordUpload2(
1374 $createNullRevision,
1377 if ( !$uploadStatus->isOK() ) {
1378 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1379 // update filenotfound error with more specific path
1380 $status->fatal( 'filenotfound', $srcPath );
1382 $status->merge( $uploadStatus );
1392 * Record a file upload in the upload log and the image table
1393 * @param string $oldver
1394 * @param string $desc
1395 * @param string $license
1396 * @param string $copyStatus
1397 * @param string $source
1398 * @param bool $watch
1399 * @param string|bool $timestamp
1400 * @param User|null $user User object or null to use $wgUser
1403 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1404 $watch = false, $timestamp = false, User
$user = null ) {
1410 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1412 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1417 $user->addWatch( $this->getTitle() );
1424 * Record a file upload in the upload log and the image table
1425 * @param string $oldver
1426 * @param string $comment
1427 * @param string $pageText
1428 * @param bool|array $props
1429 * @param string|bool $timestamp
1430 * @param null|User $user
1431 * @param string[] $tags
1432 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1433 * upload, see T193621
1434 * @param bool $revert If this file upload is a revert
1437 function recordUpload2(
1438 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1439 $createNullRevision = true, $revert = false
1441 global $wgActorTableSchemaMigrationStage;
1443 if ( is_null( $user ) ) {
1448 $dbw = $this->repo
->getMasterDB();
1450 # Imports or such might force a certain timestamp; otherwise we generate
1451 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1452 if ( $timestamp === false ) {
1453 $timestamp = $dbw->timestamp();
1454 $allowTimeKludge = true;
1456 $allowTimeKludge = false;
1459 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1460 $props['description'] = $comment;
1461 $props['user'] = $user->getId();
1462 $props['user_text'] = $user->getName();
1463 $props['actor'] = $user->getActorId( $dbw );
1464 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1465 $this->setProps( $props );
1467 # Fail now if the file isn't there
1468 if ( !$this->fileExists
) {
1469 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1471 return Status
::newFatal( 'filenotfound', $this->getRel() );
1474 $dbw->startAtomic( __METHOD__
);
1476 # Test to see if the row exists using INSERT IGNORE
1477 # This avoids race conditions by locking the row until the commit, and also
1478 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1479 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1480 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1481 $actorMigration = ActorMigration
::newMigration();
1482 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1483 $dbw->insert( 'image',
1485 'img_name' => $this->getName(),
1486 'img_size' => $this->size
,
1487 'img_width' => intval( $this->width
),
1488 'img_height' => intval( $this->height
),
1489 'img_bits' => $this->bits
,
1490 'img_media_type' => $this->media_type
,
1491 'img_major_mime' => $this->major_mime
,
1492 'img_minor_mime' => $this->minor_mime
,
1493 'img_timestamp' => $timestamp,
1494 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1495 'img_sha1' => $this->sha1
1496 ] +
$commentFields +
$actorFields,
1500 $reupload = ( $dbw->affectedRows() == 0 );
1503 $row = $dbw->selectRow(
1505 [ 'img_timestamp', 'img_sha1' ],
1506 [ 'img_name' => $this->getName() ],
1508 [ 'LOCK IN SHARE MODE' ]
1511 if ( $row && $row->img_sha1
=== $this->sha1
) {
1512 $dbw->endAtomic( __METHOD__
);
1513 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1514 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1515 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1518 if ( $allowTimeKludge ) {
1519 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1520 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1521 # Avoid a timestamp that is not newer than the last version
1522 # TODO: the image/oldimage tables should be like page/revision with an ID field
1523 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1524 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1525 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1526 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1530 $tables = [ 'image' ];
1532 'oi_name' => 'img_name',
1533 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1534 'oi_size' => 'img_size',
1535 'oi_width' => 'img_width',
1536 'oi_height' => 'img_height',
1537 'oi_bits' => 'img_bits',
1538 'oi_description_id' => 'img_description_id',
1539 'oi_timestamp' => 'img_timestamp',
1540 'oi_metadata' => 'img_metadata',
1541 'oi_media_type' => 'img_media_type',
1542 'oi_major_mime' => 'img_major_mime',
1543 'oi_minor_mime' => 'img_minor_mime',
1544 'oi_sha1' => 'img_sha1',
1548 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1549 $fields['oi_user'] = 'img_user';
1550 $fields['oi_user_text'] = 'img_user_text';
1552 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1553 $fields['oi_actor'] = 'img_actor';
1557 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1559 // Upgrade any rows that are still old-style. Otherwise an upgrade
1560 // might be missed if a deletion happens while the migration script
1562 $res = $dbw->select(
1564 [ 'img_name', 'img_user', 'img_user_text' ],
1565 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1568 foreach ( $res as $row ) {
1569 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1572 [ 'img_actor' => $actorId ],
1573 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1579 # (T36993) Note: $oldver can be empty here, if the previous
1580 # version of the file was broken. Allow registration of the new
1581 # version to continue anyway, because that's better than having
1582 # an image that's not fixable by user operations.
1583 # Collision, this is an update of a file
1584 # Insert previous contents into oldimage
1585 $dbw->insertSelect( 'oldimage', $tables, $fields,
1586 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1588 # Update the current image row
1589 $dbw->update( 'image',
1591 'img_size' => $this->size
,
1592 'img_width' => intval( $this->width
),
1593 'img_height' => intval( $this->height
),
1594 'img_bits' => $this->bits
,
1595 'img_media_type' => $this->media_type
,
1596 'img_major_mime' => $this->major_mime
,
1597 'img_minor_mime' => $this->minor_mime
,
1598 'img_timestamp' => $timestamp,
1599 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1600 'img_sha1' => $this->sha1
1601 ] +
$commentFields +
$actorFields,
1602 [ 'img_name' => $this->getName() ],
1607 $descTitle = $this->getTitle();
1608 $descId = $descTitle->getArticleID();
1609 $wikiPage = new WikiFilePage( $descTitle );
1610 $wikiPage->setFile( $this );
1612 // Determine log action. If reupload is done by reverting, use a special log_action.
1613 if ( $revert === true ) {
1614 $logAction = 'revert';
1615 } elseif ( $reupload === true ) {
1616 $logAction = 'overwrite';
1618 $logAction = 'upload';
1620 // Add the log entry...
1621 $logEntry = new ManualLogEntry( 'upload', $logAction );
1622 $logEntry->setTimestamp( $this->timestamp
);
1623 $logEntry->setPerformer( $user );
1624 $logEntry->setComment( $comment );
1625 $logEntry->setTarget( $descTitle );
1626 // Allow people using the api to associate log entries with the upload.
1627 // Log has a timestamp, but sometimes different from upload timestamp.
1628 $logEntry->setParameters(
1630 'img_sha1' => $this->sha1
,
1631 'img_timestamp' => $timestamp,
1634 // Note we keep $logId around since during new image
1635 // creation, page doesn't exist yet, so log_page = 0
1636 // but we want it to point to the page we're making,
1637 // so we later modify the log entry.
1638 // For a similar reason, we avoid making an RC entry
1639 // now and wait until the page exists.
1640 $logId = $logEntry->insert();
1642 if ( $descTitle->exists() ) {
1643 // Use own context to get the action text in content language
1644 $formatter = LogFormatter
::newFromEntry( $logEntry );
1645 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1646 $editSummary = $formatter->getPlainActionText();
1648 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1655 if ( $nullRevision ) {
1656 $nullRevision->insertOn( $dbw );
1658 'NewRevisionFromEditComplete',
1659 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1661 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1662 // Associate null revision id
1663 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1666 $newPageContent = null;
1668 // Make the description page and RC log entry post-commit
1669 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1672 # Defer purges, page creation, and link updates in case they error out.
1673 # The most important thing is that files and the DB registry stay synced.
1674 $dbw->endAtomic( __METHOD__
);
1675 $fname = __METHOD__
;
1677 # Do some cache purges after final commit so that:
1678 # a) Changes are more likely to be seen post-purge
1679 # b) They won't cause rollback of the log publish/update above
1680 DeferredUpdates
::addUpdate(
1681 new AutoCommitUpdate(
1685 $reupload, $wikiPage, $newPageContent, $comment, $user,
1686 $logEntry, $logId, $descId, $tags, $fname
1688 # Update memcache after the commit
1689 $this->invalidateCache();
1691 $updateLogPage = false;
1692 if ( $newPageContent ) {
1693 # New file page; create the description page.
1694 # There's already a log entry, so don't make a second RC entry
1695 # CDN and file cache for the description page are purged by doEditContent.
1696 $status = $wikiPage->doEditContent(
1699 EDIT_NEW | EDIT_SUPPRESS_RC
,
1704 if ( isset( $status->value
['revision'] ) ) {
1705 /** @var Revision $rev */
1706 $rev = $status->value
['revision'];
1707 // Associate new page revision id
1708 $logEntry->setAssociatedRevId( $rev->getId() );
1710 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1711 // which is triggered on $descTitle by doEditContent() above.
1712 if ( isset( $status->value
['revision'] ) ) {
1713 /** @var Revision $rev */
1714 $rev = $status->value
['revision'];
1715 $updateLogPage = $rev->getPage();
1718 # Existing file page: invalidate description page cache
1719 $wikiPage->getTitle()->invalidateCache();
1720 $wikiPage->getTitle()->purgeSquid();
1721 # Allow the new file version to be patrolled from the page footer
1722 Article
::purgePatrolFooterCache( $descId );
1725 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1726 # but setAssociatedRevId() wasn't called at that point yet...
1727 $logParams = $logEntry->getParameters();
1728 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1729 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1730 if ( $updateLogPage ) {
1731 # Also log page, in case where we just created it above
1732 $update['log_page'] = $updateLogPage;
1734 $this->getRepo()->getMasterDB()->update(
1737 [ 'log_id' => $logId ],
1740 $this->getRepo()->getMasterDB()->insert(
1743 'ls_field' => 'associated_rev_id',
1744 'ls_value' => $logEntry->getAssociatedRevId(),
1745 'ls_log_id' => $logId,
1750 # Add change tags, if any
1752 $logEntry->setTags( $tags );
1755 # Uploads can be patrolled
1756 $logEntry->setIsPatrollable( true );
1758 # Now that the log entry is up-to-date, make an RC entry.
1759 $logEntry->publish( $logId );
1761 # Run hook for other updates (typically more cache purging)
1762 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1765 # Delete old thumbnails
1766 $this->purgeThumbnails();
1767 # Remove the old file from the CDN cache
1768 DeferredUpdates
::addUpdate(
1769 new CdnCacheUpdate( [ $this->getUrl() ] ),
1770 DeferredUpdates
::PRESEND
1773 # Update backlink pages pointing to this title if created
1774 LinksUpdate
::queueRecursiveJobsForTable(
1782 $this->prerenderThumbnails();
1785 DeferredUpdates
::PRESEND
1789 # This is a new file, so update the image count
1790 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1793 # Invalidate cache for all pages using this file
1794 DeferredUpdates
::addUpdate(
1795 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1798 return Status
::newGood();
1802 * Move or copy a file to its public location. If a file exists at the
1803 * destination, move it to an archive. Returns a Status object with
1804 * the archive name in the "value" member on success.
1806 * The archive name should be passed through to recordUpload for database
1809 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1810 * @param int $flags A bitwise combination of:
1811 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1812 * @param array $options Optional additional parameters
1813 * @return Status On success, the value member contains the
1814 * archive name, or an empty string if it was a new file.
1816 function publish( $src, $flags = 0, array $options = [] ) {
1817 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1821 * Move or copy a file to a specified location. Returns a Status
1822 * object with the archive name in the "value" member on success.
1824 * The archive name should be passed through to recordUpload for database
1827 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1828 * @param string $dstRel Target relative path
1829 * @param int $flags A bitwise combination of:
1830 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1831 * @param array $options Optional additional parameters
1832 * @return Status On success, the value member contains the
1833 * archive name, or an empty string if it was a new file.
1835 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1836 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1838 $repo = $this->getRepo();
1839 if ( $repo->getReadOnlyReason() !== false ) {
1840 return $this->readOnlyFatalStatus();
1845 if ( $this->isOld() ) {
1846 $archiveRel = $dstRel;
1847 $archiveName = basename( $archiveRel );
1849 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1850 $archiveRel = $this->getArchiveRel( $archiveName );
1853 if ( $repo->hasSha1Storage() ) {
1854 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1855 ?
$repo->getFileSha1( $srcPath )
1856 : FSFile
::getSha1Base36FromPath( $srcPath );
1857 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1858 $wrapperBackend = $repo->getBackend();
1859 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1860 $status = $repo->quickImport( $src, $dst );
1861 if ( $flags & File
::DELETE_SOURCE
) {
1865 if ( $this->exists() ) {
1866 $status->value
= $archiveName;
1869 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1870 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1872 if ( $status->value
== 'new' ) {
1873 $status->value
= '';
1875 $status->value
= $archiveName;
1883 /** getLinksTo inherited */
1884 /** getExifData inherited */
1885 /** isLocal inherited */
1886 /** wasDeleted inherited */
1889 * Move file to the new title
1891 * Move current, old version and all thumbnails
1892 * to the new filename. Old file is deleted.
1894 * Cache purging is done; checks for validity
1895 * and logging are caller's responsibility
1897 * @param Title $target New file name
1900 function move( $target ) {
1901 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1902 return $this->readOnlyFatalStatus();
1905 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1906 $batch = new LocalFileMoveBatch( $this, $target );
1909 $batch->addCurrent();
1910 $archiveNames = $batch->addOlds();
1911 $status = $batch->execute();
1914 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1916 // Purge the source and target files...
1917 $oldTitleFile = wfLocalFile( $this->title
);
1918 $newTitleFile = wfLocalFile( $target );
1919 // To avoid slow purges in the transaction, move them outside...
1920 DeferredUpdates
::addUpdate(
1921 new AutoCommitUpdate(
1922 $this->getRepo()->getMasterDB(),
1924 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1925 $oldTitleFile->purgeEverything();
1926 foreach ( $archiveNames as $archiveName ) {
1927 $oldTitleFile->purgeOldThumbnails( $archiveName );
1929 $newTitleFile->purgeEverything();
1932 DeferredUpdates
::PRESEND
1935 if ( $status->isOK() ) {
1936 // Now switch the object
1937 $this->title
= $target;
1938 // Force regeneration of the name and hashpath
1939 unset( $this->name
);
1940 unset( $this->hashPath
);
1947 * Delete all versions of the file.
1949 * Moves the files into an archive directory (or deletes them)
1950 * and removes the database rows.
1952 * Cache purging is done; logging is caller's responsibility.
1954 * @param string $reason
1955 * @param bool $suppress
1956 * @param User|null $user
1959 function delete( $reason, $suppress = false, $user = null ) {
1960 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1961 return $this->readOnlyFatalStatus();
1964 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1967 $batch->addCurrent();
1968 // Get old version relative paths
1969 $archiveNames = $batch->addOlds();
1970 $status = $batch->execute();
1973 if ( $status->isOK() ) {
1974 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1977 // To avoid slow purges in the transaction, move them outside...
1978 DeferredUpdates
::addUpdate(
1979 new AutoCommitUpdate(
1980 $this->getRepo()->getMasterDB(),
1982 function () use ( $archiveNames ) {
1983 $this->purgeEverything();
1984 foreach ( $archiveNames as $archiveName ) {
1985 $this->purgeOldThumbnails( $archiveName );
1989 DeferredUpdates
::PRESEND
1994 foreach ( $archiveNames as $archiveName ) {
1995 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1997 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2003 * Delete an old version of the file.
2005 * Moves the file into an archive directory (or deletes it)
2006 * and removes the database row.
2008 * Cache purging is done; logging is caller's responsibility.
2010 * @param string $archiveName
2011 * @param string $reason
2012 * @param bool $suppress
2013 * @param User|null $user
2014 * @throws MWException Exception on database or file store failure
2017 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2018 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2019 return $this->readOnlyFatalStatus();
2022 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2025 $batch->addOld( $archiveName );
2026 $status = $batch->execute();
2029 $this->purgeOldThumbnails( $archiveName );
2030 if ( $status->isOK() ) {
2031 $this->purgeDescription();
2034 DeferredUpdates
::addUpdate(
2035 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2036 DeferredUpdates
::PRESEND
2043 * Restore all or specified deleted revisions to the given file.
2044 * Permissions and logging are left to the caller.
2046 * May throw database exceptions on error.
2048 * @param array $versions Set of record ids of deleted items to restore,
2049 * or empty to restore all revisions.
2050 * @param bool $unsuppress
2053 function restore( $versions = [], $unsuppress = false ) {
2054 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2055 return $this->readOnlyFatalStatus();
2058 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2064 $batch->addIds( $versions );
2066 $status = $batch->execute();
2067 if ( $status->isGood() ) {
2068 $cleanupStatus = $batch->cleanup();
2069 $cleanupStatus->successCount
= 0;
2070 $cleanupStatus->failCount
= 0;
2071 $status->merge( $cleanupStatus );
2078 /** isMultipage inherited */
2079 /** pageCount inherited */
2080 /** scaleHeight inherited */
2081 /** getImageSize inherited */
2084 * Get the URL of the file description page.
2087 function getDescriptionUrl() {
2088 return $this->title
->getLocalURL();
2092 * Get the HTML text of the description page
2093 * This is not used by ImagePage for local files, since (among other things)
2094 * it skips the parser cache.
2096 * @param Language|null $lang What language to get description in (Optional)
2097 * @return string|false
2099 function getDescriptionText( Language
$lang = null ) {
2100 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2101 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2106 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2107 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2110 // audience check failed
2114 $pout = $rendered->getRevisionParserOutput();
2115 return $pout->getText();
2119 * @param int $audience
2120 * @param User|null $user
2123 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2125 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2127 } elseif ( $audience == self
::FOR_THIS_USER
2128 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2132 return $this->description
;
2137 * @return bool|string
2139 function getTimestamp() {
2142 return $this->timestamp
;
2146 * @return bool|string
2148 public function getDescriptionTouched() {
2149 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2150 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2151 // need to differentiate between null (uninitialized) and false (failed to load).
2152 if ( $this->descriptionTouched
=== null ) {
2154 'page_namespace' => $this->title
->getNamespace(),
2155 'page_title' => $this->title
->getDBkey()
2157 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2158 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2161 return $this->descriptionTouched
;
2167 function getSha1() {
2169 // Initialise now if necessary
2170 if ( $this->sha1
== '' && $this->fileExists
) {
2173 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2174 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2175 $dbw = $this->repo
->getMasterDB();
2176 $dbw->update( 'image',
2177 [ 'img_sha1' => $this->sha1
],
2178 [ 'img_name' => $this->getName() ],
2180 $this->invalidateCache();
2190 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2192 function isCacheable() {
2195 // If extra data (metadata) was not loaded then it must have been large
2196 return $this->extraDataLoaded
2197 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2204 public function acquireFileLock() {
2205 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2206 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2214 public function releaseFileLock() {
2215 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2216 [ $this->getPath() ], LockManager
::LOCK_EX
2221 * Start an atomic DB section and lock the image for update
2222 * or increments a reference counter if the lock is already held
2224 * This method should not be used outside of LocalFile/LocalFile*Batch
2226 * @throws LocalFileLockError Throws an error if the lock was not acquired
2227 * @return bool Whether the file lock owns/spawned the DB transaction
2229 public function lock() {
2230 if ( !$this->locked
) {
2231 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2233 $dbw = $this->repo
->getMasterDB();
2234 $makesTransaction = !$dbw->trxLevel();
2235 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2236 // T56736: use simple lock to handle when the file does not exist.
2237 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2238 // Also, that would cause contention on INSERT of similarly named rows.
2239 $status = $this->acquireFileLock(); // represents all versions of the file
2240 if ( !$status->isGood() ) {
2241 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2242 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2244 throw new LocalFileLockError( $status );
2246 // Release the lock *after* commit to avoid row-level contention.
2247 // Make sure it triggers on rollback() as well as commit() (T132921).
2248 $dbw->onTransactionResolution(
2249 function () use ( $logger ) {
2250 $status = $this->releaseFileLock();
2251 if ( !$status->isGood() ) {
2252 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2257 // Callers might care if the SELECT snapshot is safely fresh
2258 $this->lockedOwnTrx
= $makesTransaction;
2263 return $this->lockedOwnTrx
;
2267 * Decrement the lock reference count and end the atomic section if it reaches zero
2269 * This method should not be used outside of LocalFile/LocalFile*Batch
2271 * The commit and loc release will happen when no atomic sections are active, which
2272 * may happen immediately or at some point after calling this
2274 public function unlock() {
2275 if ( $this->locked
) {
2277 if ( !$this->locked
) {
2278 $dbw = $this->repo
->getMasterDB();
2279 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2280 $this->lockedOwnTrx
= false;
2288 protected function readOnlyFatalStatus() {
2289 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2290 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2294 * Clean up any dangling locks
2296 function __destruct() {