3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use MediaWiki\Logger\LoggerFactory
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\MediaWikiServices
;
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const VERSION
= 11; // cache version
49 const CACHE_FIELD_MAX_LEN
= 1000;
51 /** @var bool Does the file exist on disk? (loadFromXxx) */
52 protected $fileExists;
54 /** @var int Image width */
57 /** @var int Image height */
60 /** @var int Returned by getimagesize (loadFromXxx) */
63 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
64 protected $media_type;
66 /** @var string MIME type, determined by MimeMagic::guessMimeType */
69 /** @var int Size in bytes (loadFromXxx) */
72 /** @var string Handler-specific metadata */
75 /** @var string SHA-1 base 36 content hash */
78 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
79 protected $dataLoaded;
81 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
82 protected $extraDataLoaded;
84 /** @var int Bitfield akin to rev_deleted */
88 protected $repoClass = LocalRepo
::class;
90 /** @var int Number of line to return by nextHistoryLine() (constructor) */
93 /** @var int Result of the query for the file's history (nextHistoryLine) */
96 /** @var string Major MIME type */
99 /** @var string Minor MIME type */
102 /** @var string Upload timestamp */
105 /** @var int User ID of uploader */
108 /** @var string User name of uploader */
111 /** @var string Description of current revision of the file */
112 private $description;
114 /** @var string TS_MW timestamp of the last change of the file description */
115 private $descriptionTouched;
117 /** @var bool Whether the row was upgraded on load */
120 /** @var bool Whether the row was scheduled to upgrade on load */
123 /** @var bool True if the image row is locked */
126 /** @var bool True if the image row is locked with a lock initiated transaction */
127 private $lockedOwnTrx;
129 /** @var bool True if file is not present in file system. Not to be cached in memcached */
132 // @note: higher than IDBAccessObject constants
133 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
135 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
138 * Create a LocalFile from a title
139 * Do not call this except from inside a repo class.
141 * Note: $unused param is only here to avoid an E_STRICT
143 * @param Title $title
144 * @param FileRepo $repo
145 * @param null $unused
149 static function newFromTitle( $title, $repo, $unused = null ) {
150 return new self( $title, $repo );
154 * Create a LocalFile from a title
155 * Do not call this except from inside a repo class.
157 * @param stdClass $row
158 * @param FileRepo $repo
162 static function newFromRow( $row, $repo ) {
163 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
164 $file = new self( $title, $repo );
165 $file->loadFromRow( $row );
171 * Create a LocalFile from a SHA-1 key
172 * Do not call this except from inside a repo class.
174 * @param string $sha1 Base-36 SHA-1
175 * @param LocalRepo $repo
176 * @param string|bool $timestamp MW_timestamp (optional)
177 * @return bool|LocalFile
179 static function newFromKey( $sha1, $repo, $timestamp = false ) {
180 $dbr = $repo->getReplicaDB();
182 $conds = [ 'img_sha1' => $sha1 ];
184 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
187 $fileQuery = self
::getQueryInfo();
188 $row = $dbr->selectRow(
189 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
192 return self
::newFromRow( $row, $repo );
199 * Fields in the image table
200 * @deprecated since 1.31, use self::getQueryInfo() instead.
203 static function selectFields() {
204 wfDeprecated( __METHOD__
, '1.31' );
219 ] + CommentStore
::getStore()->getFields( 'img_description' );
223 * Return the tables, fields, and join conditions to be selected to create
224 * a new localfile object.
226 * @param string[] $options
227 * - omit-lazy: Omit fields that are lazily cached.
228 * @return array With three keys:
229 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
230 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
231 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
233 public static function getQueryInfo( array $options = [] ) {
234 $commentQuery = CommentStore
::getStore()->getJoin( 'img_description' );
236 'tables' => [ 'image' ] +
$commentQuery['tables'],
251 ] +
$commentQuery['fields'],
252 'joins' => $commentQuery['joins'],
255 if ( in_array( 'omit-nonlazy', $options, true ) ) {
256 // Internal use only for getting only the lazy fields
259 if ( !in_array( 'omit-lazy', $options, true ) ) {
260 // Note: Keep this in sync with self::getLazyCacheFields()
261 $ret['fields'][] = 'img_metadata';
268 * Do not call this except from inside a repo class.
269 * @param Title $title
270 * @param FileRepo $repo
272 function __construct( $title, $repo ) {
273 parent
::__construct( $title, $repo );
275 $this->metadata
= '';
276 $this->historyLine
= 0;
277 $this->historyRes
= null;
278 $this->dataLoaded
= false;
279 $this->extraDataLoaded
= false;
281 $this->assertRepoDefined();
282 $this->assertTitleDefined();
286 * Get the memcached key for the main data for this file, or false if
287 * there is no access to the shared cache.
288 * @return string|bool
290 function getCacheKey() {
291 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
295 * @param WANObjectCache $cache
299 public function getMutableCacheKeys( WANObjectCache
$cache ) {
300 return [ $this->getCacheKey() ];
304 * Try to load file metadata from memcached, falling back to the database
306 private function loadFromCache() {
307 $this->dataLoaded
= false;
308 $this->extraDataLoaded
= false;
310 $key = $this->getCacheKey();
312 $this->loadFromDB( self
::READ_NORMAL
);
317 $cache = ObjectCache
::getMainWANInstance();
318 $cachedValues = $cache->getWithSetCallback(
321 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
322 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
324 $this->loadFromDB( self
::READ_NORMAL
);
326 $fields = $this->getCacheFields( '' );
327 $cacheVal['fileExists'] = $this->fileExists
;
328 if ( $this->fileExists
) {
329 foreach ( $fields as $field ) {
330 $cacheVal[$field] = $this->$field;
333 // Strip off excessive entries from the subset of fields that can become large.
334 // If the cache value gets to large it will not fit in memcached and nothing will
335 // get cached at all, causing master queries for any file access.
336 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
337 if ( isset( $cacheVal[$field] )
338 && strlen( $cacheVal[$field] ) > 100 * 1024
340 unset( $cacheVal[$field] ); // don't let the value get too big
344 if ( $this->fileExists
) {
345 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
347 $ttl = $cache::TTL_DAY
;
352 [ 'version' => self
::VERSION
]
355 $this->fileExists
= $cachedValues['fileExists'];
356 if ( $this->fileExists
) {
357 $this->setProps( $cachedValues );
360 $this->dataLoaded
= true;
361 $this->extraDataLoaded
= true;
362 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
363 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
368 * Purge the file object/metadata cache
370 public function invalidateCache() {
371 $key = $this->getCacheKey();
376 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
377 function () use ( $key ) {
378 ObjectCache
::getMainWANInstance()->delete( $key );
385 * Load metadata from the file itself
387 function loadFromFile() {
388 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
389 $this->setProps( $props );
393 * Returns the list of object properties that are included as-is in the cache.
394 * @param string $prefix Must be the empty string
396 * @since 1.31 No longer accepts a non-empty $prefix
398 protected function getCacheFields( $prefix = 'img_' ) {
399 if ( $prefix !== '' ) {
400 throw new InvalidArgumentException(
401 __METHOD__
. ' with a non-empty prefix is no longer supported.'
405 // See self::getQueryInfo() for the fetching of the data from the DB,
406 // self::loadFromRow() for the loading of the object from the DB row,
407 // and self::loadFromCache() for the caching, and self::setProps() for
408 // populating the object from an array of data.
409 return [ 'size', 'width', 'height', 'bits', 'media_type',
410 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
411 'user_text', 'description' ];
415 * Returns the list of object properties that are included as-is in the
416 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
417 * @param string $prefix Must be the empty string
419 * @since 1.31 No longer accepts a non-empty $prefix
421 protected function getLazyCacheFields( $prefix = 'img_' ) {
422 if ( $prefix !== '' ) {
423 throw new InvalidArgumentException(
424 __METHOD__
. ' with a non-empty prefix is no longer supported.'
428 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
429 return [ 'metadata' ];
433 * Load file metadata from the DB
436 function loadFromDB( $flags = 0 ) {
437 $fname = static::class . '::' . __FUNCTION__
;
439 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
440 $this->dataLoaded
= true;
441 $this->extraDataLoaded
= true;
443 $dbr = ( $flags & self
::READ_LATEST
)
444 ?
$this->repo
->getMasterDB()
445 : $this->repo
->getReplicaDB();
447 $fileQuery = static::getQueryInfo();
448 $row = $dbr->selectRow(
449 $fileQuery['tables'],
450 $fileQuery['fields'],
451 [ 'img_name' => $this->getName() ],
458 $this->loadFromRow( $row );
460 $this->fileExists
= false;
465 * Load lazy file metadata from the DB.
466 * This covers fields that are sometimes not cached.
468 protected function loadExtraFromDB() {
469 $fname = static::class . '::' . __FUNCTION__
;
471 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
472 $this->extraDataLoaded
= true;
474 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
476 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
480 foreach ( $fieldMap as $name => $value ) {
481 $this->$name = $value;
484 throw new MWException( "Could not find data for image '{$this->getName()}'." );
489 * @param IDatabase $dbr
490 * @param string $fname
493 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
496 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
497 $row = $dbr->selectRow(
498 $fileQuery['tables'],
499 $fileQuery['fields'],
501 'img_name' => $this->getName(),
502 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
509 $fieldMap = $this->unprefixRow( $row, 'img_' );
511 # File may have been uploaded over in the meantime; check the old versions
512 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
513 $row = $dbr->selectRow(
514 $fileQuery['tables'],
515 $fileQuery['fields'],
517 'oi_name' => $this->getName(),
518 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
525 $fieldMap = $this->unprefixRow( $row, 'oi_' );
529 if ( isset( $fieldMap['metadata'] ) ) {
530 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
537 * @param array|object $row
538 * @param string $prefix
539 * @throws MWException
542 protected function unprefixRow( $row, $prefix = 'img_' ) {
543 $array = (array)$row;
544 $prefixLength = strlen( $prefix );
546 // Sanity check prefix once
547 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
548 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
552 foreach ( $array as $name => $value ) {
553 $decoded[substr( $name, $prefixLength )] = $value;
560 * Decode a row from the database (either object or array) to an array
561 * with timestamps and MIME types decoded, and the field prefix removed.
563 * @param string $prefix
564 * @throws MWException
567 function decodeRow( $row, $prefix = 'img_' ) {
568 $decoded = $this->unprefixRow( $row, $prefix );
570 $decoded['description'] = CommentStore
::getStore()
571 ->getComment( 'description', (object)$decoded )->text
;
573 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
575 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
577 if ( empty( $decoded['major_mime'] ) ) {
578 $decoded['mime'] = 'unknown/unknown';
580 if ( !$decoded['minor_mime'] ) {
581 $decoded['minor_mime'] = 'unknown';
583 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
586 // Trim zero padding from char/binary field
587 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
589 // Normalize some fields to integer type, per their database definition.
590 // Use unary + so that overflows will be upgraded to double instead of
591 // being trucated as with intval(). This is important to allow >2GB
592 // files on 32-bit systems.
593 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
594 $decoded[$field] = +
$decoded[$field];
601 * Load file metadata from a DB result row
604 * @param string $prefix
606 function loadFromRow( $row, $prefix = 'img_' ) {
607 $this->dataLoaded
= true;
608 $this->extraDataLoaded
= true;
610 $array = $this->decodeRow( $row, $prefix );
612 foreach ( $array as $name => $value ) {
613 $this->$name = $value;
616 $this->fileExists
= true;
617 $this->maybeUpgradeRow();
621 * Load file metadata from cache or DB, unless already loaded
624 function load( $flags = 0 ) {
625 if ( !$this->dataLoaded
) {
626 if ( $flags & self
::READ_LATEST
) {
627 $this->loadFromDB( $flags );
629 $this->loadFromCache();
633 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
634 // @note: loads on name/timestamp to reduce race condition problems
635 $this->loadExtraFromDB();
640 * Upgrade a row if it needs it
642 function maybeUpgradeRow() {
643 global $wgUpdateCompatibleMetadata;
645 if ( wfReadOnly() ||
$this->upgrading
) {
650 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
653 $handler = $this->getHandler();
655 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
656 if ( $validity === MediaHandler
::METADATA_BAD
) {
658 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
659 $upgrade = $wgUpdateCompatibleMetadata;
665 $this->upgrading
= true;
666 // Defer updates unless in auto-commit CLI mode
667 DeferredUpdates
::addCallableUpdate( function () {
668 $this->upgrading
= false; // avoid duplicate updates
671 } catch ( LocalFileLockError
$e ) {
672 // let the other process handle it (or do it next time)
679 * @return bool Whether upgradeRow() ran for this object
681 function getUpgraded() {
682 return $this->upgraded
;
686 * Fix assorted version-related problems with the image row by reloading it from the file
688 function upgradeRow() {
689 $this->lock(); // begin
691 $this->loadFromFile();
693 # Don't destroy file info of missing files
694 if ( !$this->fileExists
) {
696 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
701 $dbw = $this->repo
->getMasterDB();
702 list( $major, $minor ) = self
::splitMime( $this->mime
);
704 if ( wfReadOnly() ) {
709 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
711 $dbw->update( 'image',
713 'img_size' => $this->size
, // sanity
714 'img_width' => $this->width
,
715 'img_height' => $this->height
,
716 'img_bits' => $this->bits
,
717 'img_media_type' => $this->media_type
,
718 'img_major_mime' => $major,
719 'img_minor_mime' => $minor,
720 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
721 'img_sha1' => $this->sha1
,
723 [ 'img_name' => $this->getName() ],
727 $this->invalidateCache();
729 $this->unlock(); // done
730 $this->upgraded
= true; // avoid rework/retries
734 * Set properties in this object to be equal to those given in the
735 * associative array $info. Only cacheable fields can be set.
736 * All fields *must* be set in $info except for getLazyCacheFields().
738 * If 'mime' is given, it will be split into major_mime/minor_mime.
739 * If major_mime/minor_mime are given, $this->mime will also be set.
743 function setProps( $info ) {
744 $this->dataLoaded
= true;
745 $fields = $this->getCacheFields( '' );
746 $fields[] = 'fileExists';
748 foreach ( $fields as $field ) {
749 if ( isset( $info[$field] ) ) {
750 $this->$field = $info[$field];
754 // Fix up mime fields
755 if ( isset( $info['major_mime'] ) ) {
756 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
757 } elseif ( isset( $info['mime'] ) ) {
758 $this->mime
= $info['mime'];
759 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
763 /** splitMime inherited */
764 /** getName inherited */
765 /** getTitle inherited */
766 /** getURL inherited */
767 /** getViewURL inherited */
768 /** getPath inherited */
769 /** isVisible inherited */
774 function isMissing() {
775 if ( $this->missing
=== null ) {
776 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
777 $this->missing
= !$fileExists;
780 return $this->missing
;
784 * Return the width of the image
789 public function getWidth( $page = 1 ) {
797 if ( $this->isMultipage() ) {
798 $handler = $this->getHandler();
802 $dim = $handler->getPageDimensions( $this, $page );
804 return $dim['width'];
806 // For non-paged media, the false goes through an
807 // intval, turning failure into 0, so do same here.
816 * Return the height of the image
821 public function getHeight( $page = 1 ) {
829 if ( $this->isMultipage() ) {
830 $handler = $this->getHandler();
834 $dim = $handler->getPageDimensions( $this, $page );
836 return $dim['height'];
838 // For non-paged media, the false goes through an
839 // intval, turning failure into 0, so do same here.
843 return $this->height
;
848 * Returns ID or name of user who uploaded the file
850 * @param string $type 'text' or 'id'
853 function getUser( $type = 'text' ) {
856 if ( $type == 'text' ) {
857 return $this->user_text
;
859 return (int)$this->user
;
864 * Get short description URL for a file based on the page ID.
866 * @return string|null
867 * @throws MWException
870 public function getDescriptionShortUrl() {
871 $pageId = $this->title
->getArticleID();
873 if ( $pageId !== null ) {
874 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
875 if ( $url !== false ) {
883 * Get handler-specific metadata
886 function getMetadata() {
887 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
888 return $this->metadata
;
894 function getBitDepth() {
897 return (int)$this->bits
;
901 * Returns the size of the image file, in bytes
904 public function getSize() {
911 * Returns the MIME type of the file.
914 function getMimeType() {
921 * Returns the type of the media in the file.
922 * Use the value returned by this function with the MEDIATYPE_xxx constants.
925 function getMediaType() {
928 return $this->media_type
;
931 /** canRender inherited */
932 /** mustRender inherited */
933 /** allowInlineDisplay inherited */
934 /** isSafeFile inherited */
935 /** isTrustedFile inherited */
938 * Returns true if the file exists on disk.
939 * @return bool Whether file exist on disk.
941 public function exists() {
944 return $this->fileExists
;
947 /** getTransformScript inherited */
948 /** getUnscaledThumb inherited */
949 /** thumbName inherited */
950 /** createThumb inherited */
951 /** transform inherited */
953 /** getHandler inherited */
954 /** iconThumb inherited */
955 /** getLastError inherited */
958 * Get all thumbnail names previously generated for this file
959 * @param string|bool $archiveName Name of an archive file, default false
960 * @return array First element is the base dir, then files in that base dir.
962 function getThumbnails( $archiveName = false ) {
963 if ( $archiveName ) {
964 $dir = $this->getArchiveThumbPath( $archiveName );
966 $dir = $this->getThumbPath();
969 $backend = $this->repo
->getBackend();
972 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
973 foreach ( $iterator as $file ) {
976 } catch ( FileBackendError
$e ) {
977 } // suppress (T56674)
983 * Refresh metadata in memcached, but don't touch thumbnails or CDN
985 function purgeMetadataCache() {
986 $this->invalidateCache();
990 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
992 * @param array $options An array potentially with the key forThumbRefresh.
994 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
996 function purgeCache( $options = [] ) {
997 // Refresh metadata cache
998 $this->purgeMetadataCache();
1000 // Delete thumbnails
1001 $this->purgeThumbnails( $options );
1003 // Purge CDN cache for this file
1004 DeferredUpdates
::addUpdate(
1005 new CdnCacheUpdate( [ $this->getUrl() ] ),
1006 DeferredUpdates
::PRESEND
1011 * Delete cached transformed files for an archived version only.
1012 * @param string $archiveName Name of the archived file
1014 function purgeOldThumbnails( $archiveName ) {
1015 // Get a list of old thumbnails and URLs
1016 $files = $this->getThumbnails( $archiveName );
1018 // Purge any custom thumbnail caches
1019 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1021 // Delete thumbnails
1022 $dir = array_shift( $files );
1023 $this->purgeThumbList( $dir, $files );
1027 foreach ( $files as $file ) {
1028 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1030 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1034 * Delete cached transformed files for the current version only.
1035 * @param array $options
1037 public function purgeThumbnails( $options = [] ) {
1038 $files = $this->getThumbnails();
1039 // Always purge all files from CDN regardless of handler filters
1041 foreach ( $files as $file ) {
1042 $urls[] = $this->getThumbUrl( $file );
1044 array_shift( $urls ); // don't purge directory
1046 // Give media handler a chance to filter the file purge list
1047 if ( !empty( $options['forThumbRefresh'] ) ) {
1048 $handler = $this->getHandler();
1050 $handler->filterThumbnailPurgeList( $files, $options );
1054 // Purge any custom thumbnail caches
1055 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1057 // Delete thumbnails
1058 $dir = array_shift( $files );
1059 $this->purgeThumbList( $dir, $files );
1062 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1066 * Prerenders a configurable set of thumbnails
1070 public function prerenderThumbnails() {
1071 global $wgUploadThumbnailRenderMap;
1075 $sizes = $wgUploadThumbnailRenderMap;
1078 foreach ( $sizes as $size ) {
1079 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1080 $jobs[] = new ThumbnailRenderJob(
1082 [ 'transformParams' => [ 'width' => $size ] ]
1088 JobQueueGroup
::singleton()->lazyPush( $jobs );
1093 * Delete a list of thumbnails visible at urls
1094 * @param string $dir Base dir of the files.
1095 * @param array $files Array of strings: relative filenames (to $dir)
1097 protected function purgeThumbList( $dir, $files ) {
1098 $fileListDebug = strtr(
1099 var_export( $files, true ),
1102 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1105 foreach ( $files as $file ) {
1106 if ( $this->repo
->supportsSha1URLs() ) {
1107 $reference = $this->getSha1();
1109 $reference = $this->getName();
1112 # Check that the reference (filename or sha1) is part of the thumb name
1113 # This is a basic sanity check to avoid erasing unrelated directories
1114 if ( strpos( $file, $reference ) !== false
1115 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1117 $purgeList[] = "{$dir}/{$file}";
1121 # Delete the thumbnails
1122 $this->repo
->quickPurgeBatch( $purgeList );
1123 # Clear out the thumbnail directory if empty
1124 $this->repo
->quickCleanDir( $dir );
1127 /** purgeDescription inherited */
1128 /** purgeEverything inherited */
1131 * @param int $limit Optional: Limit to number of results
1132 * @param int $start Optional: Timestamp, start from
1133 * @param int $end Optional: Timestamp, end at
1135 * @return OldLocalFile[]
1137 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1138 $dbr = $this->repo
->getReplicaDB();
1139 $oldFileQuery = OldLocalFile
::getQueryInfo();
1141 $tables = $oldFileQuery['tables'];
1142 $fields = $oldFileQuery['fields'];
1143 $join_conds = $oldFileQuery['joins'];
1144 $conds = $opts = [];
1145 $eq = $inc ?
'=' : '';
1146 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1149 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1153 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1157 $opts['LIMIT'] = $limit;
1160 // Search backwards for time > x queries
1161 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1162 $opts['ORDER BY'] = "oi_timestamp $order";
1163 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1165 // Avoid PHP 7.1 warning from passing $this by reference
1167 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1168 &$conds, &$opts, &$join_conds ] );
1170 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1173 foreach ( $res as $row ) {
1174 $r[] = $this->repo
->newFileFromRow( $row );
1177 if ( $order == 'ASC' ) {
1178 $r = array_reverse( $r ); // make sure it ends up descending
1185 * Returns the history of this file, line by line.
1186 * starts with current version, then old versions.
1187 * uses $this->historyLine to check which line to return:
1188 * 0 return line for current version
1189 * 1 query for old versions, return first one
1190 * 2, ... return next old version from above query
1193 public function nextHistoryLine() {
1194 # Polymorphic function name to distinguish foreign and local fetches
1195 $fname = static::class . '::' . __FUNCTION__
;
1197 $dbr = $this->repo
->getReplicaDB();
1199 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1200 $fileQuery = self
::getQueryInfo();
1201 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1202 $fileQuery['fields'] +
[
1203 'oi_archive_name' => $dbr->addQuotes( '' ),
1206 [ 'img_name' => $this->title
->getDBkey() ],
1212 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1213 $this->historyRes
= null;
1217 } elseif ( $this->historyLine
== 1 ) {
1218 $fileQuery = OldLocalFile
::getQueryInfo();
1219 $this->historyRes
= $dbr->select(
1220 $fileQuery['tables'],
1221 $fileQuery['fields'],
1222 [ 'oi_name' => $this->title
->getDBkey() ],
1224 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1228 $this->historyLine++
;
1230 return $dbr->fetchObject( $this->historyRes
);
1234 * Reset the history pointer to the first element of the history
1236 public function resetHistory() {
1237 $this->historyLine
= 0;
1239 if ( !is_null( $this->historyRes
) ) {
1240 $this->historyRes
= null;
1244 /** getHashPath inherited */
1245 /** getRel inherited */
1246 /** getUrlRel inherited */
1247 /** getArchiveRel inherited */
1248 /** getArchivePath inherited */
1249 /** getThumbPath inherited */
1250 /** getArchiveUrl inherited */
1251 /** getThumbUrl inherited */
1252 /** getArchiveVirtualUrl inherited */
1253 /** getThumbVirtualUrl inherited */
1254 /** isHashed inherited */
1257 * Upload a file and record it in the DB
1258 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1259 * @param string $comment Upload description
1260 * @param string $pageText Text to use for the new description page,
1261 * if a new description page is created
1262 * @param int|bool $flags Flags for publish()
1263 * @param array|bool $props File properties, if known. This can be used to
1264 * reduce the upload time when uploading virtual URLs for which the file
1265 * info is already known
1266 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1268 * @param User|null $user User object or null to use $wgUser
1269 * @param string[] $tags Change tags to add to the log entry and page revision.
1270 * (This doesn't check $user's permissions.)
1271 * @return Status On success, the value member contains the
1272 * archive name, or an empty string if it was a new file.
1274 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1275 $timestamp = false, $user = null, $tags = []
1277 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1278 return $this->readOnlyFatalStatus();
1279 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1280 // Check this in advance to avoid writing to FileBackend and the file tables,
1281 // only to fail on insert the revision due to the text store being unavailable.
1282 return $this->readOnlyFatalStatus();
1285 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1287 if ( $this->repo
->isVirtualUrl( $srcPath )
1288 || FileBackend
::isStoragePath( $srcPath )
1290 $props = $this->repo
->getFileProps( $srcPath );
1292 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1293 $props = $mwProps->getPropsFromPath( $srcPath, true );
1298 $handler = MediaHandler
::getHandler( $props['mime'] );
1300 $metadata = Wikimedia\
quietCall( 'unserialize', $props['metadata'] );
1302 if ( !is_array( $metadata ) ) {
1306 $options['headers'] = $handler->getContentHeaders( $metadata );
1308 $options['headers'] = [];
1311 // Trim spaces on user supplied text
1312 $comment = trim( $comment );
1314 $this->lock(); // begin
1315 $status = $this->publish( $src, $flags, $options );
1317 if ( $status->successCount
>= 2 ) {
1318 // There will be a copy+(one of move,copy,store).
1319 // The first succeeding does not commit us to updating the DB
1320 // since it simply copied the current version to a timestamped file name.
1321 // It is only *preferable* to avoid leaving such files orphaned.
1322 // Once the second operation goes through, then the current version was
1323 // updated and we must therefore update the DB too.
1324 $oldver = $status->value
;
1325 $uploadStatus = $this->recordUpload2(
1334 if ( !$uploadStatus->isOK() ) {
1335 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1336 // update filenotfound error with more specific path
1337 $status->fatal( 'filenotfound', $srcPath );
1339 $status->merge( $uploadStatus );
1344 $this->unlock(); // done
1350 * Record a file upload in the upload log and the image table
1351 * @param string $oldver
1352 * @param string $desc
1353 * @param string $license
1354 * @param string $copyStatus
1355 * @param string $source
1356 * @param bool $watch
1357 * @param string|bool $timestamp
1358 * @param User|null $user User object or null to use $wgUser
1361 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1362 $watch = false, $timestamp = false, User
$user = null ) {
1368 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1370 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1375 $user->addWatch( $this->getTitle() );
1382 * Record a file upload in the upload log and the image table
1383 * @param string $oldver
1384 * @param string $comment
1385 * @param string $pageText
1386 * @param bool|array $props
1387 * @param string|bool $timestamp
1388 * @param null|User $user
1389 * @param string[] $tags
1392 function recordUpload2(
1393 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1395 global $wgCommentTableSchemaMigrationStage;
1397 if ( is_null( $user ) ) {
1402 $dbw = $this->repo
->getMasterDB();
1404 # Imports or such might force a certain timestamp; otherwise we generate
1405 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1406 if ( $timestamp === false ) {
1407 $timestamp = $dbw->timestamp();
1408 $allowTimeKludge = true;
1410 $allowTimeKludge = false;
1413 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1414 $props['description'] = $comment;
1415 $props['user'] = $user->getId();
1416 $props['user_text'] = $user->getName();
1417 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1418 $this->setProps( $props );
1420 # Fail now if the file isn't there
1421 if ( !$this->fileExists
) {
1422 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1424 return Status
::newFatal( 'filenotfound', $this->getRel() );
1427 $dbw->startAtomic( __METHOD__
);
1429 # Test to see if the row exists using INSERT IGNORE
1430 # This avoids race conditions by locking the row until the commit, and also
1431 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1432 $commentStore = CommentStore
::getStore();
1433 list( $commentFields, $commentCallback ) =
1434 $commentStore->insertWithTempTable( $dbw, 'img_description', $comment );
1435 $dbw->insert( 'image',
1437 'img_name' => $this->getName(),
1438 'img_size' => $this->size
,
1439 'img_width' => intval( $this->width
),
1440 'img_height' => intval( $this->height
),
1441 'img_bits' => $this->bits
,
1442 'img_media_type' => $this->media_type
,
1443 'img_major_mime' => $this->major_mime
,
1444 'img_minor_mime' => $this->minor_mime
,
1445 'img_timestamp' => $timestamp,
1446 'img_user' => $user->getId(),
1447 'img_user_text' => $user->getName(),
1448 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1449 'img_sha1' => $this->sha1
1454 $reupload = ( $dbw->affectedRows() == 0 );
1457 $row = $dbw->selectRow(
1459 [ 'img_timestamp', 'img_sha1' ],
1460 [ 'img_name' => $this->getName() ],
1462 [ 'LOCK IN SHARE MODE' ]
1465 if ( $row && $row->img_sha1
=== $this->sha1
) {
1466 $dbw->endAtomic( __METHOD__
);
1467 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1468 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1469 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1472 if ( $allowTimeKludge ) {
1473 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1474 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1475 # Avoid a timestamp that is not newer than the last version
1476 # TODO: the image/oldimage tables should be like page/revision with an ID field
1477 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1478 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1479 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1480 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1484 $tables = [ 'image' ];
1486 'oi_name' => 'img_name',
1487 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1488 'oi_size' => 'img_size',
1489 'oi_width' => 'img_width',
1490 'oi_height' => 'img_height',
1491 'oi_bits' => 'img_bits',
1492 'oi_timestamp' => 'img_timestamp',
1493 'oi_user' => 'img_user',
1494 'oi_user_text' => 'img_user_text',
1495 'oi_metadata' => 'img_metadata',
1496 'oi_media_type' => 'img_media_type',
1497 'oi_major_mime' => 'img_major_mime',
1498 'oi_minor_mime' => 'img_minor_mime',
1499 'oi_sha1' => 'img_sha1',
1503 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1504 $fields['oi_description'] = 'img_description';
1506 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1507 $tables[] = 'image_comment_temp';
1508 $fields['oi_description_id'] = 'imgcomment_description_id';
1509 $joins['image_comment_temp'] = [
1510 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
1511 [ 'imgcomment_name = img_name' ]
1515 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
1516 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1518 // Upgrade any rows that are still old-style. Otherwise an upgrade
1519 // might be missed if a deletion happens while the migration script
1521 $res = $dbw->select(
1522 [ 'image', 'image_comment_temp' ],
1523 [ 'img_name', 'img_description' ],
1524 [ 'img_name' => $this->getName(), 'imgcomment_name' => null ],
1527 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1529 foreach ( $res as $row ) {
1530 list( , $callback ) = $commentStore->insertWithTempTable(
1531 $dbw, 'img_description', $row->img_description
1533 $callback( $row->img_name
);
1537 # (T36993) Note: $oldver can be empty here, if the previous
1538 # version of the file was broken. Allow registration of the new
1539 # version to continue anyway, because that's better than having
1540 # an image that's not fixable by user operations.
1541 # Collision, this is an update of a file
1542 # Insert previous contents into oldimage
1543 $dbw->insertSelect( 'oldimage', $tables, $fields,
1544 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1546 # Update the current image row
1547 $dbw->update( 'image',
1549 'img_size' => $this->size
,
1550 'img_width' => intval( $this->width
),
1551 'img_height' => intval( $this->height
),
1552 'img_bits' => $this->bits
,
1553 'img_media_type' => $this->media_type
,
1554 'img_major_mime' => $this->major_mime
,
1555 'img_minor_mime' => $this->minor_mime
,
1556 'img_timestamp' => $timestamp,
1557 'img_user' => $user->getId(),
1558 'img_user_text' => $user->getName(),
1559 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1560 'img_sha1' => $this->sha1
1562 [ 'img_name' => $this->getName() ],
1565 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
1566 // So $commentCallback can insert the new row
1567 $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__
);
1570 $commentCallback( $this->getName() );
1572 $descTitle = $this->getTitle();
1573 $descId = $descTitle->getArticleID();
1574 $wikiPage = new WikiFilePage( $descTitle );
1575 $wikiPage->setFile( $this );
1577 // Add the log entry...
1578 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1579 $logEntry->setTimestamp( $this->timestamp
);
1580 $logEntry->setPerformer( $user );
1581 $logEntry->setComment( $comment );
1582 $logEntry->setTarget( $descTitle );
1583 // Allow people using the api to associate log entries with the upload.
1584 // Log has a timestamp, but sometimes different from upload timestamp.
1585 $logEntry->setParameters(
1587 'img_sha1' => $this->sha1
,
1588 'img_timestamp' => $timestamp,
1591 // Note we keep $logId around since during new image
1592 // creation, page doesn't exist yet, so log_page = 0
1593 // but we want it to point to the page we're making,
1594 // so we later modify the log entry.
1595 // For a similar reason, we avoid making an RC entry
1596 // now and wait until the page exists.
1597 $logId = $logEntry->insert();
1599 if ( $descTitle->exists() ) {
1600 // Use own context to get the action text in content language
1601 $formatter = LogFormatter
::newFromEntry( $logEntry );
1602 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1603 $editSummary = $formatter->getPlainActionText();
1605 $nullRevision = Revision
::newNullRevision(
1612 if ( $nullRevision ) {
1613 $nullRevision->insertOn( $dbw );
1615 'NewRevisionFromEditComplete',
1616 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1618 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1619 // Associate null revision id
1620 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1623 $newPageContent = null;
1625 // Make the description page and RC log entry post-commit
1626 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1629 # Defer purges, page creation, and link updates in case they error out.
1630 # The most important thing is that files and the DB registry stay synced.
1631 $dbw->endAtomic( __METHOD__
);
1633 # Do some cache purges after final commit so that:
1634 # a) Changes are more likely to be seen post-purge
1635 # b) They won't cause rollback of the log publish/update above
1636 DeferredUpdates
::addUpdate(
1637 new AutoCommitUpdate(
1641 $reupload, $wikiPage, $newPageContent, $comment, $user,
1642 $logEntry, $logId, $descId, $tags
1644 # Update memcache after the commit
1645 $this->invalidateCache();
1647 $updateLogPage = false;
1648 if ( $newPageContent ) {
1649 # New file page; create the description page.
1650 # There's already a log entry, so don't make a second RC entry
1651 # CDN and file cache for the description page are purged by doEditContent.
1652 $status = $wikiPage->doEditContent(
1655 EDIT_NEW | EDIT_SUPPRESS_RC
,
1660 if ( isset( $status->value
['revision'] ) ) {
1661 /** @var Revision $rev */
1662 $rev = $status->value
['revision'];
1663 // Associate new page revision id
1664 $logEntry->setAssociatedRevId( $rev->getId() );
1666 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1667 // which is triggered on $descTitle by doEditContent() above.
1668 if ( isset( $status->value
['revision'] ) ) {
1669 /** @var Revision $rev */
1670 $rev = $status->value
['revision'];
1671 $updateLogPage = $rev->getPage();
1674 # Existing file page: invalidate description page cache
1675 $wikiPage->getTitle()->invalidateCache();
1676 $wikiPage->getTitle()->purgeSquid();
1677 # Allow the new file version to be patrolled from the page footer
1678 Article
::purgePatrolFooterCache( $descId );
1681 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1682 # but setAssociatedRevId() wasn't called at that point yet...
1683 $logParams = $logEntry->getParameters();
1684 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1685 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1686 if ( $updateLogPage ) {
1687 # Also log page, in case where we just created it above
1688 $update['log_page'] = $updateLogPage;
1690 $this->getRepo()->getMasterDB()->update(
1693 [ 'log_id' => $logId ],
1696 $this->getRepo()->getMasterDB()->insert(
1699 'ls_field' => 'associated_rev_id',
1700 'ls_value' => $logEntry->getAssociatedRevId(),
1701 'ls_log_id' => $logId,
1706 # Add change tags, if any
1708 $logEntry->setTags( $tags );
1711 # Uploads can be patrolled
1712 $logEntry->setIsPatrollable( true );
1714 # Now that the log entry is up-to-date, make an RC entry.
1715 $logEntry->publish( $logId );
1717 # Run hook for other updates (typically more cache purging)
1718 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1721 # Delete old thumbnails
1722 $this->purgeThumbnails();
1723 # Remove the old file from the CDN cache
1724 DeferredUpdates
::addUpdate(
1725 new CdnCacheUpdate( [ $this->getUrl() ] ),
1726 DeferredUpdates
::PRESEND
1729 # Update backlink pages pointing to this title if created
1730 LinksUpdate
::queueRecursiveJobsForTable(
1738 $this->prerenderThumbnails();
1741 DeferredUpdates
::PRESEND
1745 # This is a new file, so update the image count
1746 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1749 # Invalidate cache for all pages using this file
1750 DeferredUpdates
::addUpdate(
1751 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1754 return Status
::newGood();
1758 * Move or copy a file to its public location. If a file exists at the
1759 * destination, move it to an archive. Returns a Status object with
1760 * the archive name in the "value" member on success.
1762 * The archive name should be passed through to recordUpload for database
1765 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1766 * @param int $flags A bitwise combination of:
1767 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1768 * @param array $options Optional additional parameters
1769 * @return Status On success, the value member contains the
1770 * archive name, or an empty string if it was a new file.
1772 function publish( $src, $flags = 0, array $options = [] ) {
1773 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1777 * Move or copy a file to a specified location. Returns a Status
1778 * object with the archive name in the "value" member on success.
1780 * The archive name should be passed through to recordUpload for database
1783 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1784 * @param string $dstRel Target relative path
1785 * @param int $flags A bitwise combination of:
1786 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1787 * @param array $options Optional additional parameters
1788 * @return Status On success, the value member contains the
1789 * archive name, or an empty string if it was a new file.
1791 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1792 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1794 $repo = $this->getRepo();
1795 if ( $repo->getReadOnlyReason() !== false ) {
1796 return $this->readOnlyFatalStatus();
1799 $this->lock(); // begin
1801 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1802 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1804 if ( $repo->hasSha1Storage() ) {
1805 $sha1 = $repo->isVirtualUrl( $srcPath )
1806 ?
$repo->getFileSha1( $srcPath )
1807 : FSFile
::getSha1Base36FromPath( $srcPath );
1808 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1809 $wrapperBackend = $repo->getBackend();
1810 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1811 $status = $repo->quickImport( $src, $dst );
1812 if ( $flags & File
::DELETE_SOURCE
) {
1816 if ( $this->exists() ) {
1817 $status->value
= $archiveName;
1820 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1821 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1823 if ( $status->value
== 'new' ) {
1824 $status->value
= '';
1826 $status->value
= $archiveName;
1830 $this->unlock(); // done
1835 /** getLinksTo inherited */
1836 /** getExifData inherited */
1837 /** isLocal inherited */
1838 /** wasDeleted inherited */
1841 * Move file to the new title
1843 * Move current, old version and all thumbnails
1844 * to the new filename. Old file is deleted.
1846 * Cache purging is done; checks for validity
1847 * and logging are caller's responsibility
1849 * @param Title $target New file name
1852 function move( $target ) {
1853 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1854 return $this->readOnlyFatalStatus();
1857 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1858 $batch = new LocalFileMoveBatch( $this, $target );
1860 $this->lock(); // begin
1861 $batch->addCurrent();
1862 $archiveNames = $batch->addOlds();
1863 $status = $batch->execute();
1864 $this->unlock(); // done
1866 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1868 // Purge the source and target files...
1869 $oldTitleFile = wfLocalFile( $this->title
);
1870 $newTitleFile = wfLocalFile( $target );
1871 // To avoid slow purges in the transaction, move them outside...
1872 DeferredUpdates
::addUpdate(
1873 new AutoCommitUpdate(
1874 $this->getRepo()->getMasterDB(),
1876 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1877 $oldTitleFile->purgeEverything();
1878 foreach ( $archiveNames as $archiveName ) {
1879 $oldTitleFile->purgeOldThumbnails( $archiveName );
1881 $newTitleFile->purgeEverything();
1884 DeferredUpdates
::PRESEND
1887 if ( $status->isOK() ) {
1888 // Now switch the object
1889 $this->title
= $target;
1890 // Force regeneration of the name and hashpath
1891 unset( $this->name
);
1892 unset( $this->hashPath
);
1899 * Delete all versions of the file.
1901 * Moves the files into an archive directory (or deletes them)
1902 * and removes the database rows.
1904 * Cache purging is done; logging is caller's responsibility.
1906 * @param string $reason
1907 * @param bool $suppress
1908 * @param User|null $user
1911 function delete( $reason, $suppress = false, $user = null ) {
1912 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1913 return $this->readOnlyFatalStatus();
1916 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1918 $this->lock(); // begin
1919 $batch->addCurrent();
1920 // Get old version relative paths
1921 $archiveNames = $batch->addOlds();
1922 $status = $batch->execute();
1923 $this->unlock(); // done
1925 if ( $status->isOK() ) {
1926 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1929 // To avoid slow purges in the transaction, move them outside...
1930 DeferredUpdates
::addUpdate(
1931 new AutoCommitUpdate(
1932 $this->getRepo()->getMasterDB(),
1934 function () use ( $archiveNames ) {
1935 $this->purgeEverything();
1936 foreach ( $archiveNames as $archiveName ) {
1937 $this->purgeOldThumbnails( $archiveName );
1941 DeferredUpdates
::PRESEND
1946 foreach ( $archiveNames as $archiveName ) {
1947 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1949 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1955 * Delete an old version of the file.
1957 * Moves the file into an archive directory (or deletes it)
1958 * and removes the database row.
1960 * Cache purging is done; logging is caller's responsibility.
1962 * @param string $archiveName
1963 * @param string $reason
1964 * @param bool $suppress
1965 * @param User|null $user
1966 * @throws MWException Exception on database or file store failure
1969 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1970 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1971 return $this->readOnlyFatalStatus();
1974 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1976 $this->lock(); // begin
1977 $batch->addOld( $archiveName );
1978 $status = $batch->execute();
1979 $this->unlock(); // done
1981 $this->purgeOldThumbnails( $archiveName );
1982 if ( $status->isOK() ) {
1983 $this->purgeDescription();
1986 DeferredUpdates
::addUpdate(
1987 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1988 DeferredUpdates
::PRESEND
1995 * Restore all or specified deleted revisions to the given file.
1996 * Permissions and logging are left to the caller.
1998 * May throw database exceptions on error.
2000 * @param array $versions Set of record ids of deleted items to restore,
2001 * or empty to restore all revisions.
2002 * @param bool $unsuppress
2005 function restore( $versions = [], $unsuppress = false ) {
2006 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2007 return $this->readOnlyFatalStatus();
2010 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2012 $this->lock(); // begin
2016 $batch->addIds( $versions );
2018 $status = $batch->execute();
2019 if ( $status->isGood() ) {
2020 $cleanupStatus = $batch->cleanup();
2021 $cleanupStatus->successCount
= 0;
2022 $cleanupStatus->failCount
= 0;
2023 $status->merge( $cleanupStatus );
2025 $this->unlock(); // done
2030 /** isMultipage inherited */
2031 /** pageCount inherited */
2032 /** scaleHeight inherited */
2033 /** getImageSize inherited */
2036 * Get the URL of the file description page.
2039 function getDescriptionUrl() {
2040 return $this->title
->getLocalURL();
2044 * Get the HTML text of the description page
2045 * This is not used by ImagePage for local files, since (among other things)
2046 * it skips the parser cache.
2048 * @param Language $lang What language to get description in (Optional)
2049 * @return bool|mixed
2051 function getDescriptionText( $lang = null ) {
2052 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
2056 $content = $revision->getContent();
2060 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
2062 return $pout->getText();
2066 * @param int $audience
2070 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2072 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2074 } elseif ( $audience == self
::FOR_THIS_USER
2075 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2079 return $this->description
;
2084 * @return bool|string
2086 function getTimestamp() {
2089 return $this->timestamp
;
2093 * @return bool|string
2095 public function getDescriptionTouched() {
2096 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2097 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2098 // need to differentiate between null (uninitialized) and false (failed to load).
2099 if ( $this->descriptionTouched
=== null ) {
2101 'page_namespace' => $this->title
->getNamespace(),
2102 'page_title' => $this->title
->getDBkey()
2104 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2105 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2108 return $this->descriptionTouched
;
2114 function getSha1() {
2116 // Initialise now if necessary
2117 if ( $this->sha1
== '' && $this->fileExists
) {
2118 $this->lock(); // begin
2120 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2121 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2122 $dbw = $this->repo
->getMasterDB();
2123 $dbw->update( 'image',
2124 [ 'img_sha1' => $this->sha1
],
2125 [ 'img_name' => $this->getName() ],
2127 $this->invalidateCache();
2130 $this->unlock(); // done
2137 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2139 function isCacheable() {
2142 // If extra data (metadata) was not loaded then it must have been large
2143 return $this->extraDataLoaded
2144 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2151 public function acquireFileLock() {
2152 return $this->getRepo()->getBackend()->lockFiles(
2153 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2161 public function releaseFileLock() {
2162 return $this->getRepo()->getBackend()->unlockFiles(
2163 [ $this->getPath() ], LockManager
::LOCK_EX
2168 * Start an atomic DB section and lock the image for update
2169 * or increments a reference counter if the lock is already held
2171 * This method should not be used outside of LocalFile/LocalFile*Batch
2173 * @throws LocalFileLockError Throws an error if the lock was not acquired
2174 * @return bool Whether the file lock owns/spawned the DB transaction
2176 public function lock() {
2177 if ( !$this->locked
) {
2178 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2180 $dbw = $this->repo
->getMasterDB();
2181 $makesTransaction = !$dbw->trxLevel();
2182 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2183 // T56736: use simple lock to handle when the file does not exist.
2184 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2185 // Also, that would cause contention on INSERT of similarly named rows.
2186 $status = $this->acquireFileLock(); // represents all versions of the file
2187 if ( !$status->isGood() ) {
2188 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2189 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2191 throw new LocalFileLockError( $status );
2193 // Release the lock *after* commit to avoid row-level contention.
2194 // Make sure it triggers on rollback() as well as commit() (T132921).
2195 $dbw->onTransactionResolution(
2196 function () use ( $logger ) {
2197 $status = $this->releaseFileLock();
2198 if ( !$status->isGood() ) {
2199 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2204 // Callers might care if the SELECT snapshot is safely fresh
2205 $this->lockedOwnTrx
= $makesTransaction;
2210 return $this->lockedOwnTrx
;
2214 * Decrement the lock reference count and end the atomic section if it reaches zero
2216 * This method should not be used outside of LocalFile/LocalFile*Batch
2218 * The commit and loc release will happen when no atomic sections are active, which
2219 * may happen immediately or at some point after calling this
2221 public function unlock() {
2222 if ( $this->locked
) {
2224 if ( !$this->locked
) {
2225 $dbw = $this->repo
->getMasterDB();
2226 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2227 $this->lockedOwnTrx
= false;
2235 protected function readOnlyFatalStatus() {
2236 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2237 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2241 * Clean up any dangling locks
2243 function __destruct() {
2246 } // LocalFile class
2248 # ------------------------------------------------------------------------------
2251 * Helper class for file deletion
2252 * @ingroup FileAbstraction
2254 class LocalFileDeleteBatch
{
2255 /** @var LocalFile */
2262 private $srcRels = [];
2265 private $archiveUrls = [];
2267 /** @var array Items to be processed in the deletion batch */
2268 private $deletionBatch;
2270 /** @var bool Whether to suppress all suppressable fields when deleting */
2281 * @param string $reason
2282 * @param bool $suppress
2283 * @param User|null $user
2285 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2286 $this->file
= $file;
2287 $this->reason
= $reason;
2288 $this->suppress
= $suppress;
2290 $this->user
= $user;
2293 $this->user
= $wgUser;
2295 $this->status
= $file->repo
->newGood();
2298 public function addCurrent() {
2299 $this->srcRels
['.'] = $this->file
->getRel();
2303 * @param string $oldName
2305 public function addOld( $oldName ) {
2306 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2307 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2311 * Add the old versions of the image to the batch
2312 * @return array List of archive names from old versions
2314 public function addOlds() {
2317 $dbw = $this->file
->repo
->getMasterDB();
2318 $result = $dbw->select( 'oldimage',
2319 [ 'oi_archive_name' ],
2320 [ 'oi_name' => $this->file
->getName() ],
2324 foreach ( $result as $row ) {
2325 $this->addOld( $row->oi_archive_name
);
2326 $archiveNames[] = $row->oi_archive_name
;
2329 return $archiveNames;
2335 protected function getOldRels() {
2336 if ( !isset( $this->srcRels
['.'] ) ) {
2337 $oldRels =& $this->srcRels
;
2338 $deleteCurrent = false;
2340 $oldRels = $this->srcRels
;
2341 unset( $oldRels['.'] );
2342 $deleteCurrent = true;
2345 return [ $oldRels, $deleteCurrent ];
2351 protected function getHashes() {
2353 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2355 if ( $deleteCurrent ) {
2356 $hashes['.'] = $this->file
->getSha1();
2359 if ( count( $oldRels ) ) {
2360 $dbw = $this->file
->repo
->getMasterDB();
2361 $res = $dbw->select(
2363 [ 'oi_archive_name', 'oi_sha1' ],
2364 [ 'oi_archive_name' => array_keys( $oldRels ),
2365 'oi_name' => $this->file
->getName() ], // performance
2369 foreach ( $res as $row ) {
2370 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2371 // Get the hash from the file
2372 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2373 $props = $this->file
->repo
->getFileProps( $oldUrl );
2375 if ( $props['fileExists'] ) {
2376 // Upgrade the oldimage row
2377 $dbw->update( 'oldimage',
2378 [ 'oi_sha1' => $props['sha1'] ],
2379 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2381 $hashes[$row->oi_archive_name
] = $props['sha1'];
2383 $hashes[$row->oi_archive_name
] = false;
2386 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2391 $missing = array_diff_key( $this->srcRels
, $hashes );
2393 foreach ( $missing as $name => $rel ) {
2394 $this->status
->error( 'filedelete-old-unregistered', $name );
2397 foreach ( $hashes as $name => $hash ) {
2399 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2400 unset( $hashes[$name] );
2407 protected function doDBInserts() {
2408 global $wgCommentTableSchemaMigrationStage;
2411 $dbw = $this->file
->repo
->getMasterDB();
2413 $commentStore = CommentStore
::getStore();
2415 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2416 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2417 $encGroup = $dbw->addQuotes( 'deleted' );
2418 $ext = $this->file
->getExtension();
2419 $dotExt = $ext === '' ?
'' : ".$ext";
2420 $encExt = $dbw->addQuotes( $dotExt );
2421 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2423 // Bitfields to further suppress the content
2424 if ( $this->suppress
) {
2425 $bitfield = Revision
::SUPPRESSED_ALL
;
2427 $bitfield = 'oi_deleted';
2430 if ( $deleteCurrent ) {
2431 $tables = [ 'image' ];
2433 'fa_storage_group' => $encGroup,
2434 'fa_storage_key' => $dbw->conditional(
2435 [ 'img_sha1' => '' ],
2436 $dbw->addQuotes( '' ),
2437 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2439 'fa_deleted_user' => $encUserId,
2440 'fa_deleted_timestamp' => $encTimestamp,
2441 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2442 'fa_name' => 'img_name',
2443 'fa_archive_name' => 'NULL',
2444 'fa_size' => 'img_size',
2445 'fa_width' => 'img_width',
2446 'fa_height' => 'img_height',
2447 'fa_metadata' => 'img_metadata',
2448 'fa_bits' => 'img_bits',
2449 'fa_media_type' => 'img_media_type',
2450 'fa_major_mime' => 'img_major_mime',
2451 'fa_minor_mime' => 'img_minor_mime',
2452 'fa_user' => 'img_user',
2453 'fa_user_text' => 'img_user_text',
2454 'fa_timestamp' => 'img_timestamp',
2455 'fa_sha1' => 'img_sha1'
2459 $fields +
= array_map(
2460 [ $dbw, 'addQuotes' ],
2461 $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason
)
2464 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2465 $fields['fa_description'] = 'img_description';
2467 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2468 $tables[] = 'image_comment_temp';
2469 $fields['fa_description_id'] = 'imgcomment_description_id';
2470 $joins['image_comment_temp'] = [
2471 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
2472 [ 'imgcomment_name = img_name' ]
2476 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
2477 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2479 // Upgrade any rows that are still old-style. Otherwise an upgrade
2480 // might be missed if a deletion happens while the migration script
2482 $res = $dbw->select(
2483 [ 'image', 'image_comment_temp' ],
2484 [ 'img_name', 'img_description' ],
2485 [ 'img_name' => $this->file
->getName(), 'imgcomment_name' => null ],
2488 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2490 foreach ( $res as $row ) {
2491 list( , $callback ) = $commentStore->insertWithTempTable(
2492 $dbw, 'img_description', $row->img_description
2494 $callback( $row->img_name
);
2498 $dbw->insertSelect( 'filearchive', $tables, $fields,
2499 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2502 if ( count( $oldRels ) ) {
2503 $fileQuery = OldLocalFile
::getQueryInfo();
2504 $res = $dbw->select(
2505 $fileQuery['tables'],
2506 $fileQuery['fields'],
2508 'oi_name' => $this->file
->getName(),
2509 'oi_archive_name' => array_keys( $oldRels )
2516 if ( $res->numRows() ) {
2517 $reason = $commentStore->createComment( $dbw, $this->reason
);
2518 foreach ( $res as $row ) {
2519 $comment = $commentStore->getComment( 'oi_description', $row );
2521 // Deletion-specific fields
2522 'fa_storage_group' => 'deleted',
2523 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2525 : "{$row->oi_sha1}{$dotExt}",
2526 'fa_deleted_user' => $this->user
->getId(),
2527 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2528 // Counterpart fields
2529 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2530 'fa_name' => $row->oi_name
,
2531 'fa_archive_name' => $row->oi_archive_name
,
2532 'fa_size' => $row->oi_size
,
2533 'fa_width' => $row->oi_width
,
2534 'fa_height' => $row->oi_height
,
2535 'fa_metadata' => $row->oi_metadata
,
2536 'fa_bits' => $row->oi_bits
,
2537 'fa_media_type' => $row->oi_media_type
,
2538 'fa_major_mime' => $row->oi_major_mime
,
2539 'fa_minor_mime' => $row->oi_minor_mime
,
2540 'fa_user' => $row->oi_user
,
2541 'fa_user_text' => $row->oi_user_text
,
2542 'fa_timestamp' => $row->oi_timestamp
,
2543 'fa_sha1' => $row->oi_sha1
2544 ] +
$commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2545 +
$commentStore->insert( $dbw, 'fa_description', $comment );
2549 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2553 function doDBDeletes() {
2554 global $wgCommentTableSchemaMigrationStage;
2556 $dbw = $this->file
->repo
->getMasterDB();
2557 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2559 if ( count( $oldRels ) ) {
2560 $dbw->delete( 'oldimage',
2562 'oi_name' => $this->file
->getName(),
2563 'oi_archive_name' => array_keys( $oldRels )
2567 if ( $deleteCurrent ) {
2568 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2569 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2571 'image_comment_temp', [ 'imgcomment_name' => $this->file
->getName() ], __METHOD__
2578 * Run the transaction
2581 public function execute() {
2582 $repo = $this->file
->getRepo();
2583 $this->file
->lock();
2585 // Prepare deletion batch
2586 $hashes = $this->getHashes();
2587 $this->deletionBatch
= [];
2588 $ext = $this->file
->getExtension();
2589 $dotExt = $ext === '' ?
'' : ".$ext";
2591 foreach ( $this->srcRels
as $name => $srcRel ) {
2592 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2593 if ( isset( $hashes[$name] ) ) {
2594 $hash = $hashes[$name];
2595 $key = $hash . $dotExt;
2596 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2597 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2601 if ( !$repo->hasSha1Storage() ) {
2602 // Removes non-existent file from the batch, so we don't get errors.
2603 // This also handles files in the 'deleted' zone deleted via revision deletion.
2604 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2605 if ( !$checkStatus->isGood() ) {
2606 $this->status
->merge( $checkStatus );
2607 return $this->status
;
2609 $this->deletionBatch
= $checkStatus->value
;
2611 // Execute the file deletion batch
2612 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2613 if ( !$status->isGood() ) {
2614 $this->status
->merge( $status );
2618 if ( !$this->status
->isOK() ) {
2619 // Critical file deletion error; abort
2620 $this->file
->unlock();
2622 return $this->status
;
2625 // Copy the image/oldimage rows to filearchive
2626 $this->doDBInserts();
2627 // Delete image/oldimage rows
2628 $this->doDBDeletes();
2630 // Commit and return
2631 $this->file
->unlock();
2633 return $this->status
;
2637 * Removes non-existent files from a deletion batch.
2638 * @param array $batch
2641 protected function removeNonexistentFiles( $batch ) {
2642 $files = $newBatch = [];
2644 foreach ( $batch as $batchItem ) {
2645 list( $src, ) = $batchItem;
2646 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2649 $result = $this->file
->repo
->fileExistsBatch( $files );
2650 if ( in_array( null, $result, true ) ) {
2651 return Status
::newFatal( 'backend-fail-internal',
2652 $this->file
->repo
->getBackend()->getName() );
2655 foreach ( $batch as $batchItem ) {
2656 if ( $result[$batchItem[0]] ) {
2657 $newBatch[] = $batchItem;
2661 return Status
::newGood( $newBatch );
2665 # ------------------------------------------------------------------------------
2668 * Helper class for file undeletion
2669 * @ingroup FileAbstraction
2671 class LocalFileRestoreBatch
{
2672 /** @var LocalFile */
2675 /** @var array List of file IDs to restore */
2676 private $cleanupBatch;
2678 /** @var array List of file IDs to restore */
2681 /** @var bool Add all revisions of the file */
2684 /** @var bool Whether to remove all settings for suppressed fields */
2685 private $unsuppress = false;
2689 * @param bool $unsuppress
2691 function __construct( File
$file, $unsuppress = false ) {
2692 $this->file
= $file;
2693 $this->cleanupBatch
= $this->ids
= [];
2695 $this->unsuppress
= $unsuppress;
2702 public function addId( $fa_id ) {
2703 $this->ids
[] = $fa_id;
2707 * Add a whole lot of files by ID
2710 public function addIds( $ids ) {
2711 $this->ids
= array_merge( $this->ids
, $ids );
2715 * Add all revisions of the file
2717 public function addAll() {
2722 * Run the transaction, except the cleanup batch.
2723 * The cleanup batch should be run in a separate transaction, because it locks different
2724 * rows and there's no need to keep the image row locked while it's acquiring those locks
2725 * The caller may have its own transaction open.
2726 * So we save the batch and let the caller call cleanup()
2729 public function execute() {
2730 /** @var Language */
2733 $repo = $this->file
->getRepo();
2734 if ( !$this->all
&& !$this->ids
) {
2736 return $repo->newGood();
2739 $lockOwnsTrx = $this->file
->lock();
2741 $dbw = $this->file
->repo
->getMasterDB();
2743 $commentStore = CommentStore
::getStore();
2745 $status = $this->file
->repo
->newGood();
2747 $exists = (bool)$dbw->selectField( 'image', '1',
2748 [ 'img_name' => $this->file
->getName() ],
2750 // The lock() should already prevents changes, but this still may need
2751 // to bypass any transaction snapshot. However, if lock() started the
2752 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2753 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2756 // Fetch all or selected archived revisions for the file,
2757 // sorted from the most recent to the oldest.
2758 $conditions = [ 'fa_name' => $this->file
->getName() ];
2760 if ( !$this->all
) {
2761 $conditions['fa_id'] = $this->ids
;
2764 $arFileQuery = ArchivedFile
::getQueryInfo();
2765 $result = $dbw->select(
2766 $arFileQuery['tables'],
2767 $arFileQuery['fields'],
2770 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2771 $arFileQuery['joins']
2777 $insertCurrent = false;
2782 foreach ( $result as $row ) {
2783 $idsPresent[] = $row->fa_id
;
2785 if ( $row->fa_name
!= $this->file
->getName() ) {
2786 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2787 $status->failCount++
;
2791 if ( $row->fa_storage_key
== '' ) {
2792 // Revision was missing pre-deletion
2793 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2794 $status->failCount++
;
2798 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2799 $row->fa_storage_key
;
2800 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2802 if ( isset( $row->fa_sha1
) ) {
2803 $sha1 = $row->fa_sha1
;
2805 // old row, populate from key
2806 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2810 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2811 $sha1 = substr( $sha1, 1 );
2814 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2815 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2816 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2817 ||
is_null( $row->fa_metadata
)
2819 // Refresh our metadata
2820 // Required for a new current revision; nice for older ones too. :)
2821 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2824 'minor_mime' => $row->fa_minor_mime
,
2825 'major_mime' => $row->fa_major_mime
,
2826 'media_type' => $row->fa_media_type
,
2827 'metadata' => $row->fa_metadata
2831 $comment = $commentStore->getComment( 'fa_description', $row );
2832 if ( $first && !$exists ) {
2833 // This revision will be published as the new current version
2834 $destRel = $this->file
->getRel();
2835 list( $commentFields, $commentCallback ) =
2836 $commentStore->insertWithTempTable( $dbw, 'img_description', $comment );
2838 'img_name' => $row->fa_name
,
2839 'img_size' => $row->fa_size
,
2840 'img_width' => $row->fa_width
,
2841 'img_height' => $row->fa_height
,
2842 'img_metadata' => $props['metadata'],
2843 'img_bits' => $row->fa_bits
,
2844 'img_media_type' => $props['media_type'],
2845 'img_major_mime' => $props['major_mime'],
2846 'img_minor_mime' => $props['minor_mime'],
2847 'img_user' => $row->fa_user
,
2848 'img_user_text' => $row->fa_user_text
,
2849 'img_timestamp' => $row->fa_timestamp
,
2853 // The live (current) version cannot be hidden!
2854 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2855 $status->fatal( 'undeleterevdel' );
2856 $this->file
->unlock();
2860 $archiveName = $row->fa_archive_name
;
2862 if ( $archiveName == '' ) {
2863 // This was originally a current version; we
2864 // have to devise a new archive name for it.
2865 // Format is <timestamp of archiving>!<name>
2866 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2869 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2871 } while ( isset( $archiveNames[$archiveName] ) );
2874 $archiveNames[$archiveName] = true;
2875 $destRel = $this->file
->getArchiveRel( $archiveName );
2877 'oi_name' => $row->fa_name
,
2878 'oi_archive_name' => $archiveName,
2879 'oi_size' => $row->fa_size
,
2880 'oi_width' => $row->fa_width
,
2881 'oi_height' => $row->fa_height
,
2882 'oi_bits' => $row->fa_bits
,
2883 'oi_user' => $row->fa_user
,
2884 'oi_user_text' => $row->fa_user_text
,
2885 'oi_timestamp' => $row->fa_timestamp
,
2886 'oi_metadata' => $props['metadata'],
2887 'oi_media_type' => $props['media_type'],
2888 'oi_major_mime' => $props['major_mime'],
2889 'oi_minor_mime' => $props['minor_mime'],
2890 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2892 ] +
$commentStore->insert( $dbw, 'oi_description', $comment );
2895 $deleteIds[] = $row->fa_id
;
2897 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2898 // private files can stay where they are
2899 $status->successCount++
;
2901 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2902 $this->cleanupBatch
[] = $row->fa_storage_key
;
2910 // Add a warning to the status object for missing IDs
2911 $missingIds = array_diff( $this->ids
, $idsPresent );
2913 foreach ( $missingIds as $id ) {
2914 $status->error( 'undelete-missing-filearchive', $id );
2917 if ( !$repo->hasSha1Storage() ) {
2918 // Remove missing files from batch, so we don't get errors when undeleting them
2919 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2920 if ( !$checkStatus->isGood() ) {
2921 $status->merge( $checkStatus );
2924 $storeBatch = $checkStatus->value
;
2926 // Run the store batch
2927 // Use the OVERWRITE_SAME flag to smooth over a common error
2928 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2929 $status->merge( $storeStatus );
2931 if ( !$status->isGood() ) {
2932 // Even if some files could be copied, fail entirely as that is the
2933 // easiest thing to do without data loss
2934 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2935 $status->setOK( false );
2936 $this->file
->unlock();
2942 // Run the DB updates
2943 // Because we have locked the image row, key conflicts should be rare.
2944 // If they do occur, we can roll back the transaction at this time with
2945 // no data loss, but leaving unregistered files scattered throughout the
2947 // This is not ideal, which is why it's important to lock the image row.
2948 if ( $insertCurrent ) {
2949 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2950 $commentCallback( $insertCurrent['img_name'] );
2953 if ( $insertBatch ) {
2954 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2958 $dbw->delete( 'filearchive',
2959 [ 'fa_id' => $deleteIds ],
2963 // If store batch is empty (all files are missing), deletion is to be considered successful
2964 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2966 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2968 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2970 $this->file
->purgeEverything();
2972 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2973 $this->file
->purgeDescription();
2977 $this->file
->unlock();
2983 * Removes non-existent files from a store batch.
2984 * @param array $triplets
2987 protected function removeNonexistentFiles( $triplets ) {
2988 $files = $filteredTriplets = [];
2989 foreach ( $triplets as $file ) {
2990 $files[$file[0]] = $file[0];
2993 $result = $this->file
->repo
->fileExistsBatch( $files );
2994 if ( in_array( null, $result, true ) ) {
2995 return Status
::newFatal( 'backend-fail-internal',
2996 $this->file
->repo
->getBackend()->getName() );
2999 foreach ( $triplets as $file ) {
3000 if ( $result[$file[0]] ) {
3001 $filteredTriplets[] = $file;
3005 return Status
::newGood( $filteredTriplets );
3009 * Removes non-existent files from a cleanup batch.
3010 * @param array $batch
3013 protected function removeNonexistentFromCleanup( $batch ) {
3014 $files = $newBatch = [];
3015 $repo = $this->file
->repo
;
3017 foreach ( $batch as $file ) {
3018 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3019 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3022 $result = $repo->fileExistsBatch( $files );
3024 foreach ( $batch as $file ) {
3025 if ( $result[$file] ) {
3026 $newBatch[] = $file;
3034 * Delete unused files in the deleted zone.
3035 * This should be called from outside the transaction in which execute() was called.
3038 public function cleanup() {
3039 if ( !$this->cleanupBatch
) {
3040 return $this->file
->repo
->newGood();
3043 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
3045 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
3051 * Cleanup a failed batch. The batch was only partially successful, so
3052 * rollback by removing all items that were succesfully copied.
3054 * @param Status $storeStatus
3055 * @param array $storeBatch
3057 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3060 foreach ( $storeStatus->success
as $i => $success ) {
3061 // Check if this item of the batch was successfully copied
3063 // Item was successfully copied and needs to be removed again
3064 // Extract ($dstZone, $dstRel) from the batch
3065 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3068 $this->file
->repo
->cleanupBatch( $cleanupBatch );
3072 # ------------------------------------------------------------------------------
3075 * Helper class for file movement
3076 * @ingroup FileAbstraction
3078 class LocalFileMoveBatch
{
3079 /** @var LocalFile */
3089 protected $oldCount;
3093 /** @var IDatabase */
3098 * @param Title $target
3100 function __construct( File
$file, Title
$target ) {
3101 $this->file
= $file;
3102 $this->target
= $target;
3103 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
3104 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
3105 $this->oldName
= $this->file
->getName();
3106 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
3107 $this->oldRel
= $this->oldHash
. $this->oldName
;
3108 $this->newRel
= $this->newHash
. $this->newName
;
3109 $this->db
= $file->getRepo()->getMasterDB();
3113 * Add the current image to the batch
3115 public function addCurrent() {
3116 $this->cur
= [ $this->oldRel
, $this->newRel
];
3120 * Add the old versions of the image to the batch
3121 * @return array List of archive names from old versions
3123 public function addOlds() {
3124 $archiveBase = 'archive';
3126 $this->oldCount
= 0;
3129 $result = $this->db
->select( 'oldimage',
3130 [ 'oi_archive_name', 'oi_deleted' ],
3131 [ 'oi_name' => $this->oldName
],
3133 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3136 foreach ( $result as $row ) {
3137 $archiveNames[] = $row->oi_archive_name
;
3138 $oldName = $row->oi_archive_name
;
3139 $bits = explode( '!', $oldName, 2 );
3141 if ( count( $bits ) != 2 ) {
3142 wfDebug( "Old file name missing !: '$oldName' \n" );
3146 list( $timestamp, $filename ) = $bits;
3148 if ( $this->oldName
!= $filename ) {
3149 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3155 // Do we want to add those to oldCount?
3156 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3161 "{$archiveBase}/{$this->oldHash}{$oldName}",
3162 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3166 return $archiveNames;
3173 public function execute() {
3174 $repo = $this->file
->repo
;
3175 $status = $repo->newGood();
3176 $destFile = wfLocalFile( $this->target
);
3178 $this->file
->lock(); // begin
3179 $destFile->lock(); // quickly fail if destination is not available
3181 $triplets = $this->getMoveTriplets();
3182 $checkStatus = $this->removeNonexistentFiles( $triplets );
3183 if ( !$checkStatus->isGood() ) {
3184 $destFile->unlock();
3185 $this->file
->unlock();
3186 $status->merge( $checkStatus ); // couldn't talk to file backend
3189 $triplets = $checkStatus->value
;
3191 // Verify the file versions metadata in the DB.
3192 $statusDb = $this->verifyDBUpdates();
3193 if ( !$statusDb->isGood() ) {
3194 $destFile->unlock();
3195 $this->file
->unlock();
3196 $statusDb->setOK( false );
3201 if ( !$repo->hasSha1Storage() ) {
3202 // Copy the files into their new location.
3203 // If a prior process fataled copying or cleaning up files we tolerate any
3204 // of the existing files if they are identical to the ones being stored.
3205 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3206 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3207 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3208 if ( !$statusMove->isGood() ) {
3209 // Delete any files copied over (while the destination is still locked)
3210 $this->cleanupTarget( $triplets );
3211 $destFile->unlock();
3212 $this->file
->unlock();
3213 wfDebugLog( 'imagemove', "Error in moving files: "
3214 . $statusMove->getWikiText( false, false, 'en' ) );
3215 $statusMove->setOK( false );
3219 $status->merge( $statusMove );
3222 // Rename the file versions metadata in the DB.
3223 $this->doDBUpdates();
3225 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3226 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3228 $destFile->unlock();
3229 $this->file
->unlock(); // done
3231 // Everything went ok, remove the source files
3232 $this->cleanupSource( $triplets );
3234 $status->merge( $statusDb );
3240 * Verify the database updates and return a new Status indicating how
3241 * many rows would be updated.
3245 protected function verifyDBUpdates() {
3246 $repo = $this->file
->repo
;
3247 $status = $repo->newGood();
3250 $hasCurrent = $dbw->selectField(
3253 [ 'img_name' => $this->oldName
],
3257 $oldRowCount = $dbw->selectField(
3260 [ 'oi_name' => $this->oldName
],
3265 if ( $hasCurrent ) {
3266 $status->successCount++
;
3268 $status->failCount++
;
3270 $status->successCount +
= $oldRowCount;
3271 // T36934: oldCount is based on files that actually exist.
3272 // There may be more DB rows than such files, in which case $affected
3273 // can be greater than $total. We use max() to avoid negatives here.
3274 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3275 if ( $status->failCount
) {
3276 $status->error( 'imageinvalidfilename' );
3283 * Do the database updates and return a new Status indicating how
3284 * many rows where updated.
3286 protected function doDBUpdates() {
3289 // Update current image
3292 [ 'img_name' => $this->newName
],
3293 [ 'img_name' => $this->oldName
],
3296 // Update old images
3300 'oi_name' => $this->newName
,
3301 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3302 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3304 [ 'oi_name' => $this->oldName
],
3310 * Generate triplets for FileRepo::storeBatch().
3313 protected function getMoveTriplets() {
3314 $moves = array_merge( [ $this->cur
], $this->olds
);
3315 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3317 foreach ( $moves as $move ) {
3318 // $move: (oldRelativePath, newRelativePath)
3319 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3320 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3323 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3331 * Removes non-existent files from move batch.
3332 * @param array $triplets
3335 protected function removeNonexistentFiles( $triplets ) {
3338 foreach ( $triplets as $file ) {
3339 $files[$file[0]] = $file[0];
3342 $result = $this->file
->repo
->fileExistsBatch( $files );
3343 if ( in_array( null, $result, true ) ) {
3344 return Status
::newFatal( 'backend-fail-internal',
3345 $this->file
->repo
->getBackend()->getName() );
3348 $filteredTriplets = [];
3349 foreach ( $triplets as $file ) {
3350 if ( $result[$file[0]] ) {
3351 $filteredTriplets[] = $file;
3353 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3357 return Status
::newGood( $filteredTriplets );
3361 * Cleanup a partially moved array of triplets by deleting the target
3362 * files. Called if something went wrong half way.
3363 * @param array $triplets
3365 protected function cleanupTarget( $triplets ) {
3366 // Create dest pairs from the triplets
3368 foreach ( $triplets as $triplet ) {
3369 // $triplet: (old source virtual URL, dst zone, dest rel)
3370 $pairs[] = [ $triplet[1], $triplet[2] ];
3373 $this->file
->repo
->cleanupBatch( $pairs );
3377 * Cleanup a fully moved array of triplets by deleting the source files.
3378 * Called at the end of the move process if everything else went ok.
3379 * @param array $triplets
3381 protected function cleanupSource( $triplets ) {
3382 // Create source file names from the triplets
3384 foreach ( $triplets as $triplet ) {
3385 $files[] = $triplet[0];
3388 $this->file
->repo
->cleanupBatch( $files );
3392 class LocalFileLockError
extends ErrorPageError
{
3393 public function __construct( Status
$status ) {
3394 parent
::__construct(
3396 $status->getMessage()
3400 public function report() {
3402 $wgOut->setStatusCode( 429 );