3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use MediaWiki\Logger\LoggerFactory
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\MediaWikiServices
;
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const VERSION
= 11; // cache version
49 const CACHE_FIELD_MAX_LEN
= 1000;
51 /** @var bool Does the file exist on disk? (loadFromXxx) */
52 protected $fileExists;
54 /** @var int Image width */
57 /** @var int Image height */
60 /** @var int Returned by getimagesize (loadFromXxx) */
63 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
64 protected $media_type;
66 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
69 /** @var int Size in bytes (loadFromXxx) */
72 /** @var string Handler-specific metadata */
75 /** @var string SHA-1 base 36 content hash */
78 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
79 protected $dataLoaded;
81 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
82 protected $extraDataLoaded;
84 /** @var int Bitfield akin to rev_deleted */
88 protected $repoClass = LocalRepo
::class;
90 /** @var int Number of line to return by nextHistoryLine() (constructor) */
93 /** @var int Result of the query for the file's history (nextHistoryLine) */
96 /** @var string Major MIME type */
99 /** @var string Minor MIME type */
102 /** @var string Upload timestamp */
105 /** @var User Uploader */
108 /** @var string Description of current revision of the file */
109 private $description;
111 /** @var string TS_MW timestamp of the last change of the file description */
112 private $descriptionTouched;
114 /** @var bool Whether the row was upgraded on load */
117 /** @var bool Whether the row was scheduled to upgrade on load */
120 /** @var bool True if the image row is locked */
123 /** @var bool True if the image row is locked with a lock initiated transaction */
124 private $lockedOwnTrx;
126 /** @var bool True if file is not present in file system. Not to be cached in memcached */
129 // @note: higher than IDBAccessObject constants
130 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
132 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
135 * Create a LocalFile from a title
136 * Do not call this except from inside a repo class.
138 * Note: $unused param is only here to avoid an E_STRICT
140 * @param Title $title
141 * @param FileRepo $repo
142 * @param null $unused
146 static function newFromTitle( $title, $repo, $unused = null ) {
147 return new self( $title, $repo );
151 * Create a LocalFile from a title
152 * Do not call this except from inside a repo class.
154 * @param stdClass $row
155 * @param FileRepo $repo
159 static function newFromRow( $row, $repo ) {
160 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
161 $file = new self( $title, $repo );
162 $file->loadFromRow( $row );
168 * Create a LocalFile from a SHA-1 key
169 * Do not call this except from inside a repo class.
171 * @param string $sha1 Base-36 SHA-1
172 * @param LocalRepo $repo
173 * @param string|bool $timestamp MW_timestamp (optional)
174 * @return bool|LocalFile
176 static function newFromKey( $sha1, $repo, $timestamp = false ) {
177 $dbr = $repo->getReplicaDB();
179 $conds = [ 'img_sha1' => $sha1 ];
181 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
184 $fileQuery = self
::getQueryInfo();
185 $row = $dbr->selectRow(
186 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
189 return self
::newFromRow( $row, $repo );
196 * Fields in the image table
197 * @deprecated since 1.31, use self::getQueryInfo() instead.
200 static function selectFields() {
201 global $wgActorTableSchemaMigrationStage;
203 wfDeprecated( __METHOD__
, '1.31' );
204 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) {
205 // If code is using this instead of self::getQueryInfo(), there's a
206 // decent chance it's going to try to directly access
207 // $row->img_user or $row->img_user_text and we can't give it
208 // useful values here once those aren't being used anymore.
209 throw new BadMethodCallException(
210 'Cannot use ' . __METHOD__
211 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
227 'img_actor' => 'NULL',
230 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
234 * Return the tables, fields, and join conditions to be selected to create
235 * a new localfile object.
237 * @param string[] $options
238 * - omit-lazy: Omit fields that are lazily cached.
239 * @return array[] With three keys:
240 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
241 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
242 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
244 public static function getQueryInfo( array $options = [] ) {
245 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
246 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
248 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
261 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
262 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
265 if ( in_array( 'omit-nonlazy', $options, true ) ) {
266 // Internal use only for getting only the lazy fields
269 if ( !in_array( 'omit-lazy', $options, true ) ) {
270 // Note: Keep this in sync with self::getLazyCacheFields()
271 $ret['fields'][] = 'img_metadata';
278 * Do not call this except from inside a repo class.
279 * @param Title $title
280 * @param FileRepo $repo
282 function __construct( $title, $repo ) {
283 parent
::__construct( $title, $repo );
285 $this->metadata
= '';
286 $this->historyLine
= 0;
287 $this->historyRes
= null;
288 $this->dataLoaded
= false;
289 $this->extraDataLoaded
= false;
291 $this->assertRepoDefined();
292 $this->assertTitleDefined();
296 * Get the memcached key for the main data for this file, or false if
297 * there is no access to the shared cache.
298 * @return string|bool
300 function getCacheKey() {
301 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
305 * @param WANObjectCache $cache
309 public function getMutableCacheKeys( WANObjectCache
$cache ) {
310 return [ $this->getCacheKey() ];
314 * Try to load file metadata from memcached, falling back to the database
316 private function loadFromCache() {
317 $this->dataLoaded
= false;
318 $this->extraDataLoaded
= false;
320 $key = $this->getCacheKey();
322 $this->loadFromDB( self
::READ_NORMAL
);
327 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
328 $cachedValues = $cache->getWithSetCallback(
331 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
332 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
334 $this->loadFromDB( self
::READ_NORMAL
);
336 $fields = $this->getCacheFields( '' );
337 $cacheVal['fileExists'] = $this->fileExists
;
338 if ( $this->fileExists
) {
339 foreach ( $fields as $field ) {
340 $cacheVal[$field] = $this->$field;
343 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
344 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
345 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
347 // Strip off excessive entries from the subset of fields that can become large.
348 // If the cache value gets to large it will not fit in memcached and nothing will
349 // get cached at all, causing master queries for any file access.
350 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
351 if ( isset( $cacheVal[$field] )
352 && strlen( $cacheVal[$field] ) > 100 * 1024
354 unset( $cacheVal[$field] ); // don't let the value get too big
358 if ( $this->fileExists
) {
359 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
361 $ttl = $cache::TTL_DAY
;
366 [ 'version' => self
::VERSION
]
369 $this->fileExists
= $cachedValues['fileExists'];
370 if ( $this->fileExists
) {
371 $this->setProps( $cachedValues );
374 $this->dataLoaded
= true;
375 $this->extraDataLoaded
= true;
376 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
377 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
382 * Purge the file object/metadata cache
384 public function invalidateCache() {
385 $key = $this->getCacheKey();
390 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
391 function () use ( $key ) {
392 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
399 * Load metadata from the file itself
401 function loadFromFile() {
402 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
403 $this->setProps( $props );
407 * Returns the list of object properties that are included as-is in the cache.
408 * @param string $prefix Must be the empty string
410 * @since 1.31 No longer accepts a non-empty $prefix
412 protected function getCacheFields( $prefix = 'img_' ) {
413 if ( $prefix !== '' ) {
414 throw new InvalidArgumentException(
415 __METHOD__
. ' with a non-empty prefix is no longer supported.'
419 // See self::getQueryInfo() for the fetching of the data from the DB,
420 // self::loadFromRow() for the loading of the object from the DB row,
421 // and self::loadFromCache() for the caching, and self::setProps() for
422 // populating the object from an array of data.
423 return [ 'size', 'width', 'height', 'bits', 'media_type',
424 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
428 * Returns the list of object properties that are included as-is in the
429 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
430 * @param string $prefix Must be the empty string
432 * @since 1.31 No longer accepts a non-empty $prefix
434 protected function getLazyCacheFields( $prefix = 'img_' ) {
435 if ( $prefix !== '' ) {
436 throw new InvalidArgumentException(
437 __METHOD__
. ' with a non-empty prefix is no longer supported.'
441 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
442 return [ 'metadata' ];
446 * Load file metadata from the DB
449 function loadFromDB( $flags = 0 ) {
450 $fname = static::class . '::' . __FUNCTION__
;
452 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
453 $this->dataLoaded
= true;
454 $this->extraDataLoaded
= true;
456 $dbr = ( $flags & self
::READ_LATEST
)
457 ?
$this->repo
->getMasterDB()
458 : $this->repo
->getReplicaDB();
460 $fileQuery = static::getQueryInfo();
461 $row = $dbr->selectRow(
462 $fileQuery['tables'],
463 $fileQuery['fields'],
464 [ 'img_name' => $this->getName() ],
471 $this->loadFromRow( $row );
473 $this->fileExists
= false;
478 * Load lazy file metadata from the DB.
479 * This covers fields that are sometimes not cached.
481 protected function loadExtraFromDB() {
482 $fname = static::class . '::' . __FUNCTION__
;
484 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
485 $this->extraDataLoaded
= true;
487 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
489 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
493 foreach ( $fieldMap as $name => $value ) {
494 $this->$name = $value;
497 throw new MWException( "Could not find data for image '{$this->getName()}'." );
502 * @param IDatabase $dbr
503 * @param string $fname
504 * @return string[]|bool
506 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
509 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
510 $row = $dbr->selectRow(
511 $fileQuery['tables'],
512 $fileQuery['fields'],
514 'img_name' => $this->getName(),
515 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
522 $fieldMap = $this->unprefixRow( $row, 'img_' );
524 # File may have been uploaded over in the meantime; check the old versions
525 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
526 $row = $dbr->selectRow(
527 $fileQuery['tables'],
528 $fileQuery['fields'],
530 'oi_name' => $this->getName(),
531 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
538 $fieldMap = $this->unprefixRow( $row, 'oi_' );
542 if ( isset( $fieldMap['metadata'] ) ) {
543 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
550 * @param array|object $row
551 * @param string $prefix
552 * @throws MWException
555 protected function unprefixRow( $row, $prefix = 'img_' ) {
556 $array = (array)$row;
557 $prefixLength = strlen( $prefix );
559 // Sanity check prefix once
560 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
561 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
565 foreach ( $array as $name => $value ) {
566 $decoded[substr( $name, $prefixLength )] = $value;
573 * Decode a row from the database (either object or array) to an array
574 * with timestamps and MIME types decoded, and the field prefix removed.
576 * @param string $prefix
577 * @throws MWException
580 function decodeRow( $row, $prefix = 'img_' ) {
581 $decoded = $this->unprefixRow( $row, $prefix );
583 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
584 ->getComment( 'description', (object)$decoded )->text
;
586 $decoded['user'] = User
::newFromAnyId(
587 $decoded['user'] ??
null,
588 $decoded['user_text'] ??
null,
589 $decoded['actor'] ??
null
591 unset( $decoded['user_text'], $decoded['actor'] );
593 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
595 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
597 if ( empty( $decoded['major_mime'] ) ) {
598 $decoded['mime'] = 'unknown/unknown';
600 if ( !$decoded['minor_mime'] ) {
601 $decoded['minor_mime'] = 'unknown';
603 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
606 // Trim zero padding from char/binary field
607 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
609 // Normalize some fields to integer type, per their database definition.
610 // Use unary + so that overflows will be upgraded to double instead of
611 // being trucated as with intval(). This is important to allow >2GB
612 // files on 32-bit systems.
613 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
614 $decoded[$field] = +
$decoded[$field];
621 * Load file metadata from a DB result row
624 * @param string $prefix
626 function loadFromRow( $row, $prefix = 'img_' ) {
627 $this->dataLoaded
= true;
628 $this->extraDataLoaded
= true;
630 $array = $this->decodeRow( $row, $prefix );
632 foreach ( $array as $name => $value ) {
633 $this->$name = $value;
636 $this->fileExists
= true;
637 $this->maybeUpgradeRow();
641 * Load file metadata from cache or DB, unless already loaded
644 function load( $flags = 0 ) {
645 if ( !$this->dataLoaded
) {
646 if ( $flags & self
::READ_LATEST
) {
647 $this->loadFromDB( $flags );
649 $this->loadFromCache();
653 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
654 // @note: loads on name/timestamp to reduce race condition problems
655 $this->loadExtraFromDB();
660 * Upgrade a row if it needs it
662 function maybeUpgradeRow() {
663 global $wgUpdateCompatibleMetadata;
665 if ( wfReadOnly() ||
$this->upgrading
) {
670 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
673 $handler = $this->getHandler();
675 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
676 if ( $validity === MediaHandler
::METADATA_BAD
) {
678 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
679 $upgrade = $wgUpdateCompatibleMetadata;
685 $this->upgrading
= true;
686 // Defer updates unless in auto-commit CLI mode
687 DeferredUpdates
::addCallableUpdate( function () {
688 $this->upgrading
= false; // avoid duplicate updates
691 } catch ( LocalFileLockError
$e ) {
692 // let the other process handle it (or do it next time)
699 * @return bool Whether upgradeRow() ran for this object
701 function getUpgraded() {
702 return $this->upgraded
;
706 * Fix assorted version-related problems with the image row by reloading it from the file
708 function upgradeRow() {
711 $this->loadFromFile();
713 # Don't destroy file info of missing files
714 if ( !$this->fileExists
) {
716 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
721 $dbw = $this->repo
->getMasterDB();
722 list( $major, $minor ) = self
::splitMime( $this->mime
);
724 if ( wfReadOnly() ) {
729 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
731 $dbw->update( 'image',
733 'img_size' => $this->size
, // sanity
734 'img_width' => $this->width
,
735 'img_height' => $this->height
,
736 'img_bits' => $this->bits
,
737 'img_media_type' => $this->media_type
,
738 'img_major_mime' => $major,
739 'img_minor_mime' => $minor,
740 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
741 'img_sha1' => $this->sha1
,
743 [ 'img_name' => $this->getName() ],
747 $this->invalidateCache();
750 $this->upgraded
= true; // avoid rework/retries
754 * Set properties in this object to be equal to those given in the
755 * associative array $info. Only cacheable fields can be set.
756 * All fields *must* be set in $info except for getLazyCacheFields().
758 * If 'mime' is given, it will be split into major_mime/minor_mime.
759 * If major_mime/minor_mime are given, $this->mime will also be set.
763 function setProps( $info ) {
764 $this->dataLoaded
= true;
765 $fields = $this->getCacheFields( '' );
766 $fields[] = 'fileExists';
768 foreach ( $fields as $field ) {
769 if ( isset( $info[$field] ) ) {
770 $this->$field = $info[$field];
774 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
775 $this->user
= User
::newFromAnyId(
776 $info['user'] ??
null,
777 $info['user_text'] ??
null,
778 $info['actor'] ??
null
782 // Fix up mime fields
783 if ( isset( $info['major_mime'] ) ) {
784 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
785 } elseif ( isset( $info['mime'] ) ) {
786 $this->mime
= $info['mime'];
787 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
791 /** splitMime inherited */
792 /** getName inherited */
793 /** getTitle inherited */
794 /** getURL inherited */
795 /** getViewURL inherited */
796 /** getPath inherited */
797 /** isVisible inherited */
802 function isMissing() {
803 if ( $this->missing
=== null ) {
804 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
805 $this->missing
= !$fileExists;
808 return $this->missing
;
812 * Return the width of the image
817 public function getWidth( $page = 1 ) {
825 if ( $this->isMultipage() ) {
826 $handler = $this->getHandler();
830 $dim = $handler->getPageDimensions( $this, $page );
832 return $dim['width'];
834 // For non-paged media, the false goes through an
835 // intval, turning failure into 0, so do same here.
844 * Return the height of the image
849 public function getHeight( $page = 1 ) {
857 if ( $this->isMultipage() ) {
858 $handler = $this->getHandler();
862 $dim = $handler->getPageDimensions( $this, $page );
864 return $dim['height'];
866 // For non-paged media, the false goes through an
867 // intval, turning failure into 0, so do same here.
871 return $this->height
;
876 * Returns user who uploaded the file
878 * @param string $type 'text', 'id', or 'object'
879 * @return int|string|User
880 * @since 1.31 Added 'object'
882 function getUser( $type = 'text' ) {
885 if ( $type === 'object' ) {
887 } elseif ( $type === 'text' ) {
888 return $this->user
->getName();
889 } elseif ( $type === 'id' ) {
890 return $this->user
->getId();
893 throw new MWException( "Unknown type '$type'." );
897 * Get short description URL for a file based on the page ID.
899 * @return string|null
900 * @throws MWException
903 public function getDescriptionShortUrl() {
904 $pageId = $this->title
->getArticleID();
906 if ( $pageId !== null ) {
907 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
908 if ( $url !== false ) {
916 * Get handler-specific metadata
919 function getMetadata() {
920 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
921 return $this->metadata
;
927 function getBitDepth() {
930 return (int)$this->bits
;
934 * Returns the size of the image file, in bytes
937 public function getSize() {
944 * Returns the MIME type of the file.
947 function getMimeType() {
954 * Returns the type of the media in the file.
955 * Use the value returned by this function with the MEDIATYPE_xxx constants.
958 function getMediaType() {
961 return $this->media_type
;
964 /** canRender inherited */
965 /** mustRender inherited */
966 /** allowInlineDisplay inherited */
967 /** isSafeFile inherited */
968 /** isTrustedFile inherited */
971 * Returns true if the file exists on disk.
972 * @return bool Whether file exist on disk.
974 public function exists() {
977 return $this->fileExists
;
980 /** getTransformScript inherited */
981 /** getUnscaledThumb inherited */
982 /** thumbName inherited */
983 /** createThumb inherited */
984 /** transform inherited */
986 /** getHandler inherited */
987 /** iconThumb inherited */
988 /** getLastError inherited */
991 * Get all thumbnail names previously generated for this file
992 * @param string|bool $archiveName Name of an archive file, default false
993 * @return array First element is the base dir, then files in that base dir.
995 function getThumbnails( $archiveName = false ) {
996 if ( $archiveName ) {
997 $dir = $this->getArchiveThumbPath( $archiveName );
999 $dir = $this->getThumbPath();
1002 $backend = $this->repo
->getBackend();
1005 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1006 foreach ( $iterator as $file ) {
1009 } catch ( FileBackendError
$e ) {
1010 } // suppress (T56674)
1016 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1018 function purgeMetadataCache() {
1019 $this->invalidateCache();
1023 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1025 * @param array $options An array potentially with the key forThumbRefresh.
1027 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1029 function purgeCache( $options = [] ) {
1030 // Refresh metadata cache
1031 $this->purgeMetadataCache();
1033 // Delete thumbnails
1034 $this->purgeThumbnails( $options );
1036 // Purge CDN cache for this file
1037 DeferredUpdates
::addUpdate(
1038 new CdnCacheUpdate( [ $this->getUrl() ] ),
1039 DeferredUpdates
::PRESEND
1044 * Delete cached transformed files for an archived version only.
1045 * @param string $archiveName Name of the archived file
1047 function purgeOldThumbnails( $archiveName ) {
1048 // Get a list of old thumbnails and URLs
1049 $files = $this->getThumbnails( $archiveName );
1051 // Purge any custom thumbnail caches
1052 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1054 // Delete thumbnails
1055 $dir = array_shift( $files );
1056 $this->purgeThumbList( $dir, $files );
1060 foreach ( $files as $file ) {
1061 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1063 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1067 * Delete cached transformed files for the current version only.
1068 * @param array $options
1070 public function purgeThumbnails( $options = [] ) {
1071 $files = $this->getThumbnails();
1072 // Always purge all files from CDN regardless of handler filters
1074 foreach ( $files as $file ) {
1075 $urls[] = $this->getThumbUrl( $file );
1077 array_shift( $urls ); // don't purge directory
1079 // Give media handler a chance to filter the file purge list
1080 if ( !empty( $options['forThumbRefresh'] ) ) {
1081 $handler = $this->getHandler();
1083 $handler->filterThumbnailPurgeList( $files, $options );
1087 // Purge any custom thumbnail caches
1088 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1090 // Delete thumbnails
1091 $dir = array_shift( $files );
1092 $this->purgeThumbList( $dir, $files );
1095 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1099 * Prerenders a configurable set of thumbnails
1103 public function prerenderThumbnails() {
1104 global $wgUploadThumbnailRenderMap;
1108 $sizes = $wgUploadThumbnailRenderMap;
1111 foreach ( $sizes as $size ) {
1112 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1113 $jobs[] = new ThumbnailRenderJob(
1115 [ 'transformParams' => [ 'width' => $size ] ]
1121 JobQueueGroup
::singleton()->lazyPush( $jobs );
1126 * Delete a list of thumbnails visible at urls
1127 * @param string $dir Base dir of the files.
1128 * @param array $files Array of strings: relative filenames (to $dir)
1130 protected function purgeThumbList( $dir, $files ) {
1131 $fileListDebug = strtr(
1132 var_export( $files, true ),
1135 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1138 foreach ( $files as $file ) {
1139 if ( $this->repo
->supportsSha1URLs() ) {
1140 $reference = $this->getSha1();
1142 $reference = $this->getName();
1145 # Check that the reference (filename or sha1) is part of the thumb name
1146 # This is a basic sanity check to avoid erasing unrelated directories
1147 if ( strpos( $file, $reference ) !== false
1148 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1150 $purgeList[] = "{$dir}/{$file}";
1154 # Delete the thumbnails
1155 $this->repo
->quickPurgeBatch( $purgeList );
1156 # Clear out the thumbnail directory if empty
1157 $this->repo
->quickCleanDir( $dir );
1160 /** purgeDescription inherited */
1161 /** purgeEverything inherited */
1164 * @param int|null $limit Optional: Limit to number of results
1165 * @param string|int|null $start Optional: Timestamp, start from
1166 * @param string|int|null $end Optional: Timestamp, end at
1168 * @return OldLocalFile[]
1170 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1171 $dbr = $this->repo
->getReplicaDB();
1172 $oldFileQuery = OldLocalFile
::getQueryInfo();
1174 $tables = $oldFileQuery['tables'];
1175 $fields = $oldFileQuery['fields'];
1176 $join_conds = $oldFileQuery['joins'];
1177 $conds = $opts = [];
1178 $eq = $inc ?
'=' : '';
1179 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1182 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1186 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1190 $opts['LIMIT'] = $limit;
1193 // Search backwards for time > x queries
1194 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1195 $opts['ORDER BY'] = "oi_timestamp $order";
1196 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1198 // Avoid PHP 7.1 warning from passing $this by reference
1200 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1201 &$conds, &$opts, &$join_conds ] );
1203 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1206 foreach ( $res as $row ) {
1207 $r[] = $this->repo
->newFileFromRow( $row );
1210 if ( $order == 'ASC' ) {
1211 $r = array_reverse( $r ); // make sure it ends up descending
1218 * Returns the history of this file, line by line.
1219 * starts with current version, then old versions.
1220 * uses $this->historyLine to check which line to return:
1221 * 0 return line for current version
1222 * 1 query for old versions, return first one
1223 * 2, ... return next old version from above query
1226 public function nextHistoryLine() {
1227 # Polymorphic function name to distinguish foreign and local fetches
1228 $fname = static::class . '::' . __FUNCTION__
;
1230 $dbr = $this->repo
->getReplicaDB();
1232 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1233 $fileQuery = self
::getQueryInfo();
1234 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1235 $fileQuery['fields'] +
[
1236 'oi_archive_name' => $dbr->addQuotes( '' ),
1239 [ 'img_name' => $this->title
->getDBkey() ],
1245 if ( $dbr->numRows( $this->historyRes
) == 0 ) {
1246 $this->historyRes
= null;
1250 } elseif ( $this->historyLine
== 1 ) {
1251 $fileQuery = OldLocalFile
::getQueryInfo();
1252 $this->historyRes
= $dbr->select(
1253 $fileQuery['tables'],
1254 $fileQuery['fields'],
1255 [ 'oi_name' => $this->title
->getDBkey() ],
1257 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1261 $this->historyLine++
;
1263 return $dbr->fetchObject( $this->historyRes
);
1267 * Reset the history pointer to the first element of the history
1269 public function resetHistory() {
1270 $this->historyLine
= 0;
1272 if ( !is_null( $this->historyRes
) ) {
1273 $this->historyRes
= null;
1277 /** getHashPath inherited */
1278 /** getRel inherited */
1279 /** getUrlRel inherited */
1280 /** getArchiveRel inherited */
1281 /** getArchivePath inherited */
1282 /** getThumbPath inherited */
1283 /** getArchiveUrl inherited */
1284 /** getThumbUrl inherited */
1285 /** getArchiveVirtualUrl inherited */
1286 /** getThumbVirtualUrl inherited */
1287 /** isHashed inherited */
1290 * Upload a file and record it in the DB
1291 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1292 * @param string $comment Upload description
1293 * @param string $pageText Text to use for the new description page,
1294 * if a new description page is created
1295 * @param int|bool $flags Flags for publish()
1296 * @param array|bool $props File properties, if known. This can be used to
1297 * reduce the upload time when uploading virtual URLs for which the file
1298 * info is already known
1299 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1301 * @param User|null $user User object or null to use $wgUser
1302 * @param string[] $tags Change tags to add to the log entry and page revision.
1303 * (This doesn't check $user's permissions.)
1304 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1305 * upload, see T193621
1306 * @return Status On success, the value member contains the
1307 * archive name, or an empty string if it was a new file.
1309 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1310 $timestamp = false, $user = null, $tags = [],
1311 $createNullRevision = true
1313 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1314 return $this->readOnlyFatalStatus();
1315 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1316 // Check this in advance to avoid writing to FileBackend and the file tables,
1317 // only to fail on insert the revision due to the text store being unavailable.
1318 return $this->readOnlyFatalStatus();
1321 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1323 if ( FileRepo
::isVirtualUrl( $srcPath )
1324 || FileBackend
::isStoragePath( $srcPath )
1326 $props = $this->repo
->getFileProps( $srcPath );
1328 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1329 $props = $mwProps->getPropsFromPath( $srcPath, true );
1334 $handler = MediaHandler
::getHandler( $props['mime'] );
1336 $metadata = Wikimedia\
quietCall( 'unserialize', $props['metadata'] );
1338 if ( !is_array( $metadata ) ) {
1342 $options['headers'] = $handler->getContentHeaders( $metadata );
1344 $options['headers'] = [];
1347 // Trim spaces on user supplied text
1348 $comment = trim( $comment );
1351 $status = $this->publish( $src, $flags, $options );
1353 if ( $status->successCount
>= 2 ) {
1354 // There will be a copy+(one of move,copy,store).
1355 // The first succeeding does not commit us to updating the DB
1356 // since it simply copied the current version to a timestamped file name.
1357 // It is only *preferable* to avoid leaving such files orphaned.
1358 // Once the second operation goes through, then the current version was
1359 // updated and we must therefore update the DB too.
1360 $oldver = $status->value
;
1361 $uploadStatus = $this->recordUpload2(
1371 if ( !$uploadStatus->isOK() ) {
1372 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1373 // update filenotfound error with more specific path
1374 $status->fatal( 'filenotfound', $srcPath );
1376 $status->merge( $uploadStatus );
1386 * Record a file upload in the upload log and the image table
1387 * @param string $oldver
1388 * @param string $desc
1389 * @param string $license
1390 * @param string $copyStatus
1391 * @param string $source
1392 * @param bool $watch
1393 * @param string|bool $timestamp
1394 * @param User|null $user User object or null to use $wgUser
1397 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1398 $watch = false, $timestamp = false, User
$user = null ) {
1404 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1406 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1411 $user->addWatch( $this->getTitle() );
1418 * Record a file upload in the upload log and the image table
1419 * @param string $oldver
1420 * @param string $comment
1421 * @param string $pageText
1422 * @param bool|array $props
1423 * @param string|bool $timestamp
1424 * @param null|User $user
1425 * @param string[] $tags
1426 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1427 * upload, see T193621
1430 function recordUpload2(
1431 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1432 $createNullRevision = true
1434 global $wgActorTableSchemaMigrationStage;
1436 if ( is_null( $user ) ) {
1441 $dbw = $this->repo
->getMasterDB();
1443 # Imports or such might force a certain timestamp; otherwise we generate
1444 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1445 if ( $timestamp === false ) {
1446 $timestamp = $dbw->timestamp();
1447 $allowTimeKludge = true;
1449 $allowTimeKludge = false;
1452 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1453 $props['description'] = $comment;
1454 $props['user'] = $user->getId();
1455 $props['user_text'] = $user->getName();
1456 $props['actor'] = $user->getActorId( $dbw );
1457 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1458 $this->setProps( $props );
1460 # Fail now if the file isn't there
1461 if ( !$this->fileExists
) {
1462 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1464 return Status
::newFatal( 'filenotfound', $this->getRel() );
1467 $dbw->startAtomic( __METHOD__
);
1469 # Test to see if the row exists using INSERT IGNORE
1470 # This avoids race conditions by locking the row until the commit, and also
1471 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1472 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1473 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1474 $actorMigration = ActorMigration
::newMigration();
1475 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1476 $dbw->insert( 'image',
1478 'img_name' => $this->getName(),
1479 'img_size' => $this->size
,
1480 'img_width' => intval( $this->width
),
1481 'img_height' => intval( $this->height
),
1482 'img_bits' => $this->bits
,
1483 'img_media_type' => $this->media_type
,
1484 'img_major_mime' => $this->major_mime
,
1485 'img_minor_mime' => $this->minor_mime
,
1486 'img_timestamp' => $timestamp,
1487 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1488 'img_sha1' => $this->sha1
1489 ] +
$commentFields +
$actorFields,
1493 $reupload = ( $dbw->affectedRows() == 0 );
1496 $row = $dbw->selectRow(
1498 [ 'img_timestamp', 'img_sha1' ],
1499 [ 'img_name' => $this->getName() ],
1501 [ 'LOCK IN SHARE MODE' ]
1504 if ( $row && $row->img_sha1
=== $this->sha1
) {
1505 $dbw->endAtomic( __METHOD__
);
1506 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1507 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1508 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1511 if ( $allowTimeKludge ) {
1512 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1513 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1514 # Avoid a timestamp that is not newer than the last version
1515 # TODO: the image/oldimage tables should be like page/revision with an ID field
1516 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1517 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1518 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1519 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1523 $tables = [ 'image' ];
1525 'oi_name' => 'img_name',
1526 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1527 'oi_size' => 'img_size',
1528 'oi_width' => 'img_width',
1529 'oi_height' => 'img_height',
1530 'oi_bits' => 'img_bits',
1531 'oi_description_id' => 'img_description_id',
1532 'oi_timestamp' => 'img_timestamp',
1533 'oi_metadata' => 'img_metadata',
1534 'oi_media_type' => 'img_media_type',
1535 'oi_major_mime' => 'img_major_mime',
1536 'oi_minor_mime' => 'img_minor_mime',
1537 'oi_sha1' => 'img_sha1',
1541 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1542 $fields['oi_user'] = 'img_user';
1543 $fields['oi_user_text'] = 'img_user_text';
1545 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1546 $fields['oi_actor'] = 'img_actor';
1550 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1552 // Upgrade any rows that are still old-style. Otherwise an upgrade
1553 // might be missed if a deletion happens while the migration script
1555 $res = $dbw->select(
1557 [ 'img_name', 'img_user', 'img_user_text' ],
1558 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1561 foreach ( $res as $row ) {
1562 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1565 [ 'img_actor' => $actorId ],
1566 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1572 # (T36993) Note: $oldver can be empty here, if the previous
1573 # version of the file was broken. Allow registration of the new
1574 # version to continue anyway, because that's better than having
1575 # an image that's not fixable by user operations.
1576 # Collision, this is an update of a file
1577 # Insert previous contents into oldimage
1578 $dbw->insertSelect( 'oldimage', $tables, $fields,
1579 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1581 # Update the current image row
1582 $dbw->update( 'image',
1584 'img_size' => $this->size
,
1585 'img_width' => intval( $this->width
),
1586 'img_height' => intval( $this->height
),
1587 'img_bits' => $this->bits
,
1588 'img_media_type' => $this->media_type
,
1589 'img_major_mime' => $this->major_mime
,
1590 'img_minor_mime' => $this->minor_mime
,
1591 'img_timestamp' => $timestamp,
1592 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1593 'img_sha1' => $this->sha1
1594 ] +
$commentFields +
$actorFields,
1595 [ 'img_name' => $this->getName() ],
1600 $descTitle = $this->getTitle();
1601 $descId = $descTitle->getArticleID();
1602 $wikiPage = new WikiFilePage( $descTitle );
1603 $wikiPage->setFile( $this );
1605 // Add the log entry...
1606 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1607 $logEntry->setTimestamp( $this->timestamp
);
1608 $logEntry->setPerformer( $user );
1609 $logEntry->setComment( $comment );
1610 $logEntry->setTarget( $descTitle );
1611 // Allow people using the api to associate log entries with the upload.
1612 // Log has a timestamp, but sometimes different from upload timestamp.
1613 $logEntry->setParameters(
1615 'img_sha1' => $this->sha1
,
1616 'img_timestamp' => $timestamp,
1619 // Note we keep $logId around since during new image
1620 // creation, page doesn't exist yet, so log_page = 0
1621 // but we want it to point to the page we're making,
1622 // so we later modify the log entry.
1623 // For a similar reason, we avoid making an RC entry
1624 // now and wait until the page exists.
1625 $logId = $logEntry->insert();
1627 if ( $descTitle->exists() ) {
1628 // Use own context to get the action text in content language
1629 $formatter = LogFormatter
::newFromEntry( $logEntry );
1630 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1631 $editSummary = $formatter->getPlainActionText();
1633 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1640 if ( $nullRevision ) {
1641 $nullRevision->insertOn( $dbw );
1643 'NewRevisionFromEditComplete',
1644 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1646 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1647 // Associate null revision id
1648 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1651 $newPageContent = null;
1653 // Make the description page and RC log entry post-commit
1654 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1657 # Defer purges, page creation, and link updates in case they error out.
1658 # The most important thing is that files and the DB registry stay synced.
1659 $dbw->endAtomic( __METHOD__
);
1660 $fname = __METHOD__
;
1662 # Do some cache purges after final commit so that:
1663 # a) Changes are more likely to be seen post-purge
1664 # b) They won't cause rollback of the log publish/update above
1665 DeferredUpdates
::addUpdate(
1666 new AutoCommitUpdate(
1670 $reupload, $wikiPage, $newPageContent, $comment, $user,
1671 $logEntry, $logId, $descId, $tags, $fname
1673 # Update memcache after the commit
1674 $this->invalidateCache();
1676 $updateLogPage = false;
1677 if ( $newPageContent ) {
1678 # New file page; create the description page.
1679 # There's already a log entry, so don't make a second RC entry
1680 # CDN and file cache for the description page are purged by doEditContent.
1681 $status = $wikiPage->doEditContent(
1684 EDIT_NEW | EDIT_SUPPRESS_RC
,
1689 if ( isset( $status->value
['revision'] ) ) {
1690 /** @var Revision $rev */
1691 $rev = $status->value
['revision'];
1692 // Associate new page revision id
1693 $logEntry->setAssociatedRevId( $rev->getId() );
1695 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1696 // which is triggered on $descTitle by doEditContent() above.
1697 if ( isset( $status->value
['revision'] ) ) {
1698 /** @var Revision $rev */
1699 $rev = $status->value
['revision'];
1700 $updateLogPage = $rev->getPage();
1703 # Existing file page: invalidate description page cache
1704 $wikiPage->getTitle()->invalidateCache();
1705 $wikiPage->getTitle()->purgeSquid();
1706 # Allow the new file version to be patrolled from the page footer
1707 Article
::purgePatrolFooterCache( $descId );
1710 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1711 # but setAssociatedRevId() wasn't called at that point yet...
1712 $logParams = $logEntry->getParameters();
1713 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1714 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1715 if ( $updateLogPage ) {
1716 # Also log page, in case where we just created it above
1717 $update['log_page'] = $updateLogPage;
1719 $this->getRepo()->getMasterDB()->update(
1722 [ 'log_id' => $logId ],
1725 $this->getRepo()->getMasterDB()->insert(
1728 'ls_field' => 'associated_rev_id',
1729 'ls_value' => $logEntry->getAssociatedRevId(),
1730 'ls_log_id' => $logId,
1735 # Add change tags, if any
1737 $logEntry->setTags( $tags );
1740 # Uploads can be patrolled
1741 $logEntry->setIsPatrollable( true );
1743 # Now that the log entry is up-to-date, make an RC entry.
1744 $logEntry->publish( $logId );
1746 # Run hook for other updates (typically more cache purging)
1747 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1750 # Delete old thumbnails
1751 $this->purgeThumbnails();
1752 # Remove the old file from the CDN cache
1753 DeferredUpdates
::addUpdate(
1754 new CdnCacheUpdate( [ $this->getUrl() ] ),
1755 DeferredUpdates
::PRESEND
1758 # Update backlink pages pointing to this title if created
1759 LinksUpdate
::queueRecursiveJobsForTable(
1767 $this->prerenderThumbnails();
1770 DeferredUpdates
::PRESEND
1774 # This is a new file, so update the image count
1775 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1778 # Invalidate cache for all pages using this file
1779 DeferredUpdates
::addUpdate(
1780 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1783 return Status
::newGood();
1787 * Move or copy a file to its public location. If a file exists at the
1788 * destination, move it to an archive. Returns a Status object with
1789 * the archive name in the "value" member on success.
1791 * The archive name should be passed through to recordUpload for database
1794 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1795 * @param int $flags A bitwise combination of:
1796 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1797 * @param array $options Optional additional parameters
1798 * @return Status On success, the value member contains the
1799 * archive name, or an empty string if it was a new file.
1801 function publish( $src, $flags = 0, array $options = [] ) {
1802 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1806 * Move or copy a file to a specified location. Returns a Status
1807 * object with the archive name in the "value" member on success.
1809 * The archive name should be passed through to recordUpload for database
1812 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1813 * @param string $dstRel Target relative path
1814 * @param int $flags A bitwise combination of:
1815 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1816 * @param array $options Optional additional parameters
1817 * @return Status On success, the value member contains the
1818 * archive name, or an empty string if it was a new file.
1820 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1821 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1823 $repo = $this->getRepo();
1824 if ( $repo->getReadOnlyReason() !== false ) {
1825 return $this->readOnlyFatalStatus();
1830 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1831 $archiveRel = $this->getArchiveRel( $archiveName );
1833 if ( $repo->hasSha1Storage() ) {
1834 $sha1 = FileRepo
::isVirtualUrl( $srcPath )
1835 ?
$repo->getFileSha1( $srcPath )
1836 : FSFile
::getSha1Base36FromPath( $srcPath );
1837 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1838 $wrapperBackend = $repo->getBackend();
1839 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1840 $status = $repo->quickImport( $src, $dst );
1841 if ( $flags & File
::DELETE_SOURCE
) {
1845 if ( $this->exists() ) {
1846 $status->value
= $archiveName;
1849 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1850 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1852 if ( $status->value
== 'new' ) {
1853 $status->value
= '';
1855 $status->value
= $archiveName;
1863 /** getLinksTo inherited */
1864 /** getExifData inherited */
1865 /** isLocal inherited */
1866 /** wasDeleted inherited */
1869 * Move file to the new title
1871 * Move current, old version and all thumbnails
1872 * to the new filename. Old file is deleted.
1874 * Cache purging is done; checks for validity
1875 * and logging are caller's responsibility
1877 * @param Title $target New file name
1880 function move( $target ) {
1881 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1882 return $this->readOnlyFatalStatus();
1885 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1886 $batch = new LocalFileMoveBatch( $this, $target );
1889 $batch->addCurrent();
1890 $archiveNames = $batch->addOlds();
1891 $status = $batch->execute();
1894 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1896 // Purge the source and target files...
1897 $oldTitleFile = wfLocalFile( $this->title
);
1898 $newTitleFile = wfLocalFile( $target );
1899 // To avoid slow purges in the transaction, move them outside...
1900 DeferredUpdates
::addUpdate(
1901 new AutoCommitUpdate(
1902 $this->getRepo()->getMasterDB(),
1904 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1905 $oldTitleFile->purgeEverything();
1906 foreach ( $archiveNames as $archiveName ) {
1907 $oldTitleFile->purgeOldThumbnails( $archiveName );
1909 $newTitleFile->purgeEverything();
1912 DeferredUpdates
::PRESEND
1915 if ( $status->isOK() ) {
1916 // Now switch the object
1917 $this->title
= $target;
1918 // Force regeneration of the name and hashpath
1919 unset( $this->name
);
1920 unset( $this->hashPath
);
1927 * Delete all versions of the file.
1929 * Moves the files into an archive directory (or deletes them)
1930 * and removes the database rows.
1932 * Cache purging is done; logging is caller's responsibility.
1934 * @param string $reason
1935 * @param bool $suppress
1936 * @param User|null $user
1939 function delete( $reason, $suppress = false, $user = null ) {
1940 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1941 return $this->readOnlyFatalStatus();
1944 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1947 $batch->addCurrent();
1948 // Get old version relative paths
1949 $archiveNames = $batch->addOlds();
1950 $status = $batch->execute();
1953 if ( $status->isOK() ) {
1954 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1957 // To avoid slow purges in the transaction, move them outside...
1958 DeferredUpdates
::addUpdate(
1959 new AutoCommitUpdate(
1960 $this->getRepo()->getMasterDB(),
1962 function () use ( $archiveNames ) {
1963 $this->purgeEverything();
1964 foreach ( $archiveNames as $archiveName ) {
1965 $this->purgeOldThumbnails( $archiveName );
1969 DeferredUpdates
::PRESEND
1974 foreach ( $archiveNames as $archiveName ) {
1975 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1977 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1983 * Delete an old version of the file.
1985 * Moves the file into an archive directory (or deletes it)
1986 * and removes the database row.
1988 * Cache purging is done; logging is caller's responsibility.
1990 * @param string $archiveName
1991 * @param string $reason
1992 * @param bool $suppress
1993 * @param User|null $user
1994 * @throws MWException Exception on database or file store failure
1997 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1998 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1999 return $this->readOnlyFatalStatus();
2002 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2005 $batch->addOld( $archiveName );
2006 $status = $batch->execute();
2009 $this->purgeOldThumbnails( $archiveName );
2010 if ( $status->isOK() ) {
2011 $this->purgeDescription();
2014 DeferredUpdates
::addUpdate(
2015 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2016 DeferredUpdates
::PRESEND
2023 * Restore all or specified deleted revisions to the given file.
2024 * Permissions and logging are left to the caller.
2026 * May throw database exceptions on error.
2028 * @param array $versions Set of record ids of deleted items to restore,
2029 * or empty to restore all revisions.
2030 * @param bool $unsuppress
2033 function restore( $versions = [], $unsuppress = false ) {
2034 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2035 return $this->readOnlyFatalStatus();
2038 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2044 $batch->addIds( $versions );
2046 $status = $batch->execute();
2047 if ( $status->isGood() ) {
2048 $cleanupStatus = $batch->cleanup();
2049 $cleanupStatus->successCount
= 0;
2050 $cleanupStatus->failCount
= 0;
2051 $status->merge( $cleanupStatus );
2058 /** isMultipage inherited */
2059 /** pageCount inherited */
2060 /** scaleHeight inherited */
2061 /** getImageSize inherited */
2064 * Get the URL of the file description page.
2067 function getDescriptionUrl() {
2068 return $this->title
->getLocalURL();
2072 * Get the HTML text of the description page
2073 * This is not used by ImagePage for local files, since (among other things)
2074 * it skips the parser cache.
2076 * @param Language|null $lang What language to get description in (Optional)
2077 * @return string|false
2079 function getDescriptionText( Language
$lang = null ) {
2080 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2081 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2086 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2087 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2090 // audience check failed
2094 $pout = $rendered->getRevisionParserOutput();
2095 return $pout->getText();
2099 * @param int $audience
2100 * @param User|null $user
2103 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2105 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2107 } elseif ( $audience == self
::FOR_THIS_USER
2108 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2112 return $this->description
;
2117 * @return bool|string
2119 function getTimestamp() {
2122 return $this->timestamp
;
2126 * @return bool|string
2128 public function getDescriptionTouched() {
2129 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2130 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2131 // need to differentiate between null (uninitialized) and false (failed to load).
2132 if ( $this->descriptionTouched
=== null ) {
2134 'page_namespace' => $this->title
->getNamespace(),
2135 'page_title' => $this->title
->getDBkey()
2137 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2138 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2141 return $this->descriptionTouched
;
2147 function getSha1() {
2149 // Initialise now if necessary
2150 if ( $this->sha1
== '' && $this->fileExists
) {
2153 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2154 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2155 $dbw = $this->repo
->getMasterDB();
2156 $dbw->update( 'image',
2157 [ 'img_sha1' => $this->sha1
],
2158 [ 'img_name' => $this->getName() ],
2160 $this->invalidateCache();
2170 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2172 function isCacheable() {
2175 // If extra data (metadata) was not loaded then it must have been large
2176 return $this->extraDataLoaded
2177 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2184 public function acquireFileLock() {
2185 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2186 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2194 public function releaseFileLock() {
2195 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2196 [ $this->getPath() ], LockManager
::LOCK_EX
2201 * Start an atomic DB section and lock the image for update
2202 * or increments a reference counter if the lock is already held
2204 * This method should not be used outside of LocalFile/LocalFile*Batch
2206 * @throws LocalFileLockError Throws an error if the lock was not acquired
2207 * @return bool Whether the file lock owns/spawned the DB transaction
2209 public function lock() {
2210 if ( !$this->locked
) {
2211 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2213 $dbw = $this->repo
->getMasterDB();
2214 $makesTransaction = !$dbw->trxLevel();
2215 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2216 // T56736: use simple lock to handle when the file does not exist.
2217 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2218 // Also, that would cause contention on INSERT of similarly named rows.
2219 $status = $this->acquireFileLock(); // represents all versions of the file
2220 if ( !$status->isGood() ) {
2221 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2222 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2224 throw new LocalFileLockError( $status );
2226 // Release the lock *after* commit to avoid row-level contention.
2227 // Make sure it triggers on rollback() as well as commit() (T132921).
2228 $dbw->onTransactionResolution(
2229 function () use ( $logger ) {
2230 $status = $this->releaseFileLock();
2231 if ( !$status->isGood() ) {
2232 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2237 // Callers might care if the SELECT snapshot is safely fresh
2238 $this->lockedOwnTrx
= $makesTransaction;
2243 return $this->lockedOwnTrx
;
2247 * Decrement the lock reference count and end the atomic section if it reaches zero
2249 * This method should not be used outside of LocalFile/LocalFile*Batch
2251 * The commit and loc release will happen when no atomic sections are active, which
2252 * may happen immediately or at some point after calling this
2254 public function unlock() {
2255 if ( $this->locked
) {
2257 if ( !$this->locked
) {
2258 $dbw = $this->repo
->getMasterDB();
2259 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2260 $this->lockedOwnTrx
= false;
2268 protected function readOnlyFatalStatus() {
2269 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2270 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2274 * Clean up any dangling locks
2276 function __destruct() {
2279 } // LocalFile class
2281 # ------------------------------------------------------------------------------
2284 * Helper class for file deletion
2285 * @ingroup FileAbstraction
2287 class LocalFileDeleteBatch
{
2288 /** @var LocalFile */
2295 private $srcRels = [];
2298 private $archiveUrls = [];
2300 /** @var array Items to be processed in the deletion batch */
2301 private $deletionBatch;
2303 /** @var bool Whether to suppress all suppressable fields when deleting */
2314 * @param string $reason
2315 * @param bool $suppress
2316 * @param User|null $user
2318 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2319 $this->file
= $file;
2320 $this->reason
= $reason;
2321 $this->suppress
= $suppress;
2323 $this->user
= $user;
2326 $this->user
= $wgUser;
2328 $this->status
= $file->repo
->newGood();
2331 public function addCurrent() {
2332 $this->srcRels
['.'] = $this->file
->getRel();
2336 * @param string $oldName
2338 public function addOld( $oldName ) {
2339 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2340 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2344 * Add the old versions of the image to the batch
2345 * @return string[] List of archive names from old versions
2347 public function addOlds() {
2350 $dbw = $this->file
->repo
->getMasterDB();
2351 $result = $dbw->select( 'oldimage',
2352 [ 'oi_archive_name' ],
2353 [ 'oi_name' => $this->file
->getName() ],
2357 foreach ( $result as $row ) {
2358 $this->addOld( $row->oi_archive_name
);
2359 $archiveNames[] = $row->oi_archive_name
;
2362 return $archiveNames;
2368 protected function getOldRels() {
2369 if ( !isset( $this->srcRels
['.'] ) ) {
2370 $oldRels =& $this->srcRels
;
2371 $deleteCurrent = false;
2373 $oldRels = $this->srcRels
;
2374 unset( $oldRels['.'] );
2375 $deleteCurrent = true;
2378 return [ $oldRels, $deleteCurrent ];
2384 protected function getHashes() {
2386 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2388 if ( $deleteCurrent ) {
2389 $hashes['.'] = $this->file
->getSha1();
2392 if ( count( $oldRels ) ) {
2393 $dbw = $this->file
->repo
->getMasterDB();
2394 $res = $dbw->select(
2396 [ 'oi_archive_name', 'oi_sha1' ],
2397 [ 'oi_archive_name' => array_keys( $oldRels ),
2398 'oi_name' => $this->file
->getName() ], // performance
2402 foreach ( $res as $row ) {
2403 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2404 // Get the hash from the file
2405 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2406 $props = $this->file
->repo
->getFileProps( $oldUrl );
2408 if ( $props['fileExists'] ) {
2409 // Upgrade the oldimage row
2410 $dbw->update( 'oldimage',
2411 [ 'oi_sha1' => $props['sha1'] ],
2412 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2414 $hashes[$row->oi_archive_name
] = $props['sha1'];
2416 $hashes[$row->oi_archive_name
] = false;
2419 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2424 $missing = array_diff_key( $this->srcRels
, $hashes );
2426 foreach ( $missing as $name => $rel ) {
2427 $this->status
->error( 'filedelete-old-unregistered', $name );
2430 foreach ( $hashes as $name => $hash ) {
2432 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2433 unset( $hashes[$name] );
2440 protected function doDBInserts() {
2441 global $wgActorTableSchemaMigrationStage;
2444 $dbw = $this->file
->repo
->getMasterDB();
2446 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
2447 $actorMigration = ActorMigration
::newMigration();
2449 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2450 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2451 $encGroup = $dbw->addQuotes( 'deleted' );
2452 $ext = $this->file
->getExtension();
2453 $dotExt = $ext === '' ?
'' : ".$ext";
2454 $encExt = $dbw->addQuotes( $dotExt );
2455 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2457 // Bitfields to further suppress the content
2458 if ( $this->suppress
) {
2459 $bitfield = Revision
::SUPPRESSED_ALL
;
2461 $bitfield = 'oi_deleted';
2464 if ( $deleteCurrent ) {
2465 $tables = [ 'image' ];
2467 'fa_storage_group' => $encGroup,
2468 'fa_storage_key' => $dbw->conditional(
2469 [ 'img_sha1' => '' ],
2470 $dbw->addQuotes( '' ),
2471 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2473 'fa_deleted_user' => $encUserId,
2474 'fa_deleted_timestamp' => $encTimestamp,
2475 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2476 'fa_name' => 'img_name',
2477 'fa_archive_name' => 'NULL',
2478 'fa_size' => 'img_size',
2479 'fa_width' => 'img_width',
2480 'fa_height' => 'img_height',
2481 'fa_metadata' => 'img_metadata',
2482 'fa_bits' => 'img_bits',
2483 'fa_media_type' => 'img_media_type',
2484 'fa_major_mime' => 'img_major_mime',
2485 'fa_minor_mime' => 'img_minor_mime',
2486 'fa_description_id' => 'img_description_id',
2487 'fa_timestamp' => 'img_timestamp',
2488 'fa_sha1' => 'img_sha1'
2492 $fields +
= array_map(
2493 [ $dbw, 'addQuotes' ],
2494 $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason
)
2497 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2498 $fields['fa_user'] = 'img_user';
2499 $fields['fa_user_text'] = 'img_user_text';
2501 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2502 $fields['fa_actor'] = 'img_actor';
2506 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
2508 // Upgrade any rows that are still old-style. Otherwise an upgrade
2509 // might be missed if a deletion happens while the migration script
2511 $res = $dbw->select(
2513 [ 'img_name', 'img_user', 'img_user_text' ],
2514 [ 'img_name' => $this->file
->getName(), 'img_actor' => 0 ],
2517 foreach ( $res as $row ) {
2518 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
2521 [ 'img_actor' => $actorId ],
2522 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
2528 $dbw->insertSelect( 'filearchive', $tables, $fields,
2529 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2532 if ( count( $oldRels ) ) {
2533 $fileQuery = OldLocalFile
::getQueryInfo();
2534 $res = $dbw->select(
2535 $fileQuery['tables'],
2536 $fileQuery['fields'],
2538 'oi_name' => $this->file
->getName(),
2539 'oi_archive_name' => array_keys( $oldRels )
2546 if ( $res->numRows() ) {
2547 $reason = $commentStore->createComment( $dbw, $this->reason
);
2548 foreach ( $res as $row ) {
2549 $comment = $commentStore->getComment( 'oi_description', $row );
2550 $user = User
::newFromAnyId( $row->oi_user
, $row->oi_user_text
, $row->oi_actor
);
2552 // Deletion-specific fields
2553 'fa_storage_group' => 'deleted',
2554 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2556 : "{$row->oi_sha1}{$dotExt}",
2557 'fa_deleted_user' => $this->user
->getId(),
2558 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2559 // Counterpart fields
2560 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2561 'fa_name' => $row->oi_name
,
2562 'fa_archive_name' => $row->oi_archive_name
,
2563 'fa_size' => $row->oi_size
,
2564 'fa_width' => $row->oi_width
,
2565 'fa_height' => $row->oi_height
,
2566 'fa_metadata' => $row->oi_metadata
,
2567 'fa_bits' => $row->oi_bits
,
2568 'fa_media_type' => $row->oi_media_type
,
2569 'fa_major_mime' => $row->oi_major_mime
,
2570 'fa_minor_mime' => $row->oi_minor_mime
,
2571 'fa_timestamp' => $row->oi_timestamp
,
2572 'fa_sha1' => $row->oi_sha1
2573 ] +
$commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2574 +
$commentStore->insert( $dbw, 'fa_description', $comment )
2575 +
$actorMigration->getInsertValues( $dbw, 'fa_user', $user );
2579 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2583 function doDBDeletes() {
2584 $dbw = $this->file
->repo
->getMasterDB();
2585 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2587 if ( count( $oldRels ) ) {
2588 $dbw->delete( 'oldimage',
2590 'oi_name' => $this->file
->getName(),
2591 'oi_archive_name' => array_keys( $oldRels )
2595 if ( $deleteCurrent ) {
2596 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2601 * Run the transaction
2604 public function execute() {
2605 $repo = $this->file
->getRepo();
2606 $this->file
->lock();
2608 // Prepare deletion batch
2609 $hashes = $this->getHashes();
2610 $this->deletionBatch
= [];
2611 $ext = $this->file
->getExtension();
2612 $dotExt = $ext === '' ?
'' : ".$ext";
2614 foreach ( $this->srcRels
as $name => $srcRel ) {
2615 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2616 if ( isset( $hashes[$name] ) ) {
2617 $hash = $hashes[$name];
2618 $key = $hash . $dotExt;
2619 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2620 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2624 if ( !$repo->hasSha1Storage() ) {
2625 // Removes non-existent file from the batch, so we don't get errors.
2626 // This also handles files in the 'deleted' zone deleted via revision deletion.
2627 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2628 if ( !$checkStatus->isGood() ) {
2629 $this->status
->merge( $checkStatus );
2630 return $this->status
;
2632 $this->deletionBatch
= $checkStatus->value
;
2634 // Execute the file deletion batch
2635 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2636 if ( !$status->isGood() ) {
2637 $this->status
->merge( $status );
2641 if ( !$this->status
->isOK() ) {
2642 // Critical file deletion error; abort
2643 $this->file
->unlock();
2645 return $this->status
;
2648 // Copy the image/oldimage rows to filearchive
2649 $this->doDBInserts();
2650 // Delete image/oldimage rows
2651 $this->doDBDeletes();
2653 // Commit and return
2654 $this->file
->unlock();
2656 return $this->status
;
2660 * Removes non-existent files from a deletion batch.
2661 * @param array $batch
2664 protected function removeNonexistentFiles( $batch ) {
2665 $files = $newBatch = [];
2667 foreach ( $batch as $batchItem ) {
2668 list( $src, ) = $batchItem;
2669 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2672 $result = $this->file
->repo
->fileExistsBatch( $files );
2673 if ( in_array( null, $result, true ) ) {
2674 return Status
::newFatal( 'backend-fail-internal',
2675 $this->file
->repo
->getBackend()->getName() );
2678 foreach ( $batch as $batchItem ) {
2679 if ( $result[$batchItem[0]] ) {
2680 $newBatch[] = $batchItem;
2684 return Status
::newGood( $newBatch );
2688 # ------------------------------------------------------------------------------
2691 * Helper class for file undeletion
2692 * @ingroup FileAbstraction
2694 class LocalFileRestoreBatch
{
2695 /** @var LocalFile */
2698 /** @var string[] List of file IDs to restore */
2699 private $cleanupBatch;
2701 /** @var string[] List of file IDs to restore */
2704 /** @var bool Add all revisions of the file */
2707 /** @var bool Whether to remove all settings for suppressed fields */
2708 private $unsuppress = false;
2712 * @param bool $unsuppress
2714 function __construct( File
$file, $unsuppress = false ) {
2715 $this->file
= $file;
2716 $this->cleanupBatch
= [];
2718 $this->unsuppress
= $unsuppress;
2725 public function addId( $fa_id ) {
2726 $this->ids
[] = $fa_id;
2730 * Add a whole lot of files by ID
2733 public function addIds( $ids ) {
2734 $this->ids
= array_merge( $this->ids
, $ids );
2738 * Add all revisions of the file
2740 public function addAll() {
2745 * Run the transaction, except the cleanup batch.
2746 * The cleanup batch should be run in a separate transaction, because it locks different
2747 * rows and there's no need to keep the image row locked while it's acquiring those locks
2748 * The caller may have its own transaction open.
2749 * So we save the batch and let the caller call cleanup()
2752 public function execute() {
2753 /** @var Language */
2756 $repo = $this->file
->getRepo();
2757 if ( !$this->all
&& !$this->ids
) {
2759 return $repo->newGood();
2762 $lockOwnsTrx = $this->file
->lock();
2764 $dbw = $this->file
->repo
->getMasterDB();
2766 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
2767 $actorMigration = ActorMigration
::newMigration();
2769 $status = $this->file
->repo
->newGood();
2771 $exists = (bool)$dbw->selectField( 'image', '1',
2772 [ 'img_name' => $this->file
->getName() ],
2774 // The lock() should already prevents changes, but this still may need
2775 // to bypass any transaction snapshot. However, if lock() started the
2776 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2777 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2780 // Fetch all or selected archived revisions for the file,
2781 // sorted from the most recent to the oldest.
2782 $conditions = [ 'fa_name' => $this->file
->getName() ];
2784 if ( !$this->all
) {
2785 $conditions['fa_id'] = $this->ids
;
2788 $arFileQuery = ArchivedFile
::getQueryInfo();
2789 $result = $dbw->select(
2790 $arFileQuery['tables'],
2791 $arFileQuery['fields'],
2794 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2795 $arFileQuery['joins']
2801 $insertCurrent = false;
2806 foreach ( $result as $row ) {
2807 $idsPresent[] = $row->fa_id
;
2809 if ( $row->fa_name
!= $this->file
->getName() ) {
2810 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2811 $status->failCount++
;
2815 if ( $row->fa_storage_key
== '' ) {
2816 // Revision was missing pre-deletion
2817 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2818 $status->failCount++
;
2822 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2823 $row->fa_storage_key
;
2824 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2826 if ( isset( $row->fa_sha1
) ) {
2827 $sha1 = $row->fa_sha1
;
2829 // old row, populate from key
2830 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2834 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2835 $sha1 = substr( $sha1, 1 );
2838 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2839 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2840 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2841 ||
is_null( $row->fa_metadata
)
2843 // Refresh our metadata
2844 // Required for a new current revision; nice for older ones too. :)
2845 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2848 'minor_mime' => $row->fa_minor_mime
,
2849 'major_mime' => $row->fa_major_mime
,
2850 'media_type' => $row->fa_media_type
,
2851 'metadata' => $row->fa_metadata
2855 $comment = $commentStore->getComment( 'fa_description', $row );
2856 $user = User
::newFromAnyId( $row->fa_user
, $row->fa_user_text
, $row->fa_actor
);
2857 if ( $first && !$exists ) {
2858 // This revision will be published as the new current version
2859 $destRel = $this->file
->getRel();
2860 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
2861 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
2863 'img_name' => $row->fa_name
,
2864 'img_size' => $row->fa_size
,
2865 'img_width' => $row->fa_width
,
2866 'img_height' => $row->fa_height
,
2867 'img_metadata' => $props['metadata'],
2868 'img_bits' => $row->fa_bits
,
2869 'img_media_type' => $props['media_type'],
2870 'img_major_mime' => $props['major_mime'],
2871 'img_minor_mime' => $props['minor_mime'],
2872 'img_timestamp' => $row->fa_timestamp
,
2874 ] +
$commentFields +
$actorFields;
2876 // The live (current) version cannot be hidden!
2877 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2878 $status->fatal( 'undeleterevdel' );
2879 $this->file
->unlock();
2883 $archiveName = $row->fa_archive_name
;
2885 if ( $archiveName == '' ) {
2886 // This was originally a current version; we
2887 // have to devise a new archive name for it.
2888 // Format is <timestamp of archiving>!<name>
2889 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2892 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2894 } while ( isset( $archiveNames[$archiveName] ) );
2897 $archiveNames[$archiveName] = true;
2898 $destRel = $this->file
->getArchiveRel( $archiveName );
2900 'oi_name' => $row->fa_name
,
2901 'oi_archive_name' => $archiveName,
2902 'oi_size' => $row->fa_size
,
2903 'oi_width' => $row->fa_width
,
2904 'oi_height' => $row->fa_height
,
2905 'oi_bits' => $row->fa_bits
,
2906 'oi_timestamp' => $row->fa_timestamp
,
2907 'oi_metadata' => $props['metadata'],
2908 'oi_media_type' => $props['media_type'],
2909 'oi_major_mime' => $props['major_mime'],
2910 'oi_minor_mime' => $props['minor_mime'],
2911 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2913 ] +
$commentStore->insert( $dbw, 'oi_description', $comment )
2914 +
$actorMigration->getInsertValues( $dbw, 'oi_user', $user );
2917 $deleteIds[] = $row->fa_id
;
2919 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2920 // private files can stay where they are
2921 $status->successCount++
;
2923 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2924 $this->cleanupBatch
[] = $row->fa_storage_key
;
2932 // Add a warning to the status object for missing IDs
2933 $missingIds = array_diff( $this->ids
, $idsPresent );
2935 foreach ( $missingIds as $id ) {
2936 $status->error( 'undelete-missing-filearchive', $id );
2939 if ( !$repo->hasSha1Storage() ) {
2940 // Remove missing files from batch, so we don't get errors when undeleting them
2941 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2942 if ( !$checkStatus->isGood() ) {
2943 $status->merge( $checkStatus );
2946 $storeBatch = $checkStatus->value
;
2948 // Run the store batch
2949 // Use the OVERWRITE_SAME flag to smooth over a common error
2950 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2951 $status->merge( $storeStatus );
2953 if ( !$status->isGood() ) {
2954 // Even if some files could be copied, fail entirely as that is the
2955 // easiest thing to do without data loss
2956 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2957 $status->setOK( false );
2958 $this->file
->unlock();
2964 // Run the DB updates
2965 // Because we have locked the image row, key conflicts should be rare.
2966 // If they do occur, we can roll back the transaction at this time with
2967 // no data loss, but leaving unregistered files scattered throughout the
2969 // This is not ideal, which is why it's important to lock the image row.
2970 if ( $insertCurrent ) {
2971 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2974 if ( $insertBatch ) {
2975 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2979 $dbw->delete( 'filearchive',
2980 [ 'fa_id' => $deleteIds ],
2984 // If store batch is empty (all files are missing), deletion is to be considered successful
2985 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2987 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2989 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2991 $this->file
->purgeEverything();
2993 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2994 $this->file
->purgeDescription();
2998 $this->file
->unlock();
3004 * Removes non-existent files from a store batch.
3005 * @param array $triplets
3008 protected function removeNonexistentFiles( $triplets ) {
3009 $files = $filteredTriplets = [];
3010 foreach ( $triplets as $file ) {
3011 $files[$file[0]] = $file[0];
3014 $result = $this->file
->repo
->fileExistsBatch( $files );
3015 if ( in_array( null, $result, true ) ) {
3016 return Status
::newFatal( 'backend-fail-internal',
3017 $this->file
->repo
->getBackend()->getName() );
3020 foreach ( $triplets as $file ) {
3021 if ( $result[$file[0]] ) {
3022 $filteredTriplets[] = $file;
3026 return Status
::newGood( $filteredTriplets );
3030 * Removes non-existent files from a cleanup batch.
3031 * @param string[] $batch
3034 protected function removeNonexistentFromCleanup( $batch ) {
3035 $files = $newBatch = [];
3036 $repo = $this->file
->repo
;
3038 foreach ( $batch as $file ) {
3039 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3040 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3043 $result = $repo->fileExistsBatch( $files );
3045 foreach ( $batch as $file ) {
3046 if ( $result[$file] ) {
3047 $newBatch[] = $file;
3055 * Delete unused files in the deleted zone.
3056 * This should be called from outside the transaction in which execute() was called.
3059 public function cleanup() {
3060 if ( !$this->cleanupBatch
) {
3061 return $this->file
->repo
->newGood();
3064 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
3066 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
3072 * Cleanup a failed batch. The batch was only partially successful, so
3073 * rollback by removing all items that were successfully copied.
3075 * @param Status $storeStatus
3076 * @param array[] $storeBatch
3078 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3081 foreach ( $storeStatus->success
as $i => $success ) {
3082 // Check if this item of the batch was successfully copied
3084 // Item was successfully copied and needs to be removed again
3085 // Extract ($dstZone, $dstRel) from the batch
3086 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3089 $this->file
->repo
->cleanupBatch( $cleanupBatch );
3093 # ------------------------------------------------------------------------------
3096 * Helper class for file movement
3097 * @ingroup FileAbstraction
3099 class LocalFileMoveBatch
{
3100 /** @var LocalFile */
3110 protected $oldCount;
3114 /** @var IDatabase */
3119 * @param Title $target
3121 function __construct( File
$file, Title
$target ) {
3122 $this->file
= $file;
3123 $this->target
= $target;
3124 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
3125 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
3126 $this->oldName
= $this->file
->getName();
3127 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
3128 $this->oldRel
= $this->oldHash
. $this->oldName
;
3129 $this->newRel
= $this->newHash
. $this->newName
;
3130 $this->db
= $file->getRepo()->getMasterDB();
3134 * Add the current image to the batch
3136 public function addCurrent() {
3137 $this->cur
= [ $this->oldRel
, $this->newRel
];
3141 * Add the old versions of the image to the batch
3142 * @return string[] List of archive names from old versions
3144 public function addOlds() {
3145 $archiveBase = 'archive';
3147 $this->oldCount
= 0;
3150 $result = $this->db
->select( 'oldimage',
3151 [ 'oi_archive_name', 'oi_deleted' ],
3152 [ 'oi_name' => $this->oldName
],
3154 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3157 foreach ( $result as $row ) {
3158 $archiveNames[] = $row->oi_archive_name
;
3159 $oldName = $row->oi_archive_name
;
3160 $bits = explode( '!', $oldName, 2 );
3162 if ( count( $bits ) != 2 ) {
3163 wfDebug( "Old file name missing !: '$oldName' \n" );
3167 list( $timestamp, $filename ) = $bits;
3169 if ( $this->oldName
!= $filename ) {
3170 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3176 // Do we want to add those to oldCount?
3177 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3182 "{$archiveBase}/{$this->oldHash}{$oldName}",
3183 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3187 return $archiveNames;
3194 public function execute() {
3195 $repo = $this->file
->repo
;
3196 $status = $repo->newGood();
3197 $destFile = wfLocalFile( $this->target
);
3199 $this->file
->lock();
3200 $destFile->lock(); // quickly fail if destination is not available
3202 $triplets = $this->getMoveTriplets();
3203 $checkStatus = $this->removeNonexistentFiles( $triplets );
3204 if ( !$checkStatus->isGood() ) {
3205 $destFile->unlock();
3206 $this->file
->unlock();
3207 $status->merge( $checkStatus ); // couldn't talk to file backend
3210 $triplets = $checkStatus->value
;
3212 // Verify the file versions metadata in the DB.
3213 $statusDb = $this->verifyDBUpdates();
3214 if ( !$statusDb->isGood() ) {
3215 $destFile->unlock();
3216 $this->file
->unlock();
3217 $statusDb->setOK( false );
3222 if ( !$repo->hasSha1Storage() ) {
3223 // Copy the files into their new location.
3224 // If a prior process fataled copying or cleaning up files we tolerate any
3225 // of the existing files if they are identical to the ones being stored.
3226 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3227 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3228 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3229 if ( !$statusMove->isGood() ) {
3230 // Delete any files copied over (while the destination is still locked)
3231 $this->cleanupTarget( $triplets );
3232 $destFile->unlock();
3233 $this->file
->unlock();
3234 wfDebugLog( 'imagemove', "Error in moving files: "
3235 . $statusMove->getWikiText( false, false, 'en' ) );
3236 $statusMove->setOK( false );
3240 $status->merge( $statusMove );
3243 // Rename the file versions metadata in the DB.
3244 $this->doDBUpdates();
3246 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3247 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3249 $destFile->unlock();
3250 $this->file
->unlock();
3252 // Everything went ok, remove the source files
3253 $this->cleanupSource( $triplets );
3255 $status->merge( $statusDb );
3261 * Verify the database updates and return a new Status indicating how
3262 * many rows would be updated.
3266 protected function verifyDBUpdates() {
3267 $repo = $this->file
->repo
;
3268 $status = $repo->newGood();
3271 $hasCurrent = $dbw->lockForUpdate(
3273 [ 'img_name' => $this->oldName
],
3276 $oldRowCount = $dbw->lockForUpdate(
3278 [ 'oi_name' => $this->oldName
],
3282 if ( $hasCurrent ) {
3283 $status->successCount++
;
3285 $status->failCount++
;
3287 $status->successCount +
= $oldRowCount;
3288 // T36934: oldCount is based on files that actually exist.
3289 // There may be more DB rows than such files, in which case $affected
3290 // can be greater than $total. We use max() to avoid negatives here.
3291 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3292 if ( $status->failCount
) {
3293 $status->error( 'imageinvalidfilename' );
3300 * Do the database updates and return a new Status indicating how
3301 * many rows where updated.
3303 protected function doDBUpdates() {
3306 // Update current image
3309 [ 'img_name' => $this->newName
],
3310 [ 'img_name' => $this->oldName
],
3314 // Update old images
3318 'oi_name' => $this->newName
,
3319 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3320 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3322 [ 'oi_name' => $this->oldName
],
3328 * Generate triplets for FileRepo::storeBatch().
3331 protected function getMoveTriplets() {
3332 $moves = array_merge( [ $this->cur
], $this->olds
);
3333 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3335 foreach ( $moves as $move ) {
3336 // $move: (oldRelativePath, newRelativePath)
3337 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3338 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3341 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3349 * Removes non-existent files from move batch.
3350 * @param array $triplets
3353 protected function removeNonexistentFiles( $triplets ) {
3356 foreach ( $triplets as $file ) {
3357 $files[$file[0]] = $file[0];
3360 $result = $this->file
->repo
->fileExistsBatch( $files );
3361 if ( in_array( null, $result, true ) ) {
3362 return Status
::newFatal( 'backend-fail-internal',
3363 $this->file
->repo
->getBackend()->getName() );
3366 $filteredTriplets = [];
3367 foreach ( $triplets as $file ) {
3368 if ( $result[$file[0]] ) {
3369 $filteredTriplets[] = $file;
3371 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3375 return Status
::newGood( $filteredTriplets );
3379 * Cleanup a partially moved array of triplets by deleting the target
3380 * files. Called if something went wrong half way.
3381 * @param array[] $triplets
3383 protected function cleanupTarget( $triplets ) {
3384 // Create dest pairs from the triplets
3386 foreach ( $triplets as $triplet ) {
3387 // $triplet: (old source virtual URL, dst zone, dest rel)
3388 $pairs[] = [ $triplet[1], $triplet[2] ];
3391 $this->file
->repo
->cleanupBatch( $pairs );
3395 * Cleanup a fully moved array of triplets by deleting the source files.
3396 * Called at the end of the move process if everything else went ok.
3397 * @param array[] $triplets
3399 protected function cleanupSource( $triplets ) {
3400 // Create source file names from the triplets
3402 foreach ( $triplets as $triplet ) {
3403 $files[] = $triplet[0];
3406 $this->file
->repo
->cleanupBatch( $files );
3410 class LocalFileLockError
extends ErrorPageError
{
3411 public function __construct( Status
$status ) {
3412 parent
::__construct(
3414 $status->getMessage()
3418 public function report() {
3420 $wgOut->setStatusCode( 429 );