3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use Wikimedia\AtEase\AtEase
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\IResultWrapper
;
29 use MediaWiki\MediaWikiServices
;
32 * Class to represent a local file in the wiki's own database
34 * Provides methods to retrieve paths (physical, logical, URL),
35 * to generate image thumbnails or for uploading.
37 * Note that only the repo object knows what its file class is called. You should
38 * never name a file class explictly outside of the repo class. Instead use the
39 * repo's factory functions to generate file objects, for example:
41 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
43 * Consider the services container below;
45 * $services = MediaWikiServices::getInstance();
47 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
48 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
50 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
51 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
52 * and $this->repoGroup->getLocalRepo()->newFile().
54 * @ingroup FileAbstraction
56 class LocalFile
extends File
{
57 const VERSION
= 11; // cache version
59 const CACHE_FIELD_MAX_LEN
= 1000;
61 /** @var bool Does the file exist on disk? (loadFromXxx) */
62 protected $fileExists;
64 /** @var int Image width */
67 /** @var int Image height */
70 /** @var int Returned by getimagesize (loadFromXxx) */
73 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
74 protected $media_type;
76 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
79 /** @var int Size in bytes (loadFromXxx) */
82 /** @var string Handler-specific metadata */
85 /** @var string SHA-1 base 36 content hash */
88 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
89 protected $dataLoaded;
91 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
92 protected $extraDataLoaded;
94 /** @var int Bitfield akin to rev_deleted */
98 protected $repoClass = LocalRepo
::class;
100 /** @var int Number of line to return by nextHistoryLine() (constructor) */
101 private $historyLine;
103 /** @var IResultWrapper|null Result of the query for the file's history (nextHistoryLine) */
106 /** @var string Major MIME type */
109 /** @var string Minor MIME type */
112 /** @var string Upload timestamp */
115 /** @var User Uploader */
118 /** @var string Description of current revision of the file */
119 private $description;
121 /** @var string TS_MW timestamp of the last change of the file description */
122 private $descriptionTouched;
124 /** @var bool Whether the row was upgraded on load */
127 /** @var bool Whether the row was scheduled to upgrade on load */
130 /** @var bool True if the image row is locked */
133 /** @var bool True if the image row is locked with a lock initiated transaction */
134 private $lockedOwnTrx;
136 /** @var bool True if file is not present in file system. Not to be cached in memcached */
139 // @note: higher than IDBAccessObject constants
140 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
142 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
145 * Create a LocalFile from a title
146 * Do not call this except from inside a repo class.
148 * Note: $unused param is only here to avoid an E_STRICT
150 * @param Title $title
151 * @param FileRepo $repo
152 * @param null $unused
156 static function newFromTitle( $title, $repo, $unused = null ) {
157 return new static( $title, $repo );
161 * Create a LocalFile from a title
162 * Do not call this except from inside a repo class.
164 * @param stdClass $row
165 * @param FileRepo $repo
169 static function newFromRow( $row, $repo ) {
170 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
171 $file = new static( $title, $repo );
172 $file->loadFromRow( $row );
178 * Create a LocalFile from a SHA-1 key
179 * Do not call this except from inside a repo class.
181 * @param string $sha1 Base-36 SHA-1
182 * @param LocalRepo $repo
183 * @param string|bool $timestamp MW_timestamp (optional)
184 * @return bool|LocalFile
186 static function newFromKey( $sha1, $repo, $timestamp = false ) {
187 $dbr = $repo->getReplicaDB();
189 $conds = [ 'img_sha1' => $sha1 ];
191 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
194 $fileQuery = static::getQueryInfo();
195 $row = $dbr->selectRow(
196 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
199 return static::newFromRow( $row, $repo );
206 * Fields in the image table
207 * @deprecated since 1.31, use self::getQueryInfo() instead.
210 static function selectFields() {
211 global $wgActorTableSchemaMigrationStage;
213 wfDeprecated( __METHOD__
, '1.31' );
214 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
215 // If code is using this instead of self::getQueryInfo(), there's a
216 // decent chance it's going to try to directly access
217 // $row->img_user or $row->img_user_text and we can't give it
218 // useful values here once those aren't being used anymore.
219 throw new BadMethodCallException(
220 'Cannot use ' . __METHOD__
221 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
237 'img_actor' => 'NULL',
240 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
244 * Return the tables, fields, and join conditions to be selected to create
245 * a new localfile object.
247 * @param string[] $options
248 * - omit-lazy: Omit fields that are lazily cached.
249 * @return array[] With three keys:
250 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
251 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
252 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
254 public static function getQueryInfo( array $options = [] ) {
255 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
256 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
258 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
271 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
272 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
275 if ( in_array( 'omit-nonlazy', $options, true ) ) {
276 // Internal use only for getting only the lazy fields
279 if ( !in_array( 'omit-lazy', $options, true ) ) {
280 // Note: Keep this in sync with self::getLazyCacheFields()
281 $ret['fields'][] = 'img_metadata';
288 * Do not call this except from inside a repo class.
289 * @param Title $title
290 * @param FileRepo $repo
292 function __construct( $title, $repo ) {
293 parent
::__construct( $title, $repo );
295 $this->metadata
= '';
296 $this->historyLine
= 0;
297 $this->historyRes
= null;
298 $this->dataLoaded
= false;
299 $this->extraDataLoaded
= false;
301 $this->assertRepoDefined();
302 $this->assertTitleDefined();
306 * Get the memcached key for the main data for this file, or false if
307 * there is no access to the shared cache.
308 * @return string|bool
310 function getCacheKey() {
311 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
315 * @param WANObjectCache $cache
319 public function getMutableCacheKeys( WANObjectCache
$cache ) {
320 return [ $this->getCacheKey() ];
324 * Try to load file metadata from memcached, falling back to the database
326 private function loadFromCache() {
327 $this->dataLoaded
= false;
328 $this->extraDataLoaded
= false;
330 $key = $this->getCacheKey();
332 $this->loadFromDB( self
::READ_NORMAL
);
337 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
338 $cachedValues = $cache->getWithSetCallback(
341 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
342 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
344 $this->loadFromDB( self
::READ_NORMAL
);
346 $fields = $this->getCacheFields( '' );
348 $cacheVal['fileExists'] = $this->fileExists
;
349 if ( $this->fileExists
) {
350 foreach ( $fields as $field ) {
351 $cacheVal[$field] = $this->$field;
354 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
355 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
356 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
358 // Strip off excessive entries from the subset of fields that can become large.
359 // If the cache value gets to large it will not fit in memcached and nothing will
360 // get cached at all, causing master queries for any file access.
361 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
362 if ( isset( $cacheVal[$field] )
363 && strlen( $cacheVal[$field] ) > 100 * 1024
365 unset( $cacheVal[$field] ); // don't let the value get too big
369 if ( $this->fileExists
) {
370 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
372 $ttl = $cache::TTL_DAY
;
377 [ 'version' => self
::VERSION
]
380 $this->fileExists
= $cachedValues['fileExists'];
381 if ( $this->fileExists
) {
382 $this->setProps( $cachedValues );
385 $this->dataLoaded
= true;
386 $this->extraDataLoaded
= true;
387 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
388 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
393 * Purge the file object/metadata cache
395 public function invalidateCache() {
396 $key = $this->getCacheKey();
401 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
402 function () use ( $key ) {
403 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
410 * Load metadata from the file itself
412 function loadFromFile() {
413 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
414 $this->setProps( $props );
418 * Returns the list of object properties that are included as-is in the cache.
419 * @param string $prefix Must be the empty string
421 * @since 1.31 No longer accepts a non-empty $prefix
423 protected function getCacheFields( $prefix = 'img_' ) {
424 if ( $prefix !== '' ) {
425 throw new InvalidArgumentException(
426 __METHOD__
. ' with a non-empty prefix is no longer supported.'
430 // See self::getQueryInfo() for the fetching of the data from the DB,
431 // self::loadFromRow() for the loading of the object from the DB row,
432 // and self::loadFromCache() for the caching, and self::setProps() for
433 // populating the object from an array of data.
434 return [ 'size', 'width', 'height', 'bits', 'media_type',
435 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
439 * Returns the list of object properties that are included as-is in the
440 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
441 * @param string $prefix Must be the empty string
443 * @since 1.31 No longer accepts a non-empty $prefix
445 protected function getLazyCacheFields( $prefix = 'img_' ) {
446 if ( $prefix !== '' ) {
447 throw new InvalidArgumentException(
448 __METHOD__
. ' with a non-empty prefix is no longer supported.'
452 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
453 return [ 'metadata' ];
457 * Load file metadata from the DB
460 function loadFromDB( $flags = 0 ) {
461 $fname = static::class . '::' . __FUNCTION__
;
463 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
464 $this->dataLoaded
= true;
465 $this->extraDataLoaded
= true;
467 $dbr = ( $flags & self
::READ_LATEST
)
468 ?
$this->repo
->getMasterDB()
469 : $this->repo
->getReplicaDB();
471 $fileQuery = static::getQueryInfo();
472 $row = $dbr->selectRow(
473 $fileQuery['tables'],
474 $fileQuery['fields'],
475 [ 'img_name' => $this->getName() ],
482 $this->loadFromRow( $row );
484 $this->fileExists
= false;
489 * Load lazy file metadata from the DB.
490 * This covers fields that are sometimes not cached.
492 protected function loadExtraFromDB() {
493 $fname = static::class . '::' . __FUNCTION__
;
495 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
496 $this->extraDataLoaded
= true;
498 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
500 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
504 foreach ( $fieldMap as $name => $value ) {
505 $this->$name = $value;
508 throw new MWException( "Could not find data for image '{$this->getName()}'." );
513 * @param IDatabase $dbr
514 * @param string $fname
515 * @return string[]|bool
517 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
520 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
521 $row = $dbr->selectRow(
522 $fileQuery['tables'],
523 $fileQuery['fields'],
525 'img_name' => $this->getName(),
526 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
533 $fieldMap = $this->unprefixRow( $row, 'img_' );
535 # File may have been uploaded over in the meantime; check the old versions
536 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
537 $row = $dbr->selectRow(
538 $fileQuery['tables'],
539 $fileQuery['fields'],
541 'oi_name' => $this->getName(),
542 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
549 $fieldMap = $this->unprefixRow( $row, 'oi_' );
553 if ( isset( $fieldMap['metadata'] ) ) {
554 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
561 * @param array|object $row
562 * @param string $prefix
563 * @throws MWException
566 protected function unprefixRow( $row, $prefix = 'img_' ) {
567 $array = (array)$row;
568 $prefixLength = strlen( $prefix );
570 // Sanity check prefix once
571 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
572 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
576 foreach ( $array as $name => $value ) {
577 $decoded[substr( $name, $prefixLength )] = $value;
584 * Decode a row from the database (either object or array) to an array
585 * with timestamps and MIME types decoded, and the field prefix removed.
587 * @param string $prefix
588 * @throws MWException
591 function decodeRow( $row, $prefix = 'img_' ) {
592 $decoded = $this->unprefixRow( $row, $prefix );
594 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
595 ->getComment( 'description', (object)$decoded )->text
;
597 $decoded['user'] = User
::newFromAnyId(
598 $decoded['user'] ??
null,
599 $decoded['user_text'] ??
null,
600 $decoded['actor'] ??
null
602 unset( $decoded['user_text'], $decoded['actor'] );
604 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
606 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
608 if ( empty( $decoded['major_mime'] ) ) {
609 $decoded['mime'] = 'unknown/unknown';
611 if ( !$decoded['minor_mime'] ) {
612 $decoded['minor_mime'] = 'unknown';
614 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
617 // Trim zero padding from char/binary field
618 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
620 // Normalize some fields to integer type, per their database definition.
621 // Use unary + so that overflows will be upgraded to double instead of
622 // being trucated as with intval(). This is important to allow >2GB
623 // files on 32-bit systems.
624 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
625 $decoded[$field] = +
$decoded[$field];
632 * Load file metadata from a DB result row
635 * @param string $prefix
637 function loadFromRow( $row, $prefix = 'img_' ) {
638 $this->dataLoaded
= true;
639 $this->extraDataLoaded
= true;
641 $array = $this->decodeRow( $row, $prefix );
643 foreach ( $array as $name => $value ) {
644 $this->$name = $value;
647 $this->fileExists
= true;
651 * Load file metadata from cache or DB, unless already loaded
654 function load( $flags = 0 ) {
655 if ( !$this->dataLoaded
) {
656 if ( $flags & self
::READ_LATEST
) {
657 $this->loadFromDB( $flags );
659 $this->loadFromCache();
663 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
664 // @note: loads on name/timestamp to reduce race condition problems
665 $this->loadExtraFromDB();
670 * Upgrade a row if it needs it
672 protected function maybeUpgradeRow() {
673 global $wgUpdateCompatibleMetadata;
675 if ( wfReadOnly() ||
$this->upgrading
) {
680 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
683 $handler = $this->getHandler();
685 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
686 if ( $validity === MediaHandler
::METADATA_BAD
) {
688 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
689 $upgrade = $wgUpdateCompatibleMetadata;
695 $this->upgrading
= true;
696 // Defer updates unless in auto-commit CLI mode
697 DeferredUpdates
::addCallableUpdate( function () {
698 $this->upgrading
= false; // avoid duplicate updates
701 } catch ( LocalFileLockError
$e ) {
702 // let the other process handle it (or do it next time)
709 * @return bool Whether upgradeRow() ran for this object
711 function getUpgraded() {
712 return $this->upgraded
;
716 * Fix assorted version-related problems with the image row by reloading it from the file
718 function upgradeRow() {
721 $this->loadFromFile();
723 # Don't destroy file info of missing files
724 if ( !$this->fileExists
) {
726 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
731 $dbw = $this->repo
->getMasterDB();
732 list( $major, $minor ) = self
::splitMime( $this->mime
);
734 if ( wfReadOnly() ) {
739 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
741 $dbw->update( 'image',
743 'img_size' => $this->size
, // sanity
744 'img_width' => $this->width
,
745 'img_height' => $this->height
,
746 'img_bits' => $this->bits
,
747 'img_media_type' => $this->media_type
,
748 'img_major_mime' => $major,
749 'img_minor_mime' => $minor,
750 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
751 'img_sha1' => $this->sha1
,
753 [ 'img_name' => $this->getName() ],
757 $this->invalidateCache();
760 $this->upgraded
= true; // avoid rework/retries
764 * Set properties in this object to be equal to those given in the
765 * associative array $info. Only cacheable fields can be set.
766 * All fields *must* be set in $info except for getLazyCacheFields().
768 * If 'mime' is given, it will be split into major_mime/minor_mime.
769 * If major_mime/minor_mime are given, $this->mime will also be set.
773 function setProps( $info ) {
774 $this->dataLoaded
= true;
775 $fields = $this->getCacheFields( '' );
776 $fields[] = 'fileExists';
778 foreach ( $fields as $field ) {
779 if ( isset( $info[$field] ) ) {
780 $this->$field = $info[$field];
784 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
785 $this->user
= User
::newFromAnyId(
786 $info['user'] ??
null,
787 $info['user_text'] ??
null,
788 $info['actor'] ??
null
792 // Fix up mime fields
793 if ( isset( $info['major_mime'] ) ) {
794 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
795 } elseif ( isset( $info['mime'] ) ) {
796 $this->mime
= $info['mime'];
797 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
801 /** splitMime inherited */
802 /** getName inherited */
803 /** getTitle inherited */
804 /** getURL inherited */
805 /** getViewURL inherited */
806 /** getPath inherited */
807 /** isVisible inherited */
810 * Checks if this file exists in its parent repo, as referenced by its
815 function isMissing() {
816 if ( $this->missing
=== null ) {
817 $fileExists = $this->repo
->fileExists( $this->getVirtualUrl() );
818 $this->missing
= !$fileExists;
821 return $this->missing
;
825 * Return the width of the image
830 public function getWidth( $page = 1 ) {
838 if ( $this->isMultipage() ) {
839 $handler = $this->getHandler();
843 $dim = $handler->getPageDimensions( $this, $page );
845 return $dim['width'];
847 // For non-paged media, the false goes through an
848 // intval, turning failure into 0, so do same here.
857 * Return the height of the image
862 public function getHeight( $page = 1 ) {
870 if ( $this->isMultipage() ) {
871 $handler = $this->getHandler();
875 $dim = $handler->getPageDimensions( $this, $page );
877 return $dim['height'];
879 // For non-paged media, the false goes through an
880 // intval, turning failure into 0, so do same here.
884 return $this->height
;
889 * Returns user who uploaded the file
891 * @param string $type 'text', 'id', or 'object'
892 * @return int|string|User
893 * @since 1.31 Added 'object'
895 function getUser( $type = 'text' ) {
898 if ( $type === 'object' ) {
900 } elseif ( $type === 'text' ) {
901 return $this->user
->getName();
902 } elseif ( $type === 'id' ) {
903 return $this->user
->getId();
906 throw new MWException( "Unknown type '$type'." );
910 * Get short description URL for a file based on the page ID.
912 * @return string|null
913 * @throws MWException
916 public function getDescriptionShortUrl() {
917 $pageId = $this->title
->getArticleID();
919 if ( $pageId !== null ) {
920 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
921 if ( $url !== false ) {
929 * Get handler-specific metadata
932 function getMetadata() {
933 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
934 return $this->metadata
;
940 function getBitDepth() {
943 return (int)$this->bits
;
947 * Returns the size of the image file, in bytes
950 public function getSize() {
957 * Returns the MIME type of the file.
960 function getMimeType() {
967 * Returns the type of the media in the file.
968 * Use the value returned by this function with the MEDIATYPE_xxx constants.
971 function getMediaType() {
974 return $this->media_type
;
977 /** canRender inherited */
978 /** mustRender inherited */
979 /** allowInlineDisplay inherited */
980 /** isSafeFile inherited */
981 /** isTrustedFile inherited */
984 * Returns true if the file exists on disk.
985 * @return bool Whether file exist on disk.
987 public function exists() {
990 return $this->fileExists
;
993 /** getTransformScript inherited */
994 /** getUnscaledThumb inherited */
995 /** thumbName inherited */
996 /** createThumb inherited */
997 /** transform inherited */
999 /** getHandler inherited */
1000 /** iconThumb inherited */
1001 /** getLastError inherited */
1004 * Get all thumbnail names previously generated for this file
1005 * @param string|bool $archiveName Name of an archive file, default false
1006 * @return array First element is the base dir, then files in that base dir.
1008 function getThumbnails( $archiveName = false ) {
1009 if ( $archiveName ) {
1010 $dir = $this->getArchiveThumbPath( $archiveName );
1012 $dir = $this->getThumbPath();
1015 $backend = $this->repo
->getBackend();
1018 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1019 foreach ( $iterator as $file ) {
1022 } catch ( FileBackendError
$e ) {
1023 } // suppress (T56674)
1029 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1031 function purgeMetadataCache() {
1032 $this->invalidateCache();
1036 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1038 * @param array $options An array potentially with the key forThumbRefresh.
1040 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1042 function purgeCache( $options = [] ) {
1043 // Refresh metadata cache
1044 $this->maybeUpgradeRow();
1045 $this->purgeMetadataCache();
1047 // Delete thumbnails
1048 $this->purgeThumbnails( $options );
1050 // Purge CDN cache for this file
1051 DeferredUpdates
::addUpdate(
1052 new CdnCacheUpdate( [ $this->getUrl() ] ),
1053 DeferredUpdates
::PRESEND
1058 * Delete cached transformed files for an archived version only.
1059 * @param string $archiveName Name of the archived file
1061 function purgeOldThumbnails( $archiveName ) {
1062 // Get a list of old thumbnails and URLs
1063 $files = $this->getThumbnails( $archiveName );
1065 // Purge any custom thumbnail caches
1066 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1068 // Delete thumbnails
1069 $dir = array_shift( $files );
1070 $this->purgeThumbList( $dir, $files );
1074 foreach ( $files as $file ) {
1075 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1077 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1081 * Delete cached transformed files for the current version only.
1082 * @param array $options
1083 * @phan-param array{forThumbRefresh?:bool} $options
1085 public function purgeThumbnails( $options = [] ) {
1086 $files = $this->getThumbnails();
1087 // Always purge all files from CDN regardless of handler filters
1089 foreach ( $files as $file ) {
1090 $urls[] = $this->getThumbUrl( $file );
1092 array_shift( $urls ); // don't purge directory
1094 // Give media handler a chance to filter the file purge list
1095 // @phan-suppress-next-line PhanTypeInvalidDimOffset
1096 if ( !empty( $options['forThumbRefresh'] ) ) {
1097 $handler = $this->getHandler();
1099 $handler->filterThumbnailPurgeList( $files, $options );
1103 // Purge any custom thumbnail caches
1104 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1106 // Delete thumbnails
1107 $dir = array_shift( $files );
1108 $this->purgeThumbList( $dir, $files );
1111 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1115 * Prerenders a configurable set of thumbnails
1119 public function prerenderThumbnails() {
1120 global $wgUploadThumbnailRenderMap;
1124 $sizes = $wgUploadThumbnailRenderMap;
1127 foreach ( $sizes as $size ) {
1128 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1129 $jobs[] = new ThumbnailRenderJob(
1131 [ 'transformParams' => [ 'width' => $size ] ]
1137 JobQueueGroup
::singleton()->lazyPush( $jobs );
1142 * Delete a list of thumbnails visible at urls
1143 * @param string $dir Base dir of the files.
1144 * @param array $files Array of strings: relative filenames (to $dir)
1146 protected function purgeThumbList( $dir, $files ) {
1147 $fileListDebug = strtr(
1148 var_export( $files, true ),
1151 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1154 foreach ( $files as $file ) {
1155 if ( $this->repo
->supportsSha1URLs() ) {
1156 $reference = $this->getSha1();
1158 $reference = $this->getName();
1161 # Check that the reference (filename or sha1) is part of the thumb name
1162 # This is a basic sanity check to avoid erasing unrelated directories
1163 if ( strpos( $file, $reference ) !== false
1164 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1166 $purgeList[] = "{$dir}/{$file}";
1170 # Delete the thumbnails
1171 $this->repo
->quickPurgeBatch( $purgeList );
1172 # Clear out the thumbnail directory if empty
1173 $this->repo
->quickCleanDir( $dir );
1176 /** purgeDescription inherited */
1177 /** purgeEverything inherited */
1180 * @param int|null $limit Optional: Limit to number of results
1181 * @param string|int|null $start Optional: Timestamp, start from
1182 * @param string|int|null $end Optional: Timestamp, end at
1184 * @return OldLocalFile[]
1186 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1187 $dbr = $this->repo
->getReplicaDB();
1188 $oldFileQuery = OldLocalFile
::getQueryInfo();
1190 $tables = $oldFileQuery['tables'];
1191 $fields = $oldFileQuery['fields'];
1192 $join_conds = $oldFileQuery['joins'];
1193 $conds = $opts = [];
1194 $eq = $inc ?
'=' : '';
1195 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1198 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1202 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1206 $opts['LIMIT'] = $limit;
1209 // Search backwards for time > x queries
1210 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1211 $opts['ORDER BY'] = "oi_timestamp $order";
1212 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1214 // Avoid PHP 7.1 warning from passing $this by reference
1216 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1217 &$conds, &$opts, &$join_conds ] );
1219 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1222 foreach ( $res as $row ) {
1223 $r[] = $this->repo
->newFileFromRow( $row );
1226 if ( $order == 'ASC' ) {
1227 $r = array_reverse( $r ); // make sure it ends up descending
1234 * Returns the history of this file, line by line.
1235 * starts with current version, then old versions.
1236 * uses $this->historyLine to check which line to return:
1237 * 0 return line for current version
1238 * 1 query for old versions, return first one
1239 * 2, ... return next old version from above query
1242 public function nextHistoryLine() {
1243 # Polymorphic function name to distinguish foreign and local fetches
1244 $fname = static::class . '::' . __FUNCTION__
;
1246 $dbr = $this->repo
->getReplicaDB();
1248 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1249 $fileQuery = self
::getQueryInfo();
1250 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1251 $fileQuery['fields'] +
[
1252 'oi_archive_name' => $dbr->addQuotes( '' ),
1255 [ 'img_name' => $this->title
->getDBkey() ],
1261 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1262 $this->historyRes
= null;
1266 } elseif ( $this->historyLine
== 1 ) {
1267 $fileQuery = OldLocalFile
::getQueryInfo();
1268 $this->historyRes
= $dbr->select(
1269 $fileQuery['tables'],
1270 $fileQuery['fields'],
1271 [ 'oi_name' => $this->title
->getDBkey() ],
1273 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1277 $this->historyLine++
;
1279 return $dbr->fetchObject( $this->historyRes
);
1283 * Reset the history pointer to the first element of the history
1285 public function resetHistory() {
1286 $this->historyLine
= 0;
1288 if ( !is_null( $this->historyRes
) ) {
1289 $this->historyRes
= null;
1293 /** getHashPath inherited */
1294 /** getRel inherited */
1295 /** getUrlRel inherited */
1296 /** getArchiveRel inherited */
1297 /** getArchivePath inherited */
1298 /** getThumbPath inherited */
1299 /** getArchiveUrl inherited */
1300 /** getThumbUrl inherited */
1301 /** getArchiveVirtualUrl inherited */
1302 /** getThumbVirtualUrl inherited */
1303 /** isHashed inherited */
1306 * Upload a file and record it in the DB
1307 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1308 * @param string $comment Upload description
1309 * @param string $pageText Text to use for the new description page,
1310 * if a new description page is created
1311 * @param int|bool $flags Flags for publish()
1312 * @param array|bool $props File properties, if known. This can be used to
1313 * reduce the upload time when uploading virtual URLs for which the file
1314 * info is already known
1315 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1317 * @param User|null $user User object or null to use $wgUser
1318 * @param string[] $tags Change tags to add to the log entry and page revision.
1319 * (This doesn't check $user's permissions.)
1320 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1321 * upload, see T193621
1322 * @param bool $revert If this file upload is a revert
1323 * @return Status On success, the value member contains the
1324 * archive name, or an empty string if it was a new file.
1326 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1327 $timestamp = false, $user = null, $tags = [],
1328 $createNullRevision = true, $revert = false
1330 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1331 return $this->readOnlyFatalStatus();
1332 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1333 // Check this in advance to avoid writing to FileBackend and the file tables,
1334 // only to fail on insert the revision due to the text store being unavailable.
1335 return $this->readOnlyFatalStatus();
1338 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1340 if ( FileRepo
::isVirtualUrl( $srcPath )
1341 || FileBackend
::isStoragePath( $srcPath )
1343 $props = $this->repo
->getFileProps( $srcPath );
1345 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1346 $props = $mwProps->getPropsFromPath( $srcPath, true );
1351 $handler = MediaHandler
::getHandler( $props['mime'] );
1353 $metadata = AtEase
::quietCall( 'unserialize', $props['metadata'] );
1355 if ( !is_array( $metadata ) ) {
1359 $options['headers'] = $handler->getContentHeaders( $metadata );
1361 $options['headers'] = [];
1364 // Trim spaces on user supplied text
1365 $comment = trim( $comment );
1368 $status = $this->publish( $src, $flags, $options );
1370 if ( $status->successCount
>= 2 ) {
1371 // There will be a copy+(one of move,copy,store).
1372 // The first succeeding does not commit us to updating the DB
1373 // since it simply copied the current version to a timestamped file name.
1374 // It is only *preferable* to avoid leaving such files orphaned.
1375 // Once the second operation goes through, then the current version was
1376 // updated and we must therefore update the DB too.
1377 $oldver = $status->value
;
1378 $uploadStatus = $this->recordUpload2(
1386 $createNullRevision,
1389 if ( !$uploadStatus->isOK() ) {
1390 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1391 // update filenotfound error with more specific path
1392 $status->fatal( 'filenotfound', $srcPath );
1394 $status->merge( $uploadStatus );
1404 * Record a file upload in the upload log and the image table
1405 * @param string $oldver
1406 * @param string $desc
1407 * @param string $license
1408 * @param string $copyStatus
1409 * @param string $source
1410 * @param bool $watch
1411 * @param string|bool $timestamp
1412 * @param User|null $user User object or null to use $wgUser
1415 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1416 $watch = false, $timestamp = false, User
$user = null ) {
1422 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1424 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1429 $user->addWatch( $this->getTitle() );
1436 * Record a file upload in the upload log and the image table
1437 * @param string $oldver
1438 * @param string $comment
1439 * @param string $pageText
1440 * @param bool|array $props
1441 * @param string|bool $timestamp
1442 * @param null|User $user
1443 * @param string[] $tags
1444 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1445 * upload, see T193621
1446 * @param bool $revert If this file upload is a revert
1449 function recordUpload2(
1450 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1451 $createNullRevision = true, $revert = false
1453 global $wgActorTableSchemaMigrationStage;
1455 if ( is_null( $user ) ) {
1460 $dbw = $this->repo
->getMasterDB();
1462 # Imports or such might force a certain timestamp; otherwise we generate
1463 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1464 if ( $timestamp === false ) {
1465 $timestamp = $dbw->timestamp();
1466 $allowTimeKludge = true;
1468 $allowTimeKludge = false;
1471 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1472 $props['description'] = $comment;
1473 $props['user'] = $user->getId();
1474 $props['user_text'] = $user->getName();
1475 $props['actor'] = $user->getActorId( $dbw );
1476 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1477 $this->setProps( $props );
1479 # Fail now if the file isn't there
1480 if ( !$this->fileExists
) {
1481 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1483 return Status
::newFatal( 'filenotfound', $this->getRel() );
1486 $dbw->startAtomic( __METHOD__
);
1488 # Test to see if the row exists using INSERT IGNORE
1489 # This avoids race conditions by locking the row until the commit, and also
1490 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1491 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1492 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1493 $actorMigration = ActorMigration
::newMigration();
1494 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1495 $dbw->insert( 'image',
1497 'img_name' => $this->getName(),
1498 'img_size' => $this->size
,
1499 'img_width' => intval( $this->width
),
1500 'img_height' => intval( $this->height
),
1501 'img_bits' => $this->bits
,
1502 'img_media_type' => $this->media_type
,
1503 'img_major_mime' => $this->major_mime
,
1504 'img_minor_mime' => $this->minor_mime
,
1505 'img_timestamp' => $timestamp,
1506 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1507 'img_sha1' => $this->sha1
1508 ] +
$commentFields +
$actorFields,
1512 $reupload = ( $dbw->affectedRows() == 0 );
1515 $row = $dbw->selectRow(
1517 [ 'img_timestamp', 'img_sha1' ],
1518 [ 'img_name' => $this->getName() ],
1520 [ 'LOCK IN SHARE MODE' ]
1523 if ( $row && $row->img_sha1
=== $this->sha1
) {
1524 $dbw->endAtomic( __METHOD__
);
1525 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1526 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1527 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1530 if ( $allowTimeKludge ) {
1531 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1532 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1533 # Avoid a timestamp that is not newer than the last version
1534 # TODO: the image/oldimage tables should be like page/revision with an ID field
1535 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1536 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1537 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1538 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1542 $tables = [ 'image' ];
1544 'oi_name' => 'img_name',
1545 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1546 'oi_size' => 'img_size',
1547 'oi_width' => 'img_width',
1548 'oi_height' => 'img_height',
1549 'oi_bits' => 'img_bits',
1550 'oi_description_id' => 'img_description_id',
1551 'oi_timestamp' => 'img_timestamp',
1552 'oi_metadata' => 'img_metadata',
1553 'oi_media_type' => 'img_media_type',
1554 'oi_major_mime' => 'img_major_mime',
1555 'oi_minor_mime' => 'img_minor_mime',
1556 'oi_sha1' => 'img_sha1',
1560 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1561 $fields['oi_user'] = 'img_user';
1562 $fields['oi_user_text'] = 'img_user_text';
1564 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1565 $fields['oi_actor'] = 'img_actor';
1569 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1571 // Upgrade any rows that are still old-style. Otherwise an upgrade
1572 // might be missed if a deletion happens while the migration script
1574 $res = $dbw->select(
1576 [ 'img_name', 'img_user', 'img_user_text' ],
1577 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1580 foreach ( $res as $row ) {
1581 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1584 [ 'img_actor' => $actorId ],
1585 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1591 # (T36993) Note: $oldver can be empty here, if the previous
1592 # version of the file was broken. Allow registration of the new
1593 # version to continue anyway, because that's better than having
1594 # an image that's not fixable by user operations.
1595 # Collision, this is an update of a file
1596 # Insert previous contents into oldimage
1597 $dbw->insertSelect( 'oldimage', $tables, $fields,
1598 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1600 # Update the current image row
1601 $dbw->update( 'image',
1603 'img_size' => $this->size
,
1604 'img_width' => intval( $this->width
),
1605 'img_height' => intval( $this->height
),
1606 'img_bits' => $this->bits
,
1607 'img_media_type' => $this->media_type
,
1608 'img_major_mime' => $this->major_mime
,
1609 'img_minor_mime' => $this->minor_mime
,
1610 'img_timestamp' => $timestamp,
1611 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1612 'img_sha1' => $this->sha1
1613 ] +
$commentFields +
$actorFields,
1614 [ 'img_name' => $this->getName() ],
1619 $descTitle = $this->getTitle();
1620 $descId = $descTitle->getArticleID();
1621 $wikiPage = new WikiFilePage( $descTitle );
1622 $wikiPage->setFile( $this );
1624 // Determine log action. If reupload is done by reverting, use a special log_action.
1625 if ( $revert === true ) {
1626 $logAction = 'revert';
1627 } elseif ( $reupload === true ) {
1628 $logAction = 'overwrite';
1630 $logAction = 'upload';
1632 // Add the log entry...
1633 $logEntry = new ManualLogEntry( 'upload', $logAction );
1634 $logEntry->setTimestamp( $this->timestamp
);
1635 $logEntry->setPerformer( $user );
1636 $logEntry->setComment( $comment );
1637 $logEntry->setTarget( $descTitle );
1638 // Allow people using the api to associate log entries with the upload.
1639 // Log has a timestamp, but sometimes different from upload timestamp.
1640 $logEntry->setParameters(
1642 'img_sha1' => $this->sha1
,
1643 'img_timestamp' => $timestamp,
1646 // Note we keep $logId around since during new image
1647 // creation, page doesn't exist yet, so log_page = 0
1648 // but we want it to point to the page we're making,
1649 // so we later modify the log entry.
1650 // For a similar reason, we avoid making an RC entry
1651 // now and wait until the page exists.
1652 $logId = $logEntry->insert();
1654 if ( $descTitle->exists() ) {
1655 // Use own context to get the action text in content language
1656 $formatter = LogFormatter
::newFromEntry( $logEntry );
1657 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1658 $editSummary = $formatter->getPlainActionText();
1660 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1667 if ( $nullRevision ) {
1668 $nullRevision->insertOn( $dbw );
1670 'NewRevisionFromEditComplete',
1671 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1673 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1674 // Associate null revision id
1675 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1678 $newPageContent = null;
1680 // Make the description page and RC log entry post-commit
1681 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1684 # Defer purges, page creation, and link updates in case they error out.
1685 # The most important thing is that files and the DB registry stay synced.
1686 $dbw->endAtomic( __METHOD__
);
1687 $fname = __METHOD__
;
1689 # Do some cache purges after final commit so that:
1690 # a) Changes are more likely to be seen post-purge
1691 # b) They won't cause rollback of the log publish/update above
1692 DeferredUpdates
::addUpdate(
1693 new AutoCommitUpdate(
1697 $reupload, $wikiPage, $newPageContent, $comment, $user,
1698 $logEntry, $logId, $descId, $tags, $fname
1700 # Update memcache after the commit
1701 $this->invalidateCache();
1703 $updateLogPage = false;
1704 if ( $newPageContent ) {
1705 # New file page; create the description page.
1706 # There's already a log entry, so don't make a second RC entry
1707 # CDN and file cache for the description page are purged by doEditContent.
1708 $status = $wikiPage->doEditContent(
1711 EDIT_NEW | EDIT_SUPPRESS_RC
,
1716 if ( isset( $status->value
['revision'] ) ) {
1717 /** @var Revision $rev */
1718 $rev = $status->value
['revision'];
1719 // Associate new page revision id
1720 $logEntry->setAssociatedRevId( $rev->getId() );
1722 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1723 // which is triggered on $descTitle by doEditContent() above.
1724 if ( isset( $status->value
['revision'] ) ) {
1725 /** @var Revision $rev */
1726 $rev = $status->value
['revision'];
1727 $updateLogPage = $rev->getPage();
1730 # Existing file page: invalidate description page cache
1731 $wikiPage->getTitle()->invalidateCache();
1732 $wikiPage->getTitle()->purgeSquid();
1733 # Allow the new file version to be patrolled from the page footer
1734 Article
::purgePatrolFooterCache( $descId );
1737 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1738 # but setAssociatedRevId() wasn't called at that point yet...
1739 $logParams = $logEntry->getParameters();
1740 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1741 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1742 if ( $updateLogPage ) {
1743 # Also log page, in case where we just created it above
1744 $update['log_page'] = $updateLogPage;
1746 $this->getRepo()->getMasterDB()->update(
1749 [ 'log_id' => $logId ],
1752 $this->getRepo()->getMasterDB()->insert(
1755 'ls_field' => 'associated_rev_id',
1756 'ls_value' => $logEntry->getAssociatedRevId(),
1757 'ls_log_id' => $logId,
1762 # Add change tags, if any
1764 $logEntry->addTags( $tags );
1767 # Uploads can be patrolled
1768 $logEntry->setIsPatrollable( true );
1770 # Now that the log entry is up-to-date, make an RC entry.
1771 $logEntry->publish( $logId );
1773 # Run hook for other updates (typically more cache purging)
1774 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1777 # Delete old thumbnails
1778 $this->purgeThumbnails();
1779 # Remove the old file from the CDN cache
1780 DeferredUpdates
::addUpdate(
1781 new CdnCacheUpdate( [ $this->getUrl() ] ),
1782 DeferredUpdates
::PRESEND
1785 # Update backlink pages pointing to this title if created
1786 LinksUpdate
::queueRecursiveJobsForTable(
1794 $this->prerenderThumbnails();
1797 DeferredUpdates
::PRESEND
1801 # This is a new file, so update the image count
1802 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1805 # Invalidate cache for all pages using this file
1806 DeferredUpdates
::addUpdate(
1807 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1810 return Status
::newGood();
1814 * Move or copy a file to its public location. If a file exists at the
1815 * destination, move it to an archive. Returns a Status object with
1816 * the archive name in the "value" member on success.
1818 * The archive name should be passed through to recordUpload for database
1821 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1822 * @param int $flags A bitwise combination of:
1823 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1824 * @param array $options Optional additional parameters
1825 * @return Status On success, the value member contains the
1826 * archive name, or an empty string if it was a new file.
1828 function publish( $src, $flags = 0, array $options = [] ) {
1829 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1833 * Move or copy a file to a specified location. Returns a Status
1834 * object with the archive name in the "value" member on success.
1836 * The archive name should be passed through to recordUpload for database
1839 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1840 * @param string $dstRel Target relative path
1841 * @param int $flags A bitwise combination of:
1842 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1843 * @param array $options Optional additional parameters
1844 * @return Status On success, the value member contains the
1845 * archive name, or an empty string if it was a new file.
1847 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1848 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1850 $repo = $this->getRepo();
1851 if ( $repo->getReadOnlyReason() !== false ) {
1852 return $this->readOnlyFatalStatus();
1857 if ( $this->isOld() ) {
1858 $archiveRel = $dstRel;
1859 $archiveName = basename( $archiveRel );
1861 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1862 $archiveRel = $this->getArchiveRel( $archiveName );
1865 if ( $repo->hasSha1Storage() ) {
1866 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1867 ?
$repo->getFileSha1( $srcPath )
1868 : FSFile
::getSha1Base36FromPath( $srcPath );
1869 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1870 $wrapperBackend = $repo->getBackend();
1871 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1872 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1873 $status = $repo->quickImport( $src, $dst );
1874 if ( $flags & File
::DELETE_SOURCE
) {
1878 if ( $this->exists() ) {
1879 $status->value
= $archiveName;
1882 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1883 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1885 if ( $status->value
== 'new' ) {
1886 $status->value
= '';
1888 $status->value
= $archiveName;
1896 /** getLinksTo inherited */
1897 /** getExifData inherited */
1898 /** isLocal inherited */
1899 /** wasDeleted inherited */
1902 * Move file to the new title
1904 * Move current, old version and all thumbnails
1905 * to the new filename. Old file is deleted.
1907 * Cache purging is done; checks for validity
1908 * and logging are caller's responsibility
1910 * @param Title $target New file name
1913 function move( $target ) {
1914 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
1915 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1916 return $this->readOnlyFatalStatus();
1919 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1920 $batch = new LocalFileMoveBatch( $this, $target );
1923 $batch->addCurrent();
1924 $archiveNames = $batch->addOlds();
1925 $status = $batch->execute();
1928 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1930 // Purge the source and target files outside the transaction...
1931 $oldTitleFile = $localRepo->newFile( $this->title
);
1932 $newTitleFile = $localRepo->newFile( $target );
1933 DeferredUpdates
::addUpdate(
1934 new AutoCommitUpdate(
1935 $this->getRepo()->getMasterDB(),
1937 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1938 $oldTitleFile->purgeEverything();
1939 foreach ( $archiveNames as $archiveName ) {
1940 /** @var OldLocalFile $oldTitleFile */
1941 '@phan-var OldLocalFile $oldTitleFile';
1942 $oldTitleFile->purgeOldThumbnails( $archiveName );
1944 $newTitleFile->purgeEverything();
1947 DeferredUpdates
::PRESEND
1950 if ( $status->isOK() ) {
1951 // Now switch the object
1952 $this->title
= $target;
1953 // Force regeneration of the name and hashpath
1955 $this->hashPath
= null;
1962 * Delete all versions of the file.
1964 * Moves the files into an archive directory (or deletes them)
1965 * and removes the database rows.
1967 * Cache purging is done; logging is caller's responsibility.
1969 * @param string $reason
1970 * @param bool $suppress
1971 * @param User|null $user
1974 function delete( $reason, $suppress = false, $user = null ) {
1975 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1976 return $this->readOnlyFatalStatus();
1979 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1982 $batch->addCurrent();
1983 // Get old version relative paths
1984 $archiveNames = $batch->addOlds();
1985 $status = $batch->execute();
1988 if ( $status->isOK() ) {
1989 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1992 // To avoid slow purges in the transaction, move them outside...
1993 DeferredUpdates
::addUpdate(
1994 new AutoCommitUpdate(
1995 $this->getRepo()->getMasterDB(),
1997 function () use ( $archiveNames ) {
1998 $this->purgeEverything();
1999 foreach ( $archiveNames as $archiveName ) {
2000 $this->purgeOldThumbnails( $archiveName );
2004 DeferredUpdates
::PRESEND
2009 foreach ( $archiveNames as $archiveName ) {
2010 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2012 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2018 * Delete an old version of the file.
2020 * Moves the file into an archive directory (or deletes it)
2021 * and removes the database row.
2023 * Cache purging is done; logging is caller's responsibility.
2025 * @param string $archiveName
2026 * @param string $reason
2027 * @param bool $suppress
2028 * @param User|null $user
2029 * @throws MWException Exception on database or file store failure
2032 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2033 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2034 return $this->readOnlyFatalStatus();
2037 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2040 $batch->addOld( $archiveName );
2041 $status = $batch->execute();
2044 $this->purgeOldThumbnails( $archiveName );
2045 if ( $status->isOK() ) {
2046 $this->purgeDescription();
2049 DeferredUpdates
::addUpdate(
2050 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2051 DeferredUpdates
::PRESEND
2058 * Restore all or specified deleted revisions to the given file.
2059 * Permissions and logging are left to the caller.
2061 * May throw database exceptions on error.
2063 * @param array $versions Set of record ids of deleted items to restore,
2064 * or empty to restore all revisions.
2065 * @param bool $unsuppress
2068 function restore( $versions = [], $unsuppress = false ) {
2069 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2070 return $this->readOnlyFatalStatus();
2073 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2079 $batch->addIds( $versions );
2081 $status = $batch->execute();
2082 if ( $status->isGood() ) {
2083 $cleanupStatus = $batch->cleanup();
2084 $cleanupStatus->successCount
= 0;
2085 $cleanupStatus->failCount
= 0;
2086 $status->merge( $cleanupStatus );
2093 /** isMultipage inherited */
2094 /** pageCount inherited */
2095 /** scaleHeight inherited */
2096 /** getImageSize inherited */
2099 * Get the URL of the file description page.
2102 function getDescriptionUrl() {
2103 return $this->title
->getLocalURL();
2107 * Get the HTML text of the description page
2108 * This is not used by ImagePage for local files, since (among other things)
2109 * it skips the parser cache.
2111 * @param Language|null $lang What language to get description in (Optional)
2112 * @return string|false
2114 function getDescriptionText( Language
$lang = null ) {
2115 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2116 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2121 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2122 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2125 // audience check failed
2129 $pout = $rendered->getRevisionParserOutput();
2130 return $pout->getText();
2134 * @param int $audience
2135 * @param User|null $user
2138 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2140 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2142 } elseif ( $audience == self
::FOR_THIS_USER
2143 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2147 return $this->description
;
2152 * @return bool|string
2154 function getTimestamp() {
2157 return $this->timestamp
;
2161 * @return bool|string
2163 public function getDescriptionTouched() {
2164 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2165 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2166 // need to differentiate between null (uninitialized) and false (failed to load).
2167 if ( $this->descriptionTouched
=== null ) {
2169 'page_namespace' => $this->title
->getNamespace(),
2170 'page_title' => $this->title
->getDBkey()
2172 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2173 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2176 return $this->descriptionTouched
;
2182 function getSha1() {
2184 // Initialise now if necessary
2185 if ( $this->sha1
== '' && $this->fileExists
) {
2188 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2189 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2190 $dbw = $this->repo
->getMasterDB();
2191 $dbw->update( 'image',
2192 [ 'img_sha1' => $this->sha1
],
2193 [ 'img_name' => $this->getName() ],
2195 $this->invalidateCache();
2205 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2207 function isCacheable() {
2210 // If extra data (metadata) was not loaded then it must have been large
2211 return $this->extraDataLoaded
2212 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2219 public function acquireFileLock() {
2220 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2221 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2229 public function releaseFileLock() {
2230 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2231 [ $this->getPath() ], LockManager
::LOCK_EX
2236 * Start an atomic DB section and lock the image for update
2237 * or increments a reference counter if the lock is already held
2239 * This method should not be used outside of LocalFile/LocalFile*Batch
2241 * @throws LocalFileLockError Throws an error if the lock was not acquired
2242 * @return bool Whether the file lock owns/spawned the DB transaction
2244 public function lock() {
2245 if ( !$this->locked
) {
2246 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2248 $dbw = $this->repo
->getMasterDB();
2249 $makesTransaction = !$dbw->trxLevel();
2250 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2251 // T56736: use simple lock to handle when the file does not exist.
2252 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2253 // Also, that would cause contention on INSERT of similarly named rows.
2254 $status = $this->acquireFileLock(); // represents all versions of the file
2255 if ( !$status->isGood() ) {
2256 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2257 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2259 throw new LocalFileLockError( $status );
2261 // Release the lock *after* commit to avoid row-level contention.
2262 // Make sure it triggers on rollback() as well as commit() (T132921).
2263 $dbw->onTransactionResolution(
2264 function () use ( $logger ) {
2265 $status = $this->releaseFileLock();
2266 if ( !$status->isGood() ) {
2267 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2272 // Callers might care if the SELECT snapshot is safely fresh
2273 $this->lockedOwnTrx
= $makesTransaction;
2278 return $this->lockedOwnTrx
;
2282 * Decrement the lock reference count and end the atomic section if it reaches zero
2284 * This method should not be used outside of LocalFile/LocalFile*Batch
2286 * The commit and loc release will happen when no atomic sections are active, which
2287 * may happen immediately or at some point after calling this
2289 public function unlock() {
2290 if ( $this->locked
) {
2292 if ( !$this->locked
) {
2293 $dbw = $this->repo
->getMasterDB();
2294 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2295 $this->lockedOwnTrx
= false;
2303 protected function readOnlyFatalStatus() {
2304 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2305 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2309 * Clean up any dangling locks
2311 function __destruct() {