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
;
29 * Class to represent a local file in the wiki's own database
31 * Provides methods to retrieve paths (physical, logical, URL),
32 * to generate image thumbnails or for uploading.
34 * Note that only the repo object knows what its file class is called. You should
35 * never name a file class explictly outside of the repo class. Instead use the
36 * repo's factory functions to generate file objects, for example:
38 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
40 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
43 * @ingroup FileAbstraction
45 class LocalFile
extends File
{
46 const VERSION
= 11; // cache version
48 const CACHE_FIELD_MAX_LEN
= 1000;
50 /** @var bool Does the file exist on disk? (loadFromXxx) */
51 protected $fileExists;
53 /** @var int Image width */
56 /** @var int Image height */
59 /** @var int Returned by getimagesize (loadFromXxx) */
62 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
63 protected $media_type;
65 /** @var string MIME type, determined by MimeMagic::guessMimeType */
68 /** @var int Size in bytes (loadFromXxx) */
71 /** @var string Handler-specific metadata */
74 /** @var string SHA-1 base 36 content hash */
77 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
78 protected $dataLoaded;
80 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
81 protected $extraDataLoaded;
83 /** @var int Bitfield akin to rev_deleted */
87 protected $repoClass = LocalRepo
::class;
89 /** @var int Number of line to return by nextHistoryLine() (constructor) */
92 /** @var int Result of the query for the file's history (nextHistoryLine) */
95 /** @var string Major MIME type */
98 /** @var string Minor MIME type */
101 /** @var string Upload timestamp */
104 /** @var int User ID of uploader */
107 /** @var string User name of uploader */
110 /** @var string Description of current revision of the file */
111 private $description;
113 /** @var string TS_MW timestamp of the last change of the file description */
114 private $descriptionTouched;
116 /** @var bool Whether the row was upgraded on load */
119 /** @var bool Whether the row was scheduled to upgrade on load */
122 /** @var bool True if the image row is locked */
125 /** @var bool True if the image row is locked with a lock initiated transaction */
126 private $lockedOwnTrx;
128 /** @var bool True if file is not present in file system. Not to be cached in memcached */
131 // @note: higher than IDBAccessObject constants
132 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
134 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
137 * Create a LocalFile from a title
138 * Do not call this except from inside a repo class.
140 * Note: $unused param is only here to avoid an E_STRICT
142 * @param Title $title
143 * @param FileRepo $repo
144 * @param null $unused
148 static function newFromTitle( $title, $repo, $unused = null ) {
149 return new self( $title, $repo );
153 * Create a LocalFile from a title
154 * Do not call this except from inside a repo class.
156 * @param stdClass $row
157 * @param FileRepo $repo
161 static function newFromRow( $row, $repo ) {
162 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
163 $file = new self( $title, $repo );
164 $file->loadFromRow( $row );
170 * Create a LocalFile from a SHA-1 key
171 * Do not call this except from inside a repo class.
173 * @param string $sha1 Base-36 SHA-1
174 * @param LocalRepo $repo
175 * @param string|bool $timestamp MW_timestamp (optional)
176 * @return bool|LocalFile
178 static function newFromKey( $sha1, $repo, $timestamp = false ) {
179 $dbr = $repo->getReplicaDB();
181 $conds = [ 'img_sha1' => $sha1 ];
183 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
186 $fileQuery = self
::getQueryInfo();
187 $row = $dbr->selectRow(
188 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
191 return self
::newFromRow( $row, $repo );
198 * Fields in the image table
199 * @deprecated since 1.31, use self::getQueryInfo() instead.
202 static function selectFields() {
203 wfDeprecated( __METHOD__
, '1.31' );
218 ] + CommentStore
::newKey( 'img_description' )->getFields();
222 * Return the tables, fields, and join conditions to be selected to create
223 * a new localfile object.
225 * @param string[] $options
226 * - omit-lazy: Omit fields that are lazily cached.
227 * @return array With three keys:
228 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
229 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
230 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
232 public static function getQueryInfo( array $options = [] ) {
233 $commentQuery = CommentStore
::newKey( 'img_description' )->getJoin();
235 'tables' => [ 'image' ] +
$commentQuery['tables'],
250 ] +
$commentQuery['fields'],
251 'joins' => $commentQuery['joins'],
254 if ( in_array( 'omit-nonlazy', $options, true ) ) {
255 // Internal use only for getting only the lazy fields
258 if ( !in_array( 'omit-lazy', $options, true ) ) {
259 // Note: Keep this in sync with self::getLazyCacheFields()
260 $ret['fields'][] = 'img_metadata';
267 * Do not call this except from inside a repo class.
268 * @param Title $title
269 * @param FileRepo $repo
271 function __construct( $title, $repo ) {
272 parent
::__construct( $title, $repo );
274 $this->metadata
= '';
275 $this->historyLine
= 0;
276 $this->historyRes
= null;
277 $this->dataLoaded
= false;
278 $this->extraDataLoaded
= false;
280 $this->assertRepoDefined();
281 $this->assertTitleDefined();
285 * Get the memcached key for the main data for this file, or false if
286 * there is no access to the shared cache.
287 * @return string|bool
289 function getCacheKey() {
290 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
294 * @param WANObjectCache $cache
298 public function getMutableCacheKeys( WANObjectCache
$cache ) {
299 return [ $this->getCacheKey() ];
303 * Try to load file metadata from memcached, falling back to the database
305 private function loadFromCache() {
306 $this->dataLoaded
= false;
307 $this->extraDataLoaded
= false;
309 $key = $this->getCacheKey();
311 $this->loadFromDB( self
::READ_NORMAL
);
316 $cache = ObjectCache
::getMainWANInstance();
317 $cachedValues = $cache->getWithSetCallback(
320 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
321 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
323 $this->loadFromDB( self
::READ_NORMAL
);
325 $fields = $this->getCacheFields( '' );
326 $cacheVal['fileExists'] = $this->fileExists
;
327 if ( $this->fileExists
) {
328 foreach ( $fields as $field ) {
329 $cacheVal[$field] = $this->$field;
332 // Strip off excessive entries from the subset of fields that can become large.
333 // If the cache value gets to large it will not fit in memcached and nothing will
334 // get cached at all, causing master queries for any file access.
335 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
336 if ( isset( $cacheVal[$field] )
337 && strlen( $cacheVal[$field] ) > 100 * 1024
339 unset( $cacheVal[$field] ); // don't let the value get too big
343 if ( $this->fileExists
) {
344 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
346 $ttl = $cache::TTL_DAY
;
351 [ 'version' => self
::VERSION
]
354 $this->fileExists
= $cachedValues['fileExists'];
355 if ( $this->fileExists
) {
356 $this->setProps( $cachedValues );
359 $this->dataLoaded
= true;
360 $this->extraDataLoaded
= true;
361 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
362 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
367 * Purge the file object/metadata cache
369 public function invalidateCache() {
370 $key = $this->getCacheKey();
375 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
376 function () use ( $key ) {
377 ObjectCache
::getMainWANInstance()->delete( $key );
384 * Load metadata from the file itself
386 function loadFromFile() {
387 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
388 $this->setProps( $props );
392 * Returns the list of object properties that are included as-is in the cache.
393 * @param string $prefix Must be the empty string
395 * @since 1.31 No longer accepts a non-empty $prefix
397 protected function getCacheFields( $prefix = 'img_' ) {
398 if ( $prefix !== '' ) {
399 throw new InvalidArgumentException(
400 __METHOD__
. ' with a non-empty prefix is no longer supported.'
404 // See self::getQueryInfo() for the fetching of the data from the DB,
405 // self::loadFromRow() for the loading of the object from the DB row,
406 // and self::loadFromCache() for the caching, and self::setProps() for
407 // populating the object from an array of data.
408 return [ 'size', 'width', 'height', 'bits', 'media_type',
409 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
410 'user_text', 'description' ];
414 * Returns the list of object properties that are included as-is in the
415 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
416 * @param string $prefix Must be the empty string
418 * @since 1.31 No longer accepts a non-empty $prefix
420 protected function getLazyCacheFields( $prefix = 'img_' ) {
421 if ( $prefix !== '' ) {
422 throw new InvalidArgumentException(
423 __METHOD__
. ' with a non-empty prefix is no longer supported.'
427 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
428 return [ 'metadata' ];
432 * Load file metadata from the DB
435 function loadFromDB( $flags = 0 ) {
436 $fname = static::class . '::' . __FUNCTION__
;
438 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
439 $this->dataLoaded
= true;
440 $this->extraDataLoaded
= true;
442 $dbr = ( $flags & self
::READ_LATEST
)
443 ?
$this->repo
->getMasterDB()
444 : $this->repo
->getReplicaDB();
446 $fileQuery = static::getQueryInfo();
447 $row = $dbr->selectRow(
448 $fileQuery['tables'],
449 $fileQuery['fields'],
450 [ 'img_name' => $this->getName() ],
457 $this->loadFromRow( $row );
459 $this->fileExists
= false;
464 * Load lazy file metadata from the DB.
465 * This covers fields that are sometimes not cached.
467 protected function loadExtraFromDB() {
468 $fname = static::class . '::' . __FUNCTION__
;
470 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
471 $this->extraDataLoaded
= true;
473 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
475 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
479 foreach ( $fieldMap as $name => $value ) {
480 $this->$name = $value;
483 throw new MWException( "Could not find data for image '{$this->getName()}'." );
488 * @param IDatabase $dbr
489 * @param string $fname
492 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
495 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
496 $row = $dbr->selectRow(
497 $fileQuery['tables'],
498 $fileQuery['fields'],
500 'img_name' => $this->getName(),
501 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
508 $fieldMap = $this->unprefixRow( $row, 'img_' );
510 # File may have been uploaded over in the meantime; check the old versions
511 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
512 $row = $dbr->selectRow(
513 $fileQuery['tables'],
514 $fileQuery['fields'],
516 'oi_name' => $this->getName(),
517 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
524 $fieldMap = $this->unprefixRow( $row, 'oi_' );
528 if ( isset( $fieldMap['metadata'] ) ) {
529 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
536 * @param array|object $row
537 * @param string $prefix
538 * @throws MWException
541 protected function unprefixRow( $row, $prefix = 'img_' ) {
542 $array = (array)$row;
543 $prefixLength = strlen( $prefix );
545 // Sanity check prefix once
546 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
547 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
551 foreach ( $array as $name => $value ) {
552 $decoded[substr( $name, $prefixLength )] = $value;
559 * Decode a row from the database (either object or array) to an array
560 * with timestamps and MIME types decoded, and the field prefix removed.
562 * @param string $prefix
563 * @throws MWException
566 function decodeRow( $row, $prefix = 'img_' ) {
567 $decoded = $this->unprefixRow( $row, $prefix );
569 $decoded['description'] = CommentStore
::newKey( 'description' )
570 ->getComment( (object)$decoded )->text
;
572 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
574 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
576 if ( empty( $decoded['major_mime'] ) ) {
577 $decoded['mime'] = 'unknown/unknown';
579 if ( !$decoded['minor_mime'] ) {
580 $decoded['minor_mime'] = 'unknown';
582 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
585 // Trim zero padding from char/binary field
586 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
588 // Normalize some fields to integer type, per their database definition.
589 // Use unary + so that overflows will be upgraded to double instead of
590 // being trucated as with intval(). This is important to allow >2GB
591 // files on 32-bit systems.
592 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
593 $decoded[$field] = +
$decoded[$field];
600 * Load file metadata from a DB result row
603 * @param string $prefix
605 function loadFromRow( $row, $prefix = 'img_' ) {
606 $this->dataLoaded
= true;
607 $this->extraDataLoaded
= true;
609 $array = $this->decodeRow( $row, $prefix );
611 foreach ( $array as $name => $value ) {
612 $this->$name = $value;
615 $this->fileExists
= true;
616 $this->maybeUpgradeRow();
620 * Load file metadata from cache or DB, unless already loaded
623 function load( $flags = 0 ) {
624 if ( !$this->dataLoaded
) {
625 if ( $flags & self
::READ_LATEST
) {
626 $this->loadFromDB( $flags );
628 $this->loadFromCache();
632 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
633 // @note: loads on name/timestamp to reduce race condition problems
634 $this->loadExtraFromDB();
639 * Upgrade a row if it needs it
641 function maybeUpgradeRow() {
642 global $wgUpdateCompatibleMetadata;
644 if ( wfReadOnly() ||
$this->upgrading
) {
649 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
652 $handler = $this->getHandler();
654 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
655 if ( $validity === MediaHandler
::METADATA_BAD
) {
657 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
658 $upgrade = $wgUpdateCompatibleMetadata;
664 $this->upgrading
= true;
665 // Defer updates unless in auto-commit CLI mode
666 DeferredUpdates
::addCallableUpdate( function () {
667 $this->upgrading
= false; // avoid duplicate updates
670 } catch ( LocalFileLockError
$e ) {
671 // let the other process handle it (or do it next time)
678 * @return bool Whether upgradeRow() ran for this object
680 function getUpgraded() {
681 return $this->upgraded
;
685 * Fix assorted version-related problems with the image row by reloading it from the file
687 function upgradeRow() {
688 $this->lock(); // begin
690 $this->loadFromFile();
692 # Don't destroy file info of missing files
693 if ( !$this->fileExists
) {
695 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
700 $dbw = $this->repo
->getMasterDB();
701 list( $major, $minor ) = self
::splitMime( $this->mime
);
703 if ( wfReadOnly() ) {
708 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
710 $dbw->update( 'image',
712 'img_size' => $this->size
, // sanity
713 'img_width' => $this->width
,
714 'img_height' => $this->height
,
715 'img_bits' => $this->bits
,
716 'img_media_type' => $this->media_type
,
717 'img_major_mime' => $major,
718 'img_minor_mime' => $minor,
719 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
720 'img_sha1' => $this->sha1
,
722 [ 'img_name' => $this->getName() ],
726 $this->invalidateCache();
728 $this->unlock(); // done
729 $this->upgraded
= true; // avoid rework/retries
733 * Set properties in this object to be equal to those given in the
734 * associative array $info. Only cacheable fields can be set.
735 * All fields *must* be set in $info except for getLazyCacheFields().
737 * If 'mime' is given, it will be split into major_mime/minor_mime.
738 * If major_mime/minor_mime are given, $this->mime will also be set.
742 function setProps( $info ) {
743 $this->dataLoaded
= true;
744 $fields = $this->getCacheFields( '' );
745 $fields[] = 'fileExists';
747 foreach ( $fields as $field ) {
748 if ( isset( $info[$field] ) ) {
749 $this->$field = $info[$field];
753 // Fix up mime fields
754 if ( isset( $info['major_mime'] ) ) {
755 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
756 } elseif ( isset( $info['mime'] ) ) {
757 $this->mime
= $info['mime'];
758 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
762 /** splitMime inherited */
763 /** getName inherited */
764 /** getTitle inherited */
765 /** getURL inherited */
766 /** getViewURL inherited */
767 /** getPath inherited */
768 /** isVisible inherited */
773 function isMissing() {
774 if ( $this->missing
=== null ) {
775 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
776 $this->missing
= !$fileExists;
779 return $this->missing
;
783 * Return the width of the image
788 public function getWidth( $page = 1 ) {
796 if ( $this->isMultipage() ) {
797 $handler = $this->getHandler();
801 $dim = $handler->getPageDimensions( $this, $page );
803 return $dim['width'];
805 // For non-paged media, the false goes through an
806 // intval, turning failure into 0, so do same here.
815 * Return the height of the image
820 public function getHeight( $page = 1 ) {
828 if ( $this->isMultipage() ) {
829 $handler = $this->getHandler();
833 $dim = $handler->getPageDimensions( $this, $page );
835 return $dim['height'];
837 // For non-paged media, the false goes through an
838 // intval, turning failure into 0, so do same here.
842 return $this->height
;
847 * Returns ID or name of user who uploaded the file
849 * @param string $type 'text' or 'id'
852 function getUser( $type = 'text' ) {
855 if ( $type == 'text' ) {
856 return $this->user_text
;
858 return (int)$this->user
;
863 * Get short description URL for a file based on the page ID.
865 * @return string|null
866 * @throws MWException
869 public function getDescriptionShortUrl() {
870 $pageId = $this->title
->getArticleID();
872 if ( $pageId !== null ) {
873 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
874 if ( $url !== false ) {
882 * Get handler-specific metadata
885 function getMetadata() {
886 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
887 return $this->metadata
;
893 function getBitDepth() {
896 return (int)$this->bits
;
900 * Returns the size of the image file, in bytes
903 public function getSize() {
910 * Returns the MIME type of the file.
913 function getMimeType() {
920 * Returns the type of the media in the file.
921 * Use the value returned by this function with the MEDIATYPE_xxx constants.
924 function getMediaType() {
927 return $this->media_type
;
930 /** canRender inherited */
931 /** mustRender inherited */
932 /** allowInlineDisplay inherited */
933 /** isSafeFile inherited */
934 /** isTrustedFile inherited */
937 * Returns true if the file exists on disk.
938 * @return bool Whether file exist on disk.
940 public function exists() {
943 return $this->fileExists
;
946 /** getTransformScript inherited */
947 /** getUnscaledThumb inherited */
948 /** thumbName inherited */
949 /** createThumb inherited */
950 /** transform inherited */
952 /** getHandler inherited */
953 /** iconThumb inherited */
954 /** getLastError inherited */
957 * Get all thumbnail names previously generated for this file
958 * @param string|bool $archiveName Name of an archive file, default false
959 * @return array First element is the base dir, then files in that base dir.
961 function getThumbnails( $archiveName = false ) {
962 if ( $archiveName ) {
963 $dir = $this->getArchiveThumbPath( $archiveName );
965 $dir = $this->getThumbPath();
968 $backend = $this->repo
->getBackend();
971 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
972 foreach ( $iterator as $file ) {
975 } catch ( FileBackendError
$e ) {
976 } // suppress (T56674)
982 * Refresh metadata in memcached, but don't touch thumbnails or CDN
984 function purgeMetadataCache() {
985 $this->invalidateCache();
989 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
991 * @param array $options An array potentially with the key forThumbRefresh.
993 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
995 function purgeCache( $options = [] ) {
996 // Refresh metadata cache
997 $this->purgeMetadataCache();
1000 $this->purgeThumbnails( $options );
1002 // Purge CDN cache for this file
1003 DeferredUpdates
::addUpdate(
1004 new CdnCacheUpdate( [ $this->getUrl() ] ),
1005 DeferredUpdates
::PRESEND
1010 * Delete cached transformed files for an archived version only.
1011 * @param string $archiveName Name of the archived file
1013 function purgeOldThumbnails( $archiveName ) {
1014 // Get a list of old thumbnails and URLs
1015 $files = $this->getThumbnails( $archiveName );
1017 // Purge any custom thumbnail caches
1018 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1020 // Delete thumbnails
1021 $dir = array_shift( $files );
1022 $this->purgeThumbList( $dir, $files );
1026 foreach ( $files as $file ) {
1027 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1029 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1033 * Delete cached transformed files for the current version only.
1034 * @param array $options
1036 public function purgeThumbnails( $options = [] ) {
1037 $files = $this->getThumbnails();
1038 // Always purge all files from CDN regardless of handler filters
1040 foreach ( $files as $file ) {
1041 $urls[] = $this->getThumbUrl( $file );
1043 array_shift( $urls ); // don't purge directory
1045 // Give media handler a chance to filter the file purge list
1046 if ( !empty( $options['forThumbRefresh'] ) ) {
1047 $handler = $this->getHandler();
1049 $handler->filterThumbnailPurgeList( $files, $options );
1053 // Purge any custom thumbnail caches
1054 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1056 // Delete thumbnails
1057 $dir = array_shift( $files );
1058 $this->purgeThumbList( $dir, $files );
1061 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1065 * Prerenders a configurable set of thumbnails
1069 public function prerenderThumbnails() {
1070 global $wgUploadThumbnailRenderMap;
1074 $sizes = $wgUploadThumbnailRenderMap;
1077 foreach ( $sizes as $size ) {
1078 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1079 $jobs[] = new ThumbnailRenderJob(
1081 [ 'transformParams' => [ 'width' => $size ] ]
1087 JobQueueGroup
::singleton()->lazyPush( $jobs );
1092 * Delete a list of thumbnails visible at urls
1093 * @param string $dir Base dir of the files.
1094 * @param array $files Array of strings: relative filenames (to $dir)
1096 protected function purgeThumbList( $dir, $files ) {
1097 $fileListDebug = strtr(
1098 var_export( $files, true ),
1101 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1104 foreach ( $files as $file ) {
1105 if ( $this->repo
->supportsSha1URLs() ) {
1106 $reference = $this->getSha1();
1108 $reference = $this->getName();
1111 # Check that the reference (filename or sha1) is part of the thumb name
1112 # This is a basic sanity check to avoid erasing unrelated directories
1113 if ( strpos( $file, $reference ) !== false
1114 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1116 $purgeList[] = "{$dir}/{$file}";
1120 # Delete the thumbnails
1121 $this->repo
->quickPurgeBatch( $purgeList );
1122 # Clear out the thumbnail directory if empty
1123 $this->repo
->quickCleanDir( $dir );
1126 /** purgeDescription inherited */
1127 /** purgeEverything inherited */
1130 * @param int $limit Optional: Limit to number of results
1131 * @param int $start Optional: Timestamp, start from
1132 * @param int $end Optional: Timestamp, end at
1134 * @return OldLocalFile[]
1136 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1137 $dbr = $this->repo
->getReplicaDB();
1138 $oldFileQuery = OldLocalFile
::getQueryInfo();
1140 $tables = $oldFileQuery['tables'];
1141 $fields = $oldFileQuery['fields'];
1142 $join_conds = $oldFileQuery['joins'];
1143 $conds = $opts = [];
1144 $eq = $inc ?
'=' : '';
1145 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1148 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1152 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1156 $opts['LIMIT'] = $limit;
1159 // Search backwards for time > x queries
1160 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1161 $opts['ORDER BY'] = "oi_timestamp $order";
1162 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1164 // Avoid PHP 7.1 warning from passing $this by reference
1166 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1167 &$conds, &$opts, &$join_conds ] );
1169 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1172 foreach ( $res as $row ) {
1173 $r[] = $this->repo
->newFileFromRow( $row );
1176 if ( $order == 'ASC' ) {
1177 $r = array_reverse( $r ); // make sure it ends up descending
1184 * Returns the history of this file, line by line.
1185 * starts with current version, then old versions.
1186 * uses $this->historyLine to check which line to return:
1187 * 0 return line for current version
1188 * 1 query for old versions, return first one
1189 * 2, ... return next old version from above query
1192 public function nextHistoryLine() {
1193 # Polymorphic function name to distinguish foreign and local fetches
1194 $fname = static::class . '::' . __FUNCTION__
;
1196 $dbr = $this->repo
->getReplicaDB();
1198 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1199 $fileQuery = self
::getQueryInfo();
1200 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1201 $fileQuery['fields'] +
[
1202 'oi_archive_name' => $dbr->addQuotes( '' ),
1205 [ 'img_name' => $this->title
->getDBkey() ],
1211 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1212 $this->historyRes
= null;
1216 } elseif ( $this->historyLine
== 1 ) {
1217 $fileQuery = OldLocalFile
::getQueryInfo();
1218 $this->historyRes
= $dbr->select(
1219 $fileQuery['tables'],
1220 $fileQuery['fields'],
1221 [ 'oi_name' => $this->title
->getDBkey() ],
1223 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1227 $this->historyLine++
;
1229 return $dbr->fetchObject( $this->historyRes
);
1233 * Reset the history pointer to the first element of the history
1235 public function resetHistory() {
1236 $this->historyLine
= 0;
1238 if ( !is_null( $this->historyRes
) ) {
1239 $this->historyRes
= null;
1243 /** getHashPath inherited */
1244 /** getRel inherited */
1245 /** getUrlRel inherited */
1246 /** getArchiveRel inherited */
1247 /** getArchivePath inherited */
1248 /** getThumbPath inherited */
1249 /** getArchiveUrl inherited */
1250 /** getThumbUrl inherited */
1251 /** getArchiveVirtualUrl inherited */
1252 /** getThumbVirtualUrl inherited */
1253 /** isHashed inherited */
1256 * Upload a file and record it in the DB
1257 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1258 * @param string $comment Upload description
1259 * @param string $pageText Text to use for the new description page,
1260 * if a new description page is created
1261 * @param int|bool $flags Flags for publish()
1262 * @param array|bool $props File properties, if known. This can be used to
1263 * reduce the upload time when uploading virtual URLs for which the file
1264 * info is already known
1265 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1267 * @param User|null $user User object or null to use $wgUser
1268 * @param string[] $tags Change tags to add to the log entry and page revision.
1269 * (This doesn't check $user's permissions.)
1270 * @return Status On success, the value member contains the
1271 * archive name, or an empty string if it was a new file.
1273 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1274 $timestamp = false, $user = null, $tags = []
1276 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1277 return $this->readOnlyFatalStatus();
1280 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1282 if ( $this->repo
->isVirtualUrl( $srcPath )
1283 || FileBackend
::isStoragePath( $srcPath )
1285 $props = $this->repo
->getFileProps( $srcPath );
1287 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1288 $props = $mwProps->getPropsFromPath( $srcPath, true );
1293 $handler = MediaHandler
::getHandler( $props['mime'] );
1295 $metadata = MediaWiki\
quietCall( 'unserialize', $props['metadata'] );
1297 if ( !is_array( $metadata ) ) {
1301 $options['headers'] = $handler->getContentHeaders( $metadata );
1303 $options['headers'] = [];
1306 // Trim spaces on user supplied text
1307 $comment = trim( $comment );
1309 $this->lock(); // begin
1310 $status = $this->publish( $src, $flags, $options );
1312 if ( $status->successCount
>= 2 ) {
1313 // There will be a copy+(one of move,copy,store).
1314 // The first succeeding does not commit us to updating the DB
1315 // since it simply copied the current version to a timestamped file name.
1316 // It is only *preferable* to avoid leaving such files orphaned.
1317 // Once the second operation goes through, then the current version was
1318 // updated and we must therefore update the DB too.
1319 $oldver = $status->value
;
1320 $uploadStatus = $this->recordUpload2(
1329 if ( !$uploadStatus->isOK() ) {
1330 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1331 // update filenotfound error with more specific path
1332 $status->fatal( 'filenotfound', $srcPath );
1334 $status->merge( $uploadStatus );
1339 $this->unlock(); // done
1345 * Record a file upload in the upload log and the image table
1346 * @param string $oldver
1347 * @param string $desc
1348 * @param string $license
1349 * @param string $copyStatus
1350 * @param string $source
1351 * @param bool $watch
1352 * @param string|bool $timestamp
1353 * @param User|null $user User object or null to use $wgUser
1356 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1357 $watch = false, $timestamp = false, User
$user = null ) {
1363 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1365 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1370 $user->addWatch( $this->getTitle() );
1377 * Record a file upload in the upload log and the image table
1378 * @param string $oldver
1379 * @param string $comment
1380 * @param string $pageText
1381 * @param bool|array $props
1382 * @param string|bool $timestamp
1383 * @param null|User $user
1384 * @param string[] $tags
1387 function recordUpload2(
1388 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1390 global $wgCommentTableSchemaMigrationStage;
1392 if ( is_null( $user ) ) {
1397 $dbw = $this->repo
->getMasterDB();
1399 # Imports or such might force a certain timestamp; otherwise we generate
1400 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1401 if ( $timestamp === false ) {
1402 $timestamp = $dbw->timestamp();
1403 $allowTimeKludge = true;
1405 $allowTimeKludge = false;
1408 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1409 $props['description'] = $comment;
1410 $props['user'] = $user->getId();
1411 $props['user_text'] = $user->getName();
1412 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1413 $this->setProps( $props );
1415 # Fail now if the file isn't there
1416 if ( !$this->fileExists
) {
1417 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1419 return Status
::newFatal( 'filenotfound', $this->getRel() );
1422 $dbw->startAtomic( __METHOD__
);
1424 # Test to see if the row exists using INSERT IGNORE
1425 # This avoids race conditions by locking the row until the commit, and also
1426 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1427 $commentStore = new CommentStore( 'img_description' );
1428 list( $commentFields, $commentCallback ) =
1429 $commentStore->insertWithTempTable( $dbw, $comment );
1430 $dbw->insert( 'image',
1432 'img_name' => $this->getName(),
1433 'img_size' => $this->size
,
1434 'img_width' => intval( $this->width
),
1435 'img_height' => intval( $this->height
),
1436 'img_bits' => $this->bits
,
1437 'img_media_type' => $this->media_type
,
1438 'img_major_mime' => $this->major_mime
,
1439 'img_minor_mime' => $this->minor_mime
,
1440 'img_timestamp' => $timestamp,
1441 'img_user' => $user->getId(),
1442 'img_user_text' => $user->getName(),
1443 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1444 'img_sha1' => $this->sha1
1449 $reupload = ( $dbw->affectedRows() == 0 );
1452 $row = $dbw->selectRow(
1454 [ 'img_timestamp', 'img_sha1' ],
1455 [ 'img_name' => $this->getName() ],
1457 [ 'LOCK IN SHARE MODE' ]
1460 if ( $row && $row->img_sha1
=== $this->sha1
) {
1461 $dbw->endAtomic( __METHOD__
);
1462 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1463 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1464 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1467 if ( $allowTimeKludge ) {
1468 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1469 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1470 # Avoid a timestamp that is not newer than the last version
1471 # TODO: the image/oldimage tables should be like page/revision with an ID field
1472 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1473 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1474 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1475 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1479 $tables = [ 'image' ];
1481 'oi_name' => 'img_name',
1482 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1483 'oi_size' => 'img_size',
1484 'oi_width' => 'img_width',
1485 'oi_height' => 'img_height',
1486 'oi_bits' => 'img_bits',
1487 'oi_timestamp' => 'img_timestamp',
1488 'oi_user' => 'img_user',
1489 'oi_user_text' => 'img_user_text',
1490 'oi_metadata' => 'img_metadata',
1491 'oi_media_type' => 'img_media_type',
1492 'oi_major_mime' => 'img_major_mime',
1493 'oi_minor_mime' => 'img_minor_mime',
1494 'oi_sha1' => 'img_sha1',
1498 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1499 $fields['oi_description'] = 'img_description';
1501 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1502 $tables[] = 'image_comment_temp';
1503 $fields['oi_description_id'] = 'imgcomment_description_id';
1504 $joins['image_comment_temp'] = [
1505 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
1506 [ 'imgcomment_name = img_name' ]
1510 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
1511 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1513 // Upgrade any rows that are still old-style. Otherwise an upgrade
1514 // might be missed if a deletion happens while the migration script
1516 $res = $dbw->select(
1517 [ 'image', 'image_comment_temp' ],
1518 [ 'img_name', 'img_description' ],
1519 [ 'img_name' => $this->getName(), 'imgcomment_name' => null ],
1522 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1524 foreach ( $res as $row ) {
1525 list( , $callback ) = $commentStore->insertWithTempTable( $dbw, $row->img_description
);
1526 $callback( $row->img_name
);
1530 # (T36993) Note: $oldver can be empty here, if the previous
1531 # version of the file was broken. Allow registration of the new
1532 # version to continue anyway, because that's better than having
1533 # an image that's not fixable by user operations.
1534 # Collision, this is an update of a file
1535 # Insert previous contents into oldimage
1536 $dbw->insertSelect( 'oldimage', $tables, $fields,
1537 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1539 # Update the current image row
1540 $dbw->update( 'image',
1542 'img_size' => $this->size
,
1543 'img_width' => intval( $this->width
),
1544 'img_height' => intval( $this->height
),
1545 'img_bits' => $this->bits
,
1546 'img_media_type' => $this->media_type
,
1547 'img_major_mime' => $this->major_mime
,
1548 'img_minor_mime' => $this->minor_mime
,
1549 'img_timestamp' => $timestamp,
1550 'img_user' => $user->getId(),
1551 'img_user_text' => $user->getName(),
1552 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1553 'img_sha1' => $this->sha1
1555 [ 'img_name' => $this->getName() ],
1558 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
1559 // So $commentCallback can insert the new row
1560 $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__
);
1563 $commentCallback( $this->getName() );
1565 $descTitle = $this->getTitle();
1566 $descId = $descTitle->getArticleID();
1567 $wikiPage = new WikiFilePage( $descTitle );
1568 $wikiPage->setFile( $this );
1570 // Add the log entry...
1571 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1572 $logEntry->setTimestamp( $this->timestamp
);
1573 $logEntry->setPerformer( $user );
1574 $logEntry->setComment( $comment );
1575 $logEntry->setTarget( $descTitle );
1576 // Allow people using the api to associate log entries with the upload.
1577 // Log has a timestamp, but sometimes different from upload timestamp.
1578 $logEntry->setParameters(
1580 'img_sha1' => $this->sha1
,
1581 'img_timestamp' => $timestamp,
1584 // Note we keep $logId around since during new image
1585 // creation, page doesn't exist yet, so log_page = 0
1586 // but we want it to point to the page we're making,
1587 // so we later modify the log entry.
1588 // For a similar reason, we avoid making an RC entry
1589 // now and wait until the page exists.
1590 $logId = $logEntry->insert();
1592 if ( $descTitle->exists() ) {
1593 // Use own context to get the action text in content language
1594 $formatter = LogFormatter
::newFromEntry( $logEntry );
1595 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1596 $editSummary = $formatter->getPlainActionText();
1598 $nullRevision = Revision
::newNullRevision(
1605 if ( $nullRevision ) {
1606 $nullRevision->insertOn( $dbw );
1608 'NewRevisionFromEditComplete',
1609 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1611 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1612 // Associate null revision id
1613 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1616 $newPageContent = null;
1618 // Make the description page and RC log entry post-commit
1619 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1622 # Defer purges, page creation, and link updates in case they error out.
1623 # The most important thing is that files and the DB registry stay synced.
1624 $dbw->endAtomic( __METHOD__
);
1626 # Do some cache purges after final commit so that:
1627 # a) Changes are more likely to be seen post-purge
1628 # b) They won't cause rollback of the log publish/update above
1629 DeferredUpdates
::addUpdate(
1630 new AutoCommitUpdate(
1634 $reupload, $wikiPage, $newPageContent, $comment, $user,
1635 $logEntry, $logId, $descId, $tags
1637 # Update memcache after the commit
1638 $this->invalidateCache();
1640 $updateLogPage = false;
1641 if ( $newPageContent ) {
1642 # New file page; create the description page.
1643 # There's already a log entry, so don't make a second RC entry
1644 # CDN and file cache for the description page are purged by doEditContent.
1645 $status = $wikiPage->doEditContent(
1648 EDIT_NEW | EDIT_SUPPRESS_RC
,
1653 if ( isset( $status->value
['revision'] ) ) {
1654 /** @var Revision $rev */
1655 $rev = $status->value
['revision'];
1656 // Associate new page revision id
1657 $logEntry->setAssociatedRevId( $rev->getId() );
1659 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1660 // which is triggered on $descTitle by doEditContent() above.
1661 if ( isset( $status->value
['revision'] ) ) {
1662 /** @var Revision $rev */
1663 $rev = $status->value
['revision'];
1664 $updateLogPage = $rev->getPage();
1667 # Existing file page: invalidate description page cache
1668 $wikiPage->getTitle()->invalidateCache();
1669 $wikiPage->getTitle()->purgeSquid();
1670 # Allow the new file version to be patrolled from the page footer
1671 Article
::purgePatrolFooterCache( $descId );
1674 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1675 # but setAssociatedRevId() wasn't called at that point yet...
1676 $logParams = $logEntry->getParameters();
1677 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1678 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1679 if ( $updateLogPage ) {
1680 # Also log page, in case where we just created it above
1681 $update['log_page'] = $updateLogPage;
1683 $this->getRepo()->getMasterDB()->update(
1686 [ 'log_id' => $logId ],
1689 $this->getRepo()->getMasterDB()->insert(
1692 'ls_field' => 'associated_rev_id',
1693 'ls_value' => $logEntry->getAssociatedRevId(),
1694 'ls_log_id' => $logId,
1699 # Add change tags, if any
1701 $logEntry->setTags( $tags );
1704 # Uploads can be patrolled
1705 $logEntry->setIsPatrollable( true );
1707 # Now that the log entry is up-to-date, make an RC entry.
1708 $logEntry->publish( $logId );
1710 # Run hook for other updates (typically more cache purging)
1711 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1714 # Delete old thumbnails
1715 $this->purgeThumbnails();
1716 # Remove the old file from the CDN cache
1717 DeferredUpdates
::addUpdate(
1718 new CdnCacheUpdate( [ $this->getUrl() ] ),
1719 DeferredUpdates
::PRESEND
1722 # Update backlink pages pointing to this title if created
1723 LinksUpdate
::queueRecursiveJobsForTable(
1731 $this->prerenderThumbnails();
1734 DeferredUpdates
::PRESEND
1738 # This is a new file, so update the image count
1739 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1742 # Invalidate cache for all pages using this file
1743 DeferredUpdates
::addUpdate(
1744 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1747 return Status
::newGood();
1751 * Move or copy a file to its public location. If a file exists at the
1752 * destination, move it to an archive. Returns a Status object with
1753 * the archive name in the "value" member on success.
1755 * The archive name should be passed through to recordUpload for database
1758 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1759 * @param int $flags A bitwise combination of:
1760 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1761 * @param array $options Optional additional parameters
1762 * @return Status On success, the value member contains the
1763 * archive name, or an empty string if it was a new file.
1765 function publish( $src, $flags = 0, array $options = [] ) {
1766 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1770 * Move or copy a file to a specified location. Returns a Status
1771 * object with the archive name in the "value" member on success.
1773 * The archive name should be passed through to recordUpload for database
1776 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1777 * @param string $dstRel Target relative path
1778 * @param int $flags A bitwise combination of:
1779 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1780 * @param array $options Optional additional parameters
1781 * @return Status On success, the value member contains the
1782 * archive name, or an empty string if it was a new file.
1784 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1785 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1787 $repo = $this->getRepo();
1788 if ( $repo->getReadOnlyReason() !== false ) {
1789 return $this->readOnlyFatalStatus();
1792 $this->lock(); // begin
1794 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1795 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1797 if ( $repo->hasSha1Storage() ) {
1798 $sha1 = $repo->isVirtualUrl( $srcPath )
1799 ?
$repo->getFileSha1( $srcPath )
1800 : FSFile
::getSha1Base36FromPath( $srcPath );
1801 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1802 $wrapperBackend = $repo->getBackend();
1803 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1804 $status = $repo->quickImport( $src, $dst );
1805 if ( $flags & File
::DELETE_SOURCE
) {
1809 if ( $this->exists() ) {
1810 $status->value
= $archiveName;
1813 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1814 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1816 if ( $status->value
== 'new' ) {
1817 $status->value
= '';
1819 $status->value
= $archiveName;
1823 $this->unlock(); // done
1828 /** getLinksTo inherited */
1829 /** getExifData inherited */
1830 /** isLocal inherited */
1831 /** wasDeleted inherited */
1834 * Move file to the new title
1836 * Move current, old version and all thumbnails
1837 * to the new filename. Old file is deleted.
1839 * Cache purging is done; checks for validity
1840 * and logging are caller's responsibility
1842 * @param Title $target New file name
1845 function move( $target ) {
1846 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1847 return $this->readOnlyFatalStatus();
1850 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1851 $batch = new LocalFileMoveBatch( $this, $target );
1853 $this->lock(); // begin
1854 $batch->addCurrent();
1855 $archiveNames = $batch->addOlds();
1856 $status = $batch->execute();
1857 $this->unlock(); // done
1859 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1861 // Purge the source and target files...
1862 $oldTitleFile = wfLocalFile( $this->title
);
1863 $newTitleFile = wfLocalFile( $target );
1864 // To avoid slow purges in the transaction, move them outside...
1865 DeferredUpdates
::addUpdate(
1866 new AutoCommitUpdate(
1867 $this->getRepo()->getMasterDB(),
1869 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1870 $oldTitleFile->purgeEverything();
1871 foreach ( $archiveNames as $archiveName ) {
1872 $oldTitleFile->purgeOldThumbnails( $archiveName );
1874 $newTitleFile->purgeEverything();
1877 DeferredUpdates
::PRESEND
1880 if ( $status->isOK() ) {
1881 // Now switch the object
1882 $this->title
= $target;
1883 // Force regeneration of the name and hashpath
1884 unset( $this->name
);
1885 unset( $this->hashPath
);
1892 * Delete all versions of the file.
1894 * Moves the files into an archive directory (or deletes them)
1895 * and removes the database rows.
1897 * Cache purging is done; logging is caller's responsibility.
1899 * @param string $reason
1900 * @param bool $suppress
1901 * @param User|null $user
1904 function delete( $reason, $suppress = false, $user = null ) {
1905 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1906 return $this->readOnlyFatalStatus();
1909 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1911 $this->lock(); // begin
1912 $batch->addCurrent();
1913 // Get old version relative paths
1914 $archiveNames = $batch->addOlds();
1915 $status = $batch->execute();
1916 $this->unlock(); // done
1918 if ( $status->isOK() ) {
1919 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1922 // To avoid slow purges in the transaction, move them outside...
1923 DeferredUpdates
::addUpdate(
1924 new AutoCommitUpdate(
1925 $this->getRepo()->getMasterDB(),
1927 function () use ( $archiveNames ) {
1928 $this->purgeEverything();
1929 foreach ( $archiveNames as $archiveName ) {
1930 $this->purgeOldThumbnails( $archiveName );
1934 DeferredUpdates
::PRESEND
1939 foreach ( $archiveNames as $archiveName ) {
1940 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1942 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1948 * Delete an old version of the file.
1950 * Moves the file into an archive directory (or deletes it)
1951 * and removes the database row.
1953 * Cache purging is done; logging is caller's responsibility.
1955 * @param string $archiveName
1956 * @param string $reason
1957 * @param bool $suppress
1958 * @param User|null $user
1959 * @throws MWException Exception on database or file store failure
1962 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1963 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1964 return $this->readOnlyFatalStatus();
1967 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1969 $this->lock(); // begin
1970 $batch->addOld( $archiveName );
1971 $status = $batch->execute();
1972 $this->unlock(); // done
1974 $this->purgeOldThumbnails( $archiveName );
1975 if ( $status->isOK() ) {
1976 $this->purgeDescription();
1979 DeferredUpdates
::addUpdate(
1980 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1981 DeferredUpdates
::PRESEND
1988 * Restore all or specified deleted revisions to the given file.
1989 * Permissions and logging are left to the caller.
1991 * May throw database exceptions on error.
1993 * @param array $versions Set of record ids of deleted items to restore,
1994 * or empty to restore all revisions.
1995 * @param bool $unsuppress
1998 function restore( $versions = [], $unsuppress = false ) {
1999 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2000 return $this->readOnlyFatalStatus();
2003 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2005 $this->lock(); // begin
2009 $batch->addIds( $versions );
2011 $status = $batch->execute();
2012 if ( $status->isGood() ) {
2013 $cleanupStatus = $batch->cleanup();
2014 $cleanupStatus->successCount
= 0;
2015 $cleanupStatus->failCount
= 0;
2016 $status->merge( $cleanupStatus );
2018 $this->unlock(); // done
2023 /** isMultipage inherited */
2024 /** pageCount inherited */
2025 /** scaleHeight inherited */
2026 /** getImageSize inherited */
2029 * Get the URL of the file description page.
2032 function getDescriptionUrl() {
2033 return $this->title
->getLocalURL();
2037 * Get the HTML text of the description page
2038 * This is not used by ImagePage for local files, since (among other things)
2039 * it skips the parser cache.
2041 * @param Language $lang What language to get description in (Optional)
2042 * @return bool|mixed
2044 function getDescriptionText( $lang = null ) {
2045 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
2049 $content = $revision->getContent();
2053 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
2055 return $pout->getText();
2059 * @param int $audience
2063 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2065 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2067 } elseif ( $audience == self
::FOR_THIS_USER
2068 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2072 return $this->description
;
2077 * @return bool|string
2079 function getTimestamp() {
2082 return $this->timestamp
;
2086 * @return bool|string
2088 public function getDescriptionTouched() {
2089 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2090 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2091 // need to differentiate between null (uninitialized) and false (failed to load).
2092 if ( $this->descriptionTouched
=== null ) {
2094 'page_namespace' => $this->title
->getNamespace(),
2095 'page_title' => $this->title
->getDBkey()
2097 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2098 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2101 return $this->descriptionTouched
;
2107 function getSha1() {
2109 // Initialise now if necessary
2110 if ( $this->sha1
== '' && $this->fileExists
) {
2111 $this->lock(); // begin
2113 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2114 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2115 $dbw = $this->repo
->getMasterDB();
2116 $dbw->update( 'image',
2117 [ 'img_sha1' => $this->sha1
],
2118 [ 'img_name' => $this->getName() ],
2120 $this->invalidateCache();
2123 $this->unlock(); // done
2130 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2132 function isCacheable() {
2135 // If extra data (metadata) was not loaded then it must have been large
2136 return $this->extraDataLoaded
2137 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2144 public function acquireFileLock() {
2145 return $this->getRepo()->getBackend()->lockFiles(
2146 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2154 public function releaseFileLock() {
2155 return $this->getRepo()->getBackend()->unlockFiles(
2156 [ $this->getPath() ], LockManager
::LOCK_EX
2161 * Start an atomic DB section and lock the image for update
2162 * or increments a reference counter if the lock is already held
2164 * This method should not be used outside of LocalFile/LocalFile*Batch
2166 * @throws LocalFileLockError Throws an error if the lock was not acquired
2167 * @return bool Whether the file lock owns/spawned the DB transaction
2169 public function lock() {
2170 if ( !$this->locked
) {
2171 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2173 $dbw = $this->repo
->getMasterDB();
2174 $makesTransaction = !$dbw->trxLevel();
2175 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2176 // T56736: use simple lock to handle when the file does not exist.
2177 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2178 // Also, that would cause contention on INSERT of similarly named rows.
2179 $status = $this->acquireFileLock(); // represents all versions of the file
2180 if ( !$status->isGood() ) {
2181 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2182 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2184 throw new LocalFileLockError( $status );
2186 // Release the lock *after* commit to avoid row-level contention.
2187 // Make sure it triggers on rollback() as well as commit() (T132921).
2188 $dbw->onTransactionResolution(
2189 function () use ( $logger ) {
2190 $status = $this->releaseFileLock();
2191 if ( !$status->isGood() ) {
2192 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2197 // Callers might care if the SELECT snapshot is safely fresh
2198 $this->lockedOwnTrx
= $makesTransaction;
2203 return $this->lockedOwnTrx
;
2207 * Decrement the lock reference count and end the atomic section if it reaches zero
2209 * This method should not be used outside of LocalFile/LocalFile*Batch
2211 * The commit and loc release will happen when no atomic sections are active, which
2212 * may happen immediately or at some point after calling this
2214 public function unlock() {
2215 if ( $this->locked
) {
2217 if ( !$this->locked
) {
2218 $dbw = $this->repo
->getMasterDB();
2219 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2220 $this->lockedOwnTrx
= false;
2228 protected function readOnlyFatalStatus() {
2229 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2230 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2234 * Clean up any dangling locks
2236 function __destruct() {
2239 } // LocalFile class
2241 # ------------------------------------------------------------------------------
2244 * Helper class for file deletion
2245 * @ingroup FileAbstraction
2247 class LocalFileDeleteBatch
{
2248 /** @var LocalFile */
2255 private $srcRels = [];
2258 private $archiveUrls = [];
2260 /** @var array Items to be processed in the deletion batch */
2261 private $deletionBatch;
2263 /** @var bool Whether to suppress all suppressable fields when deleting */
2274 * @param string $reason
2275 * @param bool $suppress
2276 * @param User|null $user
2278 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2279 $this->file
= $file;
2280 $this->reason
= $reason;
2281 $this->suppress
= $suppress;
2283 $this->user
= $user;
2286 $this->user
= $wgUser;
2288 $this->status
= $file->repo
->newGood();
2291 public function addCurrent() {
2292 $this->srcRels
['.'] = $this->file
->getRel();
2296 * @param string $oldName
2298 public function addOld( $oldName ) {
2299 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2300 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2304 * Add the old versions of the image to the batch
2305 * @return array List of archive names from old versions
2307 public function addOlds() {
2310 $dbw = $this->file
->repo
->getMasterDB();
2311 $result = $dbw->select( 'oldimage',
2312 [ 'oi_archive_name' ],
2313 [ 'oi_name' => $this->file
->getName() ],
2317 foreach ( $result as $row ) {
2318 $this->addOld( $row->oi_archive_name
);
2319 $archiveNames[] = $row->oi_archive_name
;
2322 return $archiveNames;
2328 protected function getOldRels() {
2329 if ( !isset( $this->srcRels
['.'] ) ) {
2330 $oldRels =& $this->srcRels
;
2331 $deleteCurrent = false;
2333 $oldRels = $this->srcRels
;
2334 unset( $oldRels['.'] );
2335 $deleteCurrent = true;
2338 return [ $oldRels, $deleteCurrent ];
2344 protected function getHashes() {
2346 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2348 if ( $deleteCurrent ) {
2349 $hashes['.'] = $this->file
->getSha1();
2352 if ( count( $oldRels ) ) {
2353 $dbw = $this->file
->repo
->getMasterDB();
2354 $res = $dbw->select(
2356 [ 'oi_archive_name', 'oi_sha1' ],
2357 [ 'oi_archive_name' => array_keys( $oldRels ),
2358 'oi_name' => $this->file
->getName() ], // performance
2362 foreach ( $res as $row ) {
2363 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2364 // Get the hash from the file
2365 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2366 $props = $this->file
->repo
->getFileProps( $oldUrl );
2368 if ( $props['fileExists'] ) {
2369 // Upgrade the oldimage row
2370 $dbw->update( 'oldimage',
2371 [ 'oi_sha1' => $props['sha1'] ],
2372 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2374 $hashes[$row->oi_archive_name
] = $props['sha1'];
2376 $hashes[$row->oi_archive_name
] = false;
2379 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2384 $missing = array_diff_key( $this->srcRels
, $hashes );
2386 foreach ( $missing as $name => $rel ) {
2387 $this->status
->error( 'filedelete-old-unregistered', $name );
2390 foreach ( $hashes as $name => $hash ) {
2392 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2393 unset( $hashes[$name] );
2400 protected function doDBInserts() {
2401 global $wgCommentTableSchemaMigrationStage;
2404 $dbw = $this->file
->repo
->getMasterDB();
2406 $commentStoreImgDesc = new CommentStore( 'img_description' );
2407 $commentStoreOiDesc = new CommentStore( 'oi_description' );
2408 $commentStoreFaDesc = new CommentStore( 'fa_description' );
2409 $commentStoreFaReason = new CommentStore( 'fa_deleted_reason' );
2411 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2412 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2413 $encGroup = $dbw->addQuotes( 'deleted' );
2414 $ext = $this->file
->getExtension();
2415 $dotExt = $ext === '' ?
'' : ".$ext";
2416 $encExt = $dbw->addQuotes( $dotExt );
2417 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2419 // Bitfields to further suppress the content
2420 if ( $this->suppress
) {
2421 $bitfield = Revision
::SUPPRESSED_ALL
;
2423 $bitfield = 'oi_deleted';
2426 if ( $deleteCurrent ) {
2427 $tables = [ 'image' ];
2429 'fa_storage_group' => $encGroup,
2430 'fa_storage_key' => $dbw->conditional(
2431 [ 'img_sha1' => '' ],
2432 $dbw->addQuotes( '' ),
2433 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2435 'fa_deleted_user' => $encUserId,
2436 'fa_deleted_timestamp' => $encTimestamp,
2437 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2438 'fa_name' => 'img_name',
2439 'fa_archive_name' => 'NULL',
2440 'fa_size' => 'img_size',
2441 'fa_width' => 'img_width',
2442 'fa_height' => 'img_height',
2443 'fa_metadata' => 'img_metadata',
2444 'fa_bits' => 'img_bits',
2445 'fa_media_type' => 'img_media_type',
2446 'fa_major_mime' => 'img_major_mime',
2447 'fa_minor_mime' => 'img_minor_mime',
2448 'fa_user' => 'img_user',
2449 'fa_user_text' => 'img_user_text',
2450 'fa_timestamp' => 'img_timestamp',
2451 'fa_sha1' => 'img_sha1'
2455 $fields +
= array_map(
2456 [ $dbw, 'addQuotes' ],
2457 $commentStoreFaReason->insert( $dbw, $this->reason
)
2460 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2461 $fields['fa_description'] = 'img_description';
2463 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2464 $tables[] = 'image_comment_temp';
2465 $fields['fa_description_id'] = 'imgcomment_description_id';
2466 $joins['image_comment_temp'] = [
2467 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
2468 [ 'imgcomment_name = img_name' ]
2472 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
2473 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2475 // Upgrade any rows that are still old-style. Otherwise an upgrade
2476 // might be missed if a deletion happens while the migration script
2478 $res = $dbw->select(
2479 [ 'image', 'image_comment_temp' ],
2480 [ 'img_name', 'img_description' ],
2481 [ 'img_name' => $this->file
->getName(), 'imgcomment_name' => null ],
2484 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2486 foreach ( $res as $row ) {
2487 list( , $callback ) = $commentStoreImgDesc->insertWithTempTable( $dbw, $row->img_description
);
2488 $callback( $row->img_name
);
2492 $dbw->insertSelect( 'filearchive', $tables, $fields,
2493 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2496 if ( count( $oldRels ) ) {
2497 $fileQuery = OldLocalFile
::getQueryInfo();
2498 $res = $dbw->select(
2499 $fileQuery['tables'],
2500 $fileQuery['fields'],
2502 'oi_name' => $this->file
->getName(),
2503 'oi_archive_name' => array_keys( $oldRels )
2510 if ( $res->numRows() ) {
2511 $reason = $commentStoreFaReason->createComment( $dbw, $this->reason
);
2512 foreach ( $res as $row ) {
2513 $comment = $commentStoreOiDesc->getComment( $row );
2515 // Deletion-specific fields
2516 'fa_storage_group' => 'deleted',
2517 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2519 : "{$row->oi_sha1}{$dotExt}",
2520 'fa_deleted_user' => $this->user
->getId(),
2521 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2522 // Counterpart fields
2523 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2524 'fa_name' => $row->oi_name
,
2525 'fa_archive_name' => $row->oi_archive_name
,
2526 'fa_size' => $row->oi_size
,
2527 'fa_width' => $row->oi_width
,
2528 'fa_height' => $row->oi_height
,
2529 'fa_metadata' => $row->oi_metadata
,
2530 'fa_bits' => $row->oi_bits
,
2531 'fa_media_type' => $row->oi_media_type
,
2532 'fa_major_mime' => $row->oi_major_mime
,
2533 'fa_minor_mime' => $row->oi_minor_mime
,
2534 'fa_user' => $row->oi_user
,
2535 'fa_user_text' => $row->oi_user_text
,
2536 'fa_timestamp' => $row->oi_timestamp
,
2537 'fa_sha1' => $row->oi_sha1
2538 ] +
$commentStoreFaReason->insert( $dbw, $reason )
2539 +
$commentStoreFaDesc->insert( $dbw, $comment );
2543 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2547 function doDBDeletes() {
2548 global $wgCommentTableSchemaMigrationStage;
2550 $dbw = $this->file
->repo
->getMasterDB();
2551 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2553 if ( count( $oldRels ) ) {
2554 $dbw->delete( 'oldimage',
2556 'oi_name' => $this->file
->getName(),
2557 'oi_archive_name' => array_keys( $oldRels )
2561 if ( $deleteCurrent ) {
2562 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2563 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2565 'image_comment_temp', [ 'imgcomment_name' => $this->file
->getName() ], __METHOD__
2572 * Run the transaction
2575 public function execute() {
2576 $repo = $this->file
->getRepo();
2577 $this->file
->lock();
2579 // Prepare deletion batch
2580 $hashes = $this->getHashes();
2581 $this->deletionBatch
= [];
2582 $ext = $this->file
->getExtension();
2583 $dotExt = $ext === '' ?
'' : ".$ext";
2585 foreach ( $this->srcRels
as $name => $srcRel ) {
2586 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2587 if ( isset( $hashes[$name] ) ) {
2588 $hash = $hashes[$name];
2589 $key = $hash . $dotExt;
2590 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2591 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2595 if ( !$repo->hasSha1Storage() ) {
2596 // Removes non-existent file from the batch, so we don't get errors.
2597 // This also handles files in the 'deleted' zone deleted via revision deletion.
2598 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2599 if ( !$checkStatus->isGood() ) {
2600 $this->status
->merge( $checkStatus );
2601 return $this->status
;
2603 $this->deletionBatch
= $checkStatus->value
;
2605 // Execute the file deletion batch
2606 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2607 if ( !$status->isGood() ) {
2608 $this->status
->merge( $status );
2612 if ( !$this->status
->isOK() ) {
2613 // Critical file deletion error; abort
2614 $this->file
->unlock();
2616 return $this->status
;
2619 // Copy the image/oldimage rows to filearchive
2620 $this->doDBInserts();
2621 // Delete image/oldimage rows
2622 $this->doDBDeletes();
2624 // Commit and return
2625 $this->file
->unlock();
2627 return $this->status
;
2631 * Removes non-existent files from a deletion batch.
2632 * @param array $batch
2635 protected function removeNonexistentFiles( $batch ) {
2636 $files = $newBatch = [];
2638 foreach ( $batch as $batchItem ) {
2639 list( $src, ) = $batchItem;
2640 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2643 $result = $this->file
->repo
->fileExistsBatch( $files );
2644 if ( in_array( null, $result, true ) ) {
2645 return Status
::newFatal( 'backend-fail-internal',
2646 $this->file
->repo
->getBackend()->getName() );
2649 foreach ( $batch as $batchItem ) {
2650 if ( $result[$batchItem[0]] ) {
2651 $newBatch[] = $batchItem;
2655 return Status
::newGood( $newBatch );
2659 # ------------------------------------------------------------------------------
2662 * Helper class for file undeletion
2663 * @ingroup FileAbstraction
2665 class LocalFileRestoreBatch
{
2666 /** @var LocalFile */
2669 /** @var array List of file IDs to restore */
2670 private $cleanupBatch;
2672 /** @var array List of file IDs to restore */
2675 /** @var bool Add all revisions of the file */
2678 /** @var bool Whether to remove all settings for suppressed fields */
2679 private $unsuppress = false;
2683 * @param bool $unsuppress
2685 function __construct( File
$file, $unsuppress = false ) {
2686 $this->file
= $file;
2687 $this->cleanupBatch
= $this->ids
= [];
2689 $this->unsuppress
= $unsuppress;
2696 public function addId( $fa_id ) {
2697 $this->ids
[] = $fa_id;
2701 * Add a whole lot of files by ID
2704 public function addIds( $ids ) {
2705 $this->ids
= array_merge( $this->ids
, $ids );
2709 * Add all revisions of the file
2711 public function addAll() {
2716 * Run the transaction, except the cleanup batch.
2717 * The cleanup batch should be run in a separate transaction, because it locks different
2718 * rows and there's no need to keep the image row locked while it's acquiring those locks
2719 * The caller may have its own transaction open.
2720 * So we save the batch and let the caller call cleanup()
2723 public function execute() {
2724 /** @var Language */
2727 $repo = $this->file
->getRepo();
2728 if ( !$this->all
&& !$this->ids
) {
2730 return $repo->newGood();
2733 $lockOwnsTrx = $this->file
->lock();
2735 $dbw = $this->file
->repo
->getMasterDB();
2737 $commentStoreImgDesc = new CommentStore( 'img_description' );
2738 $commentStoreOiDesc = new CommentStore( 'oi_description' );
2739 $commentStoreFaDesc = new CommentStore( 'fa_description' );
2741 $status = $this->file
->repo
->newGood();
2743 $exists = (bool)$dbw->selectField( 'image', '1',
2744 [ 'img_name' => $this->file
->getName() ],
2746 // The lock() should already prevents changes, but this still may need
2747 // to bypass any transaction snapshot. However, if lock() started the
2748 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2749 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2752 // Fetch all or selected archived revisions for the file,
2753 // sorted from the most recent to the oldest.
2754 $conditions = [ 'fa_name' => $this->file
->getName() ];
2756 if ( !$this->all
) {
2757 $conditions['fa_id'] = $this->ids
;
2760 $arFileQuery = ArchivedFile
::getQueryInfo();
2761 $result = $dbw->select(
2762 $arFileQuery['tables'],
2763 $arFileQuery['fields'],
2766 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2767 $arFileQuery['joins']
2773 $insertCurrent = false;
2778 foreach ( $result as $row ) {
2779 $idsPresent[] = $row->fa_id
;
2781 if ( $row->fa_name
!= $this->file
->getName() ) {
2782 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2783 $status->failCount++
;
2787 if ( $row->fa_storage_key
== '' ) {
2788 // Revision was missing pre-deletion
2789 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2790 $status->failCount++
;
2794 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2795 $row->fa_storage_key
;
2796 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2798 if ( isset( $row->fa_sha1
) ) {
2799 $sha1 = $row->fa_sha1
;
2801 // old row, populate from key
2802 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2806 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2807 $sha1 = substr( $sha1, 1 );
2810 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2811 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2812 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2813 ||
is_null( $row->fa_metadata
)
2815 // Refresh our metadata
2816 // Required for a new current revision; nice for older ones too. :)
2817 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2820 'minor_mime' => $row->fa_minor_mime
,
2821 'major_mime' => $row->fa_major_mime
,
2822 'media_type' => $row->fa_media_type
,
2823 'metadata' => $row->fa_metadata
2827 $comment = $commentStoreFaDesc->getComment( $row );
2828 if ( $first && !$exists ) {
2829 // This revision will be published as the new current version
2830 $destRel = $this->file
->getRel();
2831 list( $commentFields, $commentCallback ) =
2832 $commentStoreImgDesc->insertWithTempTable( $dbw, $comment );
2834 'img_name' => $row->fa_name
,
2835 'img_size' => $row->fa_size
,
2836 'img_width' => $row->fa_width
,
2837 'img_height' => $row->fa_height
,
2838 'img_metadata' => $props['metadata'],
2839 'img_bits' => $row->fa_bits
,
2840 'img_media_type' => $props['media_type'],
2841 'img_major_mime' => $props['major_mime'],
2842 'img_minor_mime' => $props['minor_mime'],
2843 'img_user' => $row->fa_user
,
2844 'img_user_text' => $row->fa_user_text
,
2845 'img_timestamp' => $row->fa_timestamp
,
2849 // The live (current) version cannot be hidden!
2850 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2851 $status->fatal( 'undeleterevdel' );
2852 $this->file
->unlock();
2856 $archiveName = $row->fa_archive_name
;
2858 if ( $archiveName == '' ) {
2859 // This was originally a current version; we
2860 // have to devise a new archive name for it.
2861 // Format is <timestamp of archiving>!<name>
2862 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2865 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2867 } while ( isset( $archiveNames[$archiveName] ) );
2870 $archiveNames[$archiveName] = true;
2871 $destRel = $this->file
->getArchiveRel( $archiveName );
2873 'oi_name' => $row->fa_name
,
2874 'oi_archive_name' => $archiveName,
2875 'oi_size' => $row->fa_size
,
2876 'oi_width' => $row->fa_width
,
2877 'oi_height' => $row->fa_height
,
2878 'oi_bits' => $row->fa_bits
,
2879 'oi_user' => $row->fa_user
,
2880 'oi_user_text' => $row->fa_user_text
,
2881 'oi_timestamp' => $row->fa_timestamp
,
2882 'oi_metadata' => $props['metadata'],
2883 'oi_media_type' => $props['media_type'],
2884 'oi_major_mime' => $props['major_mime'],
2885 'oi_minor_mime' => $props['minor_mime'],
2886 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2888 ] +
$commentStoreOiDesc->insert( $dbw, $comment );
2891 $deleteIds[] = $row->fa_id
;
2893 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2894 // private files can stay where they are
2895 $status->successCount++
;
2897 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2898 $this->cleanupBatch
[] = $row->fa_storage_key
;
2906 // Add a warning to the status object for missing IDs
2907 $missingIds = array_diff( $this->ids
, $idsPresent );
2909 foreach ( $missingIds as $id ) {
2910 $status->error( 'undelete-missing-filearchive', $id );
2913 if ( !$repo->hasSha1Storage() ) {
2914 // Remove missing files from batch, so we don't get errors when undeleting them
2915 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2916 if ( !$checkStatus->isGood() ) {
2917 $status->merge( $checkStatus );
2920 $storeBatch = $checkStatus->value
;
2922 // Run the store batch
2923 // Use the OVERWRITE_SAME flag to smooth over a common error
2924 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2925 $status->merge( $storeStatus );
2927 if ( !$status->isGood() ) {
2928 // Even if some files could be copied, fail entirely as that is the
2929 // easiest thing to do without data loss
2930 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2931 $status->setOK( false );
2932 $this->file
->unlock();
2938 // Run the DB updates
2939 // Because we have locked the image row, key conflicts should be rare.
2940 // If they do occur, we can roll back the transaction at this time with
2941 // no data loss, but leaving unregistered files scattered throughout the
2943 // This is not ideal, which is why it's important to lock the image row.
2944 if ( $insertCurrent ) {
2945 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2946 $commentCallback( $insertCurrent['img_name'] );
2949 if ( $insertBatch ) {
2950 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2954 $dbw->delete( 'filearchive',
2955 [ 'fa_id' => $deleteIds ],
2959 // If store batch is empty (all files are missing), deletion is to be considered successful
2960 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2962 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2964 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2966 $this->file
->purgeEverything();
2968 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2969 $this->file
->purgeDescription();
2973 $this->file
->unlock();
2979 * Removes non-existent files from a store batch.
2980 * @param array $triplets
2983 protected function removeNonexistentFiles( $triplets ) {
2984 $files = $filteredTriplets = [];
2985 foreach ( $triplets as $file ) {
2986 $files[$file[0]] = $file[0];
2989 $result = $this->file
->repo
->fileExistsBatch( $files );
2990 if ( in_array( null, $result, true ) ) {
2991 return Status
::newFatal( 'backend-fail-internal',
2992 $this->file
->repo
->getBackend()->getName() );
2995 foreach ( $triplets as $file ) {
2996 if ( $result[$file[0]] ) {
2997 $filteredTriplets[] = $file;
3001 return Status
::newGood( $filteredTriplets );
3005 * Removes non-existent files from a cleanup batch.
3006 * @param array $batch
3009 protected function removeNonexistentFromCleanup( $batch ) {
3010 $files = $newBatch = [];
3011 $repo = $this->file
->repo
;
3013 foreach ( $batch as $file ) {
3014 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3015 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3018 $result = $repo->fileExistsBatch( $files );
3020 foreach ( $batch as $file ) {
3021 if ( $result[$file] ) {
3022 $newBatch[] = $file;
3030 * Delete unused files in the deleted zone.
3031 * This should be called from outside the transaction in which execute() was called.
3034 public function cleanup() {
3035 if ( !$this->cleanupBatch
) {
3036 return $this->file
->repo
->newGood();
3039 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
3041 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
3047 * Cleanup a failed batch. The batch was only partially successful, so
3048 * rollback by removing all items that were succesfully copied.
3050 * @param Status $storeStatus
3051 * @param array $storeBatch
3053 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3056 foreach ( $storeStatus->success
as $i => $success ) {
3057 // Check if this item of the batch was successfully copied
3059 // Item was successfully copied and needs to be removed again
3060 // Extract ($dstZone, $dstRel) from the batch
3061 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3064 $this->file
->repo
->cleanupBatch( $cleanupBatch );
3068 # ------------------------------------------------------------------------------
3071 * Helper class for file movement
3072 * @ingroup FileAbstraction
3074 class LocalFileMoveBatch
{
3075 /** @var LocalFile */
3085 protected $oldCount;
3089 /** @var IDatabase */
3094 * @param Title $target
3096 function __construct( File
$file, Title
$target ) {
3097 $this->file
= $file;
3098 $this->target
= $target;
3099 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
3100 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
3101 $this->oldName
= $this->file
->getName();
3102 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
3103 $this->oldRel
= $this->oldHash
. $this->oldName
;
3104 $this->newRel
= $this->newHash
. $this->newName
;
3105 $this->db
= $file->getRepo()->getMasterDB();
3109 * Add the current image to the batch
3111 public function addCurrent() {
3112 $this->cur
= [ $this->oldRel
, $this->newRel
];
3116 * Add the old versions of the image to the batch
3117 * @return array List of archive names from old versions
3119 public function addOlds() {
3120 $archiveBase = 'archive';
3122 $this->oldCount
= 0;
3125 $result = $this->db
->select( 'oldimage',
3126 [ 'oi_archive_name', 'oi_deleted' ],
3127 [ 'oi_name' => $this->oldName
],
3129 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3132 foreach ( $result as $row ) {
3133 $archiveNames[] = $row->oi_archive_name
;
3134 $oldName = $row->oi_archive_name
;
3135 $bits = explode( '!', $oldName, 2 );
3137 if ( count( $bits ) != 2 ) {
3138 wfDebug( "Old file name missing !: '$oldName' \n" );
3142 list( $timestamp, $filename ) = $bits;
3144 if ( $this->oldName
!= $filename ) {
3145 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3151 // Do we want to add those to oldCount?
3152 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3157 "{$archiveBase}/{$this->oldHash}{$oldName}",
3158 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3162 return $archiveNames;
3169 public function execute() {
3170 $repo = $this->file
->repo
;
3171 $status = $repo->newGood();
3172 $destFile = wfLocalFile( $this->target
);
3174 $this->file
->lock(); // begin
3175 $destFile->lock(); // quickly fail if destination is not available
3177 $triplets = $this->getMoveTriplets();
3178 $checkStatus = $this->removeNonexistentFiles( $triplets );
3179 if ( !$checkStatus->isGood() ) {
3180 $destFile->unlock();
3181 $this->file
->unlock();
3182 $status->merge( $checkStatus ); // couldn't talk to file backend
3185 $triplets = $checkStatus->value
;
3187 // Verify the file versions metadata in the DB.
3188 $statusDb = $this->verifyDBUpdates();
3189 if ( !$statusDb->isGood() ) {
3190 $destFile->unlock();
3191 $this->file
->unlock();
3192 $statusDb->setOK( false );
3197 if ( !$repo->hasSha1Storage() ) {
3198 // Copy the files into their new location.
3199 // If a prior process fataled copying or cleaning up files we tolerate any
3200 // of the existing files if they are identical to the ones being stored.
3201 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3202 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3203 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3204 if ( !$statusMove->isGood() ) {
3205 // Delete any files copied over (while the destination is still locked)
3206 $this->cleanupTarget( $triplets );
3207 $destFile->unlock();
3208 $this->file
->unlock();
3209 wfDebugLog( 'imagemove', "Error in moving files: "
3210 . $statusMove->getWikiText( false, false, 'en' ) );
3211 $statusMove->setOK( false );
3215 $status->merge( $statusMove );
3218 // Rename the file versions metadata in the DB.
3219 $this->doDBUpdates();
3221 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3222 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3224 $destFile->unlock();
3225 $this->file
->unlock(); // done
3227 // Everything went ok, remove the source files
3228 $this->cleanupSource( $triplets );
3230 $status->merge( $statusDb );
3236 * Verify the database updates and return a new Status indicating how
3237 * many rows would be updated.
3241 protected function verifyDBUpdates() {
3242 $repo = $this->file
->repo
;
3243 $status = $repo->newGood();
3246 $hasCurrent = $dbw->selectField(
3249 [ 'img_name' => $this->oldName
],
3253 $oldRowCount = $dbw->selectField(
3256 [ 'oi_name' => $this->oldName
],
3261 if ( $hasCurrent ) {
3262 $status->successCount++
;
3264 $status->failCount++
;
3266 $status->successCount +
= $oldRowCount;
3267 // T36934: oldCount is based on files that actually exist.
3268 // There may be more DB rows than such files, in which case $affected
3269 // can be greater than $total. We use max() to avoid negatives here.
3270 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3271 if ( $status->failCount
) {
3272 $status->error( 'imageinvalidfilename' );
3279 * Do the database updates and return a new Status indicating how
3280 * many rows where updated.
3282 protected function doDBUpdates() {
3285 // Update current image
3288 [ 'img_name' => $this->newName
],
3289 [ 'img_name' => $this->oldName
],
3292 // Update old images
3296 'oi_name' => $this->newName
,
3297 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3298 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3300 [ 'oi_name' => $this->oldName
],
3306 * Generate triplets for FileRepo::storeBatch().
3309 protected function getMoveTriplets() {
3310 $moves = array_merge( [ $this->cur
], $this->olds
);
3311 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3313 foreach ( $moves as $move ) {
3314 // $move: (oldRelativePath, newRelativePath)
3315 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3316 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3319 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3327 * Removes non-existent files from move batch.
3328 * @param array $triplets
3331 protected function removeNonexistentFiles( $triplets ) {
3334 foreach ( $triplets as $file ) {
3335 $files[$file[0]] = $file[0];
3338 $result = $this->file
->repo
->fileExistsBatch( $files );
3339 if ( in_array( null, $result, true ) ) {
3340 return Status
::newFatal( 'backend-fail-internal',
3341 $this->file
->repo
->getBackend()->getName() );
3344 $filteredTriplets = [];
3345 foreach ( $triplets as $file ) {
3346 if ( $result[$file[0]] ) {
3347 $filteredTriplets[] = $file;
3349 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3353 return Status
::newGood( $filteredTriplets );
3357 * Cleanup a partially moved array of triplets by deleting the target
3358 * files. Called if something went wrong half way.
3359 * @param array $triplets
3361 protected function cleanupTarget( $triplets ) {
3362 // Create dest pairs from the triplets
3364 foreach ( $triplets as $triplet ) {
3365 // $triplet: (old source virtual URL, dst zone, dest rel)
3366 $pairs[] = [ $triplet[1], $triplet[2] ];
3369 $this->file
->repo
->cleanupBatch( $pairs );
3373 * Cleanup a fully moved array of triplets by deleting the source files.
3374 * Called at the end of the move process if everything else went ok.
3375 * @param array $triplets
3377 protected function cleanupSource( $triplets ) {
3378 // Create source file names from the triplets
3380 foreach ( $triplets as $triplet ) {
3381 $files[] = $triplet[0];
3384 $this->file
->repo
->cleanupBatch( $files );
3388 class LocalFileLockError
extends ErrorPageError
{
3389 public function __construct( Status
$status ) {
3390 parent
::__construct(
3392 $status->getMessage()
3396 public function report() {
3398 $wgOut->setStatusCode( 429 );