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 * Fields in the image table
207 * @deprecated since 1.31, use self::getQueryInfo() instead.
210 static function selectFields() {
211 global $wgActorTableSchemaMigrationStage;
213 wfDeprecated( __METHOD__
, '1.31' );
214 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
215 // If code is using this instead of self::getQueryInfo(), there's a
216 // decent chance it's going to try to directly access
217 // $row->img_user or $row->img_user_text and we can't give it
218 // useful values here once those aren't being used anymore.
219 throw new BadMethodCallException(
220 'Cannot use ' . __METHOD__
221 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
237 'img_actor' => 'NULL',
240 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
244 * Return the tables, fields, and join conditions to be selected to create
245 * a new localfile object.
247 * @param string[] $options
248 * - omit-lazy: Omit fields that are lazily cached.
249 * @return array[] With three keys:
250 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
251 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
252 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
254 public static function getQueryInfo( array $options = [] ) {
255 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
256 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
258 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
271 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
272 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
275 if ( in_array( 'omit-nonlazy', $options, true ) ) {
276 // Internal use only for getting only the lazy fields
279 if ( !in_array( 'omit-lazy', $options, true ) ) {
280 // Note: Keep this in sync with self::getLazyCacheFields()
281 $ret['fields'][] = 'img_metadata';
288 * Do not call this except from inside a repo class.
289 * @param Title $title
290 * @param FileRepo $repo
292 function __construct( $title, $repo ) {
293 parent
::__construct( $title, $repo );
295 $this->metadata
= '';
296 $this->historyLine
= 0;
297 $this->historyRes
= null;
298 $this->dataLoaded
= false;
299 $this->extraDataLoaded
= false;
301 $this->assertRepoDefined();
302 $this->assertTitleDefined();
306 * Get the memcached key for the main data for this file, or false if
307 * there is no access to the shared cache.
308 * @return string|bool
310 function getCacheKey() {
311 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
315 * @param WANObjectCache $cache
319 public function getMutableCacheKeys( WANObjectCache
$cache ) {
320 return [ $this->getCacheKey() ];
324 * Try to load file metadata from memcached, falling back to the database
326 private function loadFromCache() {
327 $this->dataLoaded
= false;
328 $this->extraDataLoaded
= false;
330 $key = $this->getCacheKey();
332 $this->loadFromDB( self
::READ_NORMAL
);
337 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
338 $cachedValues = $cache->getWithSetCallback(
341 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
342 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
344 $this->loadFromDB( self
::READ_NORMAL
);
346 $fields = $this->getCacheFields( '' );
347 $cacheVal['fileExists'] = $this->fileExists
;
348 if ( $this->fileExists
) {
349 foreach ( $fields as $field ) {
350 $cacheVal[$field] = $this->$field;
353 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
354 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
355 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
357 // Strip off excessive entries from the subset of fields that can become large.
358 // If the cache value gets to large it will not fit in memcached and nothing will
359 // get cached at all, causing master queries for any file access.
360 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
361 if ( isset( $cacheVal[$field] )
362 && strlen( $cacheVal[$field] ) > 100 * 1024
364 unset( $cacheVal[$field] ); // don't let the value get too big
368 if ( $this->fileExists
) {
369 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
371 $ttl = $cache::TTL_DAY
;
376 [ 'version' => self
::VERSION
]
379 $this->fileExists
= $cachedValues['fileExists'];
380 if ( $this->fileExists
) {
381 $this->setProps( $cachedValues );
384 $this->dataLoaded
= true;
385 $this->extraDataLoaded
= true;
386 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
387 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
392 * Purge the file object/metadata cache
394 public function invalidateCache() {
395 $key = $this->getCacheKey();
400 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
401 function () use ( $key ) {
402 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
409 * Load metadata from the file itself
411 function loadFromFile() {
412 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
413 $this->setProps( $props );
417 * Returns the list of object properties that are included as-is in the cache.
418 * @param string $prefix Must be the empty string
420 * @since 1.31 No longer accepts a non-empty $prefix
422 protected function getCacheFields( $prefix = 'img_' ) {
423 if ( $prefix !== '' ) {
424 throw new InvalidArgumentException(
425 __METHOD__
. ' with a non-empty prefix is no longer supported.'
429 // See self::getQueryInfo() for the fetching of the data from the DB,
430 // self::loadFromRow() for the loading of the object from the DB row,
431 // and self::loadFromCache() for the caching, and self::setProps() for
432 // populating the object from an array of data.
433 return [ 'size', 'width', 'height', 'bits', 'media_type',
434 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
438 * Returns the list of object properties that are included as-is in the
439 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
440 * @param string $prefix Must be the empty string
442 * @since 1.31 No longer accepts a non-empty $prefix
444 protected function getLazyCacheFields( $prefix = 'img_' ) {
445 if ( $prefix !== '' ) {
446 throw new InvalidArgumentException(
447 __METHOD__
. ' with a non-empty prefix is no longer supported.'
451 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
452 return [ 'metadata' ];
456 * Load file metadata from the DB
459 function loadFromDB( $flags = 0 ) {
460 $fname = static::class . '::' . __FUNCTION__
;
462 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
463 $this->dataLoaded
= true;
464 $this->extraDataLoaded
= true;
466 $dbr = ( $flags & self
::READ_LATEST
)
467 ?
$this->repo
->getMasterDB()
468 : $this->repo
->getReplicaDB();
470 $fileQuery = static::getQueryInfo();
471 $row = $dbr->selectRow(
472 $fileQuery['tables'],
473 $fileQuery['fields'],
474 [ 'img_name' => $this->getName() ],
481 $this->loadFromRow( $row );
483 $this->fileExists
= false;
488 * Load lazy file metadata from the DB.
489 * This covers fields that are sometimes not cached.
491 protected function loadExtraFromDB() {
492 $fname = static::class . '::' . __FUNCTION__
;
494 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
495 $this->extraDataLoaded
= true;
497 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
499 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
503 foreach ( $fieldMap as $name => $value ) {
504 $this->$name = $value;
507 throw new MWException( "Could not find data for image '{$this->getName()}'." );
512 * @param IDatabase $dbr
513 * @param string $fname
514 * @return string[]|bool
516 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
519 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
520 $row = $dbr->selectRow(
521 $fileQuery['tables'],
522 $fileQuery['fields'],
524 'img_name' => $this->getName(),
525 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
532 $fieldMap = $this->unprefixRow( $row, 'img_' );
534 # File may have been uploaded over in the meantime; check the old versions
535 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
536 $row = $dbr->selectRow(
537 $fileQuery['tables'],
538 $fileQuery['fields'],
540 'oi_name' => $this->getName(),
541 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
548 $fieldMap = $this->unprefixRow( $row, 'oi_' );
552 if ( isset( $fieldMap['metadata'] ) ) {
553 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
560 * @param array|object $row
561 * @param string $prefix
562 * @throws MWException
565 protected function unprefixRow( $row, $prefix = 'img_' ) {
566 $array = (array)$row;
567 $prefixLength = strlen( $prefix );
569 // Sanity check prefix once
570 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
571 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
575 foreach ( $array as $name => $value ) {
576 $decoded[substr( $name, $prefixLength )] = $value;
583 * Decode a row from the database (either object or array) to an array
584 * with timestamps and MIME types decoded, and the field prefix removed.
586 * @param string $prefix
587 * @throws MWException
590 function decodeRow( $row, $prefix = 'img_' ) {
591 $decoded = $this->unprefixRow( $row, $prefix );
593 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
594 ->getComment( 'description', (object)$decoded )->text
;
596 $decoded['user'] = User
::newFromAnyId(
597 $decoded['user'] ??
null,
598 $decoded['user_text'] ??
null,
599 $decoded['actor'] ??
null
601 unset( $decoded['user_text'], $decoded['actor'] );
603 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
605 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
607 if ( empty( $decoded['major_mime'] ) ) {
608 $decoded['mime'] = 'unknown/unknown';
610 if ( !$decoded['minor_mime'] ) {
611 $decoded['minor_mime'] = 'unknown';
613 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
616 // Trim zero padding from char/binary field
617 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
619 // Normalize some fields to integer type, per their database definition.
620 // Use unary + so that overflows will be upgraded to double instead of
621 // being trucated as with intval(). This is important to allow >2GB
622 // files on 32-bit systems.
623 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
624 $decoded[$field] = +
$decoded[$field];
631 * Load file metadata from a DB result row
634 * @param string $prefix
636 function loadFromRow( $row, $prefix = 'img_' ) {
637 $this->dataLoaded
= true;
638 $this->extraDataLoaded
= true;
640 $array = $this->decodeRow( $row, $prefix );
642 foreach ( $array as $name => $value ) {
643 $this->$name = $value;
646 $this->fileExists
= true;
650 * Load file metadata from cache or DB, unless already loaded
653 function load( $flags = 0 ) {
654 if ( !$this->dataLoaded
) {
655 if ( $flags & self
::READ_LATEST
) {
656 $this->loadFromDB( $flags );
658 $this->loadFromCache();
662 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
663 // @note: loads on name/timestamp to reduce race condition problems
664 $this->loadExtraFromDB();
669 * Upgrade a row if it needs it
671 protected function maybeUpgradeRow() {
672 global $wgUpdateCompatibleMetadata;
674 if ( wfReadOnly() ||
$this->upgrading
) {
679 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
682 $handler = $this->getHandler();
684 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
685 if ( $validity === MediaHandler
::METADATA_BAD
) {
687 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
688 $upgrade = $wgUpdateCompatibleMetadata;
694 $this->upgrading
= true;
695 // Defer updates unless in auto-commit CLI mode
696 DeferredUpdates
::addCallableUpdate( function () {
697 $this->upgrading
= false; // avoid duplicate updates
700 } catch ( LocalFileLockError
$e ) {
701 // let the other process handle it (or do it next time)
708 * @return bool Whether upgradeRow() ran for this object
710 function getUpgraded() {
711 return $this->upgraded
;
715 * Fix assorted version-related problems with the image row by reloading it from the file
717 function upgradeRow() {
720 $this->loadFromFile();
722 # Don't destroy file info of missing files
723 if ( !$this->fileExists
) {
725 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
730 $dbw = $this->repo
->getMasterDB();
731 list( $major, $minor ) = self
::splitMime( $this->mime
);
733 if ( wfReadOnly() ) {
738 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
740 $dbw->update( 'image',
742 'img_size' => $this->size
, // sanity
743 'img_width' => $this->width
,
744 'img_height' => $this->height
,
745 'img_bits' => $this->bits
,
746 'img_media_type' => $this->media_type
,
747 'img_major_mime' => $major,
748 'img_minor_mime' => $minor,
749 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
750 'img_sha1' => $this->sha1
,
752 [ 'img_name' => $this->getName() ],
756 $this->invalidateCache();
759 $this->upgraded
= true; // avoid rework/retries
763 * Set properties in this object to be equal to those given in the
764 * associative array $info. Only cacheable fields can be set.
765 * All fields *must* be set in $info except for getLazyCacheFields().
767 * If 'mime' is given, it will be split into major_mime/minor_mime.
768 * If major_mime/minor_mime are given, $this->mime will also be set.
772 function setProps( $info ) {
773 $this->dataLoaded
= true;
774 $fields = $this->getCacheFields( '' );
775 $fields[] = 'fileExists';
777 foreach ( $fields as $field ) {
778 if ( isset( $info[$field] ) ) {
779 $this->$field = $info[$field];
783 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
784 $this->user
= User
::newFromAnyId(
785 $info['user'] ??
null,
786 $info['user_text'] ??
null,
787 $info['actor'] ??
null
791 // Fix up mime fields
792 if ( isset( $info['major_mime'] ) ) {
793 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
794 } elseif ( isset( $info['mime'] ) ) {
795 $this->mime
= $info['mime'];
796 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
800 /** splitMime inherited */
801 /** getName inherited */
802 /** getTitle inherited */
803 /** getURL inherited */
804 /** getViewURL inherited */
805 /** getPath inherited */
806 /** isVisible inherited */
809 * Checks if this file exists in its parent repo, as referenced by its
814 function isMissing() {
815 if ( $this->missing
=== null ) {
816 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
817 $this->missing
= !$fileExists;
820 return $this->missing
;
824 * Return the width of the image
829 public function getWidth( $page = 1 ) {
837 if ( $this->isMultipage() ) {
838 $handler = $this->getHandler();
842 $dim = $handler->getPageDimensions( $this, $page );
844 return $dim['width'];
846 // For non-paged media, the false goes through an
847 // intval, turning failure into 0, so do same here.
856 * Return the height of the image
861 public function getHeight( $page = 1 ) {
869 if ( $this->isMultipage() ) {
870 $handler = $this->getHandler();
874 $dim = $handler->getPageDimensions( $this, $page );
876 return $dim['height'];
878 // For non-paged media, the false goes through an
879 // intval, turning failure into 0, so do same here.
883 return $this->height
;
888 * Returns user who uploaded the file
890 * @param string $type 'text', 'id', or 'object'
891 * @return int|string|User
892 * @since 1.31 Added 'object'
894 function getUser( $type = 'text' ) {
897 if ( $type === 'object' ) {
899 } elseif ( $type === 'text' ) {
900 return $this->user
->getName();
901 } elseif ( $type === 'id' ) {
902 return $this->user
->getId();
905 throw new MWException( "Unknown type '$type'." );
909 * Get short description URL for a file based on the page ID.
911 * @return string|null
912 * @throws MWException
915 public function getDescriptionShortUrl() {
916 $pageId = $this->title
->getArticleID();
918 if ( $pageId !== null ) {
919 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
920 if ( $url !== false ) {
928 * Get handler-specific metadata
931 function getMetadata() {
932 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
933 return $this->metadata
;
939 function getBitDepth() {
942 return (int)$this->bits
;
946 * Returns the size of the image file, in bytes
949 public function getSize() {
956 * Returns the MIME type of the file.
959 function getMimeType() {
966 * Returns the type of the media in the file.
967 * Use the value returned by this function with the MEDIATYPE_xxx constants.
970 function getMediaType() {
973 return $this->media_type
;
976 /** canRender inherited */
977 /** mustRender inherited */
978 /** allowInlineDisplay inherited */
979 /** isSafeFile inherited */
980 /** isTrustedFile inherited */
983 * Returns true if the file exists on disk.
984 * @return bool Whether file exist on disk.
986 public function exists() {
989 return $this->fileExists
;
992 /** getTransformScript inherited */
993 /** getUnscaledThumb inherited */
994 /** thumbName inherited */
995 /** createThumb inherited */
996 /** transform inherited */
998 /** getHandler inherited */
999 /** iconThumb inherited */
1000 /** getLastError inherited */
1003 * Get all thumbnail names previously generated for this file
1004 * @param string|bool $archiveName Name of an archive file, default false
1005 * @return array First element is the base dir, then files in that base dir.
1007 function getThumbnails( $archiveName = false ) {
1008 if ( $archiveName ) {
1009 $dir = $this->getArchiveThumbPath( $archiveName );
1011 $dir = $this->getThumbPath();
1014 $backend = $this->repo
->getBackend();
1017 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1018 foreach ( $iterator as $file ) {
1021 } catch ( FileBackendError
$e ) {
1022 } // suppress (T56674)
1028 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1030 function purgeMetadataCache() {
1031 $this->invalidateCache();
1035 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1037 * @param array $options An array potentially with the key forThumbRefresh.
1039 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1041 function purgeCache( $options = [] ) {
1042 // Refresh metadata cache
1043 $this->maybeUpgradeRow();
1044 $this->purgeMetadataCache();
1046 // Delete thumbnails
1047 $this->purgeThumbnails( $options );
1049 // Purge CDN cache for this file
1050 DeferredUpdates
::addUpdate(
1051 new CdnCacheUpdate( [ $this->getUrl() ] ),
1052 DeferredUpdates
::PRESEND
1057 * Delete cached transformed files for an archived version only.
1058 * @param string $archiveName Name of the archived file
1060 function purgeOldThumbnails( $archiveName ) {
1061 // Get a list of old thumbnails and URLs
1062 $files = $this->getThumbnails( $archiveName );
1064 // Purge any custom thumbnail caches
1065 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1067 // Delete thumbnails
1068 $dir = array_shift( $files );
1069 $this->purgeThumbList( $dir, $files );
1073 foreach ( $files as $file ) {
1074 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1076 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1080 * Delete cached transformed files for the current version only.
1081 * @param array $options
1083 public function purgeThumbnails( $options = [] ) {
1084 $files = $this->getThumbnails();
1085 // Always purge all files from CDN regardless of handler filters
1087 foreach ( $files as $file ) {
1088 $urls[] = $this->getThumbUrl( $file );
1090 array_shift( $urls ); // don't purge directory
1092 // Give media handler a chance to filter the file purge list
1093 if ( !empty( $options['forThumbRefresh'] ) ) {
1094 $handler = $this->getHandler();
1096 $handler->filterThumbnailPurgeList( $files, $options );
1100 // Purge any custom thumbnail caches
1101 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1103 // Delete thumbnails
1104 $dir = array_shift( $files );
1105 $this->purgeThumbList( $dir, $files );
1108 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1112 * Prerenders a configurable set of thumbnails
1116 public function prerenderThumbnails() {
1117 global $wgUploadThumbnailRenderMap;
1121 $sizes = $wgUploadThumbnailRenderMap;
1124 foreach ( $sizes as $size ) {
1125 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1126 $jobs[] = new ThumbnailRenderJob(
1128 [ 'transformParams' => [ 'width' => $size ] ]
1134 JobQueueGroup
::singleton()->lazyPush( $jobs );
1139 * Delete a list of thumbnails visible at urls
1140 * @param string $dir Base dir of the files.
1141 * @param array $files Array of strings: relative filenames (to $dir)
1143 protected function purgeThumbList( $dir, $files ) {
1144 $fileListDebug = strtr(
1145 var_export( $files, true ),
1148 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1151 foreach ( $files as $file ) {
1152 if ( $this->repo
->supportsSha1URLs() ) {
1153 $reference = $this->getSha1();
1155 $reference = $this->getName();
1158 # Check that the reference (filename or sha1) is part of the thumb name
1159 # This is a basic sanity check to avoid erasing unrelated directories
1160 if ( strpos( $file, $reference ) !== false
1161 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1163 $purgeList[] = "{$dir}/{$file}";
1167 # Delete the thumbnails
1168 $this->repo
->quickPurgeBatch( $purgeList );
1169 # Clear out the thumbnail directory if empty
1170 $this->repo
->quickCleanDir( $dir );
1173 /** purgeDescription inherited */
1174 /** purgeEverything inherited */
1177 * @param int|null $limit Optional: Limit to number of results
1178 * @param string|int|null $start Optional: Timestamp, start from
1179 * @param string|int|null $end Optional: Timestamp, end at
1181 * @return OldLocalFile[]
1183 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1184 $dbr = $this->repo
->getReplicaDB();
1185 $oldFileQuery = OldLocalFile
::getQueryInfo();
1187 $tables = $oldFileQuery['tables'];
1188 $fields = $oldFileQuery['fields'];
1189 $join_conds = $oldFileQuery['joins'];
1190 $conds = $opts = [];
1191 $eq = $inc ?
'=' : '';
1192 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1195 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1199 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1203 $opts['LIMIT'] = $limit;
1206 // Search backwards for time > x queries
1207 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1208 $opts['ORDER BY'] = "oi_timestamp $order";
1209 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1211 // Avoid PHP 7.1 warning from passing $this by reference
1213 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1214 &$conds, &$opts, &$join_conds ] );
1216 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1219 foreach ( $res as $row ) {
1220 $r[] = $this->repo
->newFileFromRow( $row );
1223 if ( $order == 'ASC' ) {
1224 $r = array_reverse( $r ); // make sure it ends up descending
1231 * Returns the history of this file, line by line.
1232 * starts with current version, then old versions.
1233 * uses $this->historyLine to check which line to return:
1234 * 0 return line for current version
1235 * 1 query for old versions, return first one
1236 * 2, ... return next old version from above query
1239 public function nextHistoryLine() {
1240 # Polymorphic function name to distinguish foreign and local fetches
1241 $fname = static::class . '::' . __FUNCTION__
;
1243 $dbr = $this->repo
->getReplicaDB();
1245 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1246 $fileQuery = self
::getQueryInfo();
1247 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1248 $fileQuery['fields'] +
[
1249 'oi_archive_name' => $dbr->addQuotes( '' ),
1252 [ 'img_name' => $this->title
->getDBkey() ],
1258 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1259 $this->historyRes
= null;
1263 } elseif ( $this->historyLine
== 1 ) {
1264 $fileQuery = OldLocalFile
::getQueryInfo();
1265 $this->historyRes
= $dbr->select(
1266 $fileQuery['tables'],
1267 $fileQuery['fields'],
1268 [ 'oi_name' => $this->title
->getDBkey() ],
1270 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1274 $this->historyLine++
;
1276 return $dbr->fetchObject( $this->historyRes
);
1280 * Reset the history pointer to the first element of the history
1282 public function resetHistory() {
1283 $this->historyLine
= 0;
1285 if ( !is_null( $this->historyRes
) ) {
1286 $this->historyRes
= null;
1290 /** getHashPath inherited */
1291 /** getRel inherited */
1292 /** getUrlRel inherited */
1293 /** getArchiveRel inherited */
1294 /** getArchivePath inherited */
1295 /** getThumbPath inherited */
1296 /** getArchiveUrl inherited */
1297 /** getThumbUrl inherited */
1298 /** getArchiveVirtualUrl inherited */
1299 /** getThumbVirtualUrl inherited */
1300 /** isHashed inherited */
1303 * Upload a file and record it in the DB
1304 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1305 * @param string $comment Upload description
1306 * @param string $pageText Text to use for the new description page,
1307 * if a new description page is created
1308 * @param int|bool $flags Flags for publish()
1309 * @param array|bool $props File properties, if known. This can be used to
1310 * reduce the upload time when uploading virtual URLs for which the file
1311 * info is already known
1312 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1314 * @param User|null $user User object or null to use $wgUser
1315 * @param string[] $tags Change tags to add to the log entry and page revision.
1316 * (This doesn't check $user's permissions.)
1317 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1318 * upload, see T193621
1319 * @param bool $revert If this file upload is a revert
1320 * @return Status On success, the value member contains the
1321 * archive name, or an empty string if it was a new file.
1323 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1324 $timestamp = false, $user = null, $tags = [],
1325 $createNullRevision = true, $revert = false
1327 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1328 return $this->readOnlyFatalStatus();
1329 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1330 // Check this in advance to avoid writing to FileBackend and the file tables,
1331 // only to fail on insert the revision due to the text store being unavailable.
1332 return $this->readOnlyFatalStatus();
1335 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1337 if ( FileRepo
::isVirtualUrl( $srcPath )
1338 || FileBackend
::isStoragePath( $srcPath )
1340 $props = $this->repo
->getFileProps( $srcPath );
1342 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1343 $props = $mwProps->getPropsFromPath( $srcPath, true );
1348 $handler = MediaHandler
::getHandler( $props['mime'] );
1350 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1352 if ( !is_array( $metadata ) ) {
1356 $options['headers'] = $handler->getContentHeaders( $metadata );
1358 $options['headers'] = [];
1361 // Trim spaces on user supplied text
1362 $comment = trim( $comment );
1365 $status = $this->publish( $src, $flags, $options );
1367 if ( $status->successCount
>= 2 ) {
1368 // There will be a copy+(one of move,copy,store).
1369 // The first succeeding does not commit us to updating the DB
1370 // since it simply copied the current version to a timestamped file name.
1371 // It is only *preferable* to avoid leaving such files orphaned.
1372 // Once the second operation goes through, then the current version was
1373 // updated and we must therefore update the DB too.
1374 $oldver = $status->value
;
1375 $uploadStatus = $this->recordUpload2(
1383 $createNullRevision,
1386 if ( !$uploadStatus->isOK() ) {
1387 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1388 // update filenotfound error with more specific path
1389 $status->fatal( 'filenotfound', $srcPath );
1391 $status->merge( $uploadStatus );
1401 * Record a file upload in the upload log and the image table
1402 * @param string $oldver
1403 * @param string $desc
1404 * @param string $license
1405 * @param string $copyStatus
1406 * @param string $source
1407 * @param bool $watch
1408 * @param string|bool $timestamp
1409 * @param User|null $user User object or null to use $wgUser
1412 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1413 $watch = false, $timestamp = false, User
$user = null ) {
1419 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1421 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1426 $user->addWatch( $this->getTitle() );
1433 * Record a file upload in the upload log and the image table
1434 * @param string $oldver
1435 * @param string $comment
1436 * @param string $pageText
1437 * @param bool|array $props
1438 * @param string|bool $timestamp
1439 * @param null|User $user
1440 * @param string[] $tags
1441 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1442 * upload, see T193621
1443 * @param bool $revert If this file upload is a revert
1446 function recordUpload2(
1447 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1448 $createNullRevision = true, $revert = false
1450 global $wgActorTableSchemaMigrationStage;
1452 if ( is_null( $user ) ) {
1457 $dbw = $this->repo
->getMasterDB();
1459 # Imports or such might force a certain timestamp; otherwise we generate
1460 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1461 if ( $timestamp === false ) {
1462 $timestamp = $dbw->timestamp();
1463 $allowTimeKludge = true;
1465 $allowTimeKludge = false;
1468 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1469 $props['description'] = $comment;
1470 $props['user'] = $user->getId();
1471 $props['user_text'] = $user->getName();
1472 $props['actor'] = $user->getActorId( $dbw );
1473 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1474 $this->setProps( $props );
1476 # Fail now if the file isn't there
1477 if ( !$this->fileExists
) {
1478 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1480 return Status
::newFatal( 'filenotfound', $this->getRel() );
1483 $dbw->startAtomic( __METHOD__
);
1485 # Test to see if the row exists using INSERT IGNORE
1486 # This avoids race conditions by locking the row until the commit, and also
1487 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1488 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1489 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1490 $actorMigration = ActorMigration
::newMigration();
1491 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1492 $dbw->insert( 'image',
1494 'img_name' => $this->getName(),
1495 'img_size' => $this->size
,
1496 'img_width' => intval( $this->width
),
1497 'img_height' => intval( $this->height
),
1498 'img_bits' => $this->bits
,
1499 'img_media_type' => $this->media_type
,
1500 'img_major_mime' => $this->major_mime
,
1501 'img_minor_mime' => $this->minor_mime
,
1502 'img_timestamp' => $timestamp,
1503 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1504 'img_sha1' => $this->sha1
1505 ] +
$commentFields +
$actorFields,
1509 $reupload = ( $dbw->affectedRows() == 0 );
1512 $row = $dbw->selectRow(
1514 [ 'img_timestamp', 'img_sha1' ],
1515 [ 'img_name' => $this->getName() ],
1517 [ 'LOCK IN SHARE MODE' ]
1520 if ( $row && $row->img_sha1
=== $this->sha1
) {
1521 $dbw->endAtomic( __METHOD__
);
1522 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1523 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1524 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1527 if ( $allowTimeKludge ) {
1528 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1529 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1530 # Avoid a timestamp that is not newer than the last version
1531 # TODO: the image/oldimage tables should be like page/revision with an ID field
1532 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1533 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1534 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1535 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1539 $tables = [ 'image' ];
1541 'oi_name' => 'img_name',
1542 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1543 'oi_size' => 'img_size',
1544 'oi_width' => 'img_width',
1545 'oi_height' => 'img_height',
1546 'oi_bits' => 'img_bits',
1547 'oi_description_id' => 'img_description_id',
1548 'oi_timestamp' => 'img_timestamp',
1549 'oi_metadata' => 'img_metadata',
1550 'oi_media_type' => 'img_media_type',
1551 'oi_major_mime' => 'img_major_mime',
1552 'oi_minor_mime' => 'img_minor_mime',
1553 'oi_sha1' => 'img_sha1',
1557 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1558 $fields['oi_user'] = 'img_user';
1559 $fields['oi_user_text'] = 'img_user_text';
1561 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1562 $fields['oi_actor'] = 'img_actor';
1566 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1568 // Upgrade any rows that are still old-style. Otherwise an upgrade
1569 // might be missed if a deletion happens while the migration script
1571 $res = $dbw->select(
1573 [ 'img_name', 'img_user', 'img_user_text' ],
1574 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1577 foreach ( $res as $row ) {
1578 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1581 [ 'img_actor' => $actorId ],
1582 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1588 # (T36993) Note: $oldver can be empty here, if the previous
1589 # version of the file was broken. Allow registration of the new
1590 # version to continue anyway, because that's better than having
1591 # an image that's not fixable by user operations.
1592 # Collision, this is an update of a file
1593 # Insert previous contents into oldimage
1594 $dbw->insertSelect( 'oldimage', $tables, $fields,
1595 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1597 # Update the current image row
1598 $dbw->update( 'image',
1600 'img_size' => $this->size
,
1601 'img_width' => intval( $this->width
),
1602 'img_height' => intval( $this->height
),
1603 'img_bits' => $this->bits
,
1604 'img_media_type' => $this->media_type
,
1605 'img_major_mime' => $this->major_mime
,
1606 'img_minor_mime' => $this->minor_mime
,
1607 'img_timestamp' => $timestamp,
1608 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1609 'img_sha1' => $this->sha1
1610 ] +
$commentFields +
$actorFields,
1611 [ 'img_name' => $this->getName() ],
1616 $descTitle = $this->getTitle();
1617 $descId = $descTitle->getArticleID();
1618 $wikiPage = new WikiFilePage( $descTitle );
1619 $wikiPage->setFile( $this );
1621 // Determine log action. If reupload is done by reverting, use a special log_action.
1622 if ( $revert === true ) {
1623 $logAction = 'revert';
1624 } elseif ( $reupload === true ) {
1625 $logAction = 'overwrite';
1627 $logAction = 'upload';
1629 // Add the log entry...
1630 $logEntry = new ManualLogEntry( 'upload', $logAction );
1631 $logEntry->setTimestamp( $this->timestamp
);
1632 $logEntry->setPerformer( $user );
1633 $logEntry->setComment( $comment );
1634 $logEntry->setTarget( $descTitle );
1635 // Allow people using the api to associate log entries with the upload.
1636 // Log has a timestamp, but sometimes different from upload timestamp.
1637 $logEntry->setParameters(
1639 'img_sha1' => $this->sha1
,
1640 'img_timestamp' => $timestamp,
1643 // Note we keep $logId around since during new image
1644 // creation, page doesn't exist yet, so log_page = 0
1645 // but we want it to point to the page we're making,
1646 // so we later modify the log entry.
1647 // For a similar reason, we avoid making an RC entry
1648 // now and wait until the page exists.
1649 $logId = $logEntry->insert();
1651 if ( $descTitle->exists() ) {
1652 // Use own context to get the action text in content language
1653 $formatter = LogFormatter
::newFromEntry( $logEntry );
1654 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1655 $editSummary = $formatter->getPlainActionText();
1657 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1664 if ( $nullRevision ) {
1665 $nullRevision->insertOn( $dbw );
1667 'NewRevisionFromEditComplete',
1668 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1670 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1671 // Associate null revision id
1672 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1675 $newPageContent = null;
1677 // Make the description page and RC log entry post-commit
1678 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1681 # Defer purges, page creation, and link updates in case they error out.
1682 # The most important thing is that files and the DB registry stay synced.
1683 $dbw->endAtomic( __METHOD__
);
1684 $fname = __METHOD__
;
1686 # Do some cache purges after final commit so that:
1687 # a) Changes are more likely to be seen post-purge
1688 # b) They won't cause rollback of the log publish/update above
1689 DeferredUpdates
::addUpdate(
1690 new AutoCommitUpdate(
1694 $reupload, $wikiPage, $newPageContent, $comment, $user,
1695 $logEntry, $logId, $descId, $tags, $fname
1697 # Update memcache after the commit
1698 $this->invalidateCache();
1700 $updateLogPage = false;
1701 if ( $newPageContent ) {
1702 # New file page; create the description page.
1703 # There's already a log entry, so don't make a second RC entry
1704 # CDN and file cache for the description page are purged by doEditContent.
1705 $status = $wikiPage->doEditContent(
1708 EDIT_NEW | EDIT_SUPPRESS_RC
,
1713 if ( isset( $status->value
['revision'] ) ) {
1714 /** @var Revision $rev */
1715 $rev = $status->value
['revision'];
1716 // Associate new page revision id
1717 $logEntry->setAssociatedRevId( $rev->getId() );
1719 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1720 // which is triggered on $descTitle by doEditContent() above.
1721 if ( isset( $status->value
['revision'] ) ) {
1722 /** @var Revision $rev */
1723 $rev = $status->value
['revision'];
1724 $updateLogPage = $rev->getPage();
1727 # Existing file page: invalidate description page cache
1728 $wikiPage->getTitle()->invalidateCache();
1729 $wikiPage->getTitle()->purgeSquid();
1730 # Allow the new file version to be patrolled from the page footer
1731 Article
::purgePatrolFooterCache( $descId );
1734 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1735 # but setAssociatedRevId() wasn't called at that point yet...
1736 $logParams = $logEntry->getParameters();
1737 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1738 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1739 if ( $updateLogPage ) {
1740 # Also log page, in case where we just created it above
1741 $update['log_page'] = $updateLogPage;
1743 $this->getRepo()->getMasterDB()->update(
1746 [ 'log_id' => $logId ],
1749 $this->getRepo()->getMasterDB()->insert(
1752 'ls_field' => 'associated_rev_id',
1753 'ls_value' => $logEntry->getAssociatedRevId(),
1754 'ls_log_id' => $logId,
1759 # Add change tags, if any
1761 $logEntry->setTags( $tags );
1764 # Uploads can be patrolled
1765 $logEntry->setIsPatrollable( true );
1767 # Now that the log entry is up-to-date, make an RC entry.
1768 $logEntry->publish( $logId );
1770 # Run hook for other updates (typically more cache purging)
1771 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1774 # Delete old thumbnails
1775 $this->purgeThumbnails();
1776 # Remove the old file from the CDN cache
1777 DeferredUpdates
::addUpdate(
1778 new CdnCacheUpdate( [ $this->getUrl() ] ),
1779 DeferredUpdates
::PRESEND
1782 # Update backlink pages pointing to this title if created
1783 LinksUpdate
::queueRecursiveJobsForTable(
1791 $this->prerenderThumbnails();
1794 DeferredUpdates
::PRESEND
1798 # This is a new file, so update the image count
1799 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1802 # Invalidate cache for all pages using this file
1803 DeferredUpdates
::addUpdate(
1804 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1807 return Status
::newGood();
1811 * Move or copy a file to its public location. If a file exists at the
1812 * destination, move it to an archive. Returns a Status object with
1813 * the archive name in the "value" member on success.
1815 * The archive name should be passed through to recordUpload for database
1818 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1819 * @param int $flags A bitwise combination of:
1820 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1821 * @param array $options Optional additional parameters
1822 * @return Status On success, the value member contains the
1823 * archive name, or an empty string if it was a new file.
1825 function publish( $src, $flags = 0, array $options = [] ) {
1826 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1830 * Move or copy a file to a specified location. Returns a Status
1831 * object with the archive name in the "value" member on success.
1833 * The archive name should be passed through to recordUpload for database
1836 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1837 * @param string $dstRel Target relative path
1838 * @param int $flags A bitwise combination of:
1839 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1840 * @param array $options Optional additional parameters
1841 * @return Status On success, the value member contains the
1842 * archive name, or an empty string if it was a new file.
1844 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1845 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1847 $repo = $this->getRepo();
1848 if ( $repo->getReadOnlyReason() !== false ) {
1849 return $this->readOnlyFatalStatus();
1854 if ( $this->isOld() ) {
1855 $archiveRel = $dstRel;
1856 $archiveName = basename( $archiveRel );
1858 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1859 $archiveRel = $this->getArchiveRel( $archiveName );
1862 if ( $repo->hasSha1Storage() ) {
1863 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1864 ?
$repo->getFileSha1( $srcPath )
1865 : FSFile
::getSha1Base36FromPath( $srcPath );
1866 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1867 $wrapperBackend = $repo->getBackend();
1868 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1869 $status = $repo->quickImport( $src, $dst );
1870 if ( $flags & File
::DELETE_SOURCE
) {
1874 if ( $this->exists() ) {
1875 $status->value
= $archiveName;
1878 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1879 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1881 if ( $status->value
== 'new' ) {
1882 $status->value
= '';
1884 $status->value
= $archiveName;
1892 /** getLinksTo inherited */
1893 /** getExifData inherited */
1894 /** isLocal inherited */
1895 /** wasDeleted inherited */
1898 * Move file to the new title
1900 * Move current, old version and all thumbnails
1901 * to the new filename. Old file is deleted.
1903 * Cache purging is done; checks for validity
1904 * and logging are caller's responsibility
1906 * @param Title $target New file name
1909 function move( $target ) {
1910 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1911 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1912 return $this->readOnlyFatalStatus();
1915 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1916 $batch = new LocalFileMoveBatch( $this, $target );
1919 $batch->addCurrent();
1920 $archiveNames = $batch->addOlds();
1921 $status = $batch->execute();
1924 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1926 // Purge the source and target files outside the transaction...
1927 $oldTitleFile = $localRepo->newFile( $this->title
);
1928 $newTitleFile = $localRepo->newFile( $target );
1929 DeferredUpdates
::addUpdate(
1930 new AutoCommitUpdate(
1931 $this->getRepo()->getMasterDB(),
1933 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1934 $oldTitleFile->purgeEverything();
1935 foreach ( $archiveNames as $archiveName ) {
1936 /** @var OldLocalFile $oldTitleFile */
1937 $oldTitleFile->purgeOldThumbnails( $archiveName );
1939 $newTitleFile->purgeEverything();
1942 DeferredUpdates
::PRESEND
1945 if ( $status->isOK() ) {
1946 // Now switch the object
1947 $this->title
= $target;
1948 // Force regeneration of the name and hashpath
1950 $this->hashPath
= null;
1957 * Delete all versions of the file.
1959 * Moves the files into an archive directory (or deletes them)
1960 * and removes the database rows.
1962 * Cache purging is done; logging is caller's responsibility.
1964 * @param string $reason
1965 * @param bool $suppress
1966 * @param User|null $user
1969 function delete( $reason, $suppress = false, $user = null ) {
1970 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1971 return $this->readOnlyFatalStatus();
1974 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1977 $batch->addCurrent();
1978 // Get old version relative paths
1979 $archiveNames = $batch->addOlds();
1980 $status = $batch->execute();
1983 if ( $status->isOK() ) {
1984 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1987 // To avoid slow purges in the transaction, move them outside...
1988 DeferredUpdates
::addUpdate(
1989 new AutoCommitUpdate(
1990 $this->getRepo()->getMasterDB(),
1992 function () use ( $archiveNames ) {
1993 $this->purgeEverything();
1994 foreach ( $archiveNames as $archiveName ) {
1995 $this->purgeOldThumbnails( $archiveName );
1999 DeferredUpdates
::PRESEND
2004 foreach ( $archiveNames as $archiveName ) {
2005 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2007 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2013 * Delete an old version of the file.
2015 * Moves the file into an archive directory (or deletes it)
2016 * and removes the database row.
2018 * Cache purging is done; logging is caller's responsibility.
2020 * @param string $archiveName
2021 * @param string $reason
2022 * @param bool $suppress
2023 * @param User|null $user
2024 * @throws MWException Exception on database or file store failure
2027 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2028 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2029 return $this->readOnlyFatalStatus();
2032 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2035 $batch->addOld( $archiveName );
2036 $status = $batch->execute();
2039 $this->purgeOldThumbnails( $archiveName );
2040 if ( $status->isOK() ) {
2041 $this->purgeDescription();
2044 DeferredUpdates
::addUpdate(
2045 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2046 DeferredUpdates
::PRESEND
2053 * Restore all or specified deleted revisions to the given file.
2054 * Permissions and logging are left to the caller.
2056 * May throw database exceptions on error.
2058 * @param array $versions Set of record ids of deleted items to restore,
2059 * or empty to restore all revisions.
2060 * @param bool $unsuppress
2063 function restore( $versions = [], $unsuppress = false ) {
2064 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2065 return $this->readOnlyFatalStatus();
2068 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2074 $batch->addIds( $versions );
2076 $status = $batch->execute();
2077 if ( $status->isGood() ) {
2078 $cleanupStatus = $batch->cleanup();
2079 $cleanupStatus->successCount
= 0;
2080 $cleanupStatus->failCount
= 0;
2081 $status->merge( $cleanupStatus );
2088 /** isMultipage inherited */
2089 /** pageCount inherited */
2090 /** scaleHeight inherited */
2091 /** getImageSize inherited */
2094 * Get the URL of the file description page.
2097 function getDescriptionUrl() {
2098 return $this->title
->getLocalURL();
2102 * Get the HTML text of the description page
2103 * This is not used by ImagePage for local files, since (among other things)
2104 * it skips the parser cache.
2106 * @param Language|null $lang What language to get description in (Optional)
2107 * @return string|false
2109 function getDescriptionText( Language
$lang = null ) {
2110 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2111 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2116 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2117 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2120 // audience check failed
2124 $pout = $rendered->getRevisionParserOutput();
2125 return $pout->getText();
2129 * @param int $audience
2130 * @param User|null $user
2133 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2135 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2137 } elseif ( $audience == self
::FOR_THIS_USER
2138 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2142 return $this->description
;
2147 * @return bool|string
2149 function getTimestamp() {
2152 return $this->timestamp
;
2156 * @return bool|string
2158 public function getDescriptionTouched() {
2159 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2160 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2161 // need to differentiate between null (uninitialized) and false (failed to load).
2162 if ( $this->descriptionTouched
=== null ) {
2164 'page_namespace' => $this->title
->getNamespace(),
2165 'page_title' => $this->title
->getDBkey()
2167 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2168 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2171 return $this->descriptionTouched
;
2177 function getSha1() {
2179 // Initialise now if necessary
2180 if ( $this->sha1
== '' && $this->fileExists
) {
2183 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2184 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2185 $dbw = $this->repo
->getMasterDB();
2186 $dbw->update( 'image',
2187 [ 'img_sha1' => $this->sha1
],
2188 [ 'img_name' => $this->getName() ],
2190 $this->invalidateCache();
2200 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2202 function isCacheable() {
2205 // If extra data (metadata) was not loaded then it must have been large
2206 return $this->extraDataLoaded
2207 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2214 public function acquireFileLock() {
2215 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2216 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2224 public function releaseFileLock() {
2225 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2226 [ $this->getPath() ], LockManager
::LOCK_EX
2231 * Start an atomic DB section and lock the image for update
2232 * or increments a reference counter if the lock is already held
2234 * This method should not be used outside of LocalFile/LocalFile*Batch
2236 * @throws LocalFileLockError Throws an error if the lock was not acquired
2237 * @return bool Whether the file lock owns/spawned the DB transaction
2239 public function lock() {
2240 if ( !$this->locked
) {
2241 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2243 $dbw = $this->repo
->getMasterDB();
2244 $makesTransaction = !$dbw->trxLevel();
2245 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2246 // T56736: use simple lock to handle when the file does not exist.
2247 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2248 // Also, that would cause contention on INSERT of similarly named rows.
2249 $status = $this->acquireFileLock(); // represents all versions of the file
2250 if ( !$status->isGood() ) {
2251 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2252 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2254 throw new LocalFileLockError( $status );
2256 // Release the lock *after* commit to avoid row-level contention.
2257 // Make sure it triggers on rollback() as well as commit() (T132921).
2258 $dbw->onTransactionResolution(
2259 function () use ( $logger ) {
2260 $status = $this->releaseFileLock();
2261 if ( !$status->isGood() ) {
2262 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2267 // Callers might care if the SELECT snapshot is safely fresh
2268 $this->lockedOwnTrx
= $makesTransaction;
2273 return $this->lockedOwnTrx
;
2277 * Decrement the lock reference count and end the atomic section if it reaches zero
2279 * This method should not be used outside of LocalFile/LocalFile*Batch
2281 * The commit and loc release will happen when no atomic sections are active, which
2282 * may happen immediately or at some point after calling this
2284 public function unlock() {
2285 if ( $this->locked
) {
2287 if ( !$this->locked
) {
2288 $dbw = $this->repo
->getMasterDB();
2289 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2290 $this->lockedOwnTrx
= false;
2298 protected function readOnlyFatalStatus() {
2299 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2300 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2304 * Clean up any dangling locks
2306 function __destruct() {