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 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 > MIGRATION_WRITE_BOTH
) {
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 written anymore.
209 throw new BadMethodCallException(
210 'Cannot use ' . __METHOD__
. ' when $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH'
226 'img_actor' => $wgActorTableSchemaMigrationStage > MIGRATION_OLD ?
'img_actor' : null,
229 ] + MediaWikiServices
::getInstance()->getCommentStore()->getFields( 'img_description' );
233 * Return the tables, fields, and join conditions to be selected to create
234 * a new localfile object.
236 * @param string[] $options
237 * - omit-lazy: Omit fields that are lazily cached.
238 * @return array[] With three keys:
239 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
240 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
241 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
243 public static function getQueryInfo( array $options = [] ) {
244 $commentQuery = MediaWikiServices
::getInstance()->getCommentStore()->getJoin( 'img_description' );
245 $actorQuery = ActorMigration
::newMigration()->getJoin( 'img_user' );
247 'tables' => [ 'image' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
260 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
261 'joins' => $commentQuery['joins'] +
$actorQuery['joins'],
264 if ( in_array( 'omit-nonlazy', $options, true ) ) {
265 // Internal use only for getting only the lazy fields
268 if ( !in_array( 'omit-lazy', $options, true ) ) {
269 // Note: Keep this in sync with self::getLazyCacheFields()
270 $ret['fields'][] = 'img_metadata';
277 * Do not call this except from inside a repo class.
278 * @param Title $title
279 * @param FileRepo $repo
281 function __construct( $title, $repo ) {
282 parent
::__construct( $title, $repo );
284 $this->metadata
= '';
285 $this->historyLine
= 0;
286 $this->historyRes
= null;
287 $this->dataLoaded
= false;
288 $this->extraDataLoaded
= false;
290 $this->assertRepoDefined();
291 $this->assertTitleDefined();
295 * Get the memcached key for the main data for this file, or false if
296 * there is no access to the shared cache.
297 * @return string|bool
299 function getCacheKey() {
300 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
304 * @param WANObjectCache $cache
308 public function getMutableCacheKeys( WANObjectCache
$cache ) {
309 return [ $this->getCacheKey() ];
313 * Try to load file metadata from memcached, falling back to the database
315 private function loadFromCache() {
316 $this->dataLoaded
= false;
317 $this->extraDataLoaded
= false;
319 $key = $this->getCacheKey();
321 $this->loadFromDB( self
::READ_NORMAL
);
326 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
327 $cachedValues = $cache->getWithSetCallback(
330 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
331 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
333 $this->loadFromDB( self
::READ_NORMAL
);
335 $fields = $this->getCacheFields( '' );
336 $cacheVal['fileExists'] = $this->fileExists
;
337 if ( $this->fileExists
) {
338 foreach ( $fields as $field ) {
339 $cacheVal[$field] = $this->$field;
342 $cacheVal['user'] = $this->user ?
$this->user
->getId() : 0;
343 $cacheVal['user_text'] = $this->user ?
$this->user
->getName() : '';
344 $cacheVal['actor'] = $this->user ?
$this->user
->getActorId() : null;
346 // Strip off excessive entries from the subset of fields that can become large.
347 // If the cache value gets to large it will not fit in memcached and nothing will
348 // get cached at all, causing master queries for any file access.
349 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
350 if ( isset( $cacheVal[$field] )
351 && strlen( $cacheVal[$field] ) > 100 * 1024
353 unset( $cacheVal[$field] ); // don't let the value get too big
357 if ( $this->fileExists
) {
358 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
360 $ttl = $cache::TTL_DAY
;
365 [ 'version' => self
::VERSION
]
368 $this->fileExists
= $cachedValues['fileExists'];
369 if ( $this->fileExists
) {
370 $this->setProps( $cachedValues );
373 $this->dataLoaded
= true;
374 $this->extraDataLoaded
= true;
375 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
376 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
381 * Purge the file object/metadata cache
383 public function invalidateCache() {
384 $key = $this->getCacheKey();
389 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
390 function () use ( $key ) {
391 MediaWikiServices
::getInstance()->getMainWANObjectCache()->delete( $key );
398 * Load metadata from the file itself
400 function loadFromFile() {
401 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
402 $this->setProps( $props );
406 * Returns the list of object properties that are included as-is in the cache.
407 * @param string $prefix Must be the empty string
409 * @since 1.31 No longer accepts a non-empty $prefix
411 protected function getCacheFields( $prefix = 'img_' ) {
412 if ( $prefix !== '' ) {
413 throw new InvalidArgumentException(
414 __METHOD__
. ' with a non-empty prefix is no longer supported.'
418 // See self::getQueryInfo() for the fetching of the data from the DB,
419 // self::loadFromRow() for the loading of the object from the DB row,
420 // and self::loadFromCache() for the caching, and self::setProps() for
421 // populating the object from an array of data.
422 return [ 'size', 'width', 'height', 'bits', 'media_type',
423 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
427 * Returns the list of object properties that are included as-is in the
428 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
429 * @param string $prefix Must be the empty string
431 * @since 1.31 No longer accepts a non-empty $prefix
433 protected function getLazyCacheFields( $prefix = 'img_' ) {
434 if ( $prefix !== '' ) {
435 throw new InvalidArgumentException(
436 __METHOD__
. ' with a non-empty prefix is no longer supported.'
440 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
441 return [ 'metadata' ];
445 * Load file metadata from the DB
448 function loadFromDB( $flags = 0 ) {
449 $fname = static::class . '::' . __FUNCTION__
;
451 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
452 $this->dataLoaded
= true;
453 $this->extraDataLoaded
= true;
455 $dbr = ( $flags & self
::READ_LATEST
)
456 ?
$this->repo
->getMasterDB()
457 : $this->repo
->getReplicaDB();
459 $fileQuery = static::getQueryInfo();
460 $row = $dbr->selectRow(
461 $fileQuery['tables'],
462 $fileQuery['fields'],
463 [ 'img_name' => $this->getName() ],
470 $this->loadFromRow( $row );
472 $this->fileExists
= false;
477 * Load lazy file metadata from the DB.
478 * This covers fields that are sometimes not cached.
480 protected function loadExtraFromDB() {
481 $fname = static::class . '::' . __FUNCTION__
;
483 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
484 $this->extraDataLoaded
= true;
486 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
488 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
492 foreach ( $fieldMap as $name => $value ) {
493 $this->$name = $value;
496 throw new MWException( "Could not find data for image '{$this->getName()}'." );
501 * @param IDatabase $dbr
502 * @param string $fname
503 * @return string[]|bool
505 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
508 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
509 $row = $dbr->selectRow(
510 $fileQuery['tables'],
511 $fileQuery['fields'],
513 'img_name' => $this->getName(),
514 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
521 $fieldMap = $this->unprefixRow( $row, 'img_' );
523 # File may have been uploaded over in the meantime; check the old versions
524 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
525 $row = $dbr->selectRow(
526 $fileQuery['tables'],
527 $fileQuery['fields'],
529 'oi_name' => $this->getName(),
530 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
537 $fieldMap = $this->unprefixRow( $row, 'oi_' );
541 if ( isset( $fieldMap['metadata'] ) ) {
542 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
549 * @param array|object $row
550 * @param string $prefix
551 * @throws MWException
554 protected function unprefixRow( $row, $prefix = 'img_' ) {
555 $array = (array)$row;
556 $prefixLength = strlen( $prefix );
558 // Sanity check prefix once
559 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
560 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
564 foreach ( $array as $name => $value ) {
565 $decoded[substr( $name, $prefixLength )] = $value;
572 * Decode a row from the database (either object or array) to an array
573 * with timestamps and MIME types decoded, and the field prefix removed.
575 * @param string $prefix
576 * @throws MWException
579 function decodeRow( $row, $prefix = 'img_' ) {
580 $decoded = $this->unprefixRow( $row, $prefix );
582 $decoded['description'] = MediaWikiServices
::getInstance()->getCommentStore()
583 ->getComment( 'description', (object)$decoded )->text
;
585 $decoded['user'] = User
::newFromAnyId(
586 isset( $decoded['user'] ) ?
$decoded['user'] : null,
587 isset( $decoded['user_text'] ) ?
$decoded['user_text'] : null,
588 isset( $decoded['actor'] ) ?
$decoded['actor'] : null
590 unset( $decoded['user_text'], $decoded['actor'] );
592 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
594 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
596 if ( empty( $decoded['major_mime'] ) ) {
597 $decoded['mime'] = 'unknown/unknown';
599 if ( !$decoded['minor_mime'] ) {
600 $decoded['minor_mime'] = 'unknown';
602 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
605 // Trim zero padding from char/binary field
606 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
608 // Normalize some fields to integer type, per their database definition.
609 // Use unary + so that overflows will be upgraded to double instead of
610 // being trucated as with intval(). This is important to allow >2GB
611 // files on 32-bit systems.
612 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
613 $decoded[$field] = +
$decoded[$field];
620 * Load file metadata from a DB result row
623 * @param string $prefix
625 function loadFromRow( $row, $prefix = 'img_' ) {
626 $this->dataLoaded
= true;
627 $this->extraDataLoaded
= true;
629 $array = $this->decodeRow( $row, $prefix );
631 foreach ( $array as $name => $value ) {
632 $this->$name = $value;
635 $this->fileExists
= true;
636 $this->maybeUpgradeRow();
640 * Load file metadata from cache or DB, unless already loaded
643 function load( $flags = 0 ) {
644 if ( !$this->dataLoaded
) {
645 if ( $flags & self
::READ_LATEST
) {
646 $this->loadFromDB( $flags );
648 $this->loadFromCache();
652 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
653 // @note: loads on name/timestamp to reduce race condition problems
654 $this->loadExtraFromDB();
659 * Upgrade a row if it needs it
661 function maybeUpgradeRow() {
662 global $wgUpdateCompatibleMetadata;
664 if ( wfReadOnly() ||
$this->upgrading
) {
669 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
672 $handler = $this->getHandler();
674 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
675 if ( $validity === MediaHandler
::METADATA_BAD
) {
677 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
678 $upgrade = $wgUpdateCompatibleMetadata;
684 $this->upgrading
= true;
685 // Defer updates unless in auto-commit CLI mode
686 DeferredUpdates
::addCallableUpdate( function () {
687 $this->upgrading
= false; // avoid duplicate updates
690 } catch ( LocalFileLockError
$e ) {
691 // let the other process handle it (or do it next time)
698 * @return bool Whether upgradeRow() ran for this object
700 function getUpgraded() {
701 return $this->upgraded
;
705 * Fix assorted version-related problems with the image row by reloading it from the file
707 function upgradeRow() {
708 $this->lock(); // begin
710 $this->loadFromFile();
712 # Don't destroy file info of missing files
713 if ( !$this->fileExists
) {
715 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
720 $dbw = $this->repo
->getMasterDB();
721 list( $major, $minor ) = self
::splitMime( $this->mime
);
723 if ( wfReadOnly() ) {
728 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
730 $dbw->update( 'image',
732 'img_size' => $this->size
, // sanity
733 'img_width' => $this->width
,
734 'img_height' => $this->height
,
735 'img_bits' => $this->bits
,
736 'img_media_type' => $this->media_type
,
737 'img_major_mime' => $major,
738 'img_minor_mime' => $minor,
739 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
740 'img_sha1' => $this->sha1
,
742 [ 'img_name' => $this->getName() ],
746 $this->invalidateCache();
748 $this->unlock(); // done
749 $this->upgraded
= true; // avoid rework/retries
753 * Set properties in this object to be equal to those given in the
754 * associative array $info. Only cacheable fields can be set.
755 * All fields *must* be set in $info except for getLazyCacheFields().
757 * If 'mime' is given, it will be split into major_mime/minor_mime.
758 * If major_mime/minor_mime are given, $this->mime will also be set.
762 function setProps( $info ) {
763 $this->dataLoaded
= true;
764 $fields = $this->getCacheFields( '' );
765 $fields[] = 'fileExists';
767 foreach ( $fields as $field ) {
768 if ( isset( $info[$field] ) ) {
769 $this->$field = $info[$field];
773 if ( isset( $info['user'] ) ||
isset( $info['user_text'] ) ||
isset( $info['actor'] ) ) {
774 $this->user
= User
::newFromAnyId(
775 isset( $info['user'] ) ?
$info['user'] : null,
776 isset( $info['user_text'] ) ?
$info['user_text'] : null,
777 isset( $info['actor'] ) ?
$info['actor'] : null
781 // Fix up mime fields
782 if ( isset( $info['major_mime'] ) ) {
783 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
784 } elseif ( isset( $info['mime'] ) ) {
785 $this->mime
= $info['mime'];
786 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
790 /** splitMime inherited */
791 /** getName inherited */
792 /** getTitle inherited */
793 /** getURL inherited */
794 /** getViewURL inherited */
795 /** getPath inherited */
796 /** isVisible inherited */
801 function isMissing() {
802 if ( $this->missing
=== null ) {
803 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
804 $this->missing
= !$fileExists;
807 return $this->missing
;
811 * Return the width of the image
816 public function getWidth( $page = 1 ) {
824 if ( $this->isMultipage() ) {
825 $handler = $this->getHandler();
829 $dim = $handler->getPageDimensions( $this, $page );
831 return $dim['width'];
833 // For non-paged media, the false goes through an
834 // intval, turning failure into 0, so do same here.
843 * Return the height of the image
848 public function getHeight( $page = 1 ) {
856 if ( $this->isMultipage() ) {
857 $handler = $this->getHandler();
861 $dim = $handler->getPageDimensions( $this, $page );
863 return $dim['height'];
865 // For non-paged media, the false goes through an
866 // intval, turning failure into 0, so do same here.
870 return $this->height
;
875 * Returns user who uploaded the file
877 * @param string $type 'text', 'id', or 'object'
878 * @return int|string|User
879 * @since 1.31 Added 'object'
881 function getUser( $type = 'text' ) {
884 if ( $type === 'object' ) {
886 } elseif ( $type === 'text' ) {
887 return $this->user
->getName();
888 } elseif ( $type === 'id' ) {
889 return $this->user
->getId();
892 throw new MWException( "Unknown type '$type'." );
896 * Get short description URL for a file based on the page ID.
898 * @return string|null
899 * @throws MWException
902 public function getDescriptionShortUrl() {
903 $pageId = $this->title
->getArticleID();
905 if ( $pageId !== null ) {
906 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
907 if ( $url !== false ) {
915 * Get handler-specific metadata
918 function getMetadata() {
919 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
920 return $this->metadata
;
926 function getBitDepth() {
929 return (int)$this->bits
;
933 * Returns the size of the image file, in bytes
936 public function getSize() {
943 * Returns the MIME type of the file.
946 function getMimeType() {
953 * Returns the type of the media in the file.
954 * Use the value returned by this function with the MEDIATYPE_xxx constants.
957 function getMediaType() {
960 return $this->media_type
;
963 /** canRender inherited */
964 /** mustRender inherited */
965 /** allowInlineDisplay inherited */
966 /** isSafeFile inherited */
967 /** isTrustedFile inherited */
970 * Returns true if the file exists on disk.
971 * @return bool Whether file exist on disk.
973 public function exists() {
976 return $this->fileExists
;
979 /** getTransformScript inherited */
980 /** getUnscaledThumb inherited */
981 /** thumbName inherited */
982 /** createThumb inherited */
983 /** transform inherited */
985 /** getHandler inherited */
986 /** iconThumb inherited */
987 /** getLastError inherited */
990 * Get all thumbnail names previously generated for this file
991 * @param string|bool $archiveName Name of an archive file, default false
992 * @return array First element is the base dir, then files in that base dir.
994 function getThumbnails( $archiveName = false ) {
995 if ( $archiveName ) {
996 $dir = $this->getArchiveThumbPath( $archiveName );
998 $dir = $this->getThumbPath();
1001 $backend = $this->repo
->getBackend();
1004 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1005 foreach ( $iterator as $file ) {
1008 } catch ( FileBackendError
$e ) {
1009 } // suppress (T56674)
1015 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1017 function purgeMetadataCache() {
1018 $this->invalidateCache();
1022 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1024 * @param array $options An array potentially with the key forThumbRefresh.
1026 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1028 function purgeCache( $options = [] ) {
1029 // Refresh metadata cache
1030 $this->purgeMetadataCache();
1032 // Delete thumbnails
1033 $this->purgeThumbnails( $options );
1035 // Purge CDN cache for this file
1036 DeferredUpdates
::addUpdate(
1037 new CdnCacheUpdate( [ $this->getUrl() ] ),
1038 DeferredUpdates
::PRESEND
1043 * Delete cached transformed files for an archived version only.
1044 * @param string $archiveName Name of the archived file
1046 function purgeOldThumbnails( $archiveName ) {
1047 // Get a list of old thumbnails and URLs
1048 $files = $this->getThumbnails( $archiveName );
1050 // Purge any custom thumbnail caches
1051 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1053 // Delete thumbnails
1054 $dir = array_shift( $files );
1055 $this->purgeThumbList( $dir, $files );
1059 foreach ( $files as $file ) {
1060 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1062 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1066 * Delete cached transformed files for the current version only.
1067 * @param array $options
1069 public function purgeThumbnails( $options = [] ) {
1070 $files = $this->getThumbnails();
1071 // Always purge all files from CDN regardless of handler filters
1073 foreach ( $files as $file ) {
1074 $urls[] = $this->getThumbUrl( $file );
1076 array_shift( $urls ); // don't purge directory
1078 // Give media handler a chance to filter the file purge list
1079 if ( !empty( $options['forThumbRefresh'] ) ) {
1080 $handler = $this->getHandler();
1082 $handler->filterThumbnailPurgeList( $files, $options );
1086 // Purge any custom thumbnail caches
1087 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1089 // Delete thumbnails
1090 $dir = array_shift( $files );
1091 $this->purgeThumbList( $dir, $files );
1094 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1098 * Prerenders a configurable set of thumbnails
1102 public function prerenderThumbnails() {
1103 global $wgUploadThumbnailRenderMap;
1107 $sizes = $wgUploadThumbnailRenderMap;
1110 foreach ( $sizes as $size ) {
1111 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1112 $jobs[] = new ThumbnailRenderJob(
1114 [ 'transformParams' => [ 'width' => $size ] ]
1120 JobQueueGroup
::singleton()->lazyPush( $jobs );
1125 * Delete a list of thumbnails visible at urls
1126 * @param string $dir Base dir of the files.
1127 * @param array $files Array of strings: relative filenames (to $dir)
1129 protected function purgeThumbList( $dir, $files ) {
1130 $fileListDebug = strtr(
1131 var_export( $files, true ),
1134 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1137 foreach ( $files as $file ) {
1138 if ( $this->repo
->supportsSha1URLs() ) {
1139 $reference = $this->getSha1();
1141 $reference = $this->getName();
1144 # Check that the reference (filename or sha1) is part of the thumb name
1145 # This is a basic sanity check to avoid erasing unrelated directories
1146 if ( strpos( $file, $reference ) !== false
1147 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1149 $purgeList[] = "{$dir}/{$file}";
1153 # Delete the thumbnails
1154 $this->repo
->quickPurgeBatch( $purgeList );
1155 # Clear out the thumbnail directory if empty
1156 $this->repo
->quickCleanDir( $dir );
1159 /** purgeDescription inherited */
1160 /** purgeEverything inherited */
1163 * @param int|null $limit Optional: Limit to number of results
1164 * @param string|int|null $start Optional: Timestamp, start from
1165 * @param string|int|null $end Optional: Timestamp, end at
1167 * @return OldLocalFile[]
1169 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1170 $dbr = $this->repo
->getReplicaDB();
1171 $oldFileQuery = OldLocalFile
::getQueryInfo();
1173 $tables = $oldFileQuery['tables'];
1174 $fields = $oldFileQuery['fields'];
1175 $join_conds = $oldFileQuery['joins'];
1176 $conds = $opts = [];
1177 $eq = $inc ?
'=' : '';
1178 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1181 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1185 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1189 $opts['LIMIT'] = $limit;
1192 // Search backwards for time > x queries
1193 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1194 $opts['ORDER BY'] = "oi_timestamp $order";
1195 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1197 // Avoid PHP 7.1 warning from passing $this by reference
1199 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1200 &$conds, &$opts, &$join_conds ] );
1202 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1205 foreach ( $res as $row ) {
1206 $r[] = $this->repo
->newFileFromRow( $row );
1209 if ( $order == 'ASC' ) {
1210 $r = array_reverse( $r ); // make sure it ends up descending
1217 * Returns the history of this file, line by line.
1218 * starts with current version, then old versions.
1219 * uses $this->historyLine to check which line to return:
1220 * 0 return line for current version
1221 * 1 query for old versions, return first one
1222 * 2, ... return next old version from above query
1225 public function nextHistoryLine() {
1226 # Polymorphic function name to distinguish foreign and local fetches
1227 $fname = static::class . '::' . __FUNCTION__
;
1229 $dbr = $this->repo
->getReplicaDB();
1231 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1232 $fileQuery = self
::getQueryInfo();
1233 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1234 $fileQuery['fields'] +
[
1235 'oi_archive_name' => $dbr->addQuotes( '' ),
1238 [ 'img_name' => $this->title
->getDBkey() ],
1244 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1245 $this->historyRes
= null;
1249 } elseif ( $this->historyLine
== 1 ) {
1250 $fileQuery = OldLocalFile
::getQueryInfo();
1251 $this->historyRes
= $dbr->select(
1252 $fileQuery['tables'],
1253 $fileQuery['fields'],
1254 [ 'oi_name' => $this->title
->getDBkey() ],
1256 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1260 $this->historyLine++
;
1262 return $dbr->fetchObject( $this->historyRes
);
1266 * Reset the history pointer to the first element of the history
1268 public function resetHistory() {
1269 $this->historyLine
= 0;
1271 if ( !is_null( $this->historyRes
) ) {
1272 $this->historyRes
= null;
1276 /** getHashPath inherited */
1277 /** getRel inherited */
1278 /** getUrlRel inherited */
1279 /** getArchiveRel inherited */
1280 /** getArchivePath inherited */
1281 /** getThumbPath inherited */
1282 /** getArchiveUrl inherited */
1283 /** getThumbUrl inherited */
1284 /** getArchiveVirtualUrl inherited */
1285 /** getThumbVirtualUrl inherited */
1286 /** isHashed inherited */
1289 * Upload a file and record it in the DB
1290 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1291 * @param string $comment Upload description
1292 * @param string $pageText Text to use for the new description page,
1293 * if a new description page is created
1294 * @param int|bool $flags Flags for publish()
1295 * @param array|bool $props File properties, if known. This can be used to
1296 * reduce the upload time when uploading virtual URLs for which the file
1297 * info is already known
1298 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1300 * @param User|null $user User object or null to use $wgUser
1301 * @param string[] $tags Change tags to add to the log entry and page revision.
1302 * (This doesn't check $user's permissions.)
1303 * @return Status On success, the value member contains the
1304 * archive name, or an empty string if it was a new file.
1306 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1307 $timestamp = false, $user = null, $tags = []
1309 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1310 return $this->readOnlyFatalStatus();
1311 } elseif ( MediaWikiServices
::getInstance()->getRevisionStore()->isReadOnly() ) {
1312 // Check this in advance to avoid writing to FileBackend and the file tables,
1313 // only to fail on insert the revision due to the text store being unavailable.
1314 return $this->readOnlyFatalStatus();
1317 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1319 if ( $this->repo
->isVirtualUrl( $srcPath )
1320 || FileBackend
::isStoragePath( $srcPath )
1322 $props = $this->repo
->getFileProps( $srcPath );
1324 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
1325 $props = $mwProps->getPropsFromPath( $srcPath, true );
1330 $handler = MediaHandler
::getHandler( $props['mime'] );
1332 $metadata = Wikimedia\
quietCall( 'unserialize', $props['metadata'] );
1334 if ( !is_array( $metadata ) ) {
1338 $options['headers'] = $handler->getContentHeaders( $metadata );
1340 $options['headers'] = [];
1343 // Trim spaces on user supplied text
1344 $comment = trim( $comment );
1346 $this->lock(); // begin
1347 $status = $this->publish( $src, $flags, $options );
1349 if ( $status->successCount
>= 2 ) {
1350 // There will be a copy+(one of move,copy,store).
1351 // The first succeeding does not commit us to updating the DB
1352 // since it simply copied the current version to a timestamped file name.
1353 // It is only *preferable* to avoid leaving such files orphaned.
1354 // Once the second operation goes through, then the current version was
1355 // updated and we must therefore update the DB too.
1356 $oldver = $status->value
;
1357 $uploadStatus = $this->recordUpload2(
1366 if ( !$uploadStatus->isOK() ) {
1367 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1368 // update filenotfound error with more specific path
1369 $status->fatal( 'filenotfound', $srcPath );
1371 $status->merge( $uploadStatus );
1376 $this->unlock(); // done
1382 * Record a file upload in the upload log and the image table
1383 * @param string $oldver
1384 * @param string $desc
1385 * @param string $license
1386 * @param string $copyStatus
1387 * @param string $source
1388 * @param bool $watch
1389 * @param string|bool $timestamp
1390 * @param User|null $user User object or null to use $wgUser
1393 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1394 $watch = false, $timestamp = false, User
$user = null ) {
1400 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1402 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1407 $user->addWatch( $this->getTitle() );
1414 * Record a file upload in the upload log and the image table
1415 * @param string $oldver
1416 * @param string $comment
1417 * @param string $pageText
1418 * @param bool|array $props
1419 * @param string|bool $timestamp
1420 * @param null|User $user
1421 * @param string[] $tags
1424 function recordUpload2(
1425 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1427 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
1429 if ( is_null( $user ) ) {
1434 $dbw = $this->repo
->getMasterDB();
1436 # Imports or such might force a certain timestamp; otherwise we generate
1437 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1438 if ( $timestamp === false ) {
1439 $timestamp = $dbw->timestamp();
1440 $allowTimeKludge = true;
1442 $allowTimeKludge = false;
1445 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1446 $props['description'] = $comment;
1447 $props['user'] = $user->getId();
1448 $props['user_text'] = $user->getName();
1449 $props['actor'] = $user->getActorId( $dbw );
1450 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1451 $this->setProps( $props );
1453 # Fail now if the file isn't there
1454 if ( !$this->fileExists
) {
1455 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1457 return Status
::newFatal( 'filenotfound', $this->getRel() );
1460 $dbw->startAtomic( __METHOD__
);
1462 # Test to see if the row exists using INSERT IGNORE
1463 # This avoids race conditions by locking the row until the commit, and also
1464 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1465 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1466 list( $commentFields, $commentCallback ) =
1467 $commentStore->insertWithTempTable( $dbw, 'img_description', $comment );
1468 $actorMigration = ActorMigration
::newMigration();
1469 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1470 $dbw->insert( 'image',
1472 'img_name' => $this->getName(),
1473 'img_size' => $this->size
,
1474 'img_width' => intval( $this->width
),
1475 'img_height' => intval( $this->height
),
1476 'img_bits' => $this->bits
,
1477 'img_media_type' => $this->media_type
,
1478 'img_major_mime' => $this->major_mime
,
1479 'img_minor_mime' => $this->minor_mime
,
1480 'img_timestamp' => $timestamp,
1481 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1482 'img_sha1' => $this->sha1
1483 ] +
$commentFields +
$actorFields,
1487 $reupload = ( $dbw->affectedRows() == 0 );
1490 $row = $dbw->selectRow(
1492 [ 'img_timestamp', 'img_sha1' ],
1493 [ 'img_name' => $this->getName() ],
1495 [ 'LOCK IN SHARE MODE' ]
1498 if ( $row && $row->img_sha1
=== $this->sha1
) {
1499 $dbw->endAtomic( __METHOD__
);
1500 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1501 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1502 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1505 if ( $allowTimeKludge ) {
1506 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1507 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1508 # Avoid a timestamp that is not newer than the last version
1509 # TODO: the image/oldimage tables should be like page/revision with an ID field
1510 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1511 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1512 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1513 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1517 $tables = [ 'image' ];
1519 'oi_name' => 'img_name',
1520 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1521 'oi_size' => 'img_size',
1522 'oi_width' => 'img_width',
1523 'oi_height' => 'img_height',
1524 'oi_bits' => 'img_bits',
1525 'oi_timestamp' => 'img_timestamp',
1526 'oi_metadata' => 'img_metadata',
1527 'oi_media_type' => 'img_media_type',
1528 'oi_major_mime' => 'img_major_mime',
1529 'oi_minor_mime' => 'img_minor_mime',
1530 'oi_sha1' => 'img_sha1',
1534 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1535 $fields['oi_description'] = 'img_description';
1537 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1538 $tables[] = 'image_comment_temp';
1539 $fields['oi_description_id'] = 'imgcomment_description_id';
1540 $joins['image_comment_temp'] = [
1541 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
1542 [ 'imgcomment_name = img_name' ]
1546 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
1547 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1549 // Upgrade any rows that are still old-style. Otherwise an upgrade
1550 // might be missed if a deletion happens while the migration script
1552 $res = $dbw->select(
1553 [ 'image', 'image_comment_temp' ],
1554 [ 'img_name', 'img_description' ],
1555 [ 'img_name' => $this->getName(), 'imgcomment_name' => null ],
1558 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1560 foreach ( $res as $row ) {
1561 list( , $callback ) = $commentStore->insertWithTempTable(
1562 $dbw, 'img_description', $row->img_description
1564 $callback( $row->img_name
);
1568 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1569 $fields['oi_user'] = 'img_user';
1570 $fields['oi_user_text'] = 'img_user_text';
1572 if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1573 $fields['oi_actor'] = 'img_actor';
1576 if ( $wgActorTableSchemaMigrationStage !== MIGRATION_OLD
&&
1577 $wgActorTableSchemaMigrationStage !== MIGRATION_NEW
1579 // Upgrade any rows that are still old-style. Otherwise an upgrade
1580 // might be missed if a deletion happens while the migration script
1582 $res = $dbw->select(
1584 [ 'img_name', 'img_user', 'img_user_text' ],
1585 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1588 foreach ( $res as $row ) {
1589 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1592 [ 'img_actor' => $actorId ],
1593 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1599 # (T36993) Note: $oldver can be empty here, if the previous
1600 # version of the file was broken. Allow registration of the new
1601 # version to continue anyway, because that's better than having
1602 # an image that's not fixable by user operations.
1603 # Collision, this is an update of a file
1604 # Insert previous contents into oldimage
1605 $dbw->insertSelect( 'oldimage', $tables, $fields,
1606 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1608 # Update the current image row
1609 $dbw->update( 'image',
1611 'img_size' => $this->size
,
1612 'img_width' => intval( $this->width
),
1613 'img_height' => intval( $this->height
),
1614 'img_bits' => $this->bits
,
1615 'img_media_type' => $this->media_type
,
1616 'img_major_mime' => $this->major_mime
,
1617 'img_minor_mime' => $this->minor_mime
,
1618 'img_timestamp' => $timestamp,
1619 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1620 'img_sha1' => $this->sha1
1621 ] +
$commentFields +
$actorFields,
1622 [ 'img_name' => $this->getName() ],
1625 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
1626 // So $commentCallback can insert the new row
1627 $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__
);
1630 $commentCallback( $this->getName() );
1632 $descTitle = $this->getTitle();
1633 $descId = $descTitle->getArticleID();
1634 $wikiPage = new WikiFilePage( $descTitle );
1635 $wikiPage->setFile( $this );
1637 // Add the log entry...
1638 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1639 $logEntry->setTimestamp( $this->timestamp
);
1640 $logEntry->setPerformer( $user );
1641 $logEntry->setComment( $comment );
1642 $logEntry->setTarget( $descTitle );
1643 // Allow people using the api to associate log entries with the upload.
1644 // Log has a timestamp, but sometimes different from upload timestamp.
1645 $logEntry->setParameters(
1647 'img_sha1' => $this->sha1
,
1648 'img_timestamp' => $timestamp,
1651 // Note we keep $logId around since during new image
1652 // creation, page doesn't exist yet, so log_page = 0
1653 // but we want it to point to the page we're making,
1654 // so we later modify the log entry.
1655 // For a similar reason, we avoid making an RC entry
1656 // now and wait until the page exists.
1657 $logId = $logEntry->insert();
1659 if ( $descTitle->exists() ) {
1660 // Use own context to get the action text in content language
1661 $formatter = LogFormatter
::newFromEntry( $logEntry );
1662 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1663 $editSummary = $formatter->getPlainActionText();
1665 $nullRevision = Revision
::newNullRevision(
1672 if ( $nullRevision ) {
1673 $nullRevision->insertOn( $dbw );
1675 'NewRevisionFromEditComplete',
1676 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1678 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1679 // Associate null revision id
1680 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1683 $newPageContent = null;
1685 // Make the description page and RC log entry post-commit
1686 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1689 # Defer purges, page creation, and link updates in case they error out.
1690 # The most important thing is that files and the DB registry stay synced.
1691 $dbw->endAtomic( __METHOD__
);
1693 # Do some cache purges after final commit so that:
1694 # a) Changes are more likely to be seen post-purge
1695 # b) They won't cause rollback of the log publish/update above
1696 DeferredUpdates
::addUpdate(
1697 new AutoCommitUpdate(
1701 $reupload, $wikiPage, $newPageContent, $comment, $user,
1702 $logEntry, $logId, $descId, $tags
1704 # Update memcache after the commit
1705 $this->invalidateCache();
1707 $updateLogPage = false;
1708 if ( $newPageContent ) {
1709 # New file page; create the description page.
1710 # There's already a log entry, so don't make a second RC entry
1711 # CDN and file cache for the description page are purged by doEditContent.
1712 $status = $wikiPage->doEditContent(
1715 EDIT_NEW | EDIT_SUPPRESS_RC
,
1720 if ( isset( $status->value
['revision'] ) ) {
1721 /** @var Revision $rev */
1722 $rev = $status->value
['revision'];
1723 // Associate new page revision id
1724 $logEntry->setAssociatedRevId( $rev->getId() );
1726 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1727 // which is triggered on $descTitle by doEditContent() above.
1728 if ( isset( $status->value
['revision'] ) ) {
1729 /** @var Revision $rev */
1730 $rev = $status->value
['revision'];
1731 $updateLogPage = $rev->getPage();
1734 # Existing file page: invalidate description page cache
1735 $wikiPage->getTitle()->invalidateCache();
1736 $wikiPage->getTitle()->purgeSquid();
1737 # Allow the new file version to be patrolled from the page footer
1738 Article
::purgePatrolFooterCache( $descId );
1741 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1742 # but setAssociatedRevId() wasn't called at that point yet...
1743 $logParams = $logEntry->getParameters();
1744 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1745 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1746 if ( $updateLogPage ) {
1747 # Also log page, in case where we just created it above
1748 $update['log_page'] = $updateLogPage;
1750 $this->getRepo()->getMasterDB()->update(
1753 [ 'log_id' => $logId ],
1756 $this->getRepo()->getMasterDB()->insert(
1759 'ls_field' => 'associated_rev_id',
1760 'ls_value' => $logEntry->getAssociatedRevId(),
1761 'ls_log_id' => $logId,
1766 # Add change tags, if any
1768 $logEntry->setTags( $tags );
1771 # Uploads can be patrolled
1772 $logEntry->setIsPatrollable( true );
1774 # Now that the log entry is up-to-date, make an RC entry.
1775 $logEntry->publish( $logId );
1777 # Run hook for other updates (typically more cache purging)
1778 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1781 # Delete old thumbnails
1782 $this->purgeThumbnails();
1783 # Remove the old file from the CDN cache
1784 DeferredUpdates
::addUpdate(
1785 new CdnCacheUpdate( [ $this->getUrl() ] ),
1786 DeferredUpdates
::PRESEND
1789 # Update backlink pages pointing to this title if created
1790 LinksUpdate
::queueRecursiveJobsForTable(
1798 $this->prerenderThumbnails();
1801 DeferredUpdates
::PRESEND
1805 # This is a new file, so update the image count
1806 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1809 # Invalidate cache for all pages using this file
1810 DeferredUpdates
::addUpdate(
1811 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1814 return Status
::newGood();
1818 * Move or copy a file to its public location. If a file exists at the
1819 * destination, move it to an archive. Returns a Status object with
1820 * the archive name in the "value" member on success.
1822 * The archive name should be passed through to recordUpload for database
1825 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1826 * @param int $flags A bitwise combination of:
1827 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1828 * @param array $options Optional additional parameters
1829 * @return Status On success, the value member contains the
1830 * archive name, or an empty string if it was a new file.
1832 function publish( $src, $flags = 0, array $options = [] ) {
1833 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1837 * Move or copy a file to a specified location. Returns a Status
1838 * object with the archive name in the "value" member on success.
1840 * The archive name should be passed through to recordUpload for database
1843 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1844 * @param string $dstRel Target relative path
1845 * @param int $flags A bitwise combination of:
1846 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1847 * @param array $options Optional additional parameters
1848 * @return Status On success, the value member contains the
1849 * archive name, or an empty string if it was a new file.
1851 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1852 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1854 $repo = $this->getRepo();
1855 if ( $repo->getReadOnlyReason() !== false ) {
1856 return $this->readOnlyFatalStatus();
1859 $this->lock(); // begin
1861 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1862 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1864 if ( $repo->hasSha1Storage() ) {
1865 $sha1 = $repo->isVirtualUrl( $srcPath )
1866 ?
$repo->getFileSha1( $srcPath )
1867 : FSFile
::getSha1Base36FromPath( $srcPath );
1868 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1869 $wrapperBackend = $repo->getBackend();
1870 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1871 $status = $repo->quickImport( $src, $dst );
1872 if ( $flags & File
::DELETE_SOURCE
) {
1876 if ( $this->exists() ) {
1877 $status->value
= $archiveName;
1880 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1881 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1883 if ( $status->value
== 'new' ) {
1884 $status->value
= '';
1886 $status->value
= $archiveName;
1890 $this->unlock(); // done
1895 /** getLinksTo inherited */
1896 /** getExifData inherited */
1897 /** isLocal inherited */
1898 /** wasDeleted inherited */
1901 * Move file to the new title
1903 * Move current, old version and all thumbnails
1904 * to the new filename. Old file is deleted.
1906 * Cache purging is done; checks for validity
1907 * and logging are caller's responsibility
1909 * @param Title $target New file name
1912 function move( $target ) {
1913 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1914 return $this->readOnlyFatalStatus();
1917 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1918 $batch = new LocalFileMoveBatch( $this, $target );
1920 $this->lock(); // begin
1921 $batch->addCurrent();
1922 $archiveNames = $batch->addOlds();
1923 $status = $batch->execute();
1924 $this->unlock(); // done
1926 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1928 // Purge the source and target files...
1929 $oldTitleFile = wfLocalFile( $this->title
);
1930 $newTitleFile = wfLocalFile( $target );
1931 // To avoid slow purges in the transaction, move them outside...
1932 DeferredUpdates
::addUpdate(
1933 new AutoCommitUpdate(
1934 $this->getRepo()->getMasterDB(),
1936 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1937 $oldTitleFile->purgeEverything();
1938 foreach ( $archiveNames as $archiveName ) {
1939 $oldTitleFile->purgeOldThumbnails( $archiveName );
1941 $newTitleFile->purgeEverything();
1944 DeferredUpdates
::PRESEND
1947 if ( $status->isOK() ) {
1948 // Now switch the object
1949 $this->title
= $target;
1950 // Force regeneration of the name and hashpath
1951 unset( $this->name
);
1952 unset( $this->hashPath
);
1959 * Delete all versions of the file.
1961 * Moves the files into an archive directory (or deletes them)
1962 * and removes the database rows.
1964 * Cache purging is done; logging is caller's responsibility.
1966 * @param string $reason
1967 * @param bool $suppress
1968 * @param User|null $user
1971 function delete( $reason, $suppress = false, $user = null ) {
1972 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1973 return $this->readOnlyFatalStatus();
1976 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1978 $this->lock(); // begin
1979 $batch->addCurrent();
1980 // Get old version relative paths
1981 $archiveNames = $batch->addOlds();
1982 $status = $batch->execute();
1983 $this->unlock(); // done
1985 if ( $status->isOK() ) {
1986 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1989 // To avoid slow purges in the transaction, move them outside...
1990 DeferredUpdates
::addUpdate(
1991 new AutoCommitUpdate(
1992 $this->getRepo()->getMasterDB(),
1994 function () use ( $archiveNames ) {
1995 $this->purgeEverything();
1996 foreach ( $archiveNames as $archiveName ) {
1997 $this->purgeOldThumbnails( $archiveName );
2001 DeferredUpdates
::PRESEND
2006 foreach ( $archiveNames as $archiveName ) {
2007 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2009 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2015 * Delete an old version of the file.
2017 * Moves the file into an archive directory (or deletes it)
2018 * and removes the database row.
2020 * Cache purging is done; logging is caller's responsibility.
2022 * @param string $archiveName
2023 * @param string $reason
2024 * @param bool $suppress
2025 * @param User|null $user
2026 * @throws MWException Exception on database or file store failure
2029 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2030 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2031 return $this->readOnlyFatalStatus();
2034 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2036 $this->lock(); // begin
2037 $batch->addOld( $archiveName );
2038 $status = $batch->execute();
2039 $this->unlock(); // done
2041 $this->purgeOldThumbnails( $archiveName );
2042 if ( $status->isOK() ) {
2043 $this->purgeDescription();
2046 DeferredUpdates
::addUpdate(
2047 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2048 DeferredUpdates
::PRESEND
2055 * Restore all or specified deleted revisions to the given file.
2056 * Permissions and logging are left to the caller.
2058 * May throw database exceptions on error.
2060 * @param array $versions Set of record ids of deleted items to restore,
2061 * or empty to restore all revisions.
2062 * @param bool $unsuppress
2065 function restore( $versions = [], $unsuppress = false ) {
2066 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2067 return $this->readOnlyFatalStatus();
2070 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2072 $this->lock(); // begin
2076 $batch->addIds( $versions );
2078 $status = $batch->execute();
2079 if ( $status->isGood() ) {
2080 $cleanupStatus = $batch->cleanup();
2081 $cleanupStatus->successCount
= 0;
2082 $cleanupStatus->failCount
= 0;
2083 $status->merge( $cleanupStatus );
2085 $this->unlock(); // done
2090 /** isMultipage inherited */
2091 /** pageCount inherited */
2092 /** scaleHeight inherited */
2093 /** getImageSize inherited */
2096 * Get the URL of the file description page.
2099 function getDescriptionUrl() {
2100 return $this->title
->getLocalURL();
2104 * Get the HTML text of the description page
2105 * This is not used by ImagePage for local files, since (among other things)
2106 * it skips the parser cache.
2108 * @param Language|null $lang What language to get description in (Optional)
2109 * @return string|false
2111 function getDescriptionText( $lang = null ) {
2112 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
2116 $content = $revision->getContent();
2120 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
2122 return $pout->getText();
2126 * @param int $audience
2127 * @param User|null $user
2130 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2132 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2134 } elseif ( $audience == self
::FOR_THIS_USER
2135 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2139 return $this->description
;
2144 * @return bool|string
2146 function getTimestamp() {
2149 return $this->timestamp
;
2153 * @return bool|string
2155 public function getDescriptionTouched() {
2156 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2157 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2158 // need to differentiate between null (uninitialized) and false (failed to load).
2159 if ( $this->descriptionTouched
=== null ) {
2161 'page_namespace' => $this->title
->getNamespace(),
2162 'page_title' => $this->title
->getDBkey()
2164 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2165 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2168 return $this->descriptionTouched
;
2174 function getSha1() {
2176 // Initialise now if necessary
2177 if ( $this->sha1
== '' && $this->fileExists
) {
2178 $this->lock(); // begin
2180 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2181 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2182 $dbw = $this->repo
->getMasterDB();
2183 $dbw->update( 'image',
2184 [ 'img_sha1' => $this->sha1
],
2185 [ 'img_name' => $this->getName() ],
2187 $this->invalidateCache();
2190 $this->unlock(); // done
2197 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2199 function isCacheable() {
2202 // If extra data (metadata) was not loaded then it must have been large
2203 return $this->extraDataLoaded
2204 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2211 public function acquireFileLock() {
2212 return $this->getRepo()->getBackend()->lockFiles(
2213 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2221 public function releaseFileLock() {
2222 return $this->getRepo()->getBackend()->unlockFiles(
2223 [ $this->getPath() ], LockManager
::LOCK_EX
2228 * Start an atomic DB section and lock the image for update
2229 * or increments a reference counter if the lock is already held
2231 * This method should not be used outside of LocalFile/LocalFile*Batch
2233 * @throws LocalFileLockError Throws an error if the lock was not acquired
2234 * @return bool Whether the file lock owns/spawned the DB transaction
2236 public function lock() {
2237 if ( !$this->locked
) {
2238 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2240 $dbw = $this->repo
->getMasterDB();
2241 $makesTransaction = !$dbw->trxLevel();
2242 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2243 // T56736: use simple lock to handle when the file does not exist.
2244 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2245 // Also, that would cause contention on INSERT of similarly named rows.
2246 $status = $this->acquireFileLock(); // represents all versions of the file
2247 if ( !$status->isGood() ) {
2248 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2249 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2251 throw new LocalFileLockError( $status );
2253 // Release the lock *after* commit to avoid row-level contention.
2254 // Make sure it triggers on rollback() as well as commit() (T132921).
2255 $dbw->onTransactionResolution(
2256 function () use ( $logger ) {
2257 $status = $this->releaseFileLock();
2258 if ( !$status->isGood() ) {
2259 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2264 // Callers might care if the SELECT snapshot is safely fresh
2265 $this->lockedOwnTrx
= $makesTransaction;
2270 return $this->lockedOwnTrx
;
2274 * Decrement the lock reference count and end the atomic section if it reaches zero
2276 * This method should not be used outside of LocalFile/LocalFile*Batch
2278 * The commit and loc release will happen when no atomic sections are active, which
2279 * may happen immediately or at some point after calling this
2281 public function unlock() {
2282 if ( $this->locked
) {
2284 if ( !$this->locked
) {
2285 $dbw = $this->repo
->getMasterDB();
2286 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2287 $this->lockedOwnTrx
= false;
2295 protected function readOnlyFatalStatus() {
2296 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2297 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2301 * Clean up any dangling locks
2303 function __destruct() {
2306 } // LocalFile class
2308 # ------------------------------------------------------------------------------
2311 * Helper class for file deletion
2312 * @ingroup FileAbstraction
2314 class LocalFileDeleteBatch
{
2315 /** @var LocalFile */
2322 private $srcRels = [];
2325 private $archiveUrls = [];
2327 /** @var array Items to be processed in the deletion batch */
2328 private $deletionBatch;
2330 /** @var bool Whether to suppress all suppressable fields when deleting */
2341 * @param string $reason
2342 * @param bool $suppress
2343 * @param User|null $user
2345 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2346 $this->file
= $file;
2347 $this->reason
= $reason;
2348 $this->suppress
= $suppress;
2350 $this->user
= $user;
2353 $this->user
= $wgUser;
2355 $this->status
= $file->repo
->newGood();
2358 public function addCurrent() {
2359 $this->srcRels
['.'] = $this->file
->getRel();
2363 * @param string $oldName
2365 public function addOld( $oldName ) {
2366 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2367 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2371 * Add the old versions of the image to the batch
2372 * @return string[] List of archive names from old versions
2374 public function addOlds() {
2377 $dbw = $this->file
->repo
->getMasterDB();
2378 $result = $dbw->select( 'oldimage',
2379 [ 'oi_archive_name' ],
2380 [ 'oi_name' => $this->file
->getName() ],
2384 foreach ( $result as $row ) {
2385 $this->addOld( $row->oi_archive_name
);
2386 $archiveNames[] = $row->oi_archive_name
;
2389 return $archiveNames;
2395 protected function getOldRels() {
2396 if ( !isset( $this->srcRels
['.'] ) ) {
2397 $oldRels =& $this->srcRels
;
2398 $deleteCurrent = false;
2400 $oldRels = $this->srcRels
;
2401 unset( $oldRels['.'] );
2402 $deleteCurrent = true;
2405 return [ $oldRels, $deleteCurrent ];
2411 protected function getHashes() {
2413 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2415 if ( $deleteCurrent ) {
2416 $hashes['.'] = $this->file
->getSha1();
2419 if ( count( $oldRels ) ) {
2420 $dbw = $this->file
->repo
->getMasterDB();
2421 $res = $dbw->select(
2423 [ 'oi_archive_name', 'oi_sha1' ],
2424 [ 'oi_archive_name' => array_keys( $oldRels ),
2425 'oi_name' => $this->file
->getName() ], // performance
2429 foreach ( $res as $row ) {
2430 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2431 // Get the hash from the file
2432 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2433 $props = $this->file
->repo
->getFileProps( $oldUrl );
2435 if ( $props['fileExists'] ) {
2436 // Upgrade the oldimage row
2437 $dbw->update( 'oldimage',
2438 [ 'oi_sha1' => $props['sha1'] ],
2439 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2441 $hashes[$row->oi_archive_name
] = $props['sha1'];
2443 $hashes[$row->oi_archive_name
] = false;
2446 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2451 $missing = array_diff_key( $this->srcRels
, $hashes );
2453 foreach ( $missing as $name => $rel ) {
2454 $this->status
->error( 'filedelete-old-unregistered', $name );
2457 foreach ( $hashes as $name => $hash ) {
2459 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2460 unset( $hashes[$name] );
2467 protected function doDBInserts() {
2468 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
2471 $dbw = $this->file
->repo
->getMasterDB();
2473 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
2474 $actorMigration = ActorMigration
::newMigration();
2476 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2477 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2478 $encGroup = $dbw->addQuotes( 'deleted' );
2479 $ext = $this->file
->getExtension();
2480 $dotExt = $ext === '' ?
'' : ".$ext";
2481 $encExt = $dbw->addQuotes( $dotExt );
2482 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2484 // Bitfields to further suppress the content
2485 if ( $this->suppress
) {
2486 $bitfield = Revision
::SUPPRESSED_ALL
;
2488 $bitfield = 'oi_deleted';
2491 if ( $deleteCurrent ) {
2492 $tables = [ 'image' ];
2494 'fa_storage_group' => $encGroup,
2495 'fa_storage_key' => $dbw->conditional(
2496 [ 'img_sha1' => '' ],
2497 $dbw->addQuotes( '' ),
2498 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2500 'fa_deleted_user' => $encUserId,
2501 'fa_deleted_timestamp' => $encTimestamp,
2502 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2503 'fa_name' => 'img_name',
2504 'fa_archive_name' => 'NULL',
2505 'fa_size' => 'img_size',
2506 'fa_width' => 'img_width',
2507 'fa_height' => 'img_height',
2508 'fa_metadata' => 'img_metadata',
2509 'fa_bits' => 'img_bits',
2510 'fa_media_type' => 'img_media_type',
2511 'fa_major_mime' => 'img_major_mime',
2512 'fa_minor_mime' => 'img_minor_mime',
2513 'fa_timestamp' => 'img_timestamp',
2514 'fa_sha1' => 'img_sha1'
2518 $fields +
= array_map(
2519 [ $dbw, 'addQuotes' ],
2520 $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason
)
2523 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2524 $fields['fa_description'] = 'img_description';
2526 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2527 $tables[] = 'image_comment_temp';
2528 $fields['fa_description_id'] = 'imgcomment_description_id';
2529 $joins['image_comment_temp'] = [
2530 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
2531 [ 'imgcomment_name = img_name' ]
2535 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
2536 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2538 // Upgrade any rows that are still old-style. Otherwise an upgrade
2539 // might be missed if a deletion happens while the migration script
2541 $res = $dbw->select(
2542 [ 'image', 'image_comment_temp' ],
2543 [ 'img_name', 'img_description' ],
2544 [ 'img_name' => $this->file
->getName(), 'imgcomment_name' => null ],
2547 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2549 foreach ( $res as $row ) {
2550 list( , $callback ) = $commentStore->insertWithTempTable(
2551 $dbw, 'img_description', $row->img_description
2553 $callback( $row->img_name
);
2557 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2558 $fields['fa_user'] = 'img_user';
2559 $fields['fa_user_text'] = 'img_user_text';
2561 if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2562 $fields['fa_actor'] = 'img_actor';
2565 if ( $wgActorTableSchemaMigrationStage !== MIGRATION_OLD
&&
2566 $wgActorTableSchemaMigrationStage !== MIGRATION_NEW
2568 // Upgrade any rows that are still old-style. Otherwise an upgrade
2569 // might be missed if a deletion happens while the migration script
2571 $res = $dbw->select(
2573 [ 'img_name', 'img_user', 'img_user_text' ],
2574 [ 'img_name' => $this->file
->getName(), 'img_actor' => 0 ],
2577 foreach ( $res as $row ) {
2578 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
2581 [ 'img_actor' => $actorId ],
2582 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
2588 $dbw->insertSelect( 'filearchive', $tables, $fields,
2589 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2592 if ( count( $oldRels ) ) {
2593 $fileQuery = OldLocalFile
::getQueryInfo();
2594 $res = $dbw->select(
2595 $fileQuery['tables'],
2596 $fileQuery['fields'],
2598 'oi_name' => $this->file
->getName(),
2599 'oi_archive_name' => array_keys( $oldRels )
2606 if ( $res->numRows() ) {
2607 $reason = $commentStore->createComment( $dbw, $this->reason
);
2608 foreach ( $res as $row ) {
2609 $comment = $commentStore->getComment( 'oi_description', $row );
2610 $user = User
::newFromAnyId( $row->oi_user
, $row->oi_user_text
, $row->oi_actor
);
2612 // Deletion-specific fields
2613 'fa_storage_group' => 'deleted',
2614 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2616 : "{$row->oi_sha1}{$dotExt}",
2617 'fa_deleted_user' => $this->user
->getId(),
2618 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2619 // Counterpart fields
2620 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2621 'fa_name' => $row->oi_name
,
2622 'fa_archive_name' => $row->oi_archive_name
,
2623 'fa_size' => $row->oi_size
,
2624 'fa_width' => $row->oi_width
,
2625 'fa_height' => $row->oi_height
,
2626 'fa_metadata' => $row->oi_metadata
,
2627 'fa_bits' => $row->oi_bits
,
2628 'fa_media_type' => $row->oi_media_type
,
2629 'fa_major_mime' => $row->oi_major_mime
,
2630 'fa_minor_mime' => $row->oi_minor_mime
,
2631 'fa_timestamp' => $row->oi_timestamp
,
2632 'fa_sha1' => $row->oi_sha1
2633 ] +
$commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2634 +
$commentStore->insert( $dbw, 'fa_description', $comment )
2635 +
$actorMigration->getInsertValues( $dbw, 'fa_user', $user );
2639 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2643 function doDBDeletes() {
2644 global $wgCommentTableSchemaMigrationStage;
2646 $dbw = $this->file
->repo
->getMasterDB();
2647 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2649 if ( count( $oldRels ) ) {
2650 $dbw->delete( 'oldimage',
2652 'oi_name' => $this->file
->getName(),
2653 'oi_archive_name' => array_keys( $oldRels )
2657 if ( $deleteCurrent ) {
2658 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2659 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2661 'image_comment_temp', [ 'imgcomment_name' => $this->file
->getName() ], __METHOD__
2668 * Run the transaction
2671 public function execute() {
2672 $repo = $this->file
->getRepo();
2673 $this->file
->lock();
2675 // Prepare deletion batch
2676 $hashes = $this->getHashes();
2677 $this->deletionBatch
= [];
2678 $ext = $this->file
->getExtension();
2679 $dotExt = $ext === '' ?
'' : ".$ext";
2681 foreach ( $this->srcRels
as $name => $srcRel ) {
2682 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2683 if ( isset( $hashes[$name] ) ) {
2684 $hash = $hashes[$name];
2685 $key = $hash . $dotExt;
2686 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2687 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2691 if ( !$repo->hasSha1Storage() ) {
2692 // Removes non-existent file from the batch, so we don't get errors.
2693 // This also handles files in the 'deleted' zone deleted via revision deletion.
2694 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2695 if ( !$checkStatus->isGood() ) {
2696 $this->status
->merge( $checkStatus );
2697 return $this->status
;
2699 $this->deletionBatch
= $checkStatus->value
;
2701 // Execute the file deletion batch
2702 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2703 if ( !$status->isGood() ) {
2704 $this->status
->merge( $status );
2708 if ( !$this->status
->isOK() ) {
2709 // Critical file deletion error; abort
2710 $this->file
->unlock();
2712 return $this->status
;
2715 // Copy the image/oldimage rows to filearchive
2716 $this->doDBInserts();
2717 // Delete image/oldimage rows
2718 $this->doDBDeletes();
2720 // Commit and return
2721 $this->file
->unlock();
2723 return $this->status
;
2727 * Removes non-existent files from a deletion batch.
2728 * @param array $batch
2731 protected function removeNonexistentFiles( $batch ) {
2732 $files = $newBatch = [];
2734 foreach ( $batch as $batchItem ) {
2735 list( $src, ) = $batchItem;
2736 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2739 $result = $this->file
->repo
->fileExistsBatch( $files );
2740 if ( in_array( null, $result, true ) ) {
2741 return Status
::newFatal( 'backend-fail-internal',
2742 $this->file
->repo
->getBackend()->getName() );
2745 foreach ( $batch as $batchItem ) {
2746 if ( $result[$batchItem[0]] ) {
2747 $newBatch[] = $batchItem;
2751 return Status
::newGood( $newBatch );
2755 # ------------------------------------------------------------------------------
2758 * Helper class for file undeletion
2759 * @ingroup FileAbstraction
2761 class LocalFileRestoreBatch
{
2762 /** @var LocalFile */
2765 /** @var string[] List of file IDs to restore */
2766 private $cleanupBatch;
2768 /** @var string[] List of file IDs to restore */
2771 /** @var bool Add all revisions of the file */
2774 /** @var bool Whether to remove all settings for suppressed fields */
2775 private $unsuppress = false;
2779 * @param bool $unsuppress
2781 function __construct( File
$file, $unsuppress = false ) {
2782 $this->file
= $file;
2783 $this->cleanupBatch
= [];
2785 $this->unsuppress
= $unsuppress;
2792 public function addId( $fa_id ) {
2793 $this->ids
[] = $fa_id;
2797 * Add a whole lot of files by ID
2800 public function addIds( $ids ) {
2801 $this->ids
= array_merge( $this->ids
, $ids );
2805 * Add all revisions of the file
2807 public function addAll() {
2812 * Run the transaction, except the cleanup batch.
2813 * The cleanup batch should be run in a separate transaction, because it locks different
2814 * rows and there's no need to keep the image row locked while it's acquiring those locks
2815 * The caller may have its own transaction open.
2816 * So we save the batch and let the caller call cleanup()
2819 public function execute() {
2820 /** @var Language */
2823 $repo = $this->file
->getRepo();
2824 if ( !$this->all
&& !$this->ids
) {
2826 return $repo->newGood();
2829 $lockOwnsTrx = $this->file
->lock();
2831 $dbw = $this->file
->repo
->getMasterDB();
2833 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
2834 $actorMigration = ActorMigration
::newMigration();
2836 $status = $this->file
->repo
->newGood();
2838 $exists = (bool)$dbw->selectField( 'image', '1',
2839 [ 'img_name' => $this->file
->getName() ],
2841 // The lock() should already prevents changes, but this still may need
2842 // to bypass any transaction snapshot. However, if lock() started the
2843 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2844 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2847 // Fetch all or selected archived revisions for the file,
2848 // sorted from the most recent to the oldest.
2849 $conditions = [ 'fa_name' => $this->file
->getName() ];
2851 if ( !$this->all
) {
2852 $conditions['fa_id'] = $this->ids
;
2855 $arFileQuery = ArchivedFile
::getQueryInfo();
2856 $result = $dbw->select(
2857 $arFileQuery['tables'],
2858 $arFileQuery['fields'],
2861 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2862 $arFileQuery['joins']
2868 $insertCurrent = false;
2873 foreach ( $result as $row ) {
2874 $idsPresent[] = $row->fa_id
;
2876 if ( $row->fa_name
!= $this->file
->getName() ) {
2877 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2878 $status->failCount++
;
2882 if ( $row->fa_storage_key
== '' ) {
2883 // Revision was missing pre-deletion
2884 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2885 $status->failCount++
;
2889 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2890 $row->fa_storage_key
;
2891 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2893 if ( isset( $row->fa_sha1
) ) {
2894 $sha1 = $row->fa_sha1
;
2896 // old row, populate from key
2897 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2901 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2902 $sha1 = substr( $sha1, 1 );
2905 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2906 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2907 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2908 ||
is_null( $row->fa_metadata
)
2910 // Refresh our metadata
2911 // Required for a new current revision; nice for older ones too. :)
2912 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2915 'minor_mime' => $row->fa_minor_mime
,
2916 'major_mime' => $row->fa_major_mime
,
2917 'media_type' => $row->fa_media_type
,
2918 'metadata' => $row->fa_metadata
2922 $comment = $commentStore->getComment( 'fa_description', $row );
2923 $user = User
::newFromAnyId( $row->fa_user
, $row->fa_user_text
, $row->fa_actor
);
2924 if ( $first && !$exists ) {
2925 // This revision will be published as the new current version
2926 $destRel = $this->file
->getRel();
2927 list( $commentFields, $commentCallback ) =
2928 $commentStore->insertWithTempTable( $dbw, 'img_description', $comment );
2929 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
2931 'img_name' => $row->fa_name
,
2932 'img_size' => $row->fa_size
,
2933 'img_width' => $row->fa_width
,
2934 'img_height' => $row->fa_height
,
2935 'img_metadata' => $props['metadata'],
2936 'img_bits' => $row->fa_bits
,
2937 'img_media_type' => $props['media_type'],
2938 'img_major_mime' => $props['major_mime'],
2939 'img_minor_mime' => $props['minor_mime'],
2940 'img_timestamp' => $row->fa_timestamp
,
2942 ] +
$commentFields +
$actorFields;
2944 // The live (current) version cannot be hidden!
2945 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2946 $status->fatal( 'undeleterevdel' );
2947 $this->file
->unlock();
2951 $archiveName = $row->fa_archive_name
;
2953 if ( $archiveName == '' ) {
2954 // This was originally a current version; we
2955 // have to devise a new archive name for it.
2956 // Format is <timestamp of archiving>!<name>
2957 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2960 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2962 } while ( isset( $archiveNames[$archiveName] ) );
2965 $archiveNames[$archiveName] = true;
2966 $destRel = $this->file
->getArchiveRel( $archiveName );
2968 'oi_name' => $row->fa_name
,
2969 'oi_archive_name' => $archiveName,
2970 'oi_size' => $row->fa_size
,
2971 'oi_width' => $row->fa_width
,
2972 'oi_height' => $row->fa_height
,
2973 'oi_bits' => $row->fa_bits
,
2974 'oi_timestamp' => $row->fa_timestamp
,
2975 'oi_metadata' => $props['metadata'],
2976 'oi_media_type' => $props['media_type'],
2977 'oi_major_mime' => $props['major_mime'],
2978 'oi_minor_mime' => $props['minor_mime'],
2979 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2981 ] +
$commentStore->insert( $dbw, 'oi_description', $comment )
2982 +
$actorMigration->getInsertValues( $dbw, 'oi_user', $user );
2985 $deleteIds[] = $row->fa_id
;
2987 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2988 // private files can stay where they are
2989 $status->successCount++
;
2991 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2992 $this->cleanupBatch
[] = $row->fa_storage_key
;
3000 // Add a warning to the status object for missing IDs
3001 $missingIds = array_diff( $this->ids
, $idsPresent );
3003 foreach ( $missingIds as $id ) {
3004 $status->error( 'undelete-missing-filearchive', $id );
3007 if ( !$repo->hasSha1Storage() ) {
3008 // Remove missing files from batch, so we don't get errors when undeleting them
3009 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
3010 if ( !$checkStatus->isGood() ) {
3011 $status->merge( $checkStatus );
3014 $storeBatch = $checkStatus->value
;
3016 // Run the store batch
3017 // Use the OVERWRITE_SAME flag to smooth over a common error
3018 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
3019 $status->merge( $storeStatus );
3021 if ( !$status->isGood() ) {
3022 // Even if some files could be copied, fail entirely as that is the
3023 // easiest thing to do without data loss
3024 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
3025 $status->setOK( false );
3026 $this->file
->unlock();
3032 // Run the DB updates
3033 // Because we have locked the image row, key conflicts should be rare.
3034 // If they do occur, we can roll back the transaction at this time with
3035 // no data loss, but leaving unregistered files scattered throughout the
3037 // This is not ideal, which is why it's important to lock the image row.
3038 if ( $insertCurrent ) {
3039 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
3040 $commentCallback( $insertCurrent['img_name'] );
3043 if ( $insertBatch ) {
3044 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
3048 $dbw->delete( 'filearchive',
3049 [ 'fa_id' => $deleteIds ],
3053 // If store batch is empty (all files are missing), deletion is to be considered successful
3054 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
3056 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
3058 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
3060 $this->file
->purgeEverything();
3062 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
3063 $this->file
->purgeDescription();
3067 $this->file
->unlock();
3073 * Removes non-existent files from a store batch.
3074 * @param array $triplets
3077 protected function removeNonexistentFiles( $triplets ) {
3078 $files = $filteredTriplets = [];
3079 foreach ( $triplets as $file ) {
3080 $files[$file[0]] = $file[0];
3083 $result = $this->file
->repo
->fileExistsBatch( $files );
3084 if ( in_array( null, $result, true ) ) {
3085 return Status
::newFatal( 'backend-fail-internal',
3086 $this->file
->repo
->getBackend()->getName() );
3089 foreach ( $triplets as $file ) {
3090 if ( $result[$file[0]] ) {
3091 $filteredTriplets[] = $file;
3095 return Status
::newGood( $filteredTriplets );
3099 * Removes non-existent files from a cleanup batch.
3100 * @param string[] $batch
3103 protected function removeNonexistentFromCleanup( $batch ) {
3104 $files = $newBatch = [];
3105 $repo = $this->file
->repo
;
3107 foreach ( $batch as $file ) {
3108 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3109 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3112 $result = $repo->fileExistsBatch( $files );
3114 foreach ( $batch as $file ) {
3115 if ( $result[$file] ) {
3116 $newBatch[] = $file;
3124 * Delete unused files in the deleted zone.
3125 * This should be called from outside the transaction in which execute() was called.
3128 public function cleanup() {
3129 if ( !$this->cleanupBatch
) {
3130 return $this->file
->repo
->newGood();
3133 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
3135 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
3141 * Cleanup a failed batch. The batch was only partially successful, so
3142 * rollback by removing all items that were succesfully copied.
3144 * @param Status $storeStatus
3145 * @param array[] $storeBatch
3147 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3150 foreach ( $storeStatus->success
as $i => $success ) {
3151 // Check if this item of the batch was successfully copied
3153 // Item was successfully copied and needs to be removed again
3154 // Extract ($dstZone, $dstRel) from the batch
3155 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3158 $this->file
->repo
->cleanupBatch( $cleanupBatch );
3162 # ------------------------------------------------------------------------------
3165 * Helper class for file movement
3166 * @ingroup FileAbstraction
3168 class LocalFileMoveBatch
{
3169 /** @var LocalFile */
3179 protected $oldCount;
3183 /** @var IDatabase */
3188 * @param Title $target
3190 function __construct( File
$file, Title
$target ) {
3191 $this->file
= $file;
3192 $this->target
= $target;
3193 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
3194 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
3195 $this->oldName
= $this->file
->getName();
3196 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
3197 $this->oldRel
= $this->oldHash
. $this->oldName
;
3198 $this->newRel
= $this->newHash
. $this->newName
;
3199 $this->db
= $file->getRepo()->getMasterDB();
3203 * Add the current image to the batch
3205 public function addCurrent() {
3206 $this->cur
= [ $this->oldRel
, $this->newRel
];
3210 * Add the old versions of the image to the batch
3211 * @return string[] List of archive names from old versions
3213 public function addOlds() {
3214 $archiveBase = 'archive';
3216 $this->oldCount
= 0;
3219 $result = $this->db
->select( 'oldimage',
3220 [ 'oi_archive_name', 'oi_deleted' ],
3221 [ 'oi_name' => $this->oldName
],
3223 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3226 foreach ( $result as $row ) {
3227 $archiveNames[] = $row->oi_archive_name
;
3228 $oldName = $row->oi_archive_name
;
3229 $bits = explode( '!', $oldName, 2 );
3231 if ( count( $bits ) != 2 ) {
3232 wfDebug( "Old file name missing !: '$oldName' \n" );
3236 list( $timestamp, $filename ) = $bits;
3238 if ( $this->oldName
!= $filename ) {
3239 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3245 // Do we want to add those to oldCount?
3246 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3251 "{$archiveBase}/{$this->oldHash}{$oldName}",
3252 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3256 return $archiveNames;
3263 public function execute() {
3264 $repo = $this->file
->repo
;
3265 $status = $repo->newGood();
3266 $destFile = wfLocalFile( $this->target
);
3268 $this->file
->lock(); // begin
3269 $destFile->lock(); // quickly fail if destination is not available
3271 $triplets = $this->getMoveTriplets();
3272 $checkStatus = $this->removeNonexistentFiles( $triplets );
3273 if ( !$checkStatus->isGood() ) {
3274 $destFile->unlock();
3275 $this->file
->unlock();
3276 $status->merge( $checkStatus ); // couldn't talk to file backend
3279 $triplets = $checkStatus->value
;
3281 // Verify the file versions metadata in the DB.
3282 $statusDb = $this->verifyDBUpdates();
3283 if ( !$statusDb->isGood() ) {
3284 $destFile->unlock();
3285 $this->file
->unlock();
3286 $statusDb->setOK( false );
3291 if ( !$repo->hasSha1Storage() ) {
3292 // Copy the files into their new location.
3293 // If a prior process fataled copying or cleaning up files we tolerate any
3294 // of the existing files if they are identical to the ones being stored.
3295 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3296 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3297 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3298 if ( !$statusMove->isGood() ) {
3299 // Delete any files copied over (while the destination is still locked)
3300 $this->cleanupTarget( $triplets );
3301 $destFile->unlock();
3302 $this->file
->unlock();
3303 wfDebugLog( 'imagemove', "Error in moving files: "
3304 . $statusMove->getWikiText( false, false, 'en' ) );
3305 $statusMove->setOK( false );
3309 $status->merge( $statusMove );
3312 // Rename the file versions metadata in the DB.
3313 $this->doDBUpdates();
3315 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3316 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3318 $destFile->unlock();
3319 $this->file
->unlock(); // done
3321 // Everything went ok, remove the source files
3322 $this->cleanupSource( $triplets );
3324 $status->merge( $statusDb );
3330 * Verify the database updates and return a new Status indicating how
3331 * many rows would be updated.
3335 protected function verifyDBUpdates() {
3336 $repo = $this->file
->repo
;
3337 $status = $repo->newGood();
3340 $hasCurrent = $dbw->selectField(
3343 [ 'img_name' => $this->oldName
],
3347 $oldRowCount = $dbw->selectRowCount(
3350 [ 'oi_name' => $this->oldName
],
3355 if ( $hasCurrent ) {
3356 $status->successCount++
;
3358 $status->failCount++
;
3360 $status->successCount +
= $oldRowCount;
3361 // T36934: oldCount is based on files that actually exist.
3362 // There may be more DB rows than such files, in which case $affected
3363 // can be greater than $total. We use max() to avoid negatives here.
3364 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3365 if ( $status->failCount
) {
3366 $status->error( 'imageinvalidfilename' );
3373 * Do the database updates and return a new Status indicating how
3374 * many rows where updated.
3376 protected function doDBUpdates() {
3377 global $wgCommentTableSchemaMigrationStage;
3381 // Update current image
3384 [ 'img_name' => $this->newName
],
3385 [ 'img_name' => $this->oldName
],
3388 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
3390 'image_comment_temp',
3391 [ 'imgcomment_name' => $this->newName
],
3392 [ 'imgcomment_name' => $this->oldName
],
3397 // Update old images
3401 'oi_name' => $this->newName
,
3402 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3403 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3405 [ 'oi_name' => $this->oldName
],
3411 * Generate triplets for FileRepo::storeBatch().
3414 protected function getMoveTriplets() {
3415 $moves = array_merge( [ $this->cur
], $this->olds
);
3416 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3418 foreach ( $moves as $move ) {
3419 // $move: (oldRelativePath, newRelativePath)
3420 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3421 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3424 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3432 * Removes non-existent files from move batch.
3433 * @param array $triplets
3436 protected function removeNonexistentFiles( $triplets ) {
3439 foreach ( $triplets as $file ) {
3440 $files[$file[0]] = $file[0];
3443 $result = $this->file
->repo
->fileExistsBatch( $files );
3444 if ( in_array( null, $result, true ) ) {
3445 return Status
::newFatal( 'backend-fail-internal',
3446 $this->file
->repo
->getBackend()->getName() );
3449 $filteredTriplets = [];
3450 foreach ( $triplets as $file ) {
3451 if ( $result[$file[0]] ) {
3452 $filteredTriplets[] = $file;
3454 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3458 return Status
::newGood( $filteredTriplets );
3462 * Cleanup a partially moved array of triplets by deleting the target
3463 * files. Called if something went wrong half way.
3464 * @param array[] $triplets
3466 protected function cleanupTarget( $triplets ) {
3467 // Create dest pairs from the triplets
3469 foreach ( $triplets as $triplet ) {
3470 // $triplet: (old source virtual URL, dst zone, dest rel)
3471 $pairs[] = [ $triplet[1], $triplet[2] ];
3474 $this->file
->repo
->cleanupBatch( $pairs );
3478 * Cleanup a fully moved array of triplets by deleting the source files.
3479 * Called at the end of the move process if everything else went ok.
3480 * @param array[] $triplets
3482 protected function cleanupSource( $triplets ) {
3483 // Create source file names from the triplets
3485 foreach ( $triplets as $triplet ) {
3486 $files[] = $triplet[0];
3489 $this->file
->repo
->cleanupBatch( $files );
3493 class LocalFileLockError
extends ErrorPageError
{
3494 public function __construct( Status
$status ) {
3495 parent
::__construct(
3497 $status->getMessage()
3501 public function report() {
3503 $wgOut->setStatusCode( 429 );