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 $fname = static::class . '::' . __FUNCTION__
;
457 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
458 $this->extraDataLoaded
= true;
460 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
462 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
466 foreach ( $fieldMap as $name => $value ) {
467 $this->$name = $value;
470 throw new MWException( "Could not find data for image '{$this->getName()}'." );
475 * @param IDatabase $dbr
476 * @param string $fname
477 * @return string[]|bool
479 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
482 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
483 $row = $dbr->selectRow(
484 $fileQuery['tables'],
485 $fileQuery['fields'],
487 'img_name' => $this->getName(),
488 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
495 $fieldMap = $this->unprefixRow( $row, 'img_' );
497 # File may have been uploaded over in the meantime; check the old versions
498 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
499 $row = $dbr->selectRow(
500 $fileQuery['tables'],
501 $fileQuery['fields'],
503 'oi_name' => $this->getName(),
504 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
511 $fieldMap = $this->unprefixRow( $row, 'oi_' );
515 if ( isset( $fieldMap['metadata'] ) ) {
516 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
523 * @param array|object $row
524 * @param string $prefix
525 * @throws MWException
528 protected function unprefixRow( $row, $prefix = 'img_' ) {
529 $array = (array)$row;
530 $prefixLength = strlen( $prefix );
532 // Sanity check prefix once
533 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
534 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
538 foreach ( $array as $name => $value ) {
539 $decoded[substr( $name, $prefixLength )] = $value;
546 * Decode a row from the database (either object or array) to an array
547 * with timestamps and MIME types decoded, and the field prefix removed.
549 * @param string $prefix
550 * @throws MWException
553 function decodeRow( $row, $prefix = 'img_' ) {
554 $decoded = $this->unprefixRow( $row, $prefix );
556 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
557 ->getComment( 'description', (object)$decoded )->text
;
559 $decoded['user'] = User
::newFromAnyId(
560 $decoded['user'] ??
null,
561 $decoded['user_text'] ??
null,
562 $decoded['actor'] ??
null
564 unset( $decoded['user_text'], $decoded['actor'] );
566 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
568 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
570 if ( empty( $decoded['major_mime'] ) ) {
571 $decoded['mime'] = 'unknown/unknown';
573 if ( !$decoded['minor_mime'] ) {
574 $decoded['minor_mime'] = 'unknown';
576 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
579 // Trim zero padding from char/binary field
580 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
582 // Normalize some fields to integer type, per their database definition.
583 // Use unary + so that overflows will be upgraded to double instead of
584 // being trucated as with intval(). This is important to allow >2GB
585 // files on 32-bit systems.
586 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
587 $decoded[$field] = +
$decoded[$field];
594 * Load file metadata from a DB result row
597 * @param string $prefix
599 function loadFromRow( $row, $prefix = 'img_' ) {
600 $this->dataLoaded
= true;
601 $this->extraDataLoaded
= true;
603 $array = $this->decodeRow( $row, $prefix );
605 foreach ( $array as $name => $value ) {
606 $this->$name = $value;
609 $this->fileExists
= true;
613 * Load file metadata from cache or DB, unless already loaded
616 function load( $flags = 0 ) {
617 if ( !$this->dataLoaded
) {
618 if ( $flags & self
::READ_LATEST
) {
619 $this->loadFromDB( $flags );
621 $this->loadFromCache();
625 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
626 // @note: loads on name/timestamp to reduce race condition problems
627 $this->loadExtraFromDB();
632 * Upgrade a row if it needs it
634 protected function maybeUpgradeRow() {
635 global $wgUpdateCompatibleMetadata;
637 if ( wfReadOnly() ||
$this->upgrading
) {
642 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
645 $handler = $this->getHandler();
647 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
648 if ( $validity === MediaHandler
::METADATA_BAD
) {
650 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
651 $upgrade = $wgUpdateCompatibleMetadata;
657 $this->upgrading
= true;
658 // Defer updates unless in auto-commit CLI mode
659 DeferredUpdates
::addCallableUpdate( function () {
660 $this->upgrading
= false; // avoid duplicate updates
663 } catch ( LocalFileLockError
$e ) {
664 // let the other process handle it (or do it next time)
671 * @return bool Whether upgradeRow() ran for this object
673 function getUpgraded() {
674 return $this->upgraded
;
678 * Fix assorted version-related problems with the image row by reloading it from the file
680 function upgradeRow() {
683 $this->loadFromFile();
685 # Don't destroy file info of missing files
686 if ( !$this->fileExists
) {
688 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
693 $dbw = $this->repo
->getMasterDB();
694 list( $major, $minor ) = self
::splitMime( $this->mime
);
696 if ( wfReadOnly() ) {
701 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
703 $dbw->update( 'image',
705 'img_size' => $this->size
, // sanity
706 'img_width' => $this->width
,
707 'img_height' => $this->height
,
708 'img_bits' => $this->bits
,
709 'img_media_type' => $this->media_type
,
710 'img_major_mime' => $major,
711 'img_minor_mime' => $minor,
712 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
713 'img_sha1' => $this->sha1
,
715 [ 'img_name' => $this->getName() ],
719 $this->invalidateCache();
722 $this->upgraded
= true; // avoid rework/retries
726 * Set properties in this object to be equal to those given in the
727 * associative array $info. Only cacheable fields can be set.
728 * All fields *must* be set in $info except for getLazyCacheFields().
730 * If 'mime' is given, it will be split into major_mime/minor_mime.
731 * If major_mime/minor_mime are given, $this->mime will also be set.
735 function setProps( $info ) {
736 $this->dataLoaded
= true;
737 $fields = $this->getCacheFields( '' );
738 $fields[] = 'fileExists';
740 foreach ( $fields as $field ) {
741 if ( isset( $info[$field] ) ) {
742 $this->$field = $info[$field];
746 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
747 $this->user
= User
::newFromAnyId(
748 $info['user'] ??
null,
749 $info['user_text'] ??
null,
750 $info['actor'] ??
null
754 // Fix up mime fields
755 if ( isset( $info['major_mime'] ) ) {
756 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
757 } elseif ( isset( $info['mime'] ) ) {
758 $this->mime
= $info['mime'];
759 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
763 /** splitMime inherited */
764 /** getName inherited */
765 /** getTitle inherited */
766 /** getURL inherited */
767 /** getViewURL inherited */
768 /** getPath inherited */
769 /** isVisible inherited */
772 * Checks if this file exists in its parent repo, as referenced by its
777 function isMissing() {
778 if ( $this->missing
=== null ) {
779 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
780 $this->missing
= !$fileExists;
783 return $this->missing
;
787 * Return the width of the image
792 public function getWidth( $page = 1 ) {
800 if ( $this->isMultipage() ) {
801 $handler = $this->getHandler();
805 $dim = $handler->getPageDimensions( $this, $page );
807 return $dim['width'];
809 // For non-paged media, the false goes through an
810 // intval, turning failure into 0, so do same here.
819 * Return the height of the image
824 public function getHeight( $page = 1 ) {
832 if ( $this->isMultipage() ) {
833 $handler = $this->getHandler();
837 $dim = $handler->getPageDimensions( $this, $page );
839 return $dim['height'];
841 // For non-paged media, the false goes through an
842 // intval, turning failure into 0, so do same here.
846 return $this->height
;
851 * Returns user who uploaded the file
853 * @param string $type 'text', 'id', or 'object'
854 * @return int|string|User
855 * @since 1.31 Added 'object'
857 function getUser( $type = 'text' ) {
860 if ( $type === 'object' ) {
862 } elseif ( $type === 'text' ) {
863 return $this->user
->getName();
864 } elseif ( $type === 'id' ) {
865 return $this->user
->getId();
868 throw new MWException( "Unknown type '$type'." );
872 * Get short description URL for a file based on the page ID.
874 * @return string|null
875 * @throws MWException
878 public function getDescriptionShortUrl() {
879 $pageId = $this->title
->getArticleID();
881 if ( $pageId !== null ) {
882 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
883 if ( $url !== false ) {
891 * Get handler-specific metadata
894 function getMetadata() {
895 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
896 return $this->metadata
;
902 function getBitDepth() {
905 return (int)$this->bits
;
909 * Returns the size of the image file, in bytes
912 public function getSize() {
919 * Returns the MIME type of the file.
922 function getMimeType() {
929 * Returns the type of the media in the file.
930 * Use the value returned by this function with the MEDIATYPE_xxx constants.
933 function getMediaType() {
936 return $this->media_type
;
939 /** canRender inherited */
940 /** mustRender inherited */
941 /** allowInlineDisplay inherited */
942 /** isSafeFile inherited */
943 /** isTrustedFile inherited */
946 * Returns true if the file exists on disk.
947 * @return bool Whether file exist on disk.
949 public function exists() {
952 return $this->fileExists
;
955 /** getTransformScript inherited */
956 /** getUnscaledThumb inherited */
957 /** thumbName inherited */
958 /** createThumb inherited */
959 /** transform inherited */
961 /** getHandler inherited */
962 /** iconThumb inherited */
963 /** getLastError inherited */
966 * Get all thumbnail names previously generated for this file
967 * @param string|bool $archiveName Name of an archive file, default false
968 * @return array First element is the base dir, then files in that base dir.
970 function getThumbnails( $archiveName = false ) {
971 if ( $archiveName ) {
972 $dir = $this->getArchiveThumbPath( $archiveName );
974 $dir = $this->getThumbPath();
977 $backend = $this->repo
->getBackend();
980 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
981 foreach ( $iterator as $file ) {
984 } catch ( FileBackendError
$e ) {
985 } // suppress (T56674)
991 * Refresh metadata in memcached, but don't touch thumbnails or CDN
993 function purgeMetadataCache() {
994 $this->invalidateCache();
998 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1000 * @param array $options An array potentially with the key forThumbRefresh.
1002 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1004 function purgeCache( $options = [] ) {
1005 // Refresh metadata cache
1006 $this->maybeUpgradeRow();
1007 $this->purgeMetadataCache();
1009 // Delete thumbnails
1010 $this->purgeThumbnails( $options );
1012 // Purge CDN cache for this file
1013 DeferredUpdates
::addUpdate(
1014 new CdnCacheUpdate( [ $this->getUrl() ] ),
1015 DeferredUpdates
::PRESEND
1020 * Delete cached transformed files for an archived version only.
1021 * @param string $archiveName Name of the archived file
1023 function purgeOldThumbnails( $archiveName ) {
1024 // Get a list of old thumbnails and URLs
1025 $files = $this->getThumbnails( $archiveName );
1027 // Purge any custom thumbnail caches
1028 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1030 // Delete thumbnails
1031 $dir = array_shift( $files );
1032 $this->purgeThumbList( $dir, $files );
1036 foreach ( $files as $file ) {
1037 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1039 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1043 * Delete cached transformed files for the current version only.
1044 * @param array $options
1045 * @phan-param array{forThumbRefresh?:bool} $options
1047 public function purgeThumbnails( $options = [] ) {
1048 $files = $this->getThumbnails();
1049 // Always purge all files from CDN regardless of handler filters
1051 foreach ( $files as $file ) {
1052 $urls[] = $this->getThumbUrl( $file );
1054 array_shift( $urls ); // don't purge directory
1056 // Give media handler a chance to filter the file purge list
1057 if ( !empty( $options['forThumbRefresh'] ) ) {
1058 $handler = $this->getHandler();
1060 $handler->filterThumbnailPurgeList( $files, $options );
1064 // Purge any custom thumbnail caches
1065 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1067 // Delete thumbnails
1068 $dir = array_shift( $files );
1069 $this->purgeThumbList( $dir, $files );
1072 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1076 * Prerenders a configurable set of thumbnails
1080 public function prerenderThumbnails() {
1081 global $wgUploadThumbnailRenderMap;
1085 $sizes = $wgUploadThumbnailRenderMap;
1088 foreach ( $sizes as $size ) {
1089 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1090 $jobs[] = new ThumbnailRenderJob(
1092 [ 'transformParams' => [ 'width' => $size ] ]
1098 JobQueueGroup
::singleton()->lazyPush( $jobs );
1103 * Delete a list of thumbnails visible at urls
1104 * @param string $dir Base dir of the files.
1105 * @param array $files Array of strings: relative filenames (to $dir)
1107 protected function purgeThumbList( $dir, $files ) {
1108 $fileListDebug = strtr(
1109 var_export( $files, true ),
1112 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1115 foreach ( $files as $file ) {
1116 if ( $this->repo
->supportsSha1URLs() ) {
1117 $reference = $this->getSha1();
1119 $reference = $this->getName();
1122 # Check that the reference (filename or sha1) is part of the thumb name
1123 # This is a basic sanity check to avoid erasing unrelated directories
1124 if ( strpos( $file, $reference ) !== false
1125 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1127 $purgeList[] = "{$dir}/{$file}";
1131 # Delete the thumbnails
1132 $this->repo
->quickPurgeBatch( $purgeList );
1133 # Clear out the thumbnail directory if empty
1134 $this->repo
->quickCleanDir( $dir );
1137 /** purgeDescription inherited */
1138 /** purgeEverything inherited */
1141 * @param int|null $limit Optional: Limit to number of results
1142 * @param string|int|null $start Optional: Timestamp, start from
1143 * @param string|int|null $end Optional: Timestamp, end at
1145 * @return OldLocalFile[]
1147 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1148 $dbr = $this->repo
->getReplicaDB();
1149 $oldFileQuery = OldLocalFile
::getQueryInfo();
1151 $tables = $oldFileQuery['tables'];
1152 $fields = $oldFileQuery['fields'];
1153 $join_conds = $oldFileQuery['joins'];
1154 $conds = $opts = [];
1155 $eq = $inc ?
'=' : '';
1156 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1159 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1163 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1167 $opts['LIMIT'] = $limit;
1170 // Search backwards for time > x queries
1171 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1172 $opts['ORDER BY'] = "oi_timestamp $order";
1173 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1175 // Avoid PHP 7.1 warning from passing $this by reference
1177 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1178 &$conds, &$opts, &$join_conds ] );
1180 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1183 foreach ( $res as $row ) {
1184 $r[] = $this->repo
->newFileFromRow( $row );
1187 if ( $order == 'ASC' ) {
1188 $r = array_reverse( $r ); // make sure it ends up descending
1195 * Returns the history of this file, line by line.
1196 * starts with current version, then old versions.
1197 * uses $this->historyLine to check which line to return:
1198 * 0 return line for current version
1199 * 1 query for old versions, return first one
1200 * 2, ... return next old version from above query
1203 public function nextHistoryLine() {
1204 # Polymorphic function name to distinguish foreign and local fetches
1205 $fname = static::class . '::' . __FUNCTION__
;
1207 $dbr = $this->repo
->getReplicaDB();
1209 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1210 $fileQuery = self
::getQueryInfo();
1211 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1212 $fileQuery['fields'] +
[
1213 'oi_archive_name' => $dbr->addQuotes( '' ),
1216 [ 'img_name' => $this->title
->getDBkey() ],
1222 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1223 $this->historyRes
= null;
1227 } elseif ( $this->historyLine
== 1 ) {
1228 $fileQuery = OldLocalFile
::getQueryInfo();
1229 $this->historyRes
= $dbr->select(
1230 $fileQuery['tables'],
1231 $fileQuery['fields'],
1232 [ 'oi_name' => $this->title
->getDBkey() ],
1234 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1238 $this->historyLine++
;
1240 return $dbr->fetchObject( $this->historyRes
);
1244 * Reset the history pointer to the first element of the history
1246 public function resetHistory() {
1247 $this->historyLine
= 0;
1249 if ( !is_null( $this->historyRes
) ) {
1250 $this->historyRes
= null;
1254 /** getHashPath inherited */
1255 /** getRel inherited */
1256 /** getUrlRel inherited */
1257 /** getArchiveRel inherited */
1258 /** getArchivePath inherited */
1259 /** getThumbPath inherited */
1260 /** getArchiveUrl inherited */
1261 /** getThumbUrl inherited */
1262 /** getArchiveVirtualUrl inherited */
1263 /** getThumbVirtualUrl inherited */
1264 /** isHashed inherited */
1267 * Upload a file and record it in the DB
1268 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1269 * @param string $comment Upload description
1270 * @param string $pageText Text to use for the new description page,
1271 * if a new description page is created
1272 * @param int|bool $flags Flags for publish()
1273 * @param array|bool $props File properties, if known. This can be used to
1274 * reduce the upload time when uploading virtual URLs for which the file
1275 * info is already known
1276 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1278 * @param User|null $user User object or null to use $wgUser
1279 * @param string[] $tags Change tags to add to the log entry and page revision.
1280 * (This doesn't check $user's permissions.)
1281 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1282 * upload, see T193621
1283 * @param bool $revert If this file upload is a revert
1284 * @return Status On success, the value member contains the
1285 * archive name, or an empty string if it was a new file.
1287 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1288 $timestamp = false, $user = null, $tags = [],
1289 $createNullRevision = true, $revert = false
1291 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1292 return $this->readOnlyFatalStatus();
1293 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1294 // Check this in advance to avoid writing to FileBackend and the file tables,
1295 // only to fail on insert the revision due to the text store being unavailable.
1296 return $this->readOnlyFatalStatus();
1299 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1301 if ( FileRepo
::isVirtualUrl( $srcPath )
1302 || FileBackend
::isStoragePath( $srcPath )
1304 $props = $this->repo
->getFileProps( $srcPath );
1306 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1307 $props = $mwProps->getPropsFromPath( $srcPath, true );
1312 $handler = MediaHandler
::getHandler( $props['mime'] );
1314 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1316 if ( !is_array( $metadata ) ) {
1320 $options['headers'] = $handler->getContentHeaders( $metadata );
1322 $options['headers'] = [];
1325 // Trim spaces on user supplied text
1326 $comment = trim( $comment );
1329 $status = $this->publish( $src, $flags, $options );
1331 if ( $status->successCount
>= 2 ) {
1332 // There will be a copy+(one of move,copy,store).
1333 // The first succeeding does not commit us to updating the DB
1334 // since it simply copied the current version to a timestamped file name.
1335 // It is only *preferable* to avoid leaving such files orphaned.
1336 // Once the second operation goes through, then the current version was
1337 // updated and we must therefore update the DB too.
1338 $oldver = $status->value
;
1339 $uploadStatus = $this->recordUpload2(
1347 $createNullRevision,
1350 if ( !$uploadStatus->isOK() ) {
1351 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1352 // update filenotfound error with more specific path
1353 $status->fatal( 'filenotfound', $srcPath );
1355 $status->merge( $uploadStatus );
1365 * Record a file upload in the upload log and the image table
1366 * @param string $oldver
1367 * @param string $desc
1368 * @param string $license
1369 * @param string $copyStatus
1370 * @param string $source
1371 * @param bool $watch
1372 * @param string|bool $timestamp
1373 * @param User|null $user User object or null to use $wgUser
1376 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1377 $watch = false, $timestamp = false, User
$user = null ) {
1383 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1385 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1390 $user->addWatch( $this->getTitle() );
1397 * Record a file upload in the upload log and the image table
1398 * @param string $oldver
1399 * @param string $comment
1400 * @param string $pageText
1401 * @param bool|array $props
1402 * @param string|bool $timestamp
1403 * @param null|User $user
1404 * @param string[] $tags
1405 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1406 * upload, see T193621
1407 * @param bool $revert If this file upload is a revert
1410 function recordUpload2(
1411 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1412 $createNullRevision = true, $revert = false
1414 if ( is_null( $user ) ) {
1419 $dbw = $this->repo
->getMasterDB();
1421 # Imports or such might force a certain timestamp; otherwise we generate
1422 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1423 if ( $timestamp === false ) {
1424 $timestamp = $dbw->timestamp();
1425 $allowTimeKludge = true;
1427 $allowTimeKludge = false;
1430 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1431 $props['description'] = $comment;
1432 $props['user'] = $user->getId();
1433 $props['user_text'] = $user->getName();
1434 $props['actor'] = $user->getActorId( $dbw );
1435 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1436 $this->setProps( $props );
1438 # Fail now if the file isn't there
1439 if ( !$this->fileExists
) {
1440 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1442 return Status
::newFatal( 'filenotfound', $this->getRel() );
1445 $dbw->startAtomic( __METHOD__
);
1447 # Test to see if the row exists using INSERT IGNORE
1448 # This avoids race conditions by locking the row until the commit, and also
1449 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1450 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1451 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1452 $actorMigration = ActorMigration
::newMigration();
1453 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1454 $dbw->insert( 'image',
1456 'img_name' => $this->getName(),
1457 'img_size' => $this->size
,
1458 'img_width' => intval( $this->width
),
1459 'img_height' => intval( $this->height
),
1460 'img_bits' => $this->bits
,
1461 'img_media_type' => $this->media_type
,
1462 'img_major_mime' => $this->major_mime
,
1463 'img_minor_mime' => $this->minor_mime
,
1464 'img_timestamp' => $timestamp,
1465 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1466 'img_sha1' => $this->sha1
1467 ] +
$commentFields +
$actorFields,
1471 $reupload = ( $dbw->affectedRows() == 0 );
1474 $row = $dbw->selectRow(
1476 [ 'img_timestamp', 'img_sha1' ],
1477 [ 'img_name' => $this->getName() ],
1479 [ 'LOCK IN SHARE MODE' ]
1482 if ( $row && $row->img_sha1
=== $this->sha1
) {
1483 $dbw->endAtomic( __METHOD__
);
1484 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1485 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1486 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1489 if ( $allowTimeKludge ) {
1490 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1491 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1492 # Avoid a timestamp that is not newer than the last version
1493 # TODO: the image/oldimage tables should be like page/revision with an ID field
1494 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1495 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1496 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1497 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1501 $tables = [ 'image' ];
1503 'oi_name' => 'img_name',
1504 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1505 'oi_size' => 'img_size',
1506 'oi_width' => 'img_width',
1507 'oi_height' => 'img_height',
1508 'oi_bits' => 'img_bits',
1509 'oi_description_id' => 'img_description_id',
1510 'oi_timestamp' => 'img_timestamp',
1511 'oi_metadata' => 'img_metadata',
1512 'oi_media_type' => 'img_media_type',
1513 'oi_major_mime' => 'img_major_mime',
1514 'oi_minor_mime' => 'img_minor_mime',
1515 'oi_sha1' => 'img_sha1',
1516 'oi_actor' => 'img_actor',
1520 # (T36993) Note: $oldver can be empty here, if the previous
1521 # version of the file was broken. Allow registration of the new
1522 # version to continue anyway, because that's better than having
1523 # an image that's not fixable by user operations.
1524 # Collision, this is an update of a file
1525 # Insert previous contents into oldimage
1526 $dbw->insertSelect( 'oldimage', $tables, $fields,
1527 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1529 # Update the current image row
1530 $dbw->update( 'image',
1532 'img_size' => $this->size
,
1533 'img_width' => intval( $this->width
),
1534 'img_height' => intval( $this->height
),
1535 'img_bits' => $this->bits
,
1536 'img_media_type' => $this->media_type
,
1537 'img_major_mime' => $this->major_mime
,
1538 'img_minor_mime' => $this->minor_mime
,
1539 'img_timestamp' => $timestamp,
1540 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1541 'img_sha1' => $this->sha1
1542 ] +
$commentFields +
$actorFields,
1543 [ 'img_name' => $this->getName() ],
1548 $descTitle = $this->getTitle();
1549 $descId = $descTitle->getArticleID();
1550 $wikiPage = new WikiFilePage( $descTitle );
1551 $wikiPage->setFile( $this );
1553 // Determine log action. If reupload is done by reverting, use a special log_action.
1554 if ( $revert === true ) {
1555 $logAction = 'revert';
1556 } elseif ( $reupload === true ) {
1557 $logAction = 'overwrite';
1559 $logAction = 'upload';
1561 // Add the log entry...
1562 $logEntry = new ManualLogEntry( 'upload', $logAction );
1563 $logEntry->setTimestamp( $this->timestamp
);
1564 $logEntry->setPerformer( $user );
1565 $logEntry->setComment( $comment );
1566 $logEntry->setTarget( $descTitle );
1567 // Allow people using the api to associate log entries with the upload.
1568 // Log has a timestamp, but sometimes different from upload timestamp.
1569 $logEntry->setParameters(
1571 'img_sha1' => $this->sha1
,
1572 'img_timestamp' => $timestamp,
1575 // Note we keep $logId around since during new image
1576 // creation, page doesn't exist yet, so log_page = 0
1577 // but we want it to point to the page we're making,
1578 // so we later modify the log entry.
1579 // For a similar reason, we avoid making an RC entry
1580 // now and wait until the page exists.
1581 $logId = $logEntry->insert();
1583 if ( $descTitle->exists() ) {
1584 // Use own context to get the action text in content language
1585 $formatter = LogFormatter
::newFromEntry( $logEntry );
1586 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1587 $editSummary = $formatter->getPlainActionText();
1589 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1596 if ( $nullRevision ) {
1597 $nullRevision->insertOn( $dbw );
1599 'NewRevisionFromEditComplete',
1600 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1602 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1603 // Associate null revision id
1604 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1607 $newPageContent = null;
1609 // Make the description page and RC log entry post-commit
1610 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1613 # Defer purges, page creation, and link updates in case they error out.
1614 # The most important thing is that files and the DB registry stay synced.
1615 $dbw->endAtomic( __METHOD__
);
1616 $fname = __METHOD__
;
1618 # Do some cache purges after final commit so that:
1619 # a) Changes are more likely to be seen post-purge
1620 # b) They won't cause rollback of the log publish/update above
1621 DeferredUpdates
::addUpdate(
1622 new AutoCommitUpdate(
1626 $reupload, $wikiPage, $newPageContent, $comment, $user,
1627 $logEntry, $logId, $descId, $tags, $fname
1629 # Update memcache after the commit
1630 $this->invalidateCache();
1632 $updateLogPage = false;
1633 if ( $newPageContent ) {
1634 # New file page; create the description page.
1635 # There's already a log entry, so don't make a second RC entry
1636 # CDN and file cache for the description page are purged by doEditContent.
1637 $status = $wikiPage->doEditContent(
1640 EDIT_NEW | EDIT_SUPPRESS_RC
,
1645 if ( isset( $status->value
['revision'] ) ) {
1646 /** @var Revision $rev */
1647 $rev = $status->value
['revision'];
1648 // Associate new page revision id
1649 $logEntry->setAssociatedRevId( $rev->getId() );
1651 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1652 // which is triggered on $descTitle by doEditContent() above.
1653 if ( isset( $status->value
['revision'] ) ) {
1654 /** @var Revision $rev */
1655 $rev = $status->value
['revision'];
1656 $updateLogPage = $rev->getPage();
1659 # Existing file page: invalidate description page cache
1660 $wikiPage->getTitle()->invalidateCache();
1661 $wikiPage->getTitle()->purgeSquid();
1662 # Allow the new file version to be patrolled from the page footer
1663 Article
::purgePatrolFooterCache( $descId );
1666 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1667 # but setAssociatedRevId() wasn't called at that point yet...
1668 $logParams = $logEntry->getParameters();
1669 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1670 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1671 if ( $updateLogPage ) {
1672 # Also log page, in case where we just created it above
1673 $update['log_page'] = $updateLogPage;
1675 $this->getRepo()->getMasterDB()->update(
1678 [ 'log_id' => $logId ],
1681 $this->getRepo()->getMasterDB()->insert(
1684 'ls_field' => 'associated_rev_id',
1685 'ls_value' => $logEntry->getAssociatedRevId(),
1686 'ls_log_id' => $logId,
1691 # Add change tags, if any
1693 $logEntry->addTags( $tags );
1696 # Uploads can be patrolled
1697 $logEntry->setIsPatrollable( true );
1699 # Now that the log entry is up-to-date, make an RC entry.
1700 $logEntry->publish( $logId );
1702 # Run hook for other updates (typically more cache purging)
1703 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1706 # Delete old thumbnails
1707 $this->purgeThumbnails();
1708 # Remove the old file from the CDN cache
1709 DeferredUpdates
::addUpdate(
1710 new CdnCacheUpdate( [ $this->getUrl() ] ),
1711 DeferredUpdates
::PRESEND
1714 # Update backlink pages pointing to this title if created
1715 LinksUpdate
::queueRecursiveJobsForTable(
1723 $this->prerenderThumbnails();
1726 DeferredUpdates
::PRESEND
1730 # This is a new file, so update the image count
1731 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1734 # Invalidate cache for all pages using this file
1735 DeferredUpdates
::addUpdate(
1736 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1739 return Status
::newGood();
1743 * Move or copy a file to its public location. If a file exists at the
1744 * destination, move it to an archive. Returns a Status object with
1745 * the archive name in the "value" member on success.
1747 * The archive name should be passed through to recordUpload for database
1750 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1751 * @param int $flags A bitwise combination of:
1752 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1753 * @param array $options Optional additional parameters
1754 * @return Status On success, the value member contains the
1755 * archive name, or an empty string if it was a new file.
1757 function publish( $src, $flags = 0, array $options = [] ) {
1758 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1762 * Move or copy a file to a specified location. Returns a Status
1763 * object with the archive name in the "value" member on success.
1765 * The archive name should be passed through to recordUpload for database
1768 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1769 * @param string $dstRel Target relative path
1770 * @param int $flags A bitwise combination of:
1771 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1772 * @param array $options Optional additional parameters
1773 * @return Status On success, the value member contains the
1774 * archive name, or an empty string if it was a new file.
1776 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1777 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1779 $repo = $this->getRepo();
1780 if ( $repo->getReadOnlyReason() !== false ) {
1781 return $this->readOnlyFatalStatus();
1786 if ( $this->isOld() ) {
1787 $archiveRel = $dstRel;
1788 $archiveName = basename( $archiveRel );
1790 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1791 $archiveRel = $this->getArchiveRel( $archiveName );
1794 if ( $repo->hasSha1Storage() ) {
1795 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1796 ?
$repo->getFileSha1( $srcPath )
1797 : FSFile
::getSha1Base36FromPath( $srcPath );
1798 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1799 $wrapperBackend = $repo->getBackend();
1800 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1801 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1802 $status = $repo->quickImport( $src, $dst );
1803 if ( $flags & File
::DELETE_SOURCE
) {
1807 if ( $this->exists() ) {
1808 $status->value
= $archiveName;
1811 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1812 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1814 if ( $status->value
== 'new' ) {
1815 $status->value
= '';
1817 $status->value
= $archiveName;
1825 /** getLinksTo inherited */
1826 /** getExifData inherited */
1827 /** isLocal inherited */
1828 /** wasDeleted inherited */
1831 * Move file to the new title
1833 * Move current, old version and all thumbnails
1834 * to the new filename. Old file is deleted.
1836 * Cache purging is done; checks for validity
1837 * and logging are caller's responsibility
1839 * @param Title $target New file name
1842 function move( $target ) {
1843 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1844 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1845 return $this->readOnlyFatalStatus();
1848 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1849 $batch = new LocalFileMoveBatch( $this, $target );
1852 $batch->addCurrent();
1853 $archiveNames = $batch->addOlds();
1854 $status = $batch->execute();
1857 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1859 // Purge the source and target files outside the transaction...
1860 $oldTitleFile = $localRepo->newFile( $this->title
);
1861 $newTitleFile = $localRepo->newFile( $target );
1862 DeferredUpdates
::addUpdate(
1863 new AutoCommitUpdate(
1864 $this->getRepo()->getMasterDB(),
1866 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1867 $oldTitleFile->purgeEverything();
1868 foreach ( $archiveNames as $archiveName ) {
1869 /** @var OldLocalFile $oldTitleFile */
1870 '@phan-var OldLocalFile $oldTitleFile';
1871 $oldTitleFile->purgeOldThumbnails( $archiveName );
1873 $newTitleFile->purgeEverything();
1876 DeferredUpdates
::PRESEND
1879 if ( $status->isOK() ) {
1880 // Now switch the object
1881 $this->title
= $target;
1882 // Force regeneration of the name and hashpath
1884 $this->hashPath
= null;
1891 * Delete all versions of the file.
1893 * Moves the files into an archive directory (or deletes them)
1894 * and removes the database rows.
1896 * Cache purging is done; logging is caller's responsibility.
1898 * @param string $reason
1899 * @param bool $suppress
1900 * @param User|null $user
1903 function delete( $reason, $suppress = false, $user = null ) {
1904 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1905 return $this->readOnlyFatalStatus();
1908 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1911 $batch->addCurrent();
1912 // Get old version relative paths
1913 $archiveNames = $batch->addOlds();
1914 $status = $batch->execute();
1917 if ( $status->isOK() ) {
1918 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1921 // To avoid slow purges in the transaction, move them outside...
1922 DeferredUpdates
::addUpdate(
1923 new AutoCommitUpdate(
1924 $this->getRepo()->getMasterDB(),
1926 function () use ( $archiveNames ) {
1927 $this->purgeEverything();
1928 foreach ( $archiveNames as $archiveName ) {
1929 $this->purgeOldThumbnails( $archiveName );
1933 DeferredUpdates
::PRESEND
1938 foreach ( $archiveNames as $archiveName ) {
1939 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1941 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1947 * Delete an old version of the file.
1949 * Moves the file into an archive directory (or deletes it)
1950 * and removes the database row.
1952 * Cache purging is done; logging is caller's responsibility.
1954 * @param string $archiveName
1955 * @param string $reason
1956 * @param bool $suppress
1957 * @param User|null $user
1958 * @throws MWException Exception on database or file store failure
1961 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1962 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1963 return $this->readOnlyFatalStatus();
1966 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1969 $batch->addOld( $archiveName );
1970 $status = $batch->execute();
1973 $this->purgeOldThumbnails( $archiveName );
1974 if ( $status->isOK() ) {
1975 $this->purgeDescription();
1978 DeferredUpdates
::addUpdate(
1979 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1980 DeferredUpdates
::PRESEND
1987 * Restore all or specified deleted revisions to the given file.
1988 * Permissions and logging are left to the caller.
1990 * May throw database exceptions on error.
1992 * @param array $versions Set of record ids of deleted items to restore,
1993 * or empty to restore all revisions.
1994 * @param bool $unsuppress
1997 function restore( $versions = [], $unsuppress = false ) {
1998 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1999 return $this->readOnlyFatalStatus();
2002 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2008 $batch->addIds( $versions );
2010 $status = $batch->execute();
2011 if ( $status->isGood() ) {
2012 $cleanupStatus = $batch->cleanup();
2013 $cleanupStatus->successCount
= 0;
2014 $cleanupStatus->failCount
= 0;
2015 $status->merge( $cleanupStatus );
2022 /** isMultipage inherited */
2023 /** pageCount inherited */
2024 /** scaleHeight inherited */
2025 /** getImageSize inherited */
2028 * Get the URL of the file description page.
2031 function getDescriptionUrl() {
2032 return $this->title
->getLocalURL();
2036 * Get the HTML text of the description page
2037 * This is not used by ImagePage for local files, since (among other things)
2038 * it skips the parser cache.
2040 * @param Language|null $lang What language to get description in (Optional)
2041 * @return string|false
2043 function getDescriptionText( Language
$lang = null ) {
2044 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2045 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2050 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2051 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2054 // audience check failed
2058 $pout = $rendered->getRevisionParserOutput();
2059 return $pout->getText();
2063 * @param int $audience
2064 * @param User|null $user
2067 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2069 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2071 } elseif ( $audience == self
::FOR_THIS_USER
2072 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2076 return $this->description
;
2081 * @return bool|string
2083 function getTimestamp() {
2086 return $this->timestamp
;
2090 * @return bool|string
2092 public function getDescriptionTouched() {
2093 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2094 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2095 // need to differentiate between null (uninitialized) and false (failed to load).
2096 if ( $this->descriptionTouched
=== null ) {
2098 'page_namespace' => $this->title
->getNamespace(),
2099 'page_title' => $this->title
->getDBkey()
2101 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2102 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2105 return $this->descriptionTouched
;
2111 function getSha1() {
2113 // Initialise now if necessary
2114 if ( $this->sha1
== '' && $this->fileExists
) {
2117 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2118 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2119 $dbw = $this->repo
->getMasterDB();
2120 $dbw->update( 'image',
2121 [ 'img_sha1' => $this->sha1
],
2122 [ 'img_name' => $this->getName() ],
2124 $this->invalidateCache();
2134 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2136 function isCacheable() {
2139 // If extra data (metadata) was not loaded then it must have been large
2140 return $this->extraDataLoaded
2141 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2148 public function acquireFileLock() {
2149 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2150 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2158 public function releaseFileLock() {
2159 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2160 [ $this->getPath() ], LockManager
::LOCK_EX
2165 * Start an atomic DB section and lock the image for update
2166 * or increments a reference counter if the lock is already held
2168 * This method should not be used outside of LocalFile/LocalFile*Batch
2170 * @throws LocalFileLockError Throws an error if the lock was not acquired
2171 * @return bool Whether the file lock owns/spawned the DB transaction
2173 public function lock() {
2174 if ( !$this->locked
) {
2175 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2177 $dbw = $this->repo
->getMasterDB();
2178 $makesTransaction = !$dbw->trxLevel();
2179 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2180 // T56736: use simple lock to handle when the file does not exist.
2181 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2182 // Also, that would cause contention on INSERT of similarly named rows.
2183 $status = $this->acquireFileLock(); // represents all versions of the file
2184 if ( !$status->isGood() ) {
2185 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2186 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2188 throw new LocalFileLockError( $status );
2190 // Release the lock *after* commit to avoid row-level contention.
2191 // Make sure it triggers on rollback() as well as commit() (T132921).
2192 $dbw->onTransactionResolution(
2193 function () use ( $logger ) {
2194 $status = $this->releaseFileLock();
2195 if ( !$status->isGood() ) {
2196 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2201 // Callers might care if the SELECT snapshot is safely fresh
2202 $this->lockedOwnTrx
= $makesTransaction;
2207 return $this->lockedOwnTrx
;
2211 * Decrement the lock reference count and end the atomic section if it reaches zero
2213 * This method should not be used outside of LocalFile/LocalFile*Batch
2215 * The commit and loc release will happen when no atomic sections are active, which
2216 * may happen immediately or at some point after calling this
2218 public function unlock() {
2219 if ( $this->locked
) {
2221 if ( !$this->locked
) {
2222 $dbw = $this->repo
->getMasterDB();
2223 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2224 $this->lockedOwnTrx
= false;
2232 protected function readOnlyFatalStatus() {
2233 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2234 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2238 * Clean up any dangling locks
2240 function __destruct() {