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
1083 * @phan-param array{forThumbRefresh?:bool} $options
1085 public function purgeThumbnails( $options = [] ) {
1086 $files = $this->getThumbnails();
1087 // Always purge all files from CDN regardless of handler filters
1089 foreach ( $files as $file ) {
1090 $urls[] = $this->getThumbUrl( $file );
1092 array_shift( $urls ); // don't purge directory
1094 // Give media handler a chance to filter the file purge list
1095 if ( !empty( $options['forThumbRefresh'] ) ) {
1096 $handler = $this->getHandler();
1098 $handler->filterThumbnailPurgeList( $files, $options );
1102 // Purge any custom thumbnail caches
1103 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1105 // Delete thumbnails
1106 $dir = array_shift( $files );
1107 $this->purgeThumbList( $dir, $files );
1110 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1114 * Prerenders a configurable set of thumbnails
1118 public function prerenderThumbnails() {
1119 global $wgUploadThumbnailRenderMap;
1123 $sizes = $wgUploadThumbnailRenderMap;
1126 foreach ( $sizes as $size ) {
1127 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1128 $jobs[] = new ThumbnailRenderJob(
1130 [ 'transformParams' => [ 'width' => $size ] ]
1136 JobQueueGroup
::singleton()->lazyPush( $jobs );
1141 * Delete a list of thumbnails visible at urls
1142 * @param string $dir Base dir of the files.
1143 * @param array $files Array of strings: relative filenames (to $dir)
1145 protected function purgeThumbList( $dir, $files ) {
1146 $fileListDebug = strtr(
1147 var_export( $files, true ),
1150 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1153 foreach ( $files as $file ) {
1154 if ( $this->repo
->supportsSha1URLs() ) {
1155 $reference = $this->getSha1();
1157 $reference = $this->getName();
1160 # Check that the reference (filename or sha1) is part of the thumb name
1161 # This is a basic sanity check to avoid erasing unrelated directories
1162 if ( strpos( $file, $reference ) !== false
1163 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1165 $purgeList[] = "{$dir}/{$file}";
1169 # Delete the thumbnails
1170 $this->repo
->quickPurgeBatch( $purgeList );
1171 # Clear out the thumbnail directory if empty
1172 $this->repo
->quickCleanDir( $dir );
1175 /** purgeDescription inherited */
1176 /** purgeEverything inherited */
1179 * @param int|null $limit Optional: Limit to number of results
1180 * @param string|int|null $start Optional: Timestamp, start from
1181 * @param string|int|null $end Optional: Timestamp, end at
1183 * @return OldLocalFile[]
1185 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1186 $dbr = $this->repo
->getReplicaDB();
1187 $oldFileQuery = OldLocalFile
::getQueryInfo();
1189 $tables = $oldFileQuery['tables'];
1190 $fields = $oldFileQuery['fields'];
1191 $join_conds = $oldFileQuery['joins'];
1192 $conds = $opts = [];
1193 $eq = $inc ?
'=' : '';
1194 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1197 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1201 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1205 $opts['LIMIT'] = $limit;
1208 // Search backwards for time > x queries
1209 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1210 $opts['ORDER BY'] = "oi_timestamp $order";
1211 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1213 // Avoid PHP 7.1 warning from passing $this by reference
1215 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1216 &$conds, &$opts, &$join_conds ] );
1218 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1221 foreach ( $res as $row ) {
1222 $r[] = $this->repo
->newFileFromRow( $row );
1225 if ( $order == 'ASC' ) {
1226 $r = array_reverse( $r ); // make sure it ends up descending
1233 * Returns the history of this file, line by line.
1234 * starts with current version, then old versions.
1235 * uses $this->historyLine to check which line to return:
1236 * 0 return line for current version
1237 * 1 query for old versions, return first one
1238 * 2, ... return next old version from above query
1241 public function nextHistoryLine() {
1242 # Polymorphic function name to distinguish foreign and local fetches
1243 $fname = static::class . '::' . __FUNCTION__
;
1245 $dbr = $this->repo
->getReplicaDB();
1247 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1248 $fileQuery = self
::getQueryInfo();
1249 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1250 $fileQuery['fields'] +
[
1251 'oi_archive_name' => $dbr->addQuotes( '' ),
1254 [ 'img_name' => $this->title
->getDBkey() ],
1260 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1261 $this->historyRes
= null;
1265 } elseif ( $this->historyLine
== 1 ) {
1266 $fileQuery = OldLocalFile
::getQueryInfo();
1267 $this->historyRes
= $dbr->select(
1268 $fileQuery['tables'],
1269 $fileQuery['fields'],
1270 [ 'oi_name' => $this->title
->getDBkey() ],
1272 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1276 $this->historyLine++
;
1278 return $dbr->fetchObject( $this->historyRes
);
1282 * Reset the history pointer to the first element of the history
1284 public function resetHistory() {
1285 $this->historyLine
= 0;
1287 if ( !is_null( $this->historyRes
) ) {
1288 $this->historyRes
= null;
1292 /** getHashPath inherited */
1293 /** getRel inherited */
1294 /** getUrlRel inherited */
1295 /** getArchiveRel inherited */
1296 /** getArchivePath inherited */
1297 /** getThumbPath inherited */
1298 /** getArchiveUrl inherited */
1299 /** getThumbUrl inherited */
1300 /** getArchiveVirtualUrl inherited */
1301 /** getThumbVirtualUrl inherited */
1302 /** isHashed inherited */
1305 * Upload a file and record it in the DB
1306 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1307 * @param string $comment Upload description
1308 * @param string $pageText Text to use for the new description page,
1309 * if a new description page is created
1310 * @param int|bool $flags Flags for publish()
1311 * @param array|bool $props File properties, if known. This can be used to
1312 * reduce the upload time when uploading virtual URLs for which the file
1313 * info is already known
1314 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1316 * @param User|null $user User object or null to use $wgUser
1317 * @param string[] $tags Change tags to add to the log entry and page revision.
1318 * (This doesn't check $user's permissions.)
1319 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1320 * upload, see T193621
1321 * @param bool $revert If this file upload is a revert
1322 * @return Status On success, the value member contains the
1323 * archive name, or an empty string if it was a new file.
1325 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1326 $timestamp = false, $user = null, $tags = [],
1327 $createNullRevision = true, $revert = false
1329 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1330 return $this->readOnlyFatalStatus();
1331 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1332 // Check this in advance to avoid writing to FileBackend and the file tables,
1333 // only to fail on insert the revision due to the text store being unavailable.
1334 return $this->readOnlyFatalStatus();
1337 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1339 if ( FileRepo
::isVirtualUrl( $srcPath )
1340 || FileBackend
::isStoragePath( $srcPath )
1342 $props = $this->repo
->getFileProps( $srcPath );
1344 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1345 $props = $mwProps->getPropsFromPath( $srcPath, true );
1350 $handler = MediaHandler
::getHandler( $props['mime'] );
1352 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1354 if ( !is_array( $metadata ) ) {
1358 $options['headers'] = $handler->getContentHeaders( $metadata );
1360 $options['headers'] = [];
1363 // Trim spaces on user supplied text
1364 $comment = trim( $comment );
1367 $status = $this->publish( $src, $flags, $options );
1369 if ( $status->successCount
>= 2 ) {
1370 // There will be a copy+(one of move,copy,store).
1371 // The first succeeding does not commit us to updating the DB
1372 // since it simply copied the current version to a timestamped file name.
1373 // It is only *preferable* to avoid leaving such files orphaned.
1374 // Once the second operation goes through, then the current version was
1375 // updated and we must therefore update the DB too.
1376 $oldver = $status->value
;
1377 $uploadStatus = $this->recordUpload2(
1385 $createNullRevision,
1388 if ( !$uploadStatus->isOK() ) {
1389 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1390 // update filenotfound error with more specific path
1391 $status->fatal( 'filenotfound', $srcPath );
1393 $status->merge( $uploadStatus );
1403 * Record a file upload in the upload log and the image table
1404 * @param string $oldver
1405 * @param string $desc
1406 * @param string $license
1407 * @param string $copyStatus
1408 * @param string $source
1409 * @param bool $watch
1410 * @param string|bool $timestamp
1411 * @param User|null $user User object or null to use $wgUser
1414 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1415 $watch = false, $timestamp = false, User
$user = null ) {
1421 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1423 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1428 $user->addWatch( $this->getTitle() );
1435 * Record a file upload in the upload log and the image table
1436 * @param string $oldver
1437 * @param string $comment
1438 * @param string $pageText
1439 * @param bool|array $props
1440 * @param string|bool $timestamp
1441 * @param null|User $user
1442 * @param string[] $tags
1443 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1444 * upload, see T193621
1445 * @param bool $revert If this file upload is a revert
1448 function recordUpload2(
1449 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1450 $createNullRevision = true, $revert = false
1452 global $wgActorTableSchemaMigrationStage;
1454 if ( is_null( $user ) ) {
1459 $dbw = $this->repo
->getMasterDB();
1461 # Imports or such might force a certain timestamp; otherwise we generate
1462 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1463 if ( $timestamp === false ) {
1464 $timestamp = $dbw->timestamp();
1465 $allowTimeKludge = true;
1467 $allowTimeKludge = false;
1470 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1471 $props['description'] = $comment;
1472 $props['user'] = $user->getId();
1473 $props['user_text'] = $user->getName();
1474 $props['actor'] = $user->getActorId( $dbw );
1475 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1476 $this->setProps( $props );
1478 # Fail now if the file isn't there
1479 if ( !$this->fileExists
) {
1480 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1482 return Status
::newFatal( 'filenotfound', $this->getRel() );
1485 $dbw->startAtomic( __METHOD__
);
1487 # Test to see if the row exists using INSERT IGNORE
1488 # This avoids race conditions by locking the row until the commit, and also
1489 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1490 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1491 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1492 $actorMigration = ActorMigration
::newMigration();
1493 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1494 $dbw->insert( 'image',
1496 'img_name' => $this->getName(),
1497 'img_size' => $this->size
,
1498 'img_width' => intval( $this->width
),
1499 'img_height' => intval( $this->height
),
1500 'img_bits' => $this->bits
,
1501 'img_media_type' => $this->media_type
,
1502 'img_major_mime' => $this->major_mime
,
1503 'img_minor_mime' => $this->minor_mime
,
1504 'img_timestamp' => $timestamp,
1505 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1506 'img_sha1' => $this->sha1
1507 ] +
$commentFields +
$actorFields,
1511 $reupload = ( $dbw->affectedRows() == 0 );
1514 $row = $dbw->selectRow(
1516 [ 'img_timestamp', 'img_sha1' ],
1517 [ 'img_name' => $this->getName() ],
1519 [ 'LOCK IN SHARE MODE' ]
1522 if ( $row && $row->img_sha1
=== $this->sha1
) {
1523 $dbw->endAtomic( __METHOD__
);
1524 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1525 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1526 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1529 if ( $allowTimeKludge ) {
1530 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1531 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1532 # Avoid a timestamp that is not newer than the last version
1533 # TODO: the image/oldimage tables should be like page/revision with an ID field
1534 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1535 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1536 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1537 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1541 $tables = [ 'image' ];
1543 'oi_name' => 'img_name',
1544 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1545 'oi_size' => 'img_size',
1546 'oi_width' => 'img_width',
1547 'oi_height' => 'img_height',
1548 'oi_bits' => 'img_bits',
1549 'oi_description_id' => 'img_description_id',
1550 'oi_timestamp' => 'img_timestamp',
1551 'oi_metadata' => 'img_metadata',
1552 'oi_media_type' => 'img_media_type',
1553 'oi_major_mime' => 'img_major_mime',
1554 'oi_minor_mime' => 'img_minor_mime',
1555 'oi_sha1' => 'img_sha1',
1559 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1560 $fields['oi_user'] = 'img_user';
1561 $fields['oi_user_text'] = 'img_user_text';
1563 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1564 $fields['oi_actor'] = 'img_actor';
1568 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1570 // Upgrade any rows that are still old-style. Otherwise an upgrade
1571 // might be missed if a deletion happens while the migration script
1573 $res = $dbw->select(
1575 [ 'img_name', 'img_user', 'img_user_text' ],
1576 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1579 foreach ( $res as $row ) {
1580 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1583 [ 'img_actor' => $actorId ],
1584 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1590 # (T36993) Note: $oldver can be empty here, if the previous
1591 # version of the file was broken. Allow registration of the new
1592 # version to continue anyway, because that's better than having
1593 # an image that's not fixable by user operations.
1594 # Collision, this is an update of a file
1595 # Insert previous contents into oldimage
1596 $dbw->insertSelect( 'oldimage', $tables, $fields,
1597 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1599 # Update the current image row
1600 $dbw->update( 'image',
1602 'img_size' => $this->size
,
1603 'img_width' => intval( $this->width
),
1604 'img_height' => intval( $this->height
),
1605 'img_bits' => $this->bits
,
1606 'img_media_type' => $this->media_type
,
1607 'img_major_mime' => $this->major_mime
,
1608 'img_minor_mime' => $this->minor_mime
,
1609 'img_timestamp' => $timestamp,
1610 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1611 'img_sha1' => $this->sha1
1612 ] +
$commentFields +
$actorFields,
1613 [ 'img_name' => $this->getName() ],
1618 $descTitle = $this->getTitle();
1619 $descId = $descTitle->getArticleID();
1620 $wikiPage = new WikiFilePage( $descTitle );
1621 $wikiPage->setFile( $this );
1623 // Determine log action. If reupload is done by reverting, use a special log_action.
1624 if ( $revert === true ) {
1625 $logAction = 'revert';
1626 } elseif ( $reupload === true ) {
1627 $logAction = 'overwrite';
1629 $logAction = 'upload';
1631 // Add the log entry...
1632 $logEntry = new ManualLogEntry( 'upload', $logAction );
1633 $logEntry->setTimestamp( $this->timestamp
);
1634 $logEntry->setPerformer( $user );
1635 $logEntry->setComment( $comment );
1636 $logEntry->setTarget( $descTitle );
1637 // Allow people using the api to associate log entries with the upload.
1638 // Log has a timestamp, but sometimes different from upload timestamp.
1639 $logEntry->setParameters(
1641 'img_sha1' => $this->sha1
,
1642 'img_timestamp' => $timestamp,
1645 // Note we keep $logId around since during new image
1646 // creation, page doesn't exist yet, so log_page = 0
1647 // but we want it to point to the page we're making,
1648 // so we later modify the log entry.
1649 // For a similar reason, we avoid making an RC entry
1650 // now and wait until the page exists.
1651 $logId = $logEntry->insert();
1653 if ( $descTitle->exists() ) {
1654 // Use own context to get the action text in content language
1655 $formatter = LogFormatter
::newFromEntry( $logEntry );
1656 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1657 $editSummary = $formatter->getPlainActionText();
1659 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1666 if ( $nullRevision ) {
1667 $nullRevision->insertOn( $dbw );
1669 'NewRevisionFromEditComplete',
1670 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1672 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1673 // Associate null revision id
1674 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1677 $newPageContent = null;
1679 // Make the description page and RC log entry post-commit
1680 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1683 # Defer purges, page creation, and link updates in case they error out.
1684 # The most important thing is that files and the DB registry stay synced.
1685 $dbw->endAtomic( __METHOD__
);
1686 $fname = __METHOD__
;
1688 # Do some cache purges after final commit so that:
1689 # a) Changes are more likely to be seen post-purge
1690 # b) They won't cause rollback of the log publish/update above
1691 DeferredUpdates
::addUpdate(
1692 new AutoCommitUpdate(
1696 $reupload, $wikiPage, $newPageContent, $comment, $user,
1697 $logEntry, $logId, $descId, $tags, $fname
1699 # Update memcache after the commit
1700 $this->invalidateCache();
1702 $updateLogPage = false;
1703 if ( $newPageContent ) {
1704 # New file page; create the description page.
1705 # There's already a log entry, so don't make a second RC entry
1706 # CDN and file cache for the description page are purged by doEditContent.
1707 $status = $wikiPage->doEditContent(
1710 EDIT_NEW | EDIT_SUPPRESS_RC
,
1715 if ( isset( $status->value
['revision'] ) ) {
1716 /** @var Revision $rev */
1717 $rev = $status->value
['revision'];
1718 // Associate new page revision id
1719 $logEntry->setAssociatedRevId( $rev->getId() );
1721 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1722 // which is triggered on $descTitle by doEditContent() above.
1723 if ( isset( $status->value
['revision'] ) ) {
1724 /** @var Revision $rev */
1725 $rev = $status->value
['revision'];
1726 $updateLogPage = $rev->getPage();
1729 # Existing file page: invalidate description page cache
1730 $wikiPage->getTitle()->invalidateCache();
1731 $wikiPage->getTitle()->purgeSquid();
1732 # Allow the new file version to be patrolled from the page footer
1733 Article
::purgePatrolFooterCache( $descId );
1736 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1737 # but setAssociatedRevId() wasn't called at that point yet...
1738 $logParams = $logEntry->getParameters();
1739 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1740 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1741 if ( $updateLogPage ) {
1742 # Also log page, in case where we just created it above
1743 $update['log_page'] = $updateLogPage;
1745 $this->getRepo()->getMasterDB()->update(
1748 [ 'log_id' => $logId ],
1751 $this->getRepo()->getMasterDB()->insert(
1754 'ls_field' => 'associated_rev_id',
1755 'ls_value' => $logEntry->getAssociatedRevId(),
1756 'ls_log_id' => $logId,
1761 # Add change tags, if any
1763 $logEntry->addTags( $tags );
1766 # Uploads can be patrolled
1767 $logEntry->setIsPatrollable( true );
1769 # Now that the log entry is up-to-date, make an RC entry.
1770 $logEntry->publish( $logId );
1772 # Run hook for other updates (typically more cache purging)
1773 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1776 # Delete old thumbnails
1777 $this->purgeThumbnails();
1778 # Remove the old file from the CDN cache
1779 DeferredUpdates
::addUpdate(
1780 new CdnCacheUpdate( [ $this->getUrl() ] ),
1781 DeferredUpdates
::PRESEND
1784 # Update backlink pages pointing to this title if created
1785 LinksUpdate
::queueRecursiveJobsForTable(
1793 $this->prerenderThumbnails();
1796 DeferredUpdates
::PRESEND
1800 # This is a new file, so update the image count
1801 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1804 # Invalidate cache for all pages using this file
1805 DeferredUpdates
::addUpdate(
1806 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1809 return Status
::newGood();
1813 * Move or copy a file to its public location. If a file exists at the
1814 * destination, move it to an archive. Returns a Status object with
1815 * the archive name in the "value" member on success.
1817 * The archive name should be passed through to recordUpload for database
1820 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1821 * @param int $flags A bitwise combination of:
1822 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1823 * @param array $options Optional additional parameters
1824 * @return Status On success, the value member contains the
1825 * archive name, or an empty string if it was a new file.
1827 function publish( $src, $flags = 0, array $options = [] ) {
1828 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1832 * Move or copy a file to a specified location. Returns a Status
1833 * object with the archive name in the "value" member on success.
1835 * The archive name should be passed through to recordUpload for database
1838 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1839 * @param string $dstRel Target relative path
1840 * @param int $flags A bitwise combination of:
1841 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1842 * @param array $options Optional additional parameters
1843 * @return Status On success, the value member contains the
1844 * archive name, or an empty string if it was a new file.
1846 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1847 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1849 $repo = $this->getRepo();
1850 if ( $repo->getReadOnlyReason() !== false ) {
1851 return $this->readOnlyFatalStatus();
1856 if ( $this->isOld() ) {
1857 $archiveRel = $dstRel;
1858 $archiveName = basename( $archiveRel );
1860 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1861 $archiveRel = $this->getArchiveRel( $archiveName );
1864 if ( $repo->hasSha1Storage() ) {
1865 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1866 ?
$repo->getFileSha1( $srcPath )
1867 : FSFile
::getSha1Base36FromPath( $srcPath );
1868 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1869 $wrapperBackend = $repo->getBackend();
1870 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1871 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1872 $status = $repo->quickImport( $src, $dst );
1873 if ( $flags & File
::DELETE_SOURCE
) {
1877 if ( $this->exists() ) {
1878 $status->value
= $archiveName;
1881 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1882 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1884 if ( $status->value
== 'new' ) {
1885 $status->value
= '';
1887 $status->value
= $archiveName;
1895 /** getLinksTo inherited */
1896 /** getExifData inherited */
1897 /** isLocal inherited */
1898 /** wasDeleted inherited */
1901 * Move file to the new title
1903 * Move current, old version and all thumbnails
1904 * to the new filename. Old file is deleted.
1906 * Cache purging is done; checks for validity
1907 * and logging are caller's responsibility
1909 * @param Title $target New file name
1912 function move( $target ) {
1913 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1914 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1915 return $this->readOnlyFatalStatus();
1918 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1919 $batch = new LocalFileMoveBatch( $this, $target );
1922 $batch->addCurrent();
1923 $archiveNames = $batch->addOlds();
1924 $status = $batch->execute();
1927 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1929 // Purge the source and target files outside the transaction...
1930 $oldTitleFile = $localRepo->newFile( $this->title
);
1931 $newTitleFile = $localRepo->newFile( $target );
1932 DeferredUpdates
::addUpdate(
1933 new AutoCommitUpdate(
1934 $this->getRepo()->getMasterDB(),
1936 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1937 $oldTitleFile->purgeEverything();
1938 foreach ( $archiveNames as $archiveName ) {
1939 /** @var OldLocalFile $oldTitleFile */
1940 '@phan-var OldLocalFile $oldTitleFile';
1941 $oldTitleFile->purgeOldThumbnails( $archiveName );
1943 $newTitleFile->purgeEverything();
1946 DeferredUpdates
::PRESEND
1949 if ( $status->isOK() ) {
1950 // Now switch the object
1951 $this->title
= $target;
1952 // Force regeneration of the name and hashpath
1954 $this->hashPath
= null;
1961 * Delete all versions of the file.
1963 * Moves the files into an archive directory (or deletes them)
1964 * and removes the database rows.
1966 * Cache purging is done; logging is caller's responsibility.
1968 * @param string $reason
1969 * @param bool $suppress
1970 * @param User|null $user
1973 function delete( $reason, $suppress = false, $user = null ) {
1974 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1975 return $this->readOnlyFatalStatus();
1978 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1981 $batch->addCurrent();
1982 // Get old version relative paths
1983 $archiveNames = $batch->addOlds();
1984 $status = $batch->execute();
1987 if ( $status->isOK() ) {
1988 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1991 // To avoid slow purges in the transaction, move them outside...
1992 DeferredUpdates
::addUpdate(
1993 new AutoCommitUpdate(
1994 $this->getRepo()->getMasterDB(),
1996 function () use ( $archiveNames ) {
1997 $this->purgeEverything();
1998 foreach ( $archiveNames as $archiveName ) {
1999 $this->purgeOldThumbnails( $archiveName );
2003 DeferredUpdates
::PRESEND
2008 foreach ( $archiveNames as $archiveName ) {
2009 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2011 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2017 * Delete an old version of the file.
2019 * Moves the file into an archive directory (or deletes it)
2020 * and removes the database row.
2022 * Cache purging is done; logging is caller's responsibility.
2024 * @param string $archiveName
2025 * @param string $reason
2026 * @param bool $suppress
2027 * @param User|null $user
2028 * @throws MWException Exception on database or file store failure
2031 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2032 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2033 return $this->readOnlyFatalStatus();
2036 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2039 $batch->addOld( $archiveName );
2040 $status = $batch->execute();
2043 $this->purgeOldThumbnails( $archiveName );
2044 if ( $status->isOK() ) {
2045 $this->purgeDescription();
2048 DeferredUpdates
::addUpdate(
2049 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2050 DeferredUpdates
::PRESEND
2057 * Restore all or specified deleted revisions to the given file.
2058 * Permissions and logging are left to the caller.
2060 * May throw database exceptions on error.
2062 * @param array $versions Set of record ids of deleted items to restore,
2063 * or empty to restore all revisions.
2064 * @param bool $unsuppress
2067 function restore( $versions = [], $unsuppress = false ) {
2068 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2069 return $this->readOnlyFatalStatus();
2072 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2078 $batch->addIds( $versions );
2080 $status = $batch->execute();
2081 if ( $status->isGood() ) {
2082 $cleanupStatus = $batch->cleanup();
2083 $cleanupStatus->successCount
= 0;
2084 $cleanupStatus->failCount
= 0;
2085 $status->merge( $cleanupStatus );
2092 /** isMultipage inherited */
2093 /** pageCount inherited */
2094 /** scaleHeight inherited */
2095 /** getImageSize inherited */
2098 * Get the URL of the file description page.
2101 function getDescriptionUrl() {
2102 return $this->title
->getLocalURL();
2106 * Get the HTML text of the description page
2107 * This is not used by ImagePage for local files, since (among other things)
2108 * it skips the parser cache.
2110 * @param Language|null $lang What language to get description in (Optional)
2111 * @return string|false
2113 function getDescriptionText( Language
$lang = null ) {
2114 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2115 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2120 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2121 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2124 // audience check failed
2128 $pout = $rendered->getRevisionParserOutput();
2129 return $pout->getText();
2133 * @param int $audience
2134 * @param User|null $user
2137 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2139 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2141 } elseif ( $audience == self
::FOR_THIS_USER
2142 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2146 return $this->description
;
2151 * @return bool|string
2153 function getTimestamp() {
2156 return $this->timestamp
;
2160 * @return bool|string
2162 public function getDescriptionTouched() {
2163 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2164 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2165 // need to differentiate between null (uninitialized) and false (failed to load).
2166 if ( $this->descriptionTouched
=== null ) {
2168 'page_namespace' => $this->title
->getNamespace(),
2169 'page_title' => $this->title
->getDBkey()
2171 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2172 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2175 return $this->descriptionTouched
;
2181 function getSha1() {
2183 // Initialise now if necessary
2184 if ( $this->sha1
== '' && $this->fileExists
) {
2187 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2188 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2189 $dbw = $this->repo
->getMasterDB();
2190 $dbw->update( 'image',
2191 [ 'img_sha1' => $this->sha1
],
2192 [ 'img_name' => $this->getName() ],
2194 $this->invalidateCache();
2204 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2206 function isCacheable() {
2209 // If extra data (metadata) was not loaded then it must have been large
2210 return $this->extraDataLoaded
2211 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2218 public function acquireFileLock() {
2219 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2220 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2228 public function releaseFileLock() {
2229 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2230 [ $this->getPath() ], LockManager
::LOCK_EX
2235 * Start an atomic DB section and lock the image for update
2236 * or increments a reference counter if the lock is already held
2238 * This method should not be used outside of LocalFile/LocalFile*Batch
2240 * @throws LocalFileLockError Throws an error if the lock was not acquired
2241 * @return bool Whether the file lock owns/spawned the DB transaction
2243 public function lock() {
2244 if ( !$this->locked
) {
2245 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2247 $dbw = $this->repo
->getMasterDB();
2248 $makesTransaction = !$dbw->trxLevel();
2249 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2250 // T56736: use simple lock to handle when the file does not exist.
2251 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2252 // Also, that would cause contention on INSERT of similarly named rows.
2253 $status = $this->acquireFileLock(); // represents all versions of the file
2254 if ( !$status->isGood() ) {
2255 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2256 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2258 throw new LocalFileLockError( $status );
2260 // Release the lock *after* commit to avoid row-level contention.
2261 // Make sure it triggers on rollback() as well as commit() (T132921).
2262 $dbw->onTransactionResolution(
2263 function () use ( $logger ) {
2264 $status = $this->releaseFileLock();
2265 if ( !$status->isGood() ) {
2266 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2271 // Callers might care if the SELECT snapshot is safely fresh
2272 $this->lockedOwnTrx
= $makesTransaction;
2277 return $this->lockedOwnTrx
;
2281 * Decrement the lock reference count and end the atomic section if it reaches zero
2283 * This method should not be used outside of LocalFile/LocalFile*Batch
2285 * The commit and loc release will happen when no atomic sections are active, which
2286 * may happen immediately or at some point after calling this
2288 public function unlock() {
2289 if ( $this->locked
) {
2291 if ( !$this->locked
) {
2292 $dbw = $this->repo
->getMasterDB();
2293 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2294 $this->lockedOwnTrx
= false;
2302 protected function readOnlyFatalStatus() {
2303 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2304 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2308 * Clean up any dangling locks
2310 function __destruct() {