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 MediaWiki\Logger\LoggerFactory
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\MediaWikiServices
;
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const VERSION
= 11; // cache version
49 const CACHE_FIELD_MAX_LEN
= 1000;
51 /** @var bool Does the file exist on disk? (loadFromXxx) */
52 protected $fileExists;
54 /** @var int Image width */
57 /** @var int Image height */
60 /** @var int Returned by getimagesize (loadFromXxx) */
63 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
64 protected $media_type;
66 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
69 /** @var int Size in bytes (loadFromXxx) */
72 /** @var string Handler-specific metadata */
75 /** @var string SHA-1 base 36 content hash */
78 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
79 protected $dataLoaded;
81 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
82 protected $extraDataLoaded;
84 /** @var int Bitfield akin to rev_deleted */
88 protected $repoClass = LocalRepo
::class;
90 /** @var int Number of line to return by nextHistoryLine() (constructor) */
93 /** @var int Result of the query for the file's history (nextHistoryLine) */
96 /** @var string Major MIME type */
99 /** @var string Minor MIME type */
102 /** @var string Upload timestamp */
105 /** @var User Uploader */
108 /** @var string Description of current revision of the file */
109 private $description;
111 /** @var string TS_MW timestamp of the last change of the file description */
112 private $descriptionTouched;
114 /** @var bool Whether the row was upgraded on load */
117 /** @var bool Whether the row was scheduled to upgrade on load */
120 /** @var bool True if the image row is locked */
123 /** @var bool True if the image row is locked with a lock initiated transaction */
124 private $lockedOwnTrx;
126 /** @var bool True if file is not present in file system. Not to be cached in memcached */
129 // @note: higher than IDBAccessObject constants
130 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
132 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
135 * Create a LocalFile from a title
136 * Do not call this except from inside a repo class.
138 * Note: $unused param is only here to avoid an E_STRICT
140 * @param Title $title
141 * @param FileRepo $repo
142 * @param null $unused
146 static function newFromTitle( $title, $repo, $unused = null ) {
147 return new self( $title, $repo );
151 * Create a LocalFile from a title
152 * Do not call this except from inside a repo class.
154 * @param stdClass $row
155 * @param FileRepo $repo
159 static function newFromRow( $row, $repo ) {
160 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
161 $file = new self( $title, $repo );
162 $file->loadFromRow( $row );
168 * Create a LocalFile from a SHA-1 key
169 * Do not call this except from inside a repo class.
171 * @param string $sha1 Base-36 SHA-1
172 * @param LocalRepo $repo
173 * @param string|bool $timestamp MW_timestamp (optional)
174 * @return bool|LocalFile
176 static function newFromKey( $sha1, $repo, $timestamp = false ) {
177 $dbr = $repo->getReplicaDB();
179 $conds = [ 'img_sha1' => $sha1 ];
181 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
184 $fileQuery = self
::getQueryInfo();
185 $row = $dbr->selectRow(
186 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
189 return self
::newFromRow( $row, $repo );
196 * Fields in the image table
197 * @deprecated since 1.31, use self::getQueryInfo() instead.
200 static function selectFields() {
201 global $wgActorTableSchemaMigrationStage;
203 wfDeprecated( __METHOD__
, '1.31' );
204 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
205 // If code is using this instead of self::getQueryInfo(), there's a
206 // decent chance it's going to try to directly access
207 // $row->img_user or $row->img_user_text and we can't give it
208 // useful values here once those aren't being used anymore.
209 throw new BadMethodCallException(
210 'Cannot use ' . __METHOD__
211 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
227 'img_actor' => 'NULL',
230 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
234 * Return the tables, fields, and join conditions to be selected to create
235 * a new localfile object.
237 * @param string[] $options
238 * - omit-lazy: Omit fields that are lazily cached.
239 * @return array[] With three keys:
240 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
241 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
242 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
244 public static function getQueryInfo( array $options = [] ) {
245 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
246 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
248 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
261 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
262 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
265 if ( in_array( 'omit-nonlazy', $options, true ) ) {
266 // Internal use only for getting only the lazy fields
269 if ( !in_array( 'omit-lazy', $options, true ) ) {
270 // Note: Keep this in sync with self::getLazyCacheFields()
271 $ret['fields'][] = 'img_metadata';
278 * Do not call this except from inside a repo class.
279 * @param Title $title
280 * @param FileRepo $repo
282 function __construct( $title, $repo ) {
283 parent
::__construct( $title, $repo );
285 $this->metadata
= '';
286 $this->historyLine
= 0;
287 $this->historyRes
= null;
288 $this->dataLoaded
= false;
289 $this->extraDataLoaded
= false;
291 $this->assertRepoDefined();
292 $this->assertTitleDefined();
296 * Get the memcached key for the main data for this file, or false if
297 * there is no access to the shared cache.
298 * @return string|bool
300 function getCacheKey() {
301 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
305 * @param WANObjectCache $cache
309 public function getMutableCacheKeys( WANObjectCache
$cache ) {
310 return [ $this->getCacheKey() ];
314 * Try to load file metadata from memcached, falling back to the database
316 private function loadFromCache() {
317 $this->dataLoaded
= false;
318 $this->extraDataLoaded
= false;
320 $key = $this->getCacheKey();
322 $this->loadFromDB( self
::READ_NORMAL
);
327 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
328 $cachedValues = $cache->getWithSetCallback(
331 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
332 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
334 $this->loadFromDB( self
::READ_NORMAL
);
336 $fields = $this->getCacheFields( '' );
337 $cacheVal['fileExists'] = $this->fileExists
;
338 if ( $this->fileExists
) {
339 foreach ( $fields as $field ) {
340 $cacheVal[$field] = $this->$field;
343 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
344 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
345 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
347 // Strip off excessive entries from the subset of fields that can become large.
348 // If the cache value gets to large it will not fit in memcached and nothing will
349 // get cached at all, causing master queries for any file access.
350 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
351 if ( isset( $cacheVal[$field] )
352 && strlen( $cacheVal[$field] ) > 100 * 1024
354 unset( $cacheVal[$field] ); // don't let the value get too big
358 if ( $this->fileExists
) {
359 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
361 $ttl = $cache::TTL_DAY
;
366 [ 'version' => self
::VERSION
]
369 $this->fileExists
= $cachedValues['fileExists'];
370 if ( $this->fileExists
) {
371 $this->setProps( $cachedValues );
374 $this->dataLoaded
= true;
375 $this->extraDataLoaded
= true;
376 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
377 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
382 * Purge the file object/metadata cache
384 public function invalidateCache() {
385 $key = $this->getCacheKey();
390 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
391 function () use ( $key ) {
392 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
399 * Load metadata from the file itself
401 function loadFromFile() {
402 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
403 $this->setProps( $props );
407 * Returns the list of object properties that are included as-is in the cache.
408 * @param string $prefix Must be the empty string
410 * @since 1.31 No longer accepts a non-empty $prefix
412 protected function getCacheFields( $prefix = 'img_' ) {
413 if ( $prefix !== '' ) {
414 throw new InvalidArgumentException(
415 __METHOD__
. ' with a non-empty prefix is no longer supported.'
419 // See self::getQueryInfo() for the fetching of the data from the DB,
420 // self::loadFromRow() for the loading of the object from the DB row,
421 // and self::loadFromCache() for the caching, and self::setProps() for
422 // populating the object from an array of data.
423 return [ 'size', 'width', 'height', 'bits', 'media_type',
424 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
428 * Returns the list of object properties that are included as-is in the
429 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
430 * @param string $prefix Must be the empty string
432 * @since 1.31 No longer accepts a non-empty $prefix
434 protected function getLazyCacheFields( $prefix = 'img_' ) {
435 if ( $prefix !== '' ) {
436 throw new InvalidArgumentException(
437 __METHOD__
. ' with a non-empty prefix is no longer supported.'
441 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
442 return [ 'metadata' ];
446 * Load file metadata from the DB
449 function loadFromDB( $flags = 0 ) {
450 $fname = static::class . '::' . __FUNCTION__
;
452 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
453 $this->dataLoaded
= true;
454 $this->extraDataLoaded
= true;
456 $dbr = ( $flags & self
::READ_LATEST
)
457 ?
$this->repo
->getMasterDB()
458 : $this->repo
->getReplicaDB();
460 $fileQuery = static::getQueryInfo();
461 $row = $dbr->selectRow(
462 $fileQuery['tables'],
463 $fileQuery['fields'],
464 [ 'img_name' => $this->getName() ],
471 $this->loadFromRow( $row );
473 $this->fileExists
= false;
478 * Load lazy file metadata from the DB.
479 * This covers fields that are sometimes not cached.
481 protected function loadExtraFromDB() {
482 $fname = static::class . '::' . __FUNCTION__
;
484 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
485 $this->extraDataLoaded
= true;
487 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
489 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
493 foreach ( $fieldMap as $name => $value ) {
494 $this->$name = $value;
497 throw new MWException( "Could not find data for image '{$this->getName()}'." );
502 * @param IDatabase $dbr
503 * @param string $fname
504 * @return string[]|bool
506 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
509 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
510 $row = $dbr->selectRow(
511 $fileQuery['tables'],
512 $fileQuery['fields'],
514 'img_name' => $this->getName(),
515 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
522 $fieldMap = $this->unprefixRow( $row, 'img_' );
524 # File may have been uploaded over in the meantime; check the old versions
525 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
526 $row = $dbr->selectRow(
527 $fileQuery['tables'],
528 $fileQuery['fields'],
530 'oi_name' => $this->getName(),
531 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
538 $fieldMap = $this->unprefixRow( $row, 'oi_' );
542 if ( isset( $fieldMap['metadata'] ) ) {
543 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
550 * @param array|object $row
551 * @param string $prefix
552 * @throws MWException
555 protected function unprefixRow( $row, $prefix = 'img_' ) {
556 $array = (array)$row;
557 $prefixLength = strlen( $prefix );
559 // Sanity check prefix once
560 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
561 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
565 foreach ( $array as $name => $value ) {
566 $decoded[substr( $name, $prefixLength )] = $value;
573 * Decode a row from the database (either object or array) to an array
574 * with timestamps and MIME types decoded, and the field prefix removed.
576 * @param string $prefix
577 * @throws MWException
580 function decodeRow( $row, $prefix = 'img_' ) {
581 $decoded = $this->unprefixRow( $row, $prefix );
583 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
584 ->getComment( 'description', (object)$decoded )->text
;
586 $decoded['user'] = User
::newFromAnyId(
587 $decoded['user'] ??
null,
588 $decoded['user_text'] ??
null,
589 $decoded['actor'] ??
null
591 unset( $decoded['user_text'], $decoded['actor'] );
593 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
595 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
597 if ( empty( $decoded['major_mime'] ) ) {
598 $decoded['mime'] = 'unknown/unknown';
600 if ( !$decoded['minor_mime'] ) {
601 $decoded['minor_mime'] = 'unknown';
603 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
606 // Trim zero padding from char/binary field
607 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
609 // Normalize some fields to integer type, per their database definition.
610 // Use unary + so that overflows will be upgraded to double instead of
611 // being trucated as with intval(). This is important to allow >2GB
612 // files on 32-bit systems.
613 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
614 $decoded[$field] = +
$decoded[$field];
621 * Load file metadata from a DB result row
624 * @param string $prefix
626 function loadFromRow( $row, $prefix = 'img_' ) {
627 $this->dataLoaded
= true;
628 $this->extraDataLoaded
= true;
630 $array = $this->decodeRow( $row, $prefix );
632 foreach ( $array as $name => $value ) {
633 $this->$name = $value;
636 $this->fileExists
= true;
640 * Load file metadata from cache or DB, unless already loaded
643 function load( $flags = 0 ) {
644 if ( !$this->dataLoaded
) {
645 if ( $flags & self
::READ_LATEST
) {
646 $this->loadFromDB( $flags );
648 $this->loadFromCache();
652 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
653 // @note: loads on name/timestamp to reduce race condition problems
654 $this->loadExtraFromDB();
659 * Upgrade a row if it needs it
661 protected function maybeUpgradeRow() {
662 global $wgUpdateCompatibleMetadata;
664 if ( wfReadOnly() ||
$this->upgrading
) {
669 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
672 $handler = $this->getHandler();
674 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
675 if ( $validity === MediaHandler
::METADATA_BAD
) {
677 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
678 $upgrade = $wgUpdateCompatibleMetadata;
684 $this->upgrading
= true;
685 // Defer updates unless in auto-commit CLI mode
686 DeferredUpdates
::addCallableUpdate( function () {
687 $this->upgrading
= false; // avoid duplicate updates
690 } catch ( LocalFileLockError
$e ) {
691 // let the other process handle it (or do it next time)
698 * @return bool Whether upgradeRow() ran for this object
700 function getUpgraded() {
701 return $this->upgraded
;
705 * Fix assorted version-related problems with the image row by reloading it from the file
707 function upgradeRow() {
710 $this->loadFromFile();
712 # Don't destroy file info of missing files
713 if ( !$this->fileExists
) {
715 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
720 $dbw = $this->repo
->getMasterDB();
721 list( $major, $minor ) = self
::splitMime( $this->mime
);
723 if ( wfReadOnly() ) {
728 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
730 $dbw->update( 'image',
732 'img_size' => $this->size
, // sanity
733 'img_width' => $this->width
,
734 'img_height' => $this->height
,
735 'img_bits' => $this->bits
,
736 'img_media_type' => $this->media_type
,
737 'img_major_mime' => $major,
738 'img_minor_mime' => $minor,
739 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
740 'img_sha1' => $this->sha1
,
742 [ 'img_name' => $this->getName() ],
746 $this->invalidateCache();
749 $this->upgraded
= true; // avoid rework/retries
753 * Set properties in this object to be equal to those given in the
754 * associative array $info. Only cacheable fields can be set.
755 * All fields *must* be set in $info except for getLazyCacheFields().
757 * If 'mime' is given, it will be split into major_mime/minor_mime.
758 * If major_mime/minor_mime are given, $this->mime will also be set.
762 function setProps( $info ) {
763 $this->dataLoaded
= true;
764 $fields = $this->getCacheFields( '' );
765 $fields[] = 'fileExists';
767 foreach ( $fields as $field ) {
768 if ( isset( $info[$field] ) ) {
769 $this->$field = $info[$field];
773 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
774 $this->user
= User
::newFromAnyId(
775 $info['user'] ??
null,
776 $info['user_text'] ??
null,
777 $info['actor'] ??
null
781 // Fix up mime fields
782 if ( isset( $info['major_mime'] ) ) {
783 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
784 } elseif ( isset( $info['mime'] ) ) {
785 $this->mime
= $info['mime'];
786 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
790 /** splitMime inherited */
791 /** getName inherited */
792 /** getTitle inherited */
793 /** getURL inherited */
794 /** getViewURL inherited */
795 /** getPath inherited */
796 /** isVisible inherited */
799 * Checks if this file exists in its parent repo, as referenced by its
804 function isMissing() {
805 if ( $this->missing
=== null ) {
806 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
807 $this->missing
= !$fileExists;
810 return $this->missing
;
814 * Return the width of the image
819 public function getWidth( $page = 1 ) {
827 if ( $this->isMultipage() ) {
828 $handler = $this->getHandler();
832 $dim = $handler->getPageDimensions( $this, $page );
834 return $dim['width'];
836 // For non-paged media, the false goes through an
837 // intval, turning failure into 0, so do same here.
846 * Return the height of the image
851 public function getHeight( $page = 1 ) {
859 if ( $this->isMultipage() ) {
860 $handler = $this->getHandler();
864 $dim = $handler->getPageDimensions( $this, $page );
866 return $dim['height'];
868 // For non-paged media, the false goes through an
869 // intval, turning failure into 0, so do same here.
873 return $this->height
;
878 * Returns user who uploaded the file
880 * @param string $type 'text', 'id', or 'object'
881 * @return int|string|User
882 * @since 1.31 Added 'object'
884 function getUser( $type = 'text' ) {
887 if ( $type === 'object' ) {
889 } elseif ( $type === 'text' ) {
890 return $this->user
->getName();
891 } elseif ( $type === 'id' ) {
892 return $this->user
->getId();
895 throw new MWException( "Unknown type '$type'." );
899 * Get short description URL for a file based on the page ID.
901 * @return string|null
902 * @throws MWException
905 public function getDescriptionShortUrl() {
906 $pageId = $this->title
->getArticleID();
908 if ( $pageId !== null ) {
909 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
910 if ( $url !== false ) {
918 * Get handler-specific metadata
921 function getMetadata() {
922 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
923 return $this->metadata
;
929 function getBitDepth() {
932 return (int)$this->bits
;
936 * Returns the size of the image file, in bytes
939 public function getSize() {
946 * Returns the MIME type of the file.
949 function getMimeType() {
956 * Returns the type of the media in the file.
957 * Use the value returned by this function with the MEDIATYPE_xxx constants.
960 function getMediaType() {
963 return $this->media_type
;
966 /** canRender inherited */
967 /** mustRender inherited */
968 /** allowInlineDisplay inherited */
969 /** isSafeFile inherited */
970 /** isTrustedFile inherited */
973 * Returns true if the file exists on disk.
974 * @return bool Whether file exist on disk.
976 public function exists() {
979 return $this->fileExists
;
982 /** getTransformScript inherited */
983 /** getUnscaledThumb inherited */
984 /** thumbName inherited */
985 /** createThumb inherited */
986 /** transform inherited */
988 /** getHandler inherited */
989 /** iconThumb inherited */
990 /** getLastError inherited */
993 * Get all thumbnail names previously generated for this file
994 * @param string|bool $archiveName Name of an archive file, default false
995 * @return array First element is the base dir, then files in that base dir.
997 function getThumbnails( $archiveName = false ) {
998 if ( $archiveName ) {
999 $dir = $this->getArchiveThumbPath( $archiveName );
1001 $dir = $this->getThumbPath();
1004 $backend = $this->repo
->getBackend();
1007 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1008 foreach ( $iterator as $file ) {
1011 } catch ( FileBackendError
$e ) {
1012 } // suppress (T56674)
1018 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1020 function purgeMetadataCache() {
1021 $this->invalidateCache();
1025 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1027 * @param array $options An array potentially with the key forThumbRefresh.
1029 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1031 function purgeCache( $options = [] ) {
1032 // Refresh metadata cache
1033 $this->maybeUpgradeRow();
1034 $this->purgeMetadataCache();
1036 // Delete thumbnails
1037 $this->purgeThumbnails( $options );
1039 // Purge CDN cache for this file
1040 DeferredUpdates
::addUpdate(
1041 new CdnCacheUpdate( [ $this->getUrl() ] ),
1042 DeferredUpdates
::PRESEND
1047 * Delete cached transformed files for an archived version only.
1048 * @param string $archiveName Name of the archived file
1050 function purgeOldThumbnails( $archiveName ) {
1051 // Get a list of old thumbnails and URLs
1052 $files = $this->getThumbnails( $archiveName );
1054 // Purge any custom thumbnail caches
1055 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1057 // Delete thumbnails
1058 $dir = array_shift( $files );
1059 $this->purgeThumbList( $dir, $files );
1063 foreach ( $files as $file ) {
1064 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1066 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1070 * Delete cached transformed files for the current version only.
1071 * @param array $options
1073 public function purgeThumbnails( $options = [] ) {
1074 $files = $this->getThumbnails();
1075 // Always purge all files from CDN regardless of handler filters
1077 foreach ( $files as $file ) {
1078 $urls[] = $this->getThumbUrl( $file );
1080 array_shift( $urls ); // don't purge directory
1082 // Give media handler a chance to filter the file purge list
1083 if ( !empty( $options['forThumbRefresh'] ) ) {
1084 $handler = $this->getHandler();
1086 $handler->filterThumbnailPurgeList( $files, $options );
1090 // Purge any custom thumbnail caches
1091 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1093 // Delete thumbnails
1094 $dir = array_shift( $files );
1095 $this->purgeThumbList( $dir, $files );
1098 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1102 * Prerenders a configurable set of thumbnails
1106 public function prerenderThumbnails() {
1107 global $wgUploadThumbnailRenderMap;
1111 $sizes = $wgUploadThumbnailRenderMap;
1114 foreach ( $sizes as $size ) {
1115 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1116 $jobs[] = new ThumbnailRenderJob(
1118 [ 'transformParams' => [ 'width' => $size ] ]
1124 JobQueueGroup
::singleton()->lazyPush( $jobs );
1129 * Delete a list of thumbnails visible at urls
1130 * @param string $dir Base dir of the files.
1131 * @param array $files Array of strings: relative filenames (to $dir)
1133 protected function purgeThumbList( $dir, $files ) {
1134 $fileListDebug = strtr(
1135 var_export( $files, true ),
1138 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1141 foreach ( $files as $file ) {
1142 if ( $this->repo
->supportsSha1URLs() ) {
1143 $reference = $this->getSha1();
1145 $reference = $this->getName();
1148 # Check that the reference (filename or sha1) is part of the thumb name
1149 # This is a basic sanity check to avoid erasing unrelated directories
1150 if ( strpos( $file, $reference ) !== false
1151 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1153 $purgeList[] = "{$dir}/{$file}";
1157 # Delete the thumbnails
1158 $this->repo
->quickPurgeBatch( $purgeList );
1159 # Clear out the thumbnail directory if empty
1160 $this->repo
->quickCleanDir( $dir );
1163 /** purgeDescription inherited */
1164 /** purgeEverything inherited */
1167 * @param int|null $limit Optional: Limit to number of results
1168 * @param string|int|null $start Optional: Timestamp, start from
1169 * @param string|int|null $end Optional: Timestamp, end at
1171 * @return OldLocalFile[]
1173 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1174 $dbr = $this->repo
->getReplicaDB();
1175 $oldFileQuery = OldLocalFile
::getQueryInfo();
1177 $tables = $oldFileQuery['tables'];
1178 $fields = $oldFileQuery['fields'];
1179 $join_conds = $oldFileQuery['joins'];
1180 $conds = $opts = [];
1181 $eq = $inc ?
'=' : '';
1182 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1185 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1189 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1193 $opts['LIMIT'] = $limit;
1196 // Search backwards for time > x queries
1197 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1198 $opts['ORDER BY'] = "oi_timestamp $order";
1199 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1201 // Avoid PHP 7.1 warning from passing $this by reference
1203 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1204 &$conds, &$opts, &$join_conds ] );
1206 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1209 foreach ( $res as $row ) {
1210 $r[] = $this->repo
->newFileFromRow( $row );
1213 if ( $order == 'ASC' ) {
1214 $r = array_reverse( $r ); // make sure it ends up descending
1221 * Returns the history of this file, line by line.
1222 * starts with current version, then old versions.
1223 * uses $this->historyLine to check which line to return:
1224 * 0 return line for current version
1225 * 1 query for old versions, return first one
1226 * 2, ... return next old version from above query
1229 public function nextHistoryLine() {
1230 # Polymorphic function name to distinguish foreign and local fetches
1231 $fname = static::class . '::' . __FUNCTION__
;
1233 $dbr = $this->repo
->getReplicaDB();
1235 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1236 $fileQuery = self
::getQueryInfo();
1237 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1238 $fileQuery['fields'] +
[
1239 'oi_archive_name' => $dbr->addQuotes( '' ),
1242 [ 'img_name' => $this->title
->getDBkey() ],
1248 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1249 $this->historyRes
= null;
1253 } elseif ( $this->historyLine
== 1 ) {
1254 $fileQuery = OldLocalFile
::getQueryInfo();
1255 $this->historyRes
= $dbr->select(
1256 $fileQuery['tables'],
1257 $fileQuery['fields'],
1258 [ 'oi_name' => $this->title
->getDBkey() ],
1260 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1264 $this->historyLine++
;
1266 return $dbr->fetchObject( $this->historyRes
);
1270 * Reset the history pointer to the first element of the history
1272 public function resetHistory() {
1273 $this->historyLine
= 0;
1275 if ( !is_null( $this->historyRes
) ) {
1276 $this->historyRes
= null;
1280 /** getHashPath inherited */
1281 /** getRel inherited */
1282 /** getUrlRel inherited */
1283 /** getArchiveRel inherited */
1284 /** getArchivePath inherited */
1285 /** getThumbPath inherited */
1286 /** getArchiveUrl inherited */
1287 /** getThumbUrl inherited */
1288 /** getArchiveVirtualUrl inherited */
1289 /** getThumbVirtualUrl inherited */
1290 /** isHashed inherited */
1293 * Upload a file and record it in the DB
1294 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1295 * @param string $comment Upload description
1296 * @param string $pageText Text to use for the new description page,
1297 * if a new description page is created
1298 * @param int|bool $flags Flags for publish()
1299 * @param array|bool $props File properties, if known. This can be used to
1300 * reduce the upload time when uploading virtual URLs for which the file
1301 * info is already known
1302 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1304 * @param User|null $user User object or null to use $wgUser
1305 * @param string[] $tags Change tags to add to the log entry and page revision.
1306 * (This doesn't check $user's permissions.)
1307 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1308 * upload, see T193621
1309 * @param bool $revert If this file upload is a revert
1310 * @return Status On success, the value member contains the
1311 * archive name, or an empty string if it was a new file.
1313 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1314 $timestamp = false, $user = null, $tags = [],
1315 $createNullRevision = true, $revert = false
1317 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1318 return $this->readOnlyFatalStatus();
1319 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1320 // Check this in advance to avoid writing to FileBackend and the file tables,
1321 // only to fail on insert the revision due to the text store being unavailable.
1322 return $this->readOnlyFatalStatus();
1325 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1327 if ( FileRepo
::isVirtualUrl( $srcPath )
1328 || FileBackend
::isStoragePath( $srcPath )
1330 $props = $this->repo
->getFileProps( $srcPath );
1332 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1333 $props = $mwProps->getPropsFromPath( $srcPath, true );
1338 $handler = MediaHandler
::getHandler( $props['mime'] );
1340 $metadata = Wikimedia\
quietCall( 'unserialize', $props['metadata'] );
1342 if ( !is_array( $metadata ) ) {
1346 $options['headers'] = $handler->getContentHeaders( $metadata );
1348 $options['headers'] = [];
1351 // Trim spaces on user supplied text
1352 $comment = trim( $comment );
1355 $status = $this->publish( $src, $flags, $options );
1357 if ( $status->successCount
>= 2 ) {
1358 // There will be a copy+(one of move,copy,store).
1359 // The first succeeding does not commit us to updating the DB
1360 // since it simply copied the current version to a timestamped file name.
1361 // It is only *preferable* to avoid leaving such files orphaned.
1362 // Once the second operation goes through, then the current version was
1363 // updated and we must therefore update the DB too.
1364 $oldver = $status->value
;
1365 $uploadStatus = $this->recordUpload2(
1373 $createNullRevision,
1376 if ( !$uploadStatus->isOK() ) {
1377 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1378 // update filenotfound error with more specific path
1379 $status->fatal( 'filenotfound', $srcPath );
1381 $status->merge( $uploadStatus );
1391 * Record a file upload in the upload log and the image table
1392 * @param string $oldver
1393 * @param string $desc
1394 * @param string $license
1395 * @param string $copyStatus
1396 * @param string $source
1397 * @param bool $watch
1398 * @param string|bool $timestamp
1399 * @param User|null $user User object or null to use $wgUser
1402 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1403 $watch = false, $timestamp = false, User
$user = null ) {
1409 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1411 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1416 $user->addWatch( $this->getTitle() );
1423 * Record a file upload in the upload log and the image table
1424 * @param string $oldver
1425 * @param string $comment
1426 * @param string $pageText
1427 * @param bool|array $props
1428 * @param string|bool $timestamp
1429 * @param null|User $user
1430 * @param string[] $tags
1431 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1432 * upload, see T193621
1433 * @param bool $revert If this file upload is a revert
1436 function recordUpload2(
1437 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1438 $createNullRevision = true, $revert = false
1440 global $wgActorTableSchemaMigrationStage;
1442 if ( is_null( $user ) ) {
1447 $dbw = $this->repo
->getMasterDB();
1449 # Imports or such might force a certain timestamp; otherwise we generate
1450 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1451 if ( $timestamp === false ) {
1452 $timestamp = $dbw->timestamp();
1453 $allowTimeKludge = true;
1455 $allowTimeKludge = false;
1458 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1459 $props['description'] = $comment;
1460 $props['user'] = $user->getId();
1461 $props['user_text'] = $user->getName();
1462 $props['actor'] = $user->getActorId( $dbw );
1463 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1464 $this->setProps( $props );
1466 # Fail now if the file isn't there
1467 if ( !$this->fileExists
) {
1468 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1470 return Status
::newFatal( 'filenotfound', $this->getRel() );
1473 $dbw->startAtomic( __METHOD__
);
1475 # Test to see if the row exists using INSERT IGNORE
1476 # This avoids race conditions by locking the row until the commit, and also
1477 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1478 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1479 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1480 $actorMigration = ActorMigration
::newMigration();
1481 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1482 $dbw->insert( 'image',
1484 'img_name' => $this->getName(),
1485 'img_size' => $this->size
,
1486 'img_width' => intval( $this->width
),
1487 'img_height' => intval( $this->height
),
1488 'img_bits' => $this->bits
,
1489 'img_media_type' => $this->media_type
,
1490 'img_major_mime' => $this->major_mime
,
1491 'img_minor_mime' => $this->minor_mime
,
1492 'img_timestamp' => $timestamp,
1493 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1494 'img_sha1' => $this->sha1
1495 ] +
$commentFields +
$actorFields,
1499 $reupload = ( $dbw->affectedRows() == 0 );
1502 $row = $dbw->selectRow(
1504 [ 'img_timestamp', 'img_sha1' ],
1505 [ 'img_name' => $this->getName() ],
1507 [ 'LOCK IN SHARE MODE' ]
1510 if ( $row && $row->img_sha1
=== $this->sha1
) {
1511 $dbw->endAtomic( __METHOD__
);
1512 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1513 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1514 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1517 if ( $allowTimeKludge ) {
1518 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1519 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1520 # Avoid a timestamp that is not newer than the last version
1521 # TODO: the image/oldimage tables should be like page/revision with an ID field
1522 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1523 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1524 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1525 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1529 $tables = [ 'image' ];
1531 'oi_name' => 'img_name',
1532 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1533 'oi_size' => 'img_size',
1534 'oi_width' => 'img_width',
1535 'oi_height' => 'img_height',
1536 'oi_bits' => 'img_bits',
1537 'oi_description_id' => 'img_description_id',
1538 'oi_timestamp' => 'img_timestamp',
1539 'oi_metadata' => 'img_metadata',
1540 'oi_media_type' => 'img_media_type',
1541 'oi_major_mime' => 'img_major_mime',
1542 'oi_minor_mime' => 'img_minor_mime',
1543 'oi_sha1' => 'img_sha1',
1547 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1548 $fields['oi_user'] = 'img_user';
1549 $fields['oi_user_text'] = 'img_user_text';
1551 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1552 $fields['oi_actor'] = 'img_actor';
1556 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1558 // Upgrade any rows that are still old-style. Otherwise an upgrade
1559 // might be missed if a deletion happens while the migration script
1561 $res = $dbw->select(
1563 [ 'img_name', 'img_user', 'img_user_text' ],
1564 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1567 foreach ( $res as $row ) {
1568 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1571 [ 'img_actor' => $actorId ],
1572 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1578 # (T36993) Note: $oldver can be empty here, if the previous
1579 # version of the file was broken. Allow registration of the new
1580 # version to continue anyway, because that's better than having
1581 # an image that's not fixable by user operations.
1582 # Collision, this is an update of a file
1583 # Insert previous contents into oldimage
1584 $dbw->insertSelect( 'oldimage', $tables, $fields,
1585 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1587 # Update the current image row
1588 $dbw->update( 'image',
1590 'img_size' => $this->size
,
1591 'img_width' => intval( $this->width
),
1592 'img_height' => intval( $this->height
),
1593 'img_bits' => $this->bits
,
1594 'img_media_type' => $this->media_type
,
1595 'img_major_mime' => $this->major_mime
,
1596 'img_minor_mime' => $this->minor_mime
,
1597 'img_timestamp' => $timestamp,
1598 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1599 'img_sha1' => $this->sha1
1600 ] +
$commentFields +
$actorFields,
1601 [ 'img_name' => $this->getName() ],
1606 $descTitle = $this->getTitle();
1607 $descId = $descTitle->getArticleID();
1608 $wikiPage = new WikiFilePage( $descTitle );
1609 $wikiPage->setFile( $this );
1611 // Determine log action. If reupload is done by reverting, use a special log_action.
1612 if ( $revert === true ) {
1613 $logAction = 'revert';
1614 } elseif ( $reupload === true ) {
1615 $logAction = 'overwrite';
1617 $logAction = 'upload';
1619 // Add the log entry...
1620 $logEntry = new ManualLogEntry( 'upload', $logAction );
1621 $logEntry->setTimestamp( $this->timestamp
);
1622 $logEntry->setPerformer( $user );
1623 $logEntry->setComment( $comment );
1624 $logEntry->setTarget( $descTitle );
1625 // Allow people using the api to associate log entries with the upload.
1626 // Log has a timestamp, but sometimes different from upload timestamp.
1627 $logEntry->setParameters(
1629 'img_sha1' => $this->sha1
,
1630 'img_timestamp' => $timestamp,
1633 // Note we keep $logId around since during new image
1634 // creation, page doesn't exist yet, so log_page = 0
1635 // but we want it to point to the page we're making,
1636 // so we later modify the log entry.
1637 // For a similar reason, we avoid making an RC entry
1638 // now and wait until the page exists.
1639 $logId = $logEntry->insert();
1641 if ( $descTitle->exists() ) {
1642 // Use own context to get the action text in content language
1643 $formatter = LogFormatter
::newFromEntry( $logEntry );
1644 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1645 $editSummary = $formatter->getPlainActionText();
1647 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1654 if ( $nullRevision ) {
1655 $nullRevision->insertOn( $dbw );
1657 'NewRevisionFromEditComplete',
1658 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1660 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1661 // Associate null revision id
1662 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1665 $newPageContent = null;
1667 // Make the description page and RC log entry post-commit
1668 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1671 # Defer purges, page creation, and link updates in case they error out.
1672 # The most important thing is that files and the DB registry stay synced.
1673 $dbw->endAtomic( __METHOD__
);
1674 $fname = __METHOD__
;
1676 # Do some cache purges after final commit so that:
1677 # a) Changes are more likely to be seen post-purge
1678 # b) They won't cause rollback of the log publish/update above
1679 DeferredUpdates
::addUpdate(
1680 new AutoCommitUpdate(
1684 $reupload, $wikiPage, $newPageContent, $comment, $user,
1685 $logEntry, $logId, $descId, $tags, $fname
1687 # Update memcache after the commit
1688 $this->invalidateCache();
1690 $updateLogPage = false;
1691 if ( $newPageContent ) {
1692 # New file page; create the description page.
1693 # There's already a log entry, so don't make a second RC entry
1694 # CDN and file cache for the description page are purged by doEditContent.
1695 $status = $wikiPage->doEditContent(
1698 EDIT_NEW | EDIT_SUPPRESS_RC
,
1703 if ( isset( $status->value
['revision'] ) ) {
1704 /** @var Revision $rev */
1705 $rev = $status->value
['revision'];
1706 // Associate new page revision id
1707 $logEntry->setAssociatedRevId( $rev->getId() );
1709 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1710 // which is triggered on $descTitle by doEditContent() above.
1711 if ( isset( $status->value
['revision'] ) ) {
1712 /** @var Revision $rev */
1713 $rev = $status->value
['revision'];
1714 $updateLogPage = $rev->getPage();
1717 # Existing file page: invalidate description page cache
1718 $wikiPage->getTitle()->invalidateCache();
1719 $wikiPage->getTitle()->purgeSquid();
1720 # Allow the new file version to be patrolled from the page footer
1721 Article
::purgePatrolFooterCache( $descId );
1724 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1725 # but setAssociatedRevId() wasn't called at that point yet...
1726 $logParams = $logEntry->getParameters();
1727 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1728 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1729 if ( $updateLogPage ) {
1730 # Also log page, in case where we just created it above
1731 $update['log_page'] = $updateLogPage;
1733 $this->getRepo()->getMasterDB()->update(
1736 [ 'log_id' => $logId ],
1739 $this->getRepo()->getMasterDB()->insert(
1742 'ls_field' => 'associated_rev_id',
1743 'ls_value' => $logEntry->getAssociatedRevId(),
1744 'ls_log_id' => $logId,
1749 # Add change tags, if any
1751 $logEntry->setTags( $tags );
1754 # Uploads can be patrolled
1755 $logEntry->setIsPatrollable( true );
1757 # Now that the log entry is up-to-date, make an RC entry.
1758 $logEntry->publish( $logId );
1760 # Run hook for other updates (typically more cache purging)
1761 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1764 # Delete old thumbnails
1765 $this->purgeThumbnails();
1766 # Remove the old file from the CDN cache
1767 DeferredUpdates
::addUpdate(
1768 new CdnCacheUpdate( [ $this->getUrl() ] ),
1769 DeferredUpdates
::PRESEND
1772 # Update backlink pages pointing to this title if created
1773 LinksUpdate
::queueRecursiveJobsForTable(
1781 $this->prerenderThumbnails();
1784 DeferredUpdates
::PRESEND
1788 # This is a new file, so update the image count
1789 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1792 # Invalidate cache for all pages using this file
1793 DeferredUpdates
::addUpdate(
1794 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1797 return Status
::newGood();
1801 * Move or copy a file to its public location. If a file exists at the
1802 * destination, move it to an archive. Returns a Status object with
1803 * the archive name in the "value" member on success.
1805 * The archive name should be passed through to recordUpload for database
1808 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1809 * @param int $flags A bitwise combination of:
1810 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1811 * @param array $options Optional additional parameters
1812 * @return Status On success, the value member contains the
1813 * archive name, or an empty string if it was a new file.
1815 function publish( $src, $flags = 0, array $options = [] ) {
1816 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1820 * Move or copy a file to a specified location. Returns a Status
1821 * object with the archive name in the "value" member on success.
1823 * The archive name should be passed through to recordUpload for database
1826 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1827 * @param string $dstRel Target relative path
1828 * @param int $flags A bitwise combination of:
1829 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1830 * @param array $options Optional additional parameters
1831 * @return Status On success, the value member contains the
1832 * archive name, or an empty string if it was a new file.
1834 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1835 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1837 $repo = $this->getRepo();
1838 if ( $repo->getReadOnlyReason() !== false ) {
1839 return $this->readOnlyFatalStatus();
1844 if ( $this->isOld() ) {
1845 $archiveRel = $dstRel;
1846 $archiveName = basename( $archiveRel );
1848 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1849 $archiveRel = $this->getArchiveRel( $archiveName );
1852 if ( $repo->hasSha1Storage() ) {
1853 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1854 ?
$repo->getFileSha1( $srcPath )
1855 : FSFile
::getSha1Base36FromPath( $srcPath );
1856 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1857 $wrapperBackend = $repo->getBackend();
1858 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1859 $status = $repo->quickImport( $src, $dst );
1860 if ( $flags & File
::DELETE_SOURCE
) {
1864 if ( $this->exists() ) {
1865 $status->value
= $archiveName;
1868 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1869 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1871 if ( $status->value
== 'new' ) {
1872 $status->value
= '';
1874 $status->value
= $archiveName;
1882 /** getLinksTo inherited */
1883 /** getExifData inherited */
1884 /** isLocal inherited */
1885 /** wasDeleted inherited */
1888 * Move file to the new title
1890 * Move current, old version and all thumbnails
1891 * to the new filename. Old file is deleted.
1893 * Cache purging is done; checks for validity
1894 * and logging are caller's responsibility
1896 * @param Title $target New file name
1899 function move( $target ) {
1900 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1901 return $this->readOnlyFatalStatus();
1904 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1905 $batch = new LocalFileMoveBatch( $this, $target );
1908 $batch->addCurrent();
1909 $archiveNames = $batch->addOlds();
1910 $status = $batch->execute();
1913 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1915 // Purge the source and target files...
1916 $oldTitleFile = wfLocalFile( $this->title
);
1917 $newTitleFile = wfLocalFile( $target );
1918 // To avoid slow purges in the transaction, move them outside...
1919 DeferredUpdates
::addUpdate(
1920 new AutoCommitUpdate(
1921 $this->getRepo()->getMasterDB(),
1923 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1924 $oldTitleFile->purgeEverything();
1925 foreach ( $archiveNames as $archiveName ) {
1926 $oldTitleFile->purgeOldThumbnails( $archiveName );
1928 $newTitleFile->purgeEverything();
1931 DeferredUpdates
::PRESEND
1934 if ( $status->isOK() ) {
1935 // Now switch the object
1936 $this->title
= $target;
1937 // Force regeneration of the name and hashpath
1938 unset( $this->name
);
1939 unset( $this->hashPath
);
1946 * Delete all versions of the file.
1948 * Moves the files into an archive directory (or deletes them)
1949 * and removes the database rows.
1951 * Cache purging is done; logging is caller's responsibility.
1953 * @param string $reason
1954 * @param bool $suppress
1955 * @param User|null $user
1958 function delete( $reason, $suppress = false, $user = null ) {
1959 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1960 return $this->readOnlyFatalStatus();
1963 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1966 $batch->addCurrent();
1967 // Get old version relative paths
1968 $archiveNames = $batch->addOlds();
1969 $status = $batch->execute();
1972 if ( $status->isOK() ) {
1973 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1976 // To avoid slow purges in the transaction, move them outside...
1977 DeferredUpdates
::addUpdate(
1978 new AutoCommitUpdate(
1979 $this->getRepo()->getMasterDB(),
1981 function () use ( $archiveNames ) {
1982 $this->purgeEverything();
1983 foreach ( $archiveNames as $archiveName ) {
1984 $this->purgeOldThumbnails( $archiveName );
1988 DeferredUpdates
::PRESEND
1993 foreach ( $archiveNames as $archiveName ) {
1994 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1996 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2002 * Delete an old version of the file.
2004 * Moves the file into an archive directory (or deletes it)
2005 * and removes the database row.
2007 * Cache purging is done; logging is caller's responsibility.
2009 * @param string $archiveName
2010 * @param string $reason
2011 * @param bool $suppress
2012 * @param User|null $user
2013 * @throws MWException Exception on database or file store failure
2016 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2017 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2018 return $this->readOnlyFatalStatus();
2021 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2024 $batch->addOld( $archiveName );
2025 $status = $batch->execute();
2028 $this->purgeOldThumbnails( $archiveName );
2029 if ( $status->isOK() ) {
2030 $this->purgeDescription();
2033 DeferredUpdates
::addUpdate(
2034 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2035 DeferredUpdates
::PRESEND
2042 * Restore all or specified deleted revisions to the given file.
2043 * Permissions and logging are left to the caller.
2045 * May throw database exceptions on error.
2047 * @param array $versions Set of record ids of deleted items to restore,
2048 * or empty to restore all revisions.
2049 * @param bool $unsuppress
2052 function restore( $versions = [], $unsuppress = false ) {
2053 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2054 return $this->readOnlyFatalStatus();
2057 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2063 $batch->addIds( $versions );
2065 $status = $batch->execute();
2066 if ( $status->isGood() ) {
2067 $cleanupStatus = $batch->cleanup();
2068 $cleanupStatus->successCount
= 0;
2069 $cleanupStatus->failCount
= 0;
2070 $status->merge( $cleanupStatus );
2077 /** isMultipage inherited */
2078 /** pageCount inherited */
2079 /** scaleHeight inherited */
2080 /** getImageSize inherited */
2083 * Get the URL of the file description page.
2086 function getDescriptionUrl() {
2087 return $this->title
->getLocalURL();
2091 * Get the HTML text of the description page
2092 * This is not used by ImagePage for local files, since (among other things)
2093 * it skips the parser cache.
2095 * @param Language|null $lang What language to get description in (Optional)
2096 * @return string|false
2098 function getDescriptionText( Language
$lang = null ) {
2099 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2100 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2105 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2106 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2109 // audience check failed
2113 $pout = $rendered->getRevisionParserOutput();
2114 return $pout->getText();
2118 * @param int $audience
2119 * @param User|null $user
2122 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2124 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2126 } elseif ( $audience == self
::FOR_THIS_USER
2127 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2131 return $this->description
;
2136 * @return bool|string
2138 function getTimestamp() {
2141 return $this->timestamp
;
2145 * @return bool|string
2147 public function getDescriptionTouched() {
2148 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2149 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2150 // need to differentiate between null (uninitialized) and false (failed to load).
2151 if ( $this->descriptionTouched
=== null ) {
2153 'page_namespace' => $this->title
->getNamespace(),
2154 'page_title' => $this->title
->getDBkey()
2156 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2157 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2160 return $this->descriptionTouched
;
2166 function getSha1() {
2168 // Initialise now if necessary
2169 if ( $this->sha1
== '' && $this->fileExists
) {
2172 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2173 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2174 $dbw = $this->repo
->getMasterDB();
2175 $dbw->update( 'image',
2176 [ 'img_sha1' => $this->sha1
],
2177 [ 'img_name' => $this->getName() ],
2179 $this->invalidateCache();
2189 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2191 function isCacheable() {
2194 // If extra data (metadata) was not loaded then it must have been large
2195 return $this->extraDataLoaded
2196 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2203 public function acquireFileLock() {
2204 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2205 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2213 public function releaseFileLock() {
2214 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2215 [ $this->getPath() ], LockManager
::LOCK_EX
2220 * Start an atomic DB section and lock the image for update
2221 * or increments a reference counter if the lock is already held
2223 * This method should not be used outside of LocalFile/LocalFile*Batch
2225 * @throws LocalFileLockError Throws an error if the lock was not acquired
2226 * @return bool Whether the file lock owns/spawned the DB transaction
2228 public function lock() {
2229 if ( !$this->locked
) {
2230 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2232 $dbw = $this->repo
->getMasterDB();
2233 $makesTransaction = !$dbw->trxLevel();
2234 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2235 // T56736: use simple lock to handle when the file does not exist.
2236 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2237 // Also, that would cause contention on INSERT of similarly named rows.
2238 $status = $this->acquireFileLock(); // represents all versions of the file
2239 if ( !$status->isGood() ) {
2240 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2241 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2243 throw new LocalFileLockError( $status );
2245 // Release the lock *after* commit to avoid row-level contention.
2246 // Make sure it triggers on rollback() as well as commit() (T132921).
2247 $dbw->onTransactionResolution(
2248 function () use ( $logger ) {
2249 $status = $this->releaseFileLock();
2250 if ( !$status->isGood() ) {
2251 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2256 // Callers might care if the SELECT snapshot is safely fresh
2257 $this->lockedOwnTrx
= $makesTransaction;
2262 return $this->lockedOwnTrx
;
2266 * Decrement the lock reference count and end the atomic section if it reaches zero
2268 * This method should not be used outside of LocalFile/LocalFile*Batch
2270 * The commit and loc release will happen when no atomic sections are active, which
2271 * may happen immediately or at some point after calling this
2273 public function unlock() {
2274 if ( $this->locked
) {
2276 if ( !$this->locked
) {
2277 $dbw = $this->repo
->getMasterDB();
2278 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2279 $this->lockedOwnTrx
= false;
2287 protected function readOnlyFatalStatus() {
2288 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2289 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2293 * Clean up any dangling locks
2295 function __destruct() {