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( '' );
348 $cacheVal['fileExists'] = $this->fileExists
;
349 if ( $this->fileExists
) {
350 foreach ( $fields as $field ) {
351 $cacheVal[$field] = $this->$field;
354 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
355 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
356 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
358 // Strip off excessive entries from the subset of fields that can become large.
359 // If the cache value gets to large it will not fit in memcached and nothing will
360 // get cached at all, causing master queries for any file access.
361 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
362 if ( isset( $cacheVal[$field] )
363 && strlen( $cacheVal[$field] ) > 100 * 1024
365 unset( $cacheVal[$field] ); // don't let the value get too big
369 if ( $this->fileExists
) {
370 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
372 $ttl = $cache::TTL_DAY
;
377 [ 'version' => self
::VERSION
]
380 $this->fileExists
= $cachedValues['fileExists'];
381 if ( $this->fileExists
) {
382 $this->setProps( $cachedValues );
385 $this->dataLoaded
= true;
386 $this->extraDataLoaded
= true;
387 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
388 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
393 * Purge the file object/metadata cache
395 public function invalidateCache() {
396 $key = $this->getCacheKey();
401 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
402 function () use ( $key ) {
403 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
410 * Load metadata from the file itself
412 function loadFromFile() {
413 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
414 $this->setProps( $props );
418 * Returns the list of object properties that are included as-is in the cache.
419 * @param string $prefix Must be the empty string
421 * @since 1.31 No longer accepts a non-empty $prefix
423 protected function getCacheFields( $prefix = 'img_' ) {
424 if ( $prefix !== '' ) {
425 throw new InvalidArgumentException(
426 __METHOD__
. ' with a non-empty prefix is no longer supported.'
430 // See self::getQueryInfo() for the fetching of the data from the DB,
431 // self::loadFromRow() for the loading of the object from the DB row,
432 // and self::loadFromCache() for the caching, and self::setProps() for
433 // populating the object from an array of data.
434 return [ 'size', 'width', 'height', 'bits', 'media_type',
435 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
439 * Returns the list of object properties that are included as-is in the
440 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
441 * @param string $prefix Must be the empty string
443 * @since 1.31 No longer accepts a non-empty $prefix
445 protected function getLazyCacheFields( $prefix = 'img_' ) {
446 if ( $prefix !== '' ) {
447 throw new InvalidArgumentException(
448 __METHOD__
. ' with a non-empty prefix is no longer supported.'
452 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
453 return [ 'metadata' ];
457 * Load file metadata from the DB
460 function loadFromDB( $flags = 0 ) {
461 $fname = static::class . '::' . __FUNCTION__
;
463 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
464 $this->dataLoaded
= true;
465 $this->extraDataLoaded
= true;
467 $dbr = ( $flags & self
::READ_LATEST
)
468 ?
$this->repo
->getMasterDB()
469 : $this->repo
->getReplicaDB();
471 $fileQuery = static::getQueryInfo();
472 $row = $dbr->selectRow(
473 $fileQuery['tables'],
474 $fileQuery['fields'],
475 [ 'img_name' => $this->getName() ],
482 $this->loadFromRow( $row );
484 $this->fileExists
= false;
489 * Load lazy file metadata from the DB.
490 * This covers fields that are sometimes not cached.
492 protected function loadExtraFromDB() {
493 $fname = static::class . '::' . __FUNCTION__
;
495 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
496 $this->extraDataLoaded
= true;
498 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
500 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
504 foreach ( $fieldMap as $name => $value ) {
505 $this->$name = $value;
508 throw new MWException( "Could not find data for image '{$this->getName()}'." );
513 * @param IDatabase $dbr
514 * @param string $fname
515 * @return string[]|bool
517 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
520 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
521 $row = $dbr->selectRow(
522 $fileQuery['tables'],
523 $fileQuery['fields'],
525 'img_name' => $this->getName(),
526 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
533 $fieldMap = $this->unprefixRow( $row, 'img_' );
535 # File may have been uploaded over in the meantime; check the old versions
536 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
537 $row = $dbr->selectRow(
538 $fileQuery['tables'],
539 $fileQuery['fields'],
541 'oi_name' => $this->getName(),
542 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
549 $fieldMap = $this->unprefixRow( $row, 'oi_' );
553 if ( isset( $fieldMap['metadata'] ) ) {
554 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
561 * @param array|object $row
562 * @param string $prefix
563 * @throws MWException
566 protected function unprefixRow( $row, $prefix = 'img_' ) {
567 $array = (array)$row;
568 $prefixLength = strlen( $prefix );
570 // Sanity check prefix once
571 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
572 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
576 foreach ( $array as $name => $value ) {
577 $decoded[substr( $name, $prefixLength )] = $value;
584 * Decode a row from the database (either object or array) to an array
585 * with timestamps and MIME types decoded, and the field prefix removed.
587 * @param string $prefix
588 * @throws MWException
591 function decodeRow( $row, $prefix = 'img_' ) {
592 $decoded = $this->unprefixRow( $row, $prefix );
594 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
595 ->getComment( 'description', (object)$decoded )->text
;
597 $decoded['user'] = User
::newFromAnyId(
598 $decoded['user'] ??
null,
599 $decoded['user_text'] ??
null,
600 $decoded['actor'] ??
null
602 unset( $decoded['user_text'], $decoded['actor'] );
604 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
606 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
608 if ( empty( $decoded['major_mime'] ) ) {
609 $decoded['mime'] = 'unknown/unknown';
611 if ( !$decoded['minor_mime'] ) {
612 $decoded['minor_mime'] = 'unknown';
614 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
617 // Trim zero padding from char/binary field
618 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
620 // Normalize some fields to integer type, per their database definition.
621 // Use unary + so that overflows will be upgraded to double instead of
622 // being trucated as with intval(). This is important to allow >2GB
623 // files on 32-bit systems.
624 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
625 $decoded[$field] = +
$decoded[$field];
632 * Load file metadata from a DB result row
635 * @param string $prefix
637 function loadFromRow( $row, $prefix = 'img_' ) {
638 $this->dataLoaded
= true;
639 $this->extraDataLoaded
= true;
641 $array = $this->decodeRow( $row, $prefix );
643 foreach ( $array as $name => $value ) {
644 $this->$name = $value;
647 $this->fileExists
= true;
651 * Load file metadata from cache or DB, unless already loaded
654 function load( $flags = 0 ) {
655 if ( !$this->dataLoaded
) {
656 if ( $flags & self
::READ_LATEST
) {
657 $this->loadFromDB( $flags );
659 $this->loadFromCache();
663 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
664 // @note: loads on name/timestamp to reduce race condition problems
665 $this->loadExtraFromDB();
670 * Upgrade a row if it needs it
672 protected function maybeUpgradeRow() {
673 global $wgUpdateCompatibleMetadata;
675 if ( wfReadOnly() ||
$this->upgrading
) {
680 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
683 $handler = $this->getHandler();
685 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
686 if ( $validity === MediaHandler
::METADATA_BAD
) {
688 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
689 $upgrade = $wgUpdateCompatibleMetadata;
695 $this->upgrading
= true;
696 // Defer updates unless in auto-commit CLI mode
697 DeferredUpdates
::addCallableUpdate( function () {
698 $this->upgrading
= false; // avoid duplicate updates
701 } catch ( LocalFileLockError
$e ) {
702 // let the other process handle it (or do it next time)
709 * @return bool Whether upgradeRow() ran for this object
711 function getUpgraded() {
712 return $this->upgraded
;
716 * Fix assorted version-related problems with the image row by reloading it from the file
718 function upgradeRow() {
721 $this->loadFromFile();
723 # Don't destroy file info of missing files
724 if ( !$this->fileExists
) {
726 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
731 $dbw = $this->repo
->getMasterDB();
732 list( $major, $minor ) = self
::splitMime( $this->mime
);
734 if ( wfReadOnly() ) {
739 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
741 $dbw->update( 'image',
743 'img_size' => $this->size
, // sanity
744 'img_width' => $this->width
,
745 'img_height' => $this->height
,
746 'img_bits' => $this->bits
,
747 'img_media_type' => $this->media_type
,
748 'img_major_mime' => $major,
749 'img_minor_mime' => $minor,
750 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
751 'img_sha1' => $this->sha1
,
753 [ 'img_name' => $this->getName() ],
757 $this->invalidateCache();
760 $this->upgraded
= true; // avoid rework/retries
764 * Set properties in this object to be equal to those given in the
765 * associative array $info. Only cacheable fields can be set.
766 * All fields *must* be set in $info except for getLazyCacheFields().
768 * If 'mime' is given, it will be split into major_mime/minor_mime.
769 * If major_mime/minor_mime are given, $this->mime will also be set.
773 function setProps( $info ) {
774 $this->dataLoaded
= true;
775 $fields = $this->getCacheFields( '' );
776 $fields[] = 'fileExists';
778 foreach ( $fields as $field ) {
779 if ( isset( $info[$field] ) ) {
780 $this->$field = $info[$field];
784 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
785 $this->user
= User
::newFromAnyId(
786 $info['user'] ??
null,
787 $info['user_text'] ??
null,
788 $info['actor'] ??
null
792 // Fix up mime fields
793 if ( isset( $info['major_mime'] ) ) {
794 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
795 } elseif ( isset( $info['mime'] ) ) {
796 $this->mime
= $info['mime'];
797 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
801 /** splitMime inherited */
802 /** getName inherited */
803 /** getTitle inherited */
804 /** getURL inherited */
805 /** getViewURL inherited */
806 /** getPath inherited */
807 /** isVisible inherited */
810 * Checks if this file exists in its parent repo, as referenced by its
815 function isMissing() {
816 if ( $this->missing
=== null ) {
817 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
818 $this->missing
= !$fileExists;
821 return $this->missing
;
825 * Return the width of the image
830 public function getWidth( $page = 1 ) {
838 if ( $this->isMultipage() ) {
839 $handler = $this->getHandler();
843 $dim = $handler->getPageDimensions( $this, $page );
845 return $dim['width'];
847 // For non-paged media, the false goes through an
848 // intval, turning failure into 0, so do same here.
857 * Return the height of the image
862 public function getHeight( $page = 1 ) {
870 if ( $this->isMultipage() ) {
871 $handler = $this->getHandler();
875 $dim = $handler->getPageDimensions( $this, $page );
877 return $dim['height'];
879 // For non-paged media, the false goes through an
880 // intval, turning failure into 0, so do same here.
884 return $this->height
;
889 * Returns user who uploaded the file
891 * @param string $type 'text', 'id', or 'object'
892 * @return int|string|User
893 * @since 1.31 Added 'object'
895 function getUser( $type = 'text' ) {
898 if ( $type === 'object' ) {
900 } elseif ( $type === 'text' ) {
901 return $this->user
->getName();
902 } elseif ( $type === 'id' ) {
903 return $this->user
->getId();
906 throw new MWException( "Unknown type '$type'." );
910 * Get short description URL for a file based on the page ID.
912 * @return string|null
913 * @throws MWException
916 public function getDescriptionShortUrl() {
917 $pageId = $this->title
->getArticleID();
919 if ( $pageId !== null ) {
920 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
921 if ( $url !== false ) {
929 * Get handler-specific metadata
932 function getMetadata() {
933 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
934 return $this->metadata
;
940 function getBitDepth() {
943 return (int)$this->bits
;
947 * Returns the size of the image file, in bytes
950 public function getSize() {
957 * Returns the MIME type of the file.
960 function getMimeType() {
967 * Returns the type of the media in the file.
968 * Use the value returned by this function with the MEDIATYPE_xxx constants.
971 function getMediaType() {
974 return $this->media_type
;
977 /** canRender inherited */
978 /** mustRender inherited */
979 /** allowInlineDisplay inherited */
980 /** isSafeFile inherited */
981 /** isTrustedFile inherited */
984 * Returns true if the file exists on disk.
985 * @return bool Whether file exist on disk.
987 public function exists() {
990 return $this->fileExists
;
993 /** getTransformScript inherited */
994 /** getUnscaledThumb inherited */
995 /** thumbName inherited */
996 /** createThumb inherited */
997 /** transform inherited */
999 /** getHandler inherited */
1000 /** iconThumb inherited */
1001 /** getLastError inherited */
1004 * Get all thumbnail names previously generated for this file
1005 * @param string|bool $archiveName Name of an archive file, default false
1006 * @return array First element is the base dir, then files in that base dir.
1008 function getThumbnails( $archiveName = false ) {
1009 if ( $archiveName ) {
1010 $dir = $this->getArchiveThumbPath( $archiveName );
1012 $dir = $this->getThumbPath();
1015 $backend = $this->repo
->getBackend();
1018 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1019 foreach ( $iterator as $file ) {
1022 } catch ( FileBackendError
$e ) {
1023 } // suppress (T56674)
1029 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1031 function purgeMetadataCache() {
1032 $this->invalidateCache();
1036 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1038 * @param array $options An array potentially with the key forThumbRefresh.
1040 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1042 function purgeCache( $options = [] ) {
1043 // Refresh metadata cache
1044 $this->maybeUpgradeRow();
1045 $this->purgeMetadataCache();
1047 // Delete thumbnails
1048 $this->purgeThumbnails( $options );
1050 // Purge CDN cache for this file
1051 DeferredUpdates
::addUpdate(
1052 new CdnCacheUpdate( [ $this->getUrl() ] ),
1053 DeferredUpdates
::PRESEND
1058 * Delete cached transformed files for an archived version only.
1059 * @param string $archiveName Name of the archived file
1061 function purgeOldThumbnails( $archiveName ) {
1062 // Get a list of old thumbnails and URLs
1063 $files = $this->getThumbnails( $archiveName );
1065 // Purge any custom thumbnail caches
1066 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1068 // Delete thumbnails
1069 $dir = array_shift( $files );
1070 $this->purgeThumbList( $dir, $files );
1074 foreach ( $files as $file ) {
1075 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1077 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1081 * Delete cached transformed files for the current version only.
1082 * @param array $options
1084 public function purgeThumbnails( $options = [] ) {
1085 $files = $this->getThumbnails();
1086 // Always purge all files from CDN regardless of handler filters
1088 foreach ( $files as $file ) {
1089 $urls[] = $this->getThumbUrl( $file );
1091 array_shift( $urls ); // don't purge directory
1093 // Give media handler a chance to filter the file purge list
1094 if ( !empty( $options['forThumbRefresh'] ) ) {
1095 $handler = $this->getHandler();
1097 $handler->filterThumbnailPurgeList( $files, $options );
1101 // Purge any custom thumbnail caches
1102 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1104 // Delete thumbnails
1105 $dir = array_shift( $files );
1106 $this->purgeThumbList( $dir, $files );
1109 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1113 * Prerenders a configurable set of thumbnails
1117 public function prerenderThumbnails() {
1118 global $wgUploadThumbnailRenderMap;
1122 $sizes = $wgUploadThumbnailRenderMap;
1125 foreach ( $sizes as $size ) {
1126 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1127 $jobs[] = new ThumbnailRenderJob(
1129 [ 'transformParams' => [ 'width' => $size ] ]
1135 JobQueueGroup
::singleton()->lazyPush( $jobs );
1140 * Delete a list of thumbnails visible at urls
1141 * @param string $dir Base dir of the files.
1142 * @param array $files Array of strings: relative filenames (to $dir)
1144 protected function purgeThumbList( $dir, $files ) {
1145 $fileListDebug = strtr(
1146 var_export( $files, true ),
1149 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1152 foreach ( $files as $file ) {
1153 if ( $this->repo
->supportsSha1URLs() ) {
1154 $reference = $this->getSha1();
1156 $reference = $this->getName();
1159 # Check that the reference (filename or sha1) is part of the thumb name
1160 # This is a basic sanity check to avoid erasing unrelated directories
1161 if ( strpos( $file, $reference ) !== false
1162 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1164 $purgeList[] = "{$dir}/{$file}";
1168 # Delete the thumbnails
1169 $this->repo
->quickPurgeBatch( $purgeList );
1170 # Clear out the thumbnail directory if empty
1171 $this->repo
->quickCleanDir( $dir );
1174 /** purgeDescription inherited */
1175 /** purgeEverything inherited */
1178 * @param int|null $limit Optional: Limit to number of results
1179 * @param string|int|null $start Optional: Timestamp, start from
1180 * @param string|int|null $end Optional: Timestamp, end at
1182 * @return OldLocalFile[]
1184 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1185 $dbr = $this->repo
->getReplicaDB();
1186 $oldFileQuery = OldLocalFile
::getQueryInfo();
1188 $tables = $oldFileQuery['tables'];
1189 $fields = $oldFileQuery['fields'];
1190 $join_conds = $oldFileQuery['joins'];
1191 $conds = $opts = [];
1192 $eq = $inc ?
'=' : '';
1193 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1196 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1200 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1204 $opts['LIMIT'] = $limit;
1207 // Search backwards for time > x queries
1208 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1209 $opts['ORDER BY'] = "oi_timestamp $order";
1210 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1212 // Avoid PHP 7.1 warning from passing $this by reference
1214 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1215 &$conds, &$opts, &$join_conds ] );
1217 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1220 foreach ( $res as $row ) {
1221 $r[] = $this->repo
->newFileFromRow( $row );
1224 if ( $order == 'ASC' ) {
1225 $r = array_reverse( $r ); // make sure it ends up descending
1232 * Returns the history of this file, line by line.
1233 * starts with current version, then old versions.
1234 * uses $this->historyLine to check which line to return:
1235 * 0 return line for current version
1236 * 1 query for old versions, return first one
1237 * 2, ... return next old version from above query
1240 public function nextHistoryLine() {
1241 # Polymorphic function name to distinguish foreign and local fetches
1242 $fname = static::class . '::' . __FUNCTION__
;
1244 $dbr = $this->repo
->getReplicaDB();
1246 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1247 $fileQuery = self
::getQueryInfo();
1248 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1249 $fileQuery['fields'] +
[
1250 'oi_archive_name' => $dbr->addQuotes( '' ),
1253 [ 'img_name' => $this->title
->getDBkey() ],
1259 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1260 $this->historyRes
= null;
1264 } elseif ( $this->historyLine
== 1 ) {
1265 $fileQuery = OldLocalFile
::getQueryInfo();
1266 $this->historyRes
= $dbr->select(
1267 $fileQuery['tables'],
1268 $fileQuery['fields'],
1269 [ 'oi_name' => $this->title
->getDBkey() ],
1271 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1275 $this->historyLine++
;
1277 return $dbr->fetchObject( $this->historyRes
);
1281 * Reset the history pointer to the first element of the history
1283 public function resetHistory() {
1284 $this->historyLine
= 0;
1286 if ( !is_null( $this->historyRes
) ) {
1287 $this->historyRes
= null;
1291 /** getHashPath inherited */
1292 /** getRel inherited */
1293 /** getUrlRel inherited */
1294 /** getArchiveRel inherited */
1295 /** getArchivePath inherited */
1296 /** getThumbPath inherited */
1297 /** getArchiveUrl inherited */
1298 /** getThumbUrl inherited */
1299 /** getArchiveVirtualUrl inherited */
1300 /** getThumbVirtualUrl inherited */
1301 /** isHashed inherited */
1304 * Upload a file and record it in the DB
1305 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1306 * @param string $comment Upload description
1307 * @param string $pageText Text to use for the new description page,
1308 * if a new description page is created
1309 * @param int|bool $flags Flags for publish()
1310 * @param array|bool $props File properties, if known. This can be used to
1311 * reduce the upload time when uploading virtual URLs for which the file
1312 * info is already known
1313 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1315 * @param User|null $user User object or null to use $wgUser
1316 * @param string[] $tags Change tags to add to the log entry and page revision.
1317 * (This doesn't check $user's permissions.)
1318 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1319 * upload, see T193621
1320 * @param bool $revert If this file upload is a revert
1321 * @return Status On success, the value member contains the
1322 * archive name, or an empty string if it was a new file.
1324 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1325 $timestamp = false, $user = null, $tags = [],
1326 $createNullRevision = true, $revert = false
1328 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1329 return $this->readOnlyFatalStatus();
1330 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1331 // Check this in advance to avoid writing to FileBackend and the file tables,
1332 // only to fail on insert the revision due to the text store being unavailable.
1333 return $this->readOnlyFatalStatus();
1336 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1338 if ( FileRepo
::isVirtualUrl( $srcPath )
1339 || FileBackend
::isStoragePath( $srcPath )
1341 $props = $this->repo
->getFileProps( $srcPath );
1343 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1344 $props = $mwProps->getPropsFromPath( $srcPath, true );
1349 $handler = MediaHandler
::getHandler( $props['mime'] );
1351 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1353 if ( !is_array( $metadata ) ) {
1357 $options['headers'] = $handler->getContentHeaders( $metadata );
1359 $options['headers'] = [];
1362 // Trim spaces on user supplied text
1363 $comment = trim( $comment );
1366 $status = $this->publish( $src, $flags, $options );
1368 if ( $status->successCount
>= 2 ) {
1369 // There will be a copy+(one of move,copy,store).
1370 // The first succeeding does not commit us to updating the DB
1371 // since it simply copied the current version to a timestamped file name.
1372 // It is only *preferable* to avoid leaving such files orphaned.
1373 // Once the second operation goes through, then the current version was
1374 // updated and we must therefore update the DB too.
1375 $oldver = $status->value
;
1376 $uploadStatus = $this->recordUpload2(
1384 $createNullRevision,
1387 if ( !$uploadStatus->isOK() ) {
1388 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1389 // update filenotfound error with more specific path
1390 $status->fatal( 'filenotfound', $srcPath );
1392 $status->merge( $uploadStatus );
1402 * Record a file upload in the upload log and the image table
1403 * @param string $oldver
1404 * @param string $desc
1405 * @param string $license
1406 * @param string $copyStatus
1407 * @param string $source
1408 * @param bool $watch
1409 * @param string|bool $timestamp
1410 * @param User|null $user User object or null to use $wgUser
1413 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1414 $watch = false, $timestamp = false, User
$user = null ) {
1420 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1422 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1427 $user->addWatch( $this->getTitle() );
1434 * Record a file upload in the upload log and the image table
1435 * @param string $oldver
1436 * @param string $comment
1437 * @param string $pageText
1438 * @param bool|array $props
1439 * @param string|bool $timestamp
1440 * @param null|User $user
1441 * @param string[] $tags
1442 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1443 * upload, see T193621
1444 * @param bool $revert If this file upload is a revert
1447 function recordUpload2(
1448 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1449 $createNullRevision = true, $revert = false
1451 global $wgActorTableSchemaMigrationStage;
1453 if ( is_null( $user ) ) {
1458 $dbw = $this->repo
->getMasterDB();
1460 # Imports or such might force a certain timestamp; otherwise we generate
1461 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1462 if ( $timestamp === false ) {
1463 $timestamp = $dbw->timestamp();
1464 $allowTimeKludge = true;
1466 $allowTimeKludge = false;
1469 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1470 $props['description'] = $comment;
1471 $props['user'] = $user->getId();
1472 $props['user_text'] = $user->getName();
1473 $props['actor'] = $user->getActorId( $dbw );
1474 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1475 $this->setProps( $props );
1477 # Fail now if the file isn't there
1478 if ( !$this->fileExists
) {
1479 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1481 return Status
::newFatal( 'filenotfound', $this->getRel() );
1484 $dbw->startAtomic( __METHOD__
);
1486 # Test to see if the row exists using INSERT IGNORE
1487 # This avoids race conditions by locking the row until the commit, and also
1488 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1489 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1490 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1491 $actorMigration = ActorMigration
::newMigration();
1492 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1493 $dbw->insert( 'image',
1495 'img_name' => $this->getName(),
1496 'img_size' => $this->size
,
1497 'img_width' => intval( $this->width
),
1498 'img_height' => intval( $this->height
),
1499 'img_bits' => $this->bits
,
1500 'img_media_type' => $this->media_type
,
1501 'img_major_mime' => $this->major_mime
,
1502 'img_minor_mime' => $this->minor_mime
,
1503 'img_timestamp' => $timestamp,
1504 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1505 'img_sha1' => $this->sha1
1506 ] +
$commentFields +
$actorFields,
1510 $reupload = ( $dbw->affectedRows() == 0 );
1513 $row = $dbw->selectRow(
1515 [ 'img_timestamp', 'img_sha1' ],
1516 [ 'img_name' => $this->getName() ],
1518 [ 'LOCK IN SHARE MODE' ]
1521 if ( $row && $row->img_sha1
=== $this->sha1
) {
1522 $dbw->endAtomic( __METHOD__
);
1523 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1524 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1525 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1528 if ( $allowTimeKludge ) {
1529 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1530 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1531 # Avoid a timestamp that is not newer than the last version
1532 # TODO: the image/oldimage tables should be like page/revision with an ID field
1533 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1534 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1535 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1536 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1540 $tables = [ 'image' ];
1542 'oi_name' => 'img_name',
1543 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1544 'oi_size' => 'img_size',
1545 'oi_width' => 'img_width',
1546 'oi_height' => 'img_height',
1547 'oi_bits' => 'img_bits',
1548 'oi_description_id' => 'img_description_id',
1549 'oi_timestamp' => 'img_timestamp',
1550 'oi_metadata' => 'img_metadata',
1551 'oi_media_type' => 'img_media_type',
1552 'oi_major_mime' => 'img_major_mime',
1553 'oi_minor_mime' => 'img_minor_mime',
1554 'oi_sha1' => 'img_sha1',
1558 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1559 $fields['oi_user'] = 'img_user';
1560 $fields['oi_user_text'] = 'img_user_text';
1562 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1563 $fields['oi_actor'] = 'img_actor';
1567 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1569 // Upgrade any rows that are still old-style. Otherwise an upgrade
1570 // might be missed if a deletion happens while the migration script
1572 $res = $dbw->select(
1574 [ 'img_name', 'img_user', 'img_user_text' ],
1575 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1578 foreach ( $res as $row ) {
1579 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1582 [ 'img_actor' => $actorId ],
1583 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1589 # (T36993) Note: $oldver can be empty here, if the previous
1590 # version of the file was broken. Allow registration of the new
1591 # version to continue anyway, because that's better than having
1592 # an image that's not fixable by user operations.
1593 # Collision, this is an update of a file
1594 # Insert previous contents into oldimage
1595 $dbw->insertSelect( 'oldimage', $tables, $fields,
1596 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1598 # Update the current image row
1599 $dbw->update( 'image',
1601 'img_size' => $this->size
,
1602 'img_width' => intval( $this->width
),
1603 'img_height' => intval( $this->height
),
1604 'img_bits' => $this->bits
,
1605 'img_media_type' => $this->media_type
,
1606 'img_major_mime' => $this->major_mime
,
1607 'img_minor_mime' => $this->minor_mime
,
1608 'img_timestamp' => $timestamp,
1609 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1610 'img_sha1' => $this->sha1
1611 ] +
$commentFields +
$actorFields,
1612 [ 'img_name' => $this->getName() ],
1617 $descTitle = $this->getTitle();
1618 $descId = $descTitle->getArticleID();
1619 $wikiPage = new WikiFilePage( $descTitle );
1620 $wikiPage->setFile( $this );
1622 // Determine log action. If reupload is done by reverting, use a special log_action.
1623 if ( $revert === true ) {
1624 $logAction = 'revert';
1625 } elseif ( $reupload === true ) {
1626 $logAction = 'overwrite';
1628 $logAction = 'upload';
1630 // Add the log entry...
1631 $logEntry = new ManualLogEntry( 'upload', $logAction );
1632 $logEntry->setTimestamp( $this->timestamp
);
1633 $logEntry->setPerformer( $user );
1634 $logEntry->setComment( $comment );
1635 $logEntry->setTarget( $descTitle );
1636 // Allow people using the api to associate log entries with the upload.
1637 // Log has a timestamp, but sometimes different from upload timestamp.
1638 $logEntry->setParameters(
1640 'img_sha1' => $this->sha1
,
1641 'img_timestamp' => $timestamp,
1644 // Note we keep $logId around since during new image
1645 // creation, page doesn't exist yet, so log_page = 0
1646 // but we want it to point to the page we're making,
1647 // so we later modify the log entry.
1648 // For a similar reason, we avoid making an RC entry
1649 // now and wait until the page exists.
1650 $logId = $logEntry->insert();
1652 if ( $descTitle->exists() ) {
1653 // Use own context to get the action text in content language
1654 $formatter = LogFormatter
::newFromEntry( $logEntry );
1655 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1656 $editSummary = $formatter->getPlainActionText();
1658 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1665 if ( $nullRevision ) {
1666 $nullRevision->insertOn( $dbw );
1668 'NewRevisionFromEditComplete',
1669 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1671 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1672 // Associate null revision id
1673 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1676 $newPageContent = null;
1678 // Make the description page and RC log entry post-commit
1679 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1682 # Defer purges, page creation, and link updates in case they error out.
1683 # The most important thing is that files and the DB registry stay synced.
1684 $dbw->endAtomic( __METHOD__
);
1685 $fname = __METHOD__
;
1687 # Do some cache purges after final commit so that:
1688 # a) Changes are more likely to be seen post-purge
1689 # b) They won't cause rollback of the log publish/update above
1690 DeferredUpdates
::addUpdate(
1691 new AutoCommitUpdate(
1695 $reupload, $wikiPage, $newPageContent, $comment, $user,
1696 $logEntry, $logId, $descId, $tags, $fname
1698 # Update memcache after the commit
1699 $this->invalidateCache();
1701 $updateLogPage = false;
1702 if ( $newPageContent ) {
1703 # New file page; create the description page.
1704 # There's already a log entry, so don't make a second RC entry
1705 # CDN and file cache for the description page are purged by doEditContent.
1706 $status = $wikiPage->doEditContent(
1709 EDIT_NEW | EDIT_SUPPRESS_RC
,
1714 if ( isset( $status->value
['revision'] ) ) {
1715 /** @var Revision $rev */
1716 $rev = $status->value
['revision'];
1717 // Associate new page revision id
1718 $logEntry->setAssociatedRevId( $rev->getId() );
1720 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1721 // which is triggered on $descTitle by doEditContent() above.
1722 if ( isset( $status->value
['revision'] ) ) {
1723 /** @var Revision $rev */
1724 $rev = $status->value
['revision'];
1725 $updateLogPage = $rev->getPage();
1728 # Existing file page: invalidate description page cache
1729 $wikiPage->getTitle()->invalidateCache();
1730 $wikiPage->getTitle()->purgeSquid();
1731 # Allow the new file version to be patrolled from the page footer
1732 Article
::purgePatrolFooterCache( $descId );
1735 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1736 # but setAssociatedRevId() wasn't called at that point yet...
1737 $logParams = $logEntry->getParameters();
1738 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1739 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1740 if ( $updateLogPage ) {
1741 # Also log page, in case where we just created it above
1742 $update['log_page'] = $updateLogPage;
1744 $this->getRepo()->getMasterDB()->update(
1747 [ 'log_id' => $logId ],
1750 $this->getRepo()->getMasterDB()->insert(
1753 'ls_field' => 'associated_rev_id',
1754 'ls_value' => $logEntry->getAssociatedRevId(),
1755 'ls_log_id' => $logId,
1760 # Add change tags, if any
1762 $logEntry->setTags( $tags );
1765 # Uploads can be patrolled
1766 $logEntry->setIsPatrollable( true );
1768 # Now that the log entry is up-to-date, make an RC entry.
1769 $logEntry->publish( $logId );
1771 # Run hook for other updates (typically more cache purging)
1772 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1775 # Delete old thumbnails
1776 $this->purgeThumbnails();
1777 # Remove the old file from the CDN cache
1778 DeferredUpdates
::addUpdate(
1779 new CdnCacheUpdate( [ $this->getUrl() ] ),
1780 DeferredUpdates
::PRESEND
1783 # Update backlink pages pointing to this title if created
1784 LinksUpdate
::queueRecursiveJobsForTable(
1792 $this->prerenderThumbnails();
1795 DeferredUpdates
::PRESEND
1799 # This is a new file, so update the image count
1800 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1803 # Invalidate cache for all pages using this file
1804 DeferredUpdates
::addUpdate(
1805 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1808 return Status
::newGood();
1812 * Move or copy a file to its public location. If a file exists at the
1813 * destination, move it to an archive. Returns a Status object with
1814 * the archive name in the "value" member on success.
1816 * The archive name should be passed through to recordUpload for database
1819 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1820 * @param int $flags A bitwise combination of:
1821 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1822 * @param array $options Optional additional parameters
1823 * @return Status On success, the value member contains the
1824 * archive name, or an empty string if it was a new file.
1826 function publish( $src, $flags = 0, array $options = [] ) {
1827 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1831 * Move or copy a file to a specified location. Returns a Status
1832 * object with the archive name in the "value" member on success.
1834 * The archive name should be passed through to recordUpload for database
1837 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1838 * @param string $dstRel Target relative path
1839 * @param int $flags A bitwise combination of:
1840 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1841 * @param array $options Optional additional parameters
1842 * @return Status On success, the value member contains the
1843 * archive name, or an empty string if it was a new file.
1845 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1846 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1848 $repo = $this->getRepo();
1849 if ( $repo->getReadOnlyReason() !== false ) {
1850 return $this->readOnlyFatalStatus();
1855 if ( $this->isOld() ) {
1856 $archiveRel = $dstRel;
1857 $archiveName = basename( $archiveRel );
1859 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1860 $archiveRel = $this->getArchiveRel( $archiveName );
1863 if ( $repo->hasSha1Storage() ) {
1864 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1865 ?
$repo->getFileSha1( $srcPath )
1866 : FSFile
::getSha1Base36FromPath( $srcPath );
1867 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1868 $wrapperBackend = $repo->getBackend();
1869 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1870 $status = $repo->quickImport( $src, $dst );
1871 if ( $flags & File
::DELETE_SOURCE
) {
1875 if ( $this->exists() ) {
1876 $status->value
= $archiveName;
1879 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1880 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1882 if ( $status->value
== 'new' ) {
1883 $status->value
= '';
1885 $status->value
= $archiveName;
1893 /** getLinksTo inherited */
1894 /** getExifData inherited */
1895 /** isLocal inherited */
1896 /** wasDeleted inherited */
1899 * Move file to the new title
1901 * Move current, old version and all thumbnails
1902 * to the new filename. Old file is deleted.
1904 * Cache purging is done; checks for validity
1905 * and logging are caller's responsibility
1907 * @param Title $target New file name
1910 function move( $target ) {
1911 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1912 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1913 return $this->readOnlyFatalStatus();
1916 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1917 $batch = new LocalFileMoveBatch( $this, $target );
1920 $batch->addCurrent();
1921 $archiveNames = $batch->addOlds();
1922 $status = $batch->execute();
1925 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1927 // Purge the source and target files outside the transaction...
1928 $oldTitleFile = $localRepo->newFile( $this->title
);
1929 $newTitleFile = $localRepo->newFile( $target );
1930 DeferredUpdates
::addUpdate(
1931 new AutoCommitUpdate(
1932 $this->getRepo()->getMasterDB(),
1934 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1935 $oldTitleFile->purgeEverything();
1936 foreach ( $archiveNames as $archiveName ) {
1937 /** @var OldLocalFile $oldTitleFile */
1938 $oldTitleFile->purgeOldThumbnails( $archiveName );
1940 $newTitleFile->purgeEverything();
1943 DeferredUpdates
::PRESEND
1946 if ( $status->isOK() ) {
1947 // Now switch the object
1948 $this->title
= $target;
1949 // Force regeneration of the name and hashpath
1951 $this->hashPath
= null;
1958 * Delete all versions of the file.
1960 * Moves the files into an archive directory (or deletes them)
1961 * and removes the database rows.
1963 * Cache purging is done; logging is caller's responsibility.
1965 * @param string $reason
1966 * @param bool $suppress
1967 * @param User|null $user
1970 function delete( $reason, $suppress = false, $user = null ) {
1971 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1972 return $this->readOnlyFatalStatus();
1975 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1978 $batch->addCurrent();
1979 // Get old version relative paths
1980 $archiveNames = $batch->addOlds();
1981 $status = $batch->execute();
1984 if ( $status->isOK() ) {
1985 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1988 // To avoid slow purges in the transaction, move them outside...
1989 DeferredUpdates
::addUpdate(
1990 new AutoCommitUpdate(
1991 $this->getRepo()->getMasterDB(),
1993 function () use ( $archiveNames ) {
1994 $this->purgeEverything();
1995 foreach ( $archiveNames as $archiveName ) {
1996 $this->purgeOldThumbnails( $archiveName );
2000 DeferredUpdates
::PRESEND
2005 foreach ( $archiveNames as $archiveName ) {
2006 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2008 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2014 * Delete an old version of the file.
2016 * Moves the file into an archive directory (or deletes it)
2017 * and removes the database row.
2019 * Cache purging is done; logging is caller's responsibility.
2021 * @param string $archiveName
2022 * @param string $reason
2023 * @param bool $suppress
2024 * @param User|null $user
2025 * @throws MWException Exception on database or file store failure
2028 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2029 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2030 return $this->readOnlyFatalStatus();
2033 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2036 $batch->addOld( $archiveName );
2037 $status = $batch->execute();
2040 $this->purgeOldThumbnails( $archiveName );
2041 if ( $status->isOK() ) {
2042 $this->purgeDescription();
2045 DeferredUpdates
::addUpdate(
2046 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2047 DeferredUpdates
::PRESEND
2054 * Restore all or specified deleted revisions to the given file.
2055 * Permissions and logging are left to the caller.
2057 * May throw database exceptions on error.
2059 * @param array $versions Set of record ids of deleted items to restore,
2060 * or empty to restore all revisions.
2061 * @param bool $unsuppress
2064 function restore( $versions = [], $unsuppress = false ) {
2065 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2066 return $this->readOnlyFatalStatus();
2069 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2075 $batch->addIds( $versions );
2077 $status = $batch->execute();
2078 if ( $status->isGood() ) {
2079 $cleanupStatus = $batch->cleanup();
2080 $cleanupStatus->successCount
= 0;
2081 $cleanupStatus->failCount
= 0;
2082 $status->merge( $cleanupStatus );
2089 /** isMultipage inherited */
2090 /** pageCount inherited */
2091 /** scaleHeight inherited */
2092 /** getImageSize inherited */
2095 * Get the URL of the file description page.
2098 function getDescriptionUrl() {
2099 return $this->title
->getLocalURL();
2103 * Get the HTML text of the description page
2104 * This is not used by ImagePage for local files, since (among other things)
2105 * it skips the parser cache.
2107 * @param Language|null $lang What language to get description in (Optional)
2108 * @return string|false
2110 function getDescriptionText( Language
$lang = null ) {
2111 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2112 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2117 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2118 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2121 // audience check failed
2125 $pout = $rendered->getRevisionParserOutput();
2126 return $pout->getText();
2130 * @param int $audience
2131 * @param User|null $user
2134 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2136 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2138 } elseif ( $audience == self
::FOR_THIS_USER
2139 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2143 return $this->description
;
2148 * @return bool|string
2150 function getTimestamp() {
2153 return $this->timestamp
;
2157 * @return bool|string
2159 public function getDescriptionTouched() {
2160 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2161 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2162 // need to differentiate between null (uninitialized) and false (failed to load).
2163 if ( $this->descriptionTouched
=== null ) {
2165 'page_namespace' => $this->title
->getNamespace(),
2166 'page_title' => $this->title
->getDBkey()
2168 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2169 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2172 return $this->descriptionTouched
;
2178 function getSha1() {
2180 // Initialise now if necessary
2181 if ( $this->sha1
== '' && $this->fileExists
) {
2184 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2185 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2186 $dbw = $this->repo
->getMasterDB();
2187 $dbw->update( 'image',
2188 [ 'img_sha1' => $this->sha1
],
2189 [ 'img_name' => $this->getName() ],
2191 $this->invalidateCache();
2201 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2203 function isCacheable() {
2206 // If extra data (metadata) was not loaded then it must have been large
2207 return $this->extraDataLoaded
2208 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2215 public function acquireFileLock() {
2216 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2217 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2225 public function releaseFileLock() {
2226 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2227 [ $this->getPath() ], LockManager
::LOCK_EX
2232 * Start an atomic DB section and lock the image for update
2233 * or increments a reference counter if the lock is already held
2235 * This method should not be used outside of LocalFile/LocalFile*Batch
2237 * @throws LocalFileLockError Throws an error if the lock was not acquired
2238 * @return bool Whether the file lock owns/spawned the DB transaction
2240 public function lock() {
2241 if ( !$this->locked
) {
2242 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2244 $dbw = $this->repo
->getMasterDB();
2245 $makesTransaction = !$dbw->trxLevel();
2246 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2247 // T56736: use simple lock to handle when the file does not exist.
2248 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2249 // Also, that would cause contention on INSERT of similarly named rows.
2250 $status = $this->acquireFileLock(); // represents all versions of the file
2251 if ( !$status->isGood() ) {
2252 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2253 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2255 throw new LocalFileLockError( $status );
2257 // Release the lock *after* commit to avoid row-level contention.
2258 // Make sure it triggers on rollback() as well as commit() (T132921).
2259 $dbw->onTransactionResolution(
2260 function () use ( $logger ) {
2261 $status = $this->releaseFileLock();
2262 if ( !$status->isGood() ) {
2263 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2268 // Callers might care if the SELECT snapshot is safely fresh
2269 $this->lockedOwnTrx
= $makesTransaction;
2274 return $this->lockedOwnTrx
;
2278 * Decrement the lock reference count and end the atomic section if it reaches zero
2280 * This method should not be used outside of LocalFile/LocalFile*Batch
2282 * The commit and loc release will happen when no atomic sections are active, which
2283 * may happen immediately or at some point after calling this
2285 public function unlock() {
2286 if ( $this->locked
) {
2288 if ( !$this->locked
) {
2289 $dbw = $this->repo
->getMasterDB();
2290 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2291 $this->lockedOwnTrx
= false;
2299 protected function readOnlyFatalStatus() {
2300 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2301 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2305 * Clean up any dangling locks
2307 function __destruct() {