3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use Wikimedia\AtEase\AtEase
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\IResultWrapper
;
29 use MediaWiki\MediaWikiServices
;
32 * Class to represent a local file in the wiki's own database
34 * Provides methods to retrieve paths (physical, logical, URL),
35 * to generate image thumbnails or for uploading.
37 * Note that only the repo object knows what its file class is called. You should
38 * never name a file class explictly outside of the repo class. Instead use the
39 * repo's factory functions to generate file objects, for example:
41 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
43 * Consider the services container below;
45 * $services = MediaWikiServices::getInstance();
47 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
48 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
50 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
51 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
52 * and $this->repoGroup->getLocalRepo()->newFile().
54 * @ingroup FileAbstraction
56 class LocalFile
extends File
{
57 const VERSION
= 11; // cache version
59 const CACHE_FIELD_MAX_LEN
= 1000;
61 /** @var bool Does the file exist on disk? (loadFromXxx) */
62 protected $fileExists;
64 /** @var int Image width */
67 /** @var int Image height */
70 /** @var int Returned by getimagesize (loadFromXxx) */
73 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
74 protected $media_type;
76 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
79 /** @var int Size in bytes (loadFromXxx) */
82 /** @var string Handler-specific metadata */
85 /** @var string SHA-1 base 36 content hash */
88 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
89 protected $dataLoaded;
91 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
92 protected $extraDataLoaded;
94 /** @var int Bitfield akin to rev_deleted */
98 protected $repoClass = LocalRepo
::class;
100 /** @var int Number of line to return by nextHistoryLine() (constructor) */
101 private $historyLine;
103 /** @var IResultWrapper|null Result of the query for the file's history (nextHistoryLine) */
106 /** @var string Major MIME type */
109 /** @var string Minor MIME type */
112 /** @var string Upload timestamp */
115 /** @var User Uploader */
118 /** @var string Description of current revision of the file */
119 private $description;
121 /** @var string TS_MW timestamp of the last change of the file description */
122 private $descriptionTouched;
124 /** @var bool Whether the row was upgraded on load */
127 /** @var bool Whether the row was scheduled to upgrade on load */
130 /** @var bool True if the image row is locked */
133 /** @var bool True if the image row is locked with a lock initiated transaction */
134 private $lockedOwnTrx;
136 /** @var bool True if file is not present in file system. Not to be cached in memcached */
139 // @note: higher than IDBAccessObject constants
140 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
142 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
145 * Create a LocalFile from a title
146 * Do not call this except from inside a repo class.
148 * Note: $unused param is only here to avoid an E_STRICT
150 * @param Title $title
151 * @param FileRepo $repo
152 * @param null $unused
156 static function newFromTitle( $title, $repo, $unused = null ) {
157 return new static( $title, $repo );
161 * Create a LocalFile from a title
162 * Do not call this except from inside a repo class.
164 * @param stdClass $row
165 * @param FileRepo $repo
169 static function newFromRow( $row, $repo ) {
170 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
171 $file = new static( $title, $repo );
172 $file->loadFromRow( $row );
178 * Create a LocalFile from a SHA-1 key
179 * Do not call this except from inside a repo class.
181 * @param string $sha1 Base-36 SHA-1
182 * @param LocalRepo $repo
183 * @param string|bool $timestamp MW_timestamp (optional)
184 * @return bool|LocalFile
186 static function newFromKey( $sha1, $repo, $timestamp = false ) {
187 $dbr = $repo->getReplicaDB();
189 $conds = [ 'img_sha1' => $sha1 ];
191 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
194 $fileQuery = static::getQueryInfo();
195 $row = $dbr->selectRow(
196 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
199 return static::newFromRow( $row, $repo );
206 * Fields in the image table
207 * @deprecated since 1.31, use self::getQueryInfo() instead.
210 static function selectFields() {
211 global $wgActorTableSchemaMigrationStage;
213 wfDeprecated( __METHOD__
, '1.31' );
214 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
215 // If code is using this instead of self::getQueryInfo(), there's a
216 // decent chance it's going to try to directly access
217 // $row->img_user or $row->img_user_text and we can't give it
218 // useful values here once those aren't being used anymore.
219 throw new BadMethodCallException(
220 'Cannot use ' . __METHOD__
221 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
237 'img_actor' => 'NULL',
240 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
244 * Return the tables, fields, and join conditions to be selected to create
245 * a new localfile object.
247 * @param string[] $options
248 * - omit-lazy: Omit fields that are lazily cached.
249 * @return array[] With three keys:
250 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
251 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
252 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
254 public static function getQueryInfo( array $options = [] ) {
255 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
256 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
258 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
271 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
272 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
275 if ( in_array( 'omit-nonlazy', $options, true ) ) {
276 // Internal use only for getting only the lazy fields
279 if ( !in_array( 'omit-lazy', $options, true ) ) {
280 // Note: Keep this in sync with self::getLazyCacheFields()
281 $ret['fields'][] = 'img_metadata';
288 * Do not call this except from inside a repo class.
289 * @param Title $title
290 * @param FileRepo $repo
292 function __construct( $title, $repo ) {
293 parent
::__construct( $title, $repo );
295 $this->metadata
= '';
296 $this->historyLine
= 0;
297 $this->historyRes
= null;
298 $this->dataLoaded
= false;
299 $this->extraDataLoaded
= false;
301 $this->assertRepoDefined();
302 $this->assertTitleDefined();
306 * Get the memcached key for the main data for this file, or false if
307 * there is no access to the shared cache.
308 * @return string|bool
310 function getCacheKey() {
311 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
315 * @param WANObjectCache $cache
319 public function getMutableCacheKeys( WANObjectCache
$cache ) {
320 return [ $this->getCacheKey() ];
324 * Try to load file metadata from memcached, falling back to the database
326 private function loadFromCache() {
327 $this->dataLoaded
= false;
328 $this->extraDataLoaded
= false;
330 $key = $this->getCacheKey();
332 $this->loadFromDB( self
::READ_NORMAL
);
337 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
338 $cachedValues = $cache->getWithSetCallback(
341 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
342 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
344 $this->loadFromDB( self
::READ_NORMAL
);
346 $fields = $this->getCacheFields( '' );
347 $cacheVal['fileExists'] = $this->fileExists
;
348 if ( $this->fileExists
) {
349 foreach ( $fields as $field ) {
350 $cacheVal[$field] = $this->$field;
353 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
354 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
355 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
357 // Strip off excessive entries from the subset of fields that can become large.
358 // If the cache value gets to large it will not fit in memcached and nothing will
359 // get cached at all, causing master queries for any file access.
360 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
361 if ( isset( $cacheVal[$field] )
362 && strlen( $cacheVal[$field] ) > 100 * 1024
364 unset( $cacheVal[$field] ); // don't let the value get too big
368 if ( $this->fileExists
) {
369 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
371 $ttl = $cache::TTL_DAY
;
376 [ 'version' => self
::VERSION
]
379 $this->fileExists
= $cachedValues['fileExists'];
380 if ( $this->fileExists
) {
381 $this->setProps( $cachedValues );
384 $this->dataLoaded
= true;
385 $this->extraDataLoaded
= true;
386 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
387 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
392 * Purge the file object/metadata cache
394 public function invalidateCache() {
395 $key = $this->getCacheKey();
400 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
401 function () use ( $key ) {
402 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
409 * Load metadata from the file itself
411 function loadFromFile() {
412 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
413 $this->setProps( $props );
417 * Returns the list of object properties that are included as-is in the cache.
418 * @param string $prefix Must be the empty string
420 * @since 1.31 No longer accepts a non-empty $prefix
422 protected function getCacheFields( $prefix = 'img_' ) {
423 if ( $prefix !== '' ) {
424 throw new InvalidArgumentException(
425 __METHOD__
. ' with a non-empty prefix is no longer supported.'
429 // See self::getQueryInfo() for the fetching of the data from the DB,
430 // self::loadFromRow() for the loading of the object from the DB row,
431 // and self::loadFromCache() for the caching, and self::setProps() for
432 // populating the object from an array of data.
433 return [ 'size', 'width', 'height', 'bits', 'media_type',
434 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
438 * Returns the list of object properties that are included as-is in the
439 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
440 * @param string $prefix Must be the empty string
442 * @since 1.31 No longer accepts a non-empty $prefix
444 protected function getLazyCacheFields( $prefix = 'img_' ) {
445 if ( $prefix !== '' ) {
446 throw new InvalidArgumentException(
447 __METHOD__
. ' with a non-empty prefix is no longer supported.'
451 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
452 return [ 'metadata' ];
456 * Load file metadata from the DB
459 function loadFromDB( $flags = 0 ) {
460 $fname = static::class . '::' . __FUNCTION__
;
462 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
463 $this->dataLoaded
= true;
464 $this->extraDataLoaded
= true;
466 $dbr = ( $flags & self
::READ_LATEST
)
467 ?
$this->repo
->getMasterDB()
468 : $this->repo
->getReplicaDB();
470 $fileQuery = static::getQueryInfo();
471 $row = $dbr->selectRow(
472 $fileQuery['tables'],
473 $fileQuery['fields'],
474 [ 'img_name' => $this->getName() ],
481 $this->loadFromRow( $row );
483 $this->fileExists
= false;
488 * Load lazy file metadata from the DB.
489 * This covers fields that are sometimes not cached.
491 protected function loadExtraFromDB() {
492 $fname = static::class . '::' . __FUNCTION__
;
494 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
495 $this->extraDataLoaded
= true;
497 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
499 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
503 foreach ( $fieldMap as $name => $value ) {
504 $this->$name = $value;
507 throw new MWException( "Could not find data for image '{$this->getName()}'." );
512 * @param IDatabase $dbr
513 * @param string $fname
514 * @return string[]|bool
516 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
519 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
520 $row = $dbr->selectRow(
521 $fileQuery['tables'],
522 $fileQuery['fields'],
524 'img_name' => $this->getName(),
525 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
532 $fieldMap = $this->unprefixRow( $row, 'img_' );
534 # File may have been uploaded over in the meantime; check the old versions
535 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
536 $row = $dbr->selectRow(
537 $fileQuery['tables'],
538 $fileQuery['fields'],
540 'oi_name' => $this->getName(),
541 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
548 $fieldMap = $this->unprefixRow( $row, 'oi_' );
552 if ( isset( $fieldMap['metadata'] ) ) {
553 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
560 * @param array|object $row
561 * @param string $prefix
562 * @throws MWException
565 protected function unprefixRow( $row, $prefix = 'img_' ) {
566 $array = (array)$row;
567 $prefixLength = strlen( $prefix );
569 // Sanity check prefix once
570 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
571 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
575 foreach ( $array as $name => $value ) {
576 $decoded[substr( $name, $prefixLength )] = $value;
583 * Decode a row from the database (either object or array) to an array
584 * with timestamps and MIME types decoded, and the field prefix removed.
586 * @param string $prefix
587 * @throws MWException
590 function decodeRow( $row, $prefix = 'img_' ) {
591 $decoded = $this->unprefixRow( $row, $prefix );
593 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
594 ->getComment( 'description', (object)$decoded )->text
;
596 $decoded['user'] = User
::newFromAnyId(
597 $decoded['user'] ??
null,
598 $decoded['user_text'] ??
null,
599 $decoded['actor'] ??
null
601 unset( $decoded['user_text'], $decoded['actor'] );
603 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
605 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
607 if ( empty( $decoded['major_mime'] ) ) {
608 $decoded['mime'] = 'unknown/unknown';
610 if ( !$decoded['minor_mime'] ) {
611 $decoded['minor_mime'] = 'unknown';
613 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
616 // Trim zero padding from char/binary field
617 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
619 // Normalize some fields to integer type, per their database definition.
620 // Use unary + so that overflows will be upgraded to double instead of
621 // being trucated as with intval(). This is important to allow >2GB
622 // files on 32-bit systems.
623 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
624 $decoded[$field] = +
$decoded[$field];
631 * Load file metadata from a DB result row
634 * @param string $prefix
636 function loadFromRow( $row, $prefix = 'img_' ) {
637 $this->dataLoaded
= true;
638 $this->extraDataLoaded
= true;
640 $array = $this->decodeRow( $row, $prefix );
642 foreach ( $array as $name => $value ) {
643 $this->$name = $value;
646 $this->fileExists
= true;
650 * Load file metadata from cache or DB, unless already loaded
653 function load( $flags = 0 ) {
654 if ( !$this->dataLoaded
) {
655 if ( $flags & self
::READ_LATEST
) {
656 $this->loadFromDB( $flags );
658 $this->loadFromCache();
662 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
663 // @note: loads on name/timestamp to reduce race condition problems
664 $this->loadExtraFromDB();
669 * Upgrade a row if it needs it
671 protected function maybeUpgradeRow() {
672 global $wgUpdateCompatibleMetadata;
674 if ( wfReadOnly() ||
$this->upgrading
) {
679 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
682 $handler = $this->getHandler();
684 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
685 if ( $validity === MediaHandler
::METADATA_BAD
) {
687 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
688 $upgrade = $wgUpdateCompatibleMetadata;
694 $this->upgrading
= true;
695 // Defer updates unless in auto-commit CLI mode
696 DeferredUpdates
::addCallableUpdate( function () {
697 $this->upgrading
= false; // avoid duplicate updates
700 } catch ( LocalFileLockError
$e ) {
701 // let the other process handle it (or do it next time)
708 * @return bool Whether upgradeRow() ran for this object
710 function getUpgraded() {
711 return $this->upgraded
;
715 * Fix assorted version-related problems with the image row by reloading it from the file
717 function upgradeRow() {
720 $this->loadFromFile();
722 # Don't destroy file info of missing files
723 if ( !$this->fileExists
) {
725 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
730 $dbw = $this->repo
->getMasterDB();
731 list( $major, $minor ) = self
::splitMime( $this->mime
);
733 if ( wfReadOnly() ) {
738 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
740 $dbw->update( 'image',
742 'img_size' => $this->size
, // sanity
743 'img_width' => $this->width
,
744 'img_height' => $this->height
,
745 'img_bits' => $this->bits
,
746 'img_media_type' => $this->media_type
,
747 'img_major_mime' => $major,
748 'img_minor_mime' => $minor,
749 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
750 'img_sha1' => $this->sha1
,
752 [ 'img_name' => $this->getName() ],
756 $this->invalidateCache();
759 $this->upgraded
= true; // avoid rework/retries
763 * Set properties in this object to be equal to those given in the
764 * associative array $info. Only cacheable fields can be set.
765 * All fields *must* be set in $info except for getLazyCacheFields().
767 * If 'mime' is given, it will be split into major_mime/minor_mime.
768 * If major_mime/minor_mime are given, $this->mime will also be set.
772 function setProps( $info ) {
773 $this->dataLoaded
= true;
774 $fields = $this->getCacheFields( '' );
775 $fields[] = 'fileExists';
777 foreach ( $fields as $field ) {
778 if ( isset( $info[$field] ) ) {
779 $this->$field = $info[$field];
783 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
784 $this->user
= User
::newFromAnyId(
785 $info['user'] ??
null,
786 $info['user_text'] ??
null,
787 $info['actor'] ??
null
791 // Fix up mime fields
792 if ( isset( $info['major_mime'] ) ) {
793 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
794 } elseif ( isset( $info['mime'] ) ) {
795 $this->mime
= $info['mime'];
796 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
800 /** splitMime inherited */
801 /** getName inherited */
802 /** getTitle inherited */
803 /** getURL inherited */
804 /** getViewURL inherited */
805 /** getPath inherited */
806 /** isVisible inherited */
809 * Checks if this file exists in its parent repo, as referenced by its
814 function isMissing() {
815 if ( $this->missing
=== null ) {
816 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
817 $this->missing
= !$fileExists;
820 return $this->missing
;
824 * Return the width of the image
829 public function getWidth( $page = 1 ) {
837 if ( $this->isMultipage() ) {
838 $handler = $this->getHandler();
842 $dim = $handler->getPageDimensions( $this, $page );
844 return $dim['width'];
846 // For non-paged media, the false goes through an
847 // intval, turning failure into 0, so do same here.
856 * Return the height of the image
861 public function getHeight( $page = 1 ) {
869 if ( $this->isMultipage() ) {
870 $handler = $this->getHandler();
874 $dim = $handler->getPageDimensions( $this, $page );
876 return $dim['height'];
878 // For non-paged media, the false goes through an
879 // intval, turning failure into 0, so do same here.
883 return $this->height
;
888 * Returns user who uploaded the file
890 * @param string $type 'text', 'id', or 'object'
891 * @return int|string|User
892 * @since 1.31 Added 'object'
894 function getUser( $type = 'text' ) {
897 if ( $type === 'object' ) {
899 } elseif ( $type === 'text' ) {
900 return $this->user
->getName();
901 } elseif ( $type === 'id' ) {
902 return $this->user
->getId();
905 throw new MWException( "Unknown type '$type'." );
909 * Get short description URL for a file based on the page ID.
911 * @return string|null
912 * @throws MWException
915 public function getDescriptionShortUrl() {
916 $pageId = $this->title
->getArticleID();
918 if ( $pageId !== null ) {
919 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
920 if ( $url !== false ) {
928 * Get handler-specific metadata
931 function getMetadata() {
932 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
933 return $this->metadata
;
939 function getBitDepth() {
942 return (int)$this->bits
;
946 * Returns the size of the image file, in bytes
949 public function getSize() {
956 * Returns the MIME type of the file.
959 function getMimeType() {
966 * Returns the type of the media in the file.
967 * Use the value returned by this function with the MEDIATYPE_xxx constants.
970 function getMediaType() {
973 return $this->media_type
;
976 /** canRender inherited */
977 /** mustRender inherited */
978 /** allowInlineDisplay inherited */
979 /** isSafeFile inherited */
980 /** isTrustedFile inherited */
983 * Returns true if the file exists on disk.
984 * @return bool Whether file exist on disk.
986 public function exists() {
989 return $this->fileExists
;
992 /** getTransformScript inherited */
993 /** getUnscaledThumb inherited */
994 /** thumbName inherited */
995 /** createThumb inherited */
996 /** transform inherited */
998 /** getHandler inherited */
999 /** iconThumb inherited */
1000 /** getLastError inherited */
1003 * Get all thumbnail names previously generated for this file
1004 * @param string|bool $archiveName Name of an archive file, default false
1005 * @return array First element is the base dir, then files in that base dir.
1007 function getThumbnails( $archiveName = false ) {
1008 if ( $archiveName ) {
1009 $dir = $this->getArchiveThumbPath( $archiveName );
1011 $dir = $this->getThumbPath();
1014 $backend = $this->repo
->getBackend();
1017 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1018 foreach ( $iterator as $file ) {
1021 } catch ( FileBackendError
$e ) {
1022 } // suppress (T56674)
1028 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1030 function purgeMetadataCache() {
1031 $this->invalidateCache();
1035 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1037 * @param array $options An array potentially with the key forThumbRefresh.
1039 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1041 function purgeCache( $options = [] ) {
1042 // Refresh metadata cache
1043 $this->maybeUpgradeRow();
1044 $this->purgeMetadataCache();
1046 // Delete thumbnails
1047 $this->purgeThumbnails( $options );
1049 // Purge CDN cache for this file
1050 MediaWikiServices
::getInstance()->getHtmlCacheUpdater()->purge( $this->getUrl() );
1054 * Delete cached transformed files for an archived version only.
1055 * @param string $archiveName Name of the archived file
1057 function purgeOldThumbnails( $archiveName ) {
1058 // Get a list of old thumbnails and URLs
1059 $files = $this->getThumbnails( $archiveName );
1061 // Purge any custom thumbnail caches
1062 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1064 // Delete thumbnails
1065 $dir = array_shift( $files );
1066 $this->purgeThumbList( $dir, $files );
1070 foreach ( $files as $file ) {
1071 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1073 MediaWikiServices
::getInstance()->getHtmlCacheUpdater()->purge( $urls );
1077 * Delete cached transformed files for the current version only.
1078 * @param array $options
1080 public function purgeThumbnails( $options = [] ) {
1081 $files = $this->getThumbnails();
1082 // Always purge all files from CDN regardless of handler filters
1084 foreach ( $files as $file ) {
1085 $urls[] = $this->getThumbUrl( $file );
1087 array_shift( $urls ); // don't purge directory
1089 // Give media handler a chance to filter the file purge list
1090 if ( !empty( $options['forThumbRefresh'] ) ) {
1091 $handler = $this->getHandler();
1093 $handler->filterThumbnailPurgeList( $files, $options );
1097 // Purge any custom thumbnail caches
1098 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1100 // Delete thumbnails
1101 $dir = array_shift( $files );
1102 $this->purgeThumbList( $dir, $files );
1105 MediaWikiServices
::getInstance()->getHtmlCacheUpdater()->purge( $urls );
1109 * Prerenders a configurable set of thumbnails
1113 public function prerenderThumbnails() {
1114 global $wgUploadThumbnailRenderMap;
1118 $sizes = $wgUploadThumbnailRenderMap;
1121 foreach ( $sizes as $size ) {
1122 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1123 $jobs[] = new ThumbnailRenderJob(
1125 [ 'transformParams' => [ 'width' => $size ] ]
1131 JobQueueGroup
::singleton()->lazyPush( $jobs );
1136 * Delete a list of thumbnails visible at urls
1137 * @param string $dir Base dir of the files.
1138 * @param array $files Array of strings: relative filenames (to $dir)
1140 protected function purgeThumbList( $dir, $files ) {
1141 $fileListDebug = strtr(
1142 var_export( $files, true ),
1145 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1148 foreach ( $files as $file ) {
1149 if ( $this->repo
->supportsSha1URLs() ) {
1150 $reference = $this->getSha1();
1152 $reference = $this->getName();
1155 # Check that the reference (filename or sha1) is part of the thumb name
1156 # This is a basic sanity check to avoid erasing unrelated directories
1157 if ( strpos( $file, $reference ) !== false
1158 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1160 $purgeList[] = "{$dir}/{$file}";
1164 # Delete the thumbnails
1165 $this->repo
->quickPurgeBatch( $purgeList );
1166 # Clear out the thumbnail directory if empty
1167 $this->repo
->quickCleanDir( $dir );
1170 /** purgeDescription inherited */
1171 /** purgeEverything inherited */
1174 * @param int|null $limit Optional: Limit to number of results
1175 * @param string|int|null $start Optional: Timestamp, start from
1176 * @param string|int|null $end Optional: Timestamp, end at
1178 * @return OldLocalFile[]
1180 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1181 $dbr = $this->repo
->getReplicaDB();
1182 $oldFileQuery = OldLocalFile
::getQueryInfo();
1184 $tables = $oldFileQuery['tables'];
1185 $fields = $oldFileQuery['fields'];
1186 $join_conds = $oldFileQuery['joins'];
1187 $conds = $opts = [];
1188 $eq = $inc ?
'=' : '';
1189 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1192 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1196 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1200 $opts['LIMIT'] = $limit;
1203 // Search backwards for time > x queries
1204 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1205 $opts['ORDER BY'] = "oi_timestamp $order";
1206 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1208 // Avoid PHP 7.1 warning from passing $this by reference
1210 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1211 &$conds, &$opts, &$join_conds ] );
1213 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1216 foreach ( $res as $row ) {
1217 $r[] = $this->repo
->newFileFromRow( $row );
1220 if ( $order == 'ASC' ) {
1221 $r = array_reverse( $r ); // make sure it ends up descending
1228 * Returns the history of this file, line by line.
1229 * starts with current version, then old versions.
1230 * uses $this->historyLine to check which line to return:
1231 * 0 return line for current version
1232 * 1 query for old versions, return first one
1233 * 2, ... return next old version from above query
1236 public function nextHistoryLine() {
1237 # Polymorphic function name to distinguish foreign and local fetches
1238 $fname = static::class . '::' . __FUNCTION__
;
1240 $dbr = $this->repo
->getReplicaDB();
1242 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1243 $fileQuery = self
::getQueryInfo();
1244 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1245 $fileQuery['fields'] +
[
1246 'oi_archive_name' => $dbr->addQuotes( '' ),
1249 [ 'img_name' => $this->title
->getDBkey() ],
1255 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1256 $this->historyRes
= null;
1260 } elseif ( $this->historyLine
== 1 ) {
1261 $fileQuery = OldLocalFile
::getQueryInfo();
1262 $this->historyRes
= $dbr->select(
1263 $fileQuery['tables'],
1264 $fileQuery['fields'],
1265 [ 'oi_name' => $this->title
->getDBkey() ],
1267 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1271 $this->historyLine++
;
1273 return $dbr->fetchObject( $this->historyRes
);
1277 * Reset the history pointer to the first element of the history
1279 public function resetHistory() {
1280 $this->historyLine
= 0;
1282 if ( !is_null( $this->historyRes
) ) {
1283 $this->historyRes
= null;
1287 /** getHashPath inherited */
1288 /** getRel inherited */
1289 /** getUrlRel inherited */
1290 /** getArchiveRel inherited */
1291 /** getArchivePath inherited */
1292 /** getThumbPath inherited */
1293 /** getArchiveUrl inherited */
1294 /** getThumbUrl inherited */
1295 /** getArchiveVirtualUrl inherited */
1296 /** getThumbVirtualUrl inherited */
1297 /** isHashed inherited */
1300 * Upload a file and record it in the DB
1301 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1302 * @param string $comment Upload description
1303 * @param string $pageText Text to use for the new description page,
1304 * if a new description page is created
1305 * @param int|bool $flags Flags for publish()
1306 * @param array|bool $props File properties, if known. This can be used to
1307 * reduce the upload time when uploading virtual URLs for which the file
1308 * info is already known
1309 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1311 * @param User|null $user User object or null to use $wgUser
1312 * @param string[] $tags Change tags to add to the log entry and page revision.
1313 * (This doesn't check $user's permissions.)
1314 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1315 * upload, see T193621
1316 * @param bool $revert If this file upload is a revert
1317 * @return Status On success, the value member contains the
1318 * archive name, or an empty string if it was a new file.
1320 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1321 $timestamp = false, $user = null, $tags = [],
1322 $createNullRevision = true, $revert = false
1324 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1325 return $this->readOnlyFatalStatus();
1326 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1327 // Check this in advance to avoid writing to FileBackend and the file tables,
1328 // only to fail on insert the revision due to the text store being unavailable.
1329 return $this->readOnlyFatalStatus();
1332 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1334 if ( FileRepo
::isVirtualUrl( $srcPath )
1335 || FileBackend
::isStoragePath( $srcPath )
1337 $props = $this->repo
->getFileProps( $srcPath );
1339 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1340 $props = $mwProps->getPropsFromPath( $srcPath, true );
1345 $handler = MediaHandler
::getHandler( $props['mime'] );
1347 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1349 if ( !is_array( $metadata ) ) {
1353 $options['headers'] = $handler->getContentHeaders( $metadata );
1355 $options['headers'] = [];
1358 // Trim spaces on user supplied text
1359 $comment = trim( $comment );
1362 $status = $this->publish( $src, $flags, $options );
1364 if ( $status->successCount
>= 2 ) {
1365 // There will be a copy+(one of move,copy,store).
1366 // The first succeeding does not commit us to updating the DB
1367 // since it simply copied the current version to a timestamped file name.
1368 // It is only *preferable* to avoid leaving such files orphaned.
1369 // Once the second operation goes through, then the current version was
1370 // updated and we must therefore update the DB too.
1371 $oldver = $status->value
;
1372 $uploadStatus = $this->recordUpload2(
1380 $createNullRevision,
1383 if ( !$uploadStatus->isOK() ) {
1384 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1385 // update filenotfound error with more specific path
1386 $status->fatal( 'filenotfound', $srcPath );
1388 $status->merge( $uploadStatus );
1398 * Record a file upload in the upload log and the image table
1399 * @param string $oldver
1400 * @param string $desc
1401 * @param string $license
1402 * @param string $copyStatus
1403 * @param string $source
1404 * @param bool $watch
1405 * @param string|bool $timestamp
1406 * @param User|null $user User object or null to use $wgUser
1409 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1410 $watch = false, $timestamp = false, User
$user = null ) {
1416 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1418 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1423 $user->addWatch( $this->getTitle() );
1430 * Record a file upload in the upload log and the image table
1431 * @param string $oldver
1432 * @param string $comment
1433 * @param string $pageText
1434 * @param bool|array $props
1435 * @param string|bool $timestamp
1436 * @param null|User $user
1437 * @param string[] $tags
1438 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1439 * upload, see T193621
1440 * @param bool $revert If this file upload is a revert
1443 function recordUpload2(
1444 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1445 $createNullRevision = true, $revert = false
1447 global $wgActorTableSchemaMigrationStage;
1449 if ( is_null( $user ) ) {
1454 $dbw = $this->repo
->getMasterDB();
1456 # Imports or such might force a certain timestamp; otherwise we generate
1457 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1458 if ( $timestamp === false ) {
1459 $timestamp = $dbw->timestamp();
1460 $allowTimeKludge = true;
1462 $allowTimeKludge = false;
1465 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1466 $props['description'] = $comment;
1467 $props['user'] = $user->getId();
1468 $props['user_text'] = $user->getName();
1469 $props['actor'] = $user->getActorId( $dbw );
1470 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1471 $this->setProps( $props );
1473 # Fail now if the file isn't there
1474 if ( !$this->fileExists
) {
1475 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1477 return Status
::newFatal( 'filenotfound', $this->getRel() );
1480 $dbw->startAtomic( __METHOD__
);
1482 # Test to see if the row exists using INSERT IGNORE
1483 # This avoids race conditions by locking the row until the commit, and also
1484 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1485 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1486 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1487 $actorMigration = ActorMigration
::newMigration();
1488 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1489 $dbw->insert( 'image',
1491 'img_name' => $this->getName(),
1492 'img_size' => $this->size
,
1493 'img_width' => intval( $this->width
),
1494 'img_height' => intval( $this->height
),
1495 'img_bits' => $this->bits
,
1496 'img_media_type' => $this->media_type
,
1497 'img_major_mime' => $this->major_mime
,
1498 'img_minor_mime' => $this->minor_mime
,
1499 'img_timestamp' => $timestamp,
1500 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1501 'img_sha1' => $this->sha1
1502 ] +
$commentFields +
$actorFields,
1506 $reupload = ( $dbw->affectedRows() == 0 );
1509 $row = $dbw->selectRow(
1511 [ 'img_timestamp', 'img_sha1' ],
1512 [ 'img_name' => $this->getName() ],
1514 [ 'LOCK IN SHARE MODE' ]
1517 if ( $row && $row->img_sha1
=== $this->sha1
) {
1518 $dbw->endAtomic( __METHOD__
);
1519 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1520 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1521 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1524 if ( $allowTimeKludge ) {
1525 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1526 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1527 # Avoid a timestamp that is not newer than the last version
1528 # TODO: the image/oldimage tables should be like page/revision with an ID field
1529 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1530 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1531 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1532 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1536 $tables = [ 'image' ];
1538 'oi_name' => 'img_name',
1539 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1540 'oi_size' => 'img_size',
1541 'oi_width' => 'img_width',
1542 'oi_height' => 'img_height',
1543 'oi_bits' => 'img_bits',
1544 'oi_description_id' => 'img_description_id',
1545 'oi_timestamp' => 'img_timestamp',
1546 'oi_metadata' => 'img_metadata',
1547 'oi_media_type' => 'img_media_type',
1548 'oi_major_mime' => 'img_major_mime',
1549 'oi_minor_mime' => 'img_minor_mime',
1550 'oi_sha1' => 'img_sha1',
1554 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1555 $fields['oi_user'] = 'img_user';
1556 $fields['oi_user_text'] = 'img_user_text';
1558 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1559 $fields['oi_actor'] = 'img_actor';
1563 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1565 // Upgrade any rows that are still old-style. Otherwise an upgrade
1566 // might be missed if a deletion happens while the migration script
1568 $res = $dbw->select(
1570 [ 'img_name', 'img_user', 'img_user_text' ],
1571 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1574 foreach ( $res as $row ) {
1575 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1578 [ 'img_actor' => $actorId ],
1579 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1585 # (T36993) Note: $oldver can be empty here, if the previous
1586 # version of the file was broken. Allow registration of the new
1587 # version to continue anyway, because that's better than having
1588 # an image that's not fixable by user operations.
1589 # Collision, this is an update of a file
1590 # Insert previous contents into oldimage
1591 $dbw->insertSelect( 'oldimage', $tables, $fields,
1592 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1594 # Update the current image row
1595 $dbw->update( 'image',
1597 'img_size' => $this->size
,
1598 'img_width' => intval( $this->width
),
1599 'img_height' => intval( $this->height
),
1600 'img_bits' => $this->bits
,
1601 'img_media_type' => $this->media_type
,
1602 'img_major_mime' => $this->major_mime
,
1603 'img_minor_mime' => $this->minor_mime
,
1604 'img_timestamp' => $timestamp,
1605 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1606 'img_sha1' => $this->sha1
1607 ] +
$commentFields +
$actorFields,
1608 [ 'img_name' => $this->getName() ],
1613 $descTitle = $this->getTitle();
1614 $descId = $descTitle->getArticleID();
1615 $wikiPage = new WikiFilePage( $descTitle );
1616 $wikiPage->setFile( $this );
1618 // Determine log action. If reupload is done by reverting, use a special log_action.
1619 if ( $revert === true ) {
1620 $logAction = 'revert';
1621 } elseif ( $reupload === true ) {
1622 $logAction = 'overwrite';
1624 $logAction = 'upload';
1626 // Add the log entry...
1627 $logEntry = new ManualLogEntry( 'upload', $logAction );
1628 $logEntry->setTimestamp( $this->timestamp
);
1629 $logEntry->setPerformer( $user );
1630 $logEntry->setComment( $comment );
1631 $logEntry->setTarget( $descTitle );
1632 // Allow people using the api to associate log entries with the upload.
1633 // Log has a timestamp, but sometimes different from upload timestamp.
1634 $logEntry->setParameters(
1636 'img_sha1' => $this->sha1
,
1637 'img_timestamp' => $timestamp,
1640 // Note we keep $logId around since during new image
1641 // creation, page doesn't exist yet, so log_page = 0
1642 // but we want it to point to the page we're making,
1643 // so we later modify the log entry.
1644 // For a similar reason, we avoid making an RC entry
1645 // now and wait until the page exists.
1646 $logId = $logEntry->insert();
1648 if ( $descTitle->exists() ) {
1649 // Use own context to get the action text in content language
1650 $formatter = LogFormatter
::newFromEntry( $logEntry );
1651 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1652 $editSummary = $formatter->getPlainActionText();
1654 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1661 if ( $nullRevision ) {
1662 $nullRevision->insertOn( $dbw );
1664 'NewRevisionFromEditComplete',
1665 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1667 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1668 // Associate null revision id
1669 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1672 $newPageContent = null;
1674 // Make the description page and RC log entry post-commit
1675 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1678 # Defer purges, page creation, and link updates in case they error out.
1679 # The most important thing is that files and the DB registry stay synced.
1680 $dbw->endAtomic( __METHOD__
);
1681 $fname = __METHOD__
;
1683 # Do some cache purges after final commit so that:
1684 # a) Changes are more likely to be seen post-purge
1685 # b) They won't cause rollback of the log publish/update above
1686 DeferredUpdates
::addUpdate(
1687 new AutoCommitUpdate(
1691 $reupload, $wikiPage, $newPageContent, $comment, $user,
1692 $logEntry, $logId, $descId, $tags, $fname
1694 # Update memcache after the commit
1695 $this->invalidateCache();
1697 $updateLogPage = false;
1698 if ( $newPageContent ) {
1699 # New file page; create the description page.
1700 # There's already a log entry, so don't make a second RC entry
1701 # CDN and file cache for the description page are purged by doEditContent.
1702 $status = $wikiPage->doEditContent(
1705 EDIT_NEW | EDIT_SUPPRESS_RC
,
1710 if ( isset( $status->value
['revision'] ) ) {
1711 /** @var Revision $rev */
1712 $rev = $status->value
['revision'];
1713 // Associate new page revision id
1714 $logEntry->setAssociatedRevId( $rev->getId() );
1716 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1717 // which is triggered on $descTitle by doEditContent() above.
1718 if ( isset( $status->value
['revision'] ) ) {
1719 /** @var Revision $rev */
1720 $rev = $status->value
['revision'];
1721 $updateLogPage = $rev->getPage();
1724 # Existing file page: invalidate description page cache
1725 $title = $wikiPage->getTitle();
1726 $title->invalidateCache();
1727 MediaWikiServices
::getInstance()->getHtmlCacheUpdater()->purge( $title );
1728 # Allow the new file version to be patrolled from the page footer
1729 Article
::purgePatrolFooterCache( $descId );
1732 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1733 # but setAssociatedRevId() wasn't called at that point yet...
1734 $logParams = $logEntry->getParameters();
1735 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1736 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1737 if ( $updateLogPage ) {
1738 # Also log page, in case where we just created it above
1739 $update['log_page'] = $updateLogPage;
1741 $this->getRepo()->getMasterDB()->update(
1744 [ 'log_id' => $logId ],
1747 $this->getRepo()->getMasterDB()->insert(
1750 'ls_field' => 'associated_rev_id',
1751 'ls_value' => $logEntry->getAssociatedRevId(),
1752 'ls_log_id' => $logId,
1757 # Add change tags, if any
1759 $logEntry->setTags( $tags );
1762 # Uploads can be patrolled
1763 $logEntry->setIsPatrollable( true );
1765 # Now that the log entry is up-to-date, make an RC entry.
1766 $logEntry->publish( $logId );
1768 # Run hook for other updates (typically more cache purging)
1769 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1772 # Delete old thumbnails
1773 $this->purgeThumbnails();
1774 # Remove the old file from the CDN cache
1775 MediaWikiServices
::getInstance()
1776 ->getHtmlCacheUpdater()->purge( $this->getUrl() );
1778 # Update backlink pages pointing to this title if created
1779 LinksUpdate
::queueRecursiveJobsForTable(
1787 $this->prerenderThumbnails();
1790 DeferredUpdates
::PRESEND
1794 # This is a new file, so update the image count
1795 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1798 # Invalidate cache for all pages using this file
1799 $job = HTMLCacheUpdateJob
::newForBacklinks(
1802 [ 'causeAction' => 'file-upload', 'causeAgent' => $user->getName() ]
1804 JobQueueGroup
::singleton()->lazyPush( $job );
1806 return Status
::newGood();
1810 * Move or copy a file to its public location. If a file exists at the
1811 * destination, move it to an archive. Returns a Status object with
1812 * the archive name in the "value" member on success.
1814 * The archive name should be passed through to recordUpload for database
1817 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1818 * @param int $flags A bitwise combination of:
1819 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1820 * @param array $options Optional additional parameters
1821 * @return Status On success, the value member contains the
1822 * archive name, or an empty string if it was a new file.
1824 function publish( $src, $flags = 0, array $options = [] ) {
1825 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1829 * Move or copy a file to a specified location. Returns a Status
1830 * object with the archive name in the "value" member on success.
1832 * The archive name should be passed through to recordUpload for database
1835 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1836 * @param string $dstRel Target relative path
1837 * @param int $flags A bitwise combination of:
1838 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1839 * @param array $options Optional additional parameters
1840 * @return Status On success, the value member contains the
1841 * archive name, or an empty string if it was a new file.
1843 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1844 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1846 $repo = $this->getRepo();
1847 if ( $repo->getReadOnlyReason() !== false ) {
1848 return $this->readOnlyFatalStatus();
1853 if ( $this->isOld() ) {
1854 $archiveRel = $dstRel;
1855 $archiveName = basename( $archiveRel );
1857 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1858 $archiveRel = $this->getArchiveRel( $archiveName );
1861 if ( $repo->hasSha1Storage() ) {
1862 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1863 ?
$repo->getFileSha1( $srcPath )
1864 : FSFile
::getSha1Base36FromPath( $srcPath );
1865 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1866 $wrapperBackend = $repo->getBackend();
1867 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1868 $status = $repo->quickImport( $src, $dst );
1869 if ( $flags & File
::DELETE_SOURCE
) {
1873 if ( $this->exists() ) {
1874 $status->value
= $archiveName;
1877 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1878 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1880 if ( $status->value
== 'new' ) {
1881 $status->value
= '';
1883 $status->value
= $archiveName;
1891 /** getLinksTo inherited */
1892 /** getExifData inherited */
1893 /** isLocal inherited */
1894 /** wasDeleted inherited */
1897 * Move file to the new title
1899 * Move current, old version and all thumbnails
1900 * to the new filename. Old file is deleted.
1902 * Cache purging is done; checks for validity
1903 * and logging are caller's responsibility
1905 * @param Title $target New file name
1908 function move( $target ) {
1909 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1910 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1911 return $this->readOnlyFatalStatus();
1914 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1915 $batch = new LocalFileMoveBatch( $this, $target );
1918 $batch->addCurrent();
1919 $archiveNames = $batch->addOlds();
1920 $status = $batch->execute();
1923 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1925 // Purge the source and target files...
1926 $oldTitleFile = $localRepo->newFile( $this->title
);
1927 $newTitleFile = $localRepo->newFile( $target );
1928 // To avoid slow purges in the transaction, move them outside...
1929 DeferredUpdates
::addUpdate(
1930 new AutoCommitUpdate(
1931 $this->getRepo()->getMasterDB(),
1933 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1934 $oldTitleFile->purgeEverything();
1935 foreach ( $archiveNames as $archiveName ) {
1936 $oldTitleFile->purgeOldThumbnails( $archiveName );
1938 $newTitleFile->purgeEverything();
1941 DeferredUpdates
::PRESEND
1944 if ( $status->isOK() ) {
1945 // Now switch the object
1946 $this->title
= $target;
1947 // Force regeneration of the name and hashpath
1948 unset( $this->name
);
1949 unset( $this->hashPath
);
1956 * Delete all versions of the file.
1958 * Moves the files into an archive directory (or deletes them)
1959 * and removes the database rows.
1961 * Cache purging is done; logging is caller's responsibility.
1963 * @param string $reason
1964 * @param bool $suppress
1965 * @param User|null $user
1968 function delete( $reason, $suppress = false, $user = null ) {
1969 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1970 return $this->readOnlyFatalStatus();
1973 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1976 $batch->addCurrent();
1977 // Get old version relative paths
1978 $archiveNames = $batch->addOlds();
1979 $status = $batch->execute();
1982 if ( $status->isOK() ) {
1983 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1986 // To avoid slow purges in the transaction, move them outside...
1987 DeferredUpdates
::addUpdate(
1988 new AutoCommitUpdate(
1989 $this->getRepo()->getMasterDB(),
1991 function () use ( $archiveNames ) {
1992 $this->purgeEverything();
1993 foreach ( $archiveNames as $archiveName ) {
1994 $this->purgeOldThumbnails( $archiveName );
1998 DeferredUpdates
::PRESEND
2003 foreach ( $archiveNames as $archiveName ) {
2004 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2006 MediaWikiServices
::getInstance()->getHtmlCacheUpdater()->purge( $purgeUrls );
2012 * Delete an old version of the file.
2014 * Moves the file into an archive directory (or deletes it)
2015 * and removes the database row.
2017 * Cache purging is done; logging is caller's responsibility.
2019 * @param string $archiveName
2020 * @param string $reason
2021 * @param bool $suppress
2022 * @param User|null $user
2023 * @throws MWException Exception on database or file store failure
2026 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2027 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2028 return $this->readOnlyFatalStatus();
2031 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2034 $batch->addOld( $archiveName );
2035 $status = $batch->execute();
2038 $this->purgeOldThumbnails( $archiveName );
2039 if ( $status->isOK() ) {
2040 $this->purgeDescription();
2043 $url = $this->getArchiveUrl( $archiveName );
2044 MediaWikiServices
::getInstance()->getHtmlCacheUpdater()->purge( $url );
2050 * Restore all or specified deleted revisions to the given file.
2051 * Permissions and logging are left to the caller.
2053 * May throw database exceptions on error.
2055 * @param array $versions Set of record ids of deleted items to restore,
2056 * or empty to restore all revisions.
2057 * @param bool $unsuppress
2060 function restore( $versions = [], $unsuppress = false ) {
2061 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2062 return $this->readOnlyFatalStatus();
2065 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2071 $batch->addIds( $versions );
2073 $status = $batch->execute();
2074 if ( $status->isGood() ) {
2075 $cleanupStatus = $batch->cleanup();
2076 $cleanupStatus->successCount
= 0;
2077 $cleanupStatus->failCount
= 0;
2078 $status->merge( $cleanupStatus );
2085 /** isMultipage inherited */
2086 /** pageCount inherited */
2087 /** scaleHeight inherited */
2088 /** getImageSize inherited */
2091 * Get the URL of the file description page.
2094 function getDescriptionUrl() {
2095 return $this->title
->getLocalURL();
2099 * Get the HTML text of the description page
2100 * This is not used by ImagePage for local files, since (among other things)
2101 * it skips the parser cache.
2103 * @param Language|null $lang What language to get description in (Optional)
2104 * @return string|false
2106 function getDescriptionText( Language
$lang = null ) {
2107 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2108 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2113 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2114 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2117 // audience check failed
2121 $pout = $rendered->getRevisionParserOutput();
2122 return $pout->getText();
2126 * @param int $audience
2127 * @param User|null $user
2130 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2132 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2134 } elseif ( $audience == self
::FOR_THIS_USER
2135 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2139 return $this->description
;
2144 * @return bool|string
2146 function getTimestamp() {
2149 return $this->timestamp
;
2153 * @return bool|string
2155 public function getDescriptionTouched() {
2156 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2157 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2158 // need to differentiate between null (uninitialized) and false (failed to load).
2159 if ( $this->descriptionTouched
=== null ) {
2161 'page_namespace' => $this->title
->getNamespace(),
2162 'page_title' => $this->title
->getDBkey()
2164 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2165 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2168 return $this->descriptionTouched
;
2174 function getSha1() {
2176 // Initialise now if necessary
2177 if ( $this->sha1
== '' && $this->fileExists
) {
2180 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2181 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2182 $dbw = $this->repo
->getMasterDB();
2183 $dbw->update( 'image',
2184 [ 'img_sha1' => $this->sha1
],
2185 [ 'img_name' => $this->getName() ],
2187 $this->invalidateCache();
2197 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2199 function isCacheable() {
2202 // If extra data (metadata) was not loaded then it must have been large
2203 return $this->extraDataLoaded
2204 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2211 public function acquireFileLock() {
2212 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2213 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2221 public function releaseFileLock() {
2222 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2223 [ $this->getPath() ], LockManager
::LOCK_EX
2228 * Start an atomic DB section and lock the image for update
2229 * or increments a reference counter if the lock is already held
2231 * This method should not be used outside of LocalFile/LocalFile*Batch
2233 * @throws LocalFileLockError Throws an error if the lock was not acquired
2234 * @return bool Whether the file lock owns/spawned the DB transaction
2236 public function lock() {
2237 if ( !$this->locked
) {
2238 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2240 $dbw = $this->repo
->getMasterDB();
2241 $makesTransaction = !$dbw->trxLevel();
2242 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2243 // T56736: use simple lock to handle when the file does not exist.
2244 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2245 // Also, that would cause contention on INSERT of similarly named rows.
2246 $status = $this->acquireFileLock(); // represents all versions of the file
2247 if ( !$status->isGood() ) {
2248 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2249 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2251 throw new LocalFileLockError( $status );
2253 // Release the lock *after* commit to avoid row-level contention.
2254 // Make sure it triggers on rollback() as well as commit() (T132921).
2255 $dbw->onTransactionResolution(
2256 function () use ( $logger ) {
2257 $status = $this->releaseFileLock();
2258 if ( !$status->isGood() ) {
2259 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2264 // Callers might care if the SELECT snapshot is safely fresh
2265 $this->lockedOwnTrx
= $makesTransaction;
2270 return $this->lockedOwnTrx
;
2274 * Decrement the lock reference count and end the atomic section if it reaches zero
2276 * This method should not be used outside of LocalFile/LocalFile*Batch
2278 * The commit and loc release will happen when no atomic sections are active, which
2279 * may happen immediately or at some point after calling this
2281 public function unlock() {
2282 if ( $this->locked
) {
2284 if ( !$this->locked
) {
2285 $dbw = $this->repo
->getMasterDB();
2286 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2287 $this->lockedOwnTrx
= false;
2295 protected function readOnlyFatalStatus() {
2296 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2297 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2301 * Clean up any dangling locks
2303 function __destruct() {