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() {
709 $this->lock(); // begin
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();
749 $this->unlock(); // done
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 ( 0 == $dbr->numRows( $this->historyRes
) ) {
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 ( $this->repo
->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 );
1350 $this->lock(); // begin
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 );
1381 $this->unlock(); // done
1387 * Record a file upload in the upload log and the image table
1388 * @param string $oldver
1389 * @param string $desc
1390 * @param string $license
1391 * @param string $copyStatus
1392 * @param string $source
1393 * @param bool $watch
1394 * @param string|bool $timestamp
1395 * @param User|null $user User object or null to use $wgUser
1398 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1399 $watch = false, $timestamp = false, User
$user = null ) {
1405 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1407 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1412 $user->addWatch( $this->getTitle() );
1419 * Record a file upload in the upload log and the image table
1420 * @param string $oldver
1421 * @param string $comment
1422 * @param string $pageText
1423 * @param bool|array $props
1424 * @param string|bool $timestamp
1425 * @param null|User $user
1426 * @param string[] $tags
1427 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1428 * upload, see T193621
1431 function recordUpload2(
1432 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1433 $createNullRevision = true
1435 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
1437 if ( is_null( $user ) ) {
1442 $dbw = $this->repo
->getMasterDB();
1444 # Imports or such might force a certain timestamp; otherwise we generate
1445 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1446 if ( $timestamp === false ) {
1447 $timestamp = $dbw->timestamp();
1448 $allowTimeKludge = true;
1450 $allowTimeKludge = false;
1453 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1454 $props['description'] = $comment;
1455 $props['user'] = $user->getId();
1456 $props['user_text'] = $user->getName();
1457 $props['actor'] = $user->getActorId( $dbw );
1458 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1459 $this->setProps( $props );
1461 # Fail now if the file isn't there
1462 if ( !$this->fileExists
) {
1463 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1465 return Status
::newFatal( 'filenotfound', $this->getRel() );
1468 $dbw->startAtomic( __METHOD__
);
1470 # Test to see if the row exists using INSERT IGNORE
1471 # This avoids race conditions by locking the row until the commit, and also
1472 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1473 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
1474 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1475 $actorMigration = ActorMigration
::newMigration();
1476 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1477 $dbw->insert( 'image',
1479 'img_name' => $this->getName(),
1480 'img_size' => $this->size
,
1481 'img_width' => intval( $this->width
),
1482 'img_height' => intval( $this->height
),
1483 'img_bits' => $this->bits
,
1484 'img_media_type' => $this->media_type
,
1485 'img_major_mime' => $this->major_mime
,
1486 'img_minor_mime' => $this->minor_mime
,
1487 'img_timestamp' => $timestamp,
1488 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1489 'img_sha1' => $this->sha1
1490 ] +
$commentFields +
$actorFields,
1494 $reupload = ( $dbw->affectedRows() == 0 );
1497 $row = $dbw->selectRow(
1499 [ 'img_timestamp', 'img_sha1' ],
1500 [ 'img_name' => $this->getName() ],
1502 [ 'LOCK IN SHARE MODE' ]
1505 if ( $row && $row->img_sha1
=== $this->sha1
) {
1506 $dbw->endAtomic( __METHOD__
);
1507 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1508 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1509 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1512 if ( $allowTimeKludge ) {
1513 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1514 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1515 # Avoid a timestamp that is not newer than the last version
1516 # TODO: the image/oldimage tables should be like page/revision with an ID field
1517 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1518 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1519 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1520 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1524 $tables = [ 'image' ];
1526 'oi_name' => 'img_name',
1527 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1528 'oi_size' => 'img_size',
1529 'oi_width' => 'img_width',
1530 'oi_height' => 'img_height',
1531 'oi_bits' => 'img_bits',
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 ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1542 $fields['oi_description'] = 'img_description';
1544 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1545 $tables[] = 'image_comment_temp';
1546 $fields['oi_description_id'] = 'CASE WHEN img_description_id = 0 '
1547 . 'THEN COALESCE(imgcomment_description_id, 0) ELSE img_description_id END';
1548 $joins['image_comment_temp'] = [
1549 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
1550 [ 'imgcomment_name = img_name' ]
1554 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
1555 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1557 // Upgrade any rows that are still old-style. Otherwise an upgrade
1558 // might be missed if a deletion happens while the migration script
1560 $res = $dbw->select(
1561 [ 'image', 'image_comment_temp' ],
1562 [ 'img_name', 'img_description' ],
1564 'img_name' => $this->getName(),
1565 'imgcomment_name' => null,
1566 'img_description_id' => 0,
1570 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1572 foreach ( $res as $row ) {
1573 $imgFields = $commentStore->insert( $dbw, 'img_description', $row->img_description
);
1577 [ 'img_name' => $row->img_name
],
1583 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
1584 $fields['oi_user'] = 'img_user';
1585 $fields['oi_user_text'] = 'img_user_text';
1587 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1588 $fields['oi_actor'] = 'img_actor';
1592 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
1594 // Upgrade any rows that are still old-style. Otherwise an upgrade
1595 // might be missed if a deletion happens while the migration script
1597 $res = $dbw->select(
1599 [ 'img_name', 'img_user', 'img_user_text' ],
1600 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1603 foreach ( $res as $row ) {
1604 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
1607 [ 'img_actor' => $actorId ],
1608 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
1614 # (T36993) Note: $oldver can be empty here, if the previous
1615 # version of the file was broken. Allow registration of the new
1616 # version to continue anyway, because that's better than having
1617 # an image that's not fixable by user operations.
1618 # Collision, this is an update of a file
1619 # Insert previous contents into oldimage
1620 $dbw->insertSelect( 'oldimage', $tables, $fields,
1621 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1623 # Update the current image row
1624 $dbw->update( 'image',
1626 'img_size' => $this->size
,
1627 'img_width' => intval( $this->width
),
1628 'img_height' => intval( $this->height
),
1629 'img_bits' => $this->bits
,
1630 'img_media_type' => $this->media_type
,
1631 'img_major_mime' => $this->major_mime
,
1632 'img_minor_mime' => $this->minor_mime
,
1633 'img_timestamp' => $timestamp,
1634 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1635 'img_sha1' => $this->sha1
1636 ] +
$commentFields +
$actorFields,
1637 [ 'img_name' => $this->getName() ],
1640 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
1641 // Clear deprecated table row
1642 $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__
);
1646 $descTitle = $this->getTitle();
1647 $descId = $descTitle->getArticleID();
1648 $wikiPage = new WikiFilePage( $descTitle );
1649 $wikiPage->setFile( $this );
1651 // Add the log entry...
1652 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1653 $logEntry->setTimestamp( $this->timestamp
);
1654 $logEntry->setPerformer( $user );
1655 $logEntry->setComment( $comment );
1656 $logEntry->setTarget( $descTitle );
1657 // Allow people using the api to associate log entries with the upload.
1658 // Log has a timestamp, but sometimes different from upload timestamp.
1659 $logEntry->setParameters(
1661 'img_sha1' => $this->sha1
,
1662 'img_timestamp' => $timestamp,
1665 // Note we keep $logId around since during new image
1666 // creation, page doesn't exist yet, so log_page = 0
1667 // but we want it to point to the page we're making,
1668 // so we later modify the log entry.
1669 // For a similar reason, we avoid making an RC entry
1670 // now and wait until the page exists.
1671 $logId = $logEntry->insert();
1673 if ( $descTitle->exists() ) {
1674 // Use own context to get the action text in content language
1675 $formatter = LogFormatter
::newFromEntry( $logEntry );
1676 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1677 $editSummary = $formatter->getPlainActionText();
1679 $nullRevision = $createNullRevision === false ?
null : Revision
::newNullRevision(
1686 if ( $nullRevision ) {
1687 $nullRevision->insertOn( $dbw );
1689 'NewRevisionFromEditComplete',
1690 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1692 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1693 // Associate null revision id
1694 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1697 $newPageContent = null;
1699 // Make the description page and RC log entry post-commit
1700 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1703 # Defer purges, page creation, and link updates in case they error out.
1704 # The most important thing is that files and the DB registry stay synced.
1705 $dbw->endAtomic( __METHOD__
);
1706 $fname = __METHOD__
;
1708 # Do some cache purges after final commit so that:
1709 # a) Changes are more likely to be seen post-purge
1710 # b) They won't cause rollback of the log publish/update above
1711 DeferredUpdates
::addUpdate(
1712 new AutoCommitUpdate(
1716 $reupload, $wikiPage, $newPageContent, $comment, $user,
1717 $logEntry, $logId, $descId, $tags, $fname
1719 # Update memcache after the commit
1720 $this->invalidateCache();
1722 $updateLogPage = false;
1723 if ( $newPageContent ) {
1724 # New file page; create the description page.
1725 # There's already a log entry, so don't make a second RC entry
1726 # CDN and file cache for the description page are purged by doEditContent.
1727 $status = $wikiPage->doEditContent(
1730 EDIT_NEW | EDIT_SUPPRESS_RC
,
1735 if ( isset( $status->value
['revision'] ) ) {
1736 /** @var Revision $rev */
1737 $rev = $status->value
['revision'];
1738 // Associate new page revision id
1739 $logEntry->setAssociatedRevId( $rev->getId() );
1741 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1742 // which is triggered on $descTitle by doEditContent() above.
1743 if ( isset( $status->value
['revision'] ) ) {
1744 /** @var Revision $rev */
1745 $rev = $status->value
['revision'];
1746 $updateLogPage = $rev->getPage();
1749 # Existing file page: invalidate description page cache
1750 $wikiPage->getTitle()->invalidateCache();
1751 $wikiPage->getTitle()->purgeSquid();
1752 # Allow the new file version to be patrolled from the page footer
1753 Article
::purgePatrolFooterCache( $descId );
1756 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1757 # but setAssociatedRevId() wasn't called at that point yet...
1758 $logParams = $logEntry->getParameters();
1759 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1760 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1761 if ( $updateLogPage ) {
1762 # Also log page, in case where we just created it above
1763 $update['log_page'] = $updateLogPage;
1765 $this->getRepo()->getMasterDB()->update(
1768 [ 'log_id' => $logId ],
1771 $this->getRepo()->getMasterDB()->insert(
1774 'ls_field' => 'associated_rev_id',
1775 'ls_value' => $logEntry->getAssociatedRevId(),
1776 'ls_log_id' => $logId,
1781 # Add change tags, if any
1783 $logEntry->setTags( $tags );
1786 # Uploads can be patrolled
1787 $logEntry->setIsPatrollable( true );
1789 # Now that the log entry is up-to-date, make an RC entry.
1790 $logEntry->publish( $logId );
1792 # Run hook for other updates (typically more cache purging)
1793 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1796 # Delete old thumbnails
1797 $this->purgeThumbnails();
1798 # Remove the old file from the CDN cache
1799 DeferredUpdates
::addUpdate(
1800 new CdnCacheUpdate( [ $this->getUrl() ] ),
1801 DeferredUpdates
::PRESEND
1804 # Update backlink pages pointing to this title if created
1805 LinksUpdate
::queueRecursiveJobsForTable(
1813 $this->prerenderThumbnails();
1816 DeferredUpdates
::PRESEND
1820 # This is a new file, so update the image count
1821 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1824 # Invalidate cache for all pages using this file
1825 DeferredUpdates
::addUpdate(
1826 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1829 return Status
::newGood();
1833 * Move or copy a file to its public location. If a file exists at the
1834 * destination, move it to an archive. Returns a Status object with
1835 * the archive name in the "value" member on success.
1837 * The archive name should be passed through to recordUpload for database
1840 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1841 * @param int $flags A bitwise combination of:
1842 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1843 * @param array $options Optional additional parameters
1844 * @return Status On success, the value member contains the
1845 * archive name, or an empty string if it was a new file.
1847 function publish( $src, $flags = 0, array $options = [] ) {
1848 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1852 * Move or copy a file to a specified location. Returns a Status
1853 * object with the archive name in the "value" member on success.
1855 * The archive name should be passed through to recordUpload for database
1858 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1859 * @param string $dstRel Target relative path
1860 * @param int $flags A bitwise combination of:
1861 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1862 * @param array $options Optional additional parameters
1863 * @return Status On success, the value member contains the
1864 * archive name, or an empty string if it was a new file.
1866 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1867 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1869 $repo = $this->getRepo();
1870 if ( $repo->getReadOnlyReason() !== false ) {
1871 return $this->readOnlyFatalStatus();
1874 $this->lock(); // begin
1876 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1877 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1879 if ( $repo->hasSha1Storage() ) {
1880 $sha1 = $repo->isVirtualUrl( $srcPath )
1881 ?
$repo->getFileSha1( $srcPath )
1882 : FSFile
::getSha1Base36FromPath( $srcPath );
1883 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1884 $wrapperBackend = $repo->getBackend();
1885 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1886 $status = $repo->quickImport( $src, $dst );
1887 if ( $flags & File
::DELETE_SOURCE
) {
1891 if ( $this->exists() ) {
1892 $status->value
= $archiveName;
1895 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1896 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1898 if ( $status->value
== 'new' ) {
1899 $status->value
= '';
1901 $status->value
= $archiveName;
1905 $this->unlock(); // done
1910 /** getLinksTo inherited */
1911 /** getExifData inherited */
1912 /** isLocal inherited */
1913 /** wasDeleted inherited */
1916 * Move file to the new title
1918 * Move current, old version and all thumbnails
1919 * to the new filename. Old file is deleted.
1921 * Cache purging is done; checks for validity
1922 * and logging are caller's responsibility
1924 * @param Title $target New file name
1927 function move( $target ) {
1928 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1929 return $this->readOnlyFatalStatus();
1932 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1933 $batch = new LocalFileMoveBatch( $this, $target );
1935 $this->lock(); // begin
1936 $batch->addCurrent();
1937 $archiveNames = $batch->addOlds();
1938 $status = $batch->execute();
1939 $this->unlock(); // done
1941 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1943 // Purge the source and target files...
1944 $oldTitleFile = wfLocalFile( $this->title
);
1945 $newTitleFile = wfLocalFile( $target );
1946 // To avoid slow purges in the transaction, move them outside...
1947 DeferredUpdates
::addUpdate(
1948 new AutoCommitUpdate(
1949 $this->getRepo()->getMasterDB(),
1951 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1952 $oldTitleFile->purgeEverything();
1953 foreach ( $archiveNames as $archiveName ) {
1954 $oldTitleFile->purgeOldThumbnails( $archiveName );
1956 $newTitleFile->purgeEverything();
1959 DeferredUpdates
::PRESEND
1962 if ( $status->isOK() ) {
1963 // Now switch the object
1964 $this->title
= $target;
1965 // Force regeneration of the name and hashpath
1966 unset( $this->name
);
1967 unset( $this->hashPath
);
1974 * Delete all versions of the file.
1976 * Moves the files into an archive directory (or deletes them)
1977 * and removes the database rows.
1979 * Cache purging is done; logging is caller's responsibility.
1981 * @param string $reason
1982 * @param bool $suppress
1983 * @param User|null $user
1986 function delete( $reason, $suppress = false, $user = null ) {
1987 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1988 return $this->readOnlyFatalStatus();
1991 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1993 $this->lock(); // begin
1994 $batch->addCurrent();
1995 // Get old version relative paths
1996 $archiveNames = $batch->addOlds();
1997 $status = $batch->execute();
1998 $this->unlock(); // done
2000 if ( $status->isOK() ) {
2001 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
2004 // To avoid slow purges in the transaction, move them outside...
2005 DeferredUpdates
::addUpdate(
2006 new AutoCommitUpdate(
2007 $this->getRepo()->getMasterDB(),
2009 function () use ( $archiveNames ) {
2010 $this->purgeEverything();
2011 foreach ( $archiveNames as $archiveName ) {
2012 $this->purgeOldThumbnails( $archiveName );
2016 DeferredUpdates
::PRESEND
2021 foreach ( $archiveNames as $archiveName ) {
2022 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2024 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
2030 * Delete an old version of the file.
2032 * Moves the file into an archive directory (or deletes it)
2033 * and removes the database row.
2035 * Cache purging is done; logging is caller's responsibility.
2037 * @param string $archiveName
2038 * @param string $reason
2039 * @param bool $suppress
2040 * @param User|null $user
2041 * @throws MWException Exception on database or file store failure
2044 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2045 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2046 return $this->readOnlyFatalStatus();
2049 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2051 $this->lock(); // begin
2052 $batch->addOld( $archiveName );
2053 $status = $batch->execute();
2054 $this->unlock(); // done
2056 $this->purgeOldThumbnails( $archiveName );
2057 if ( $status->isOK() ) {
2058 $this->purgeDescription();
2061 DeferredUpdates
::addUpdate(
2062 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2063 DeferredUpdates
::PRESEND
2070 * Restore all or specified deleted revisions to the given file.
2071 * Permissions and logging are left to the caller.
2073 * May throw database exceptions on error.
2075 * @param array $versions Set of record ids of deleted items to restore,
2076 * or empty to restore all revisions.
2077 * @param bool $unsuppress
2080 function restore( $versions = [], $unsuppress = false ) {
2081 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2082 return $this->readOnlyFatalStatus();
2085 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2087 $this->lock(); // begin
2091 $batch->addIds( $versions );
2093 $status = $batch->execute();
2094 if ( $status->isGood() ) {
2095 $cleanupStatus = $batch->cleanup();
2096 $cleanupStatus->successCount
= 0;
2097 $cleanupStatus->failCount
= 0;
2098 $status->merge( $cleanupStatus );
2100 $this->unlock(); // done
2105 /** isMultipage inherited */
2106 /** pageCount inherited */
2107 /** scaleHeight inherited */
2108 /** getImageSize inherited */
2111 * Get the URL of the file description page.
2114 function getDescriptionUrl() {
2115 return $this->title
->getLocalURL();
2119 * Get the HTML text of the description page
2120 * This is not used by ImagePage for local files, since (among other things)
2121 * it skips the parser cache.
2123 * @param Language|null $lang What language to get description in (Optional)
2124 * @return string|false
2126 function getDescriptionText( Language
$lang = null ) {
2127 $store = MediaWikiServices
::getInstance()->getRevisionStore();
2128 $revision = $store->getRevisionByTitle( $this->title
, 0, Revision
::READ_NORMAL
);
2133 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
2134 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2137 // audience check failed
2141 $pout = $rendered->getRevisionParserOutput();
2142 return $pout->getText();
2146 * @param int $audience
2147 * @param User|null $user
2150 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2152 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2154 } elseif ( $audience == self
::FOR_THIS_USER
2155 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2159 return $this->description
;
2164 * @return bool|string
2166 function getTimestamp() {
2169 return $this->timestamp
;
2173 * @return bool|string
2175 public function getDescriptionTouched() {
2176 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2177 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2178 // need to differentiate between null (uninitialized) and false (failed to load).
2179 if ( $this->descriptionTouched
=== null ) {
2181 'page_namespace' => $this->title
->getNamespace(),
2182 'page_title' => $this->title
->getDBkey()
2184 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2185 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2188 return $this->descriptionTouched
;
2194 function getSha1() {
2196 // Initialise now if necessary
2197 if ( $this->sha1
== '' && $this->fileExists
) {
2198 $this->lock(); // begin
2200 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2201 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2202 $dbw = $this->repo
->getMasterDB();
2203 $dbw->update( 'image',
2204 [ 'img_sha1' => $this->sha1
],
2205 [ 'img_name' => $this->getName() ],
2207 $this->invalidateCache();
2210 $this->unlock(); // done
2217 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2219 function isCacheable() {
2222 // If extra data (metadata) was not loaded then it must have been large
2223 return $this->extraDataLoaded
2224 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2231 public function acquireFileLock() {
2232 return Status
::wrap( $this->getRepo()->getBackend()->lockFiles(
2233 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2241 public function releaseFileLock() {
2242 return Status
::wrap( $this->getRepo()->getBackend()->unlockFiles(
2243 [ $this->getPath() ], LockManager
::LOCK_EX
2248 * Start an atomic DB section and lock the image for update
2249 * or increments a reference counter if the lock is already held
2251 * This method should not be used outside of LocalFile/LocalFile*Batch
2253 * @throws LocalFileLockError Throws an error if the lock was not acquired
2254 * @return bool Whether the file lock owns/spawned the DB transaction
2256 public function lock() {
2257 if ( !$this->locked
) {
2258 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2260 $dbw = $this->repo
->getMasterDB();
2261 $makesTransaction = !$dbw->trxLevel();
2262 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2263 // T56736: use simple lock to handle when the file does not exist.
2264 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2265 // Also, that would cause contention on INSERT of similarly named rows.
2266 $status = $this->acquireFileLock(); // represents all versions of the file
2267 if ( !$status->isGood() ) {
2268 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2269 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2271 throw new LocalFileLockError( $status );
2273 // Release the lock *after* commit to avoid row-level contention.
2274 // Make sure it triggers on rollback() as well as commit() (T132921).
2275 $dbw->onTransactionResolution(
2276 function () use ( $logger ) {
2277 $status = $this->releaseFileLock();
2278 if ( !$status->isGood() ) {
2279 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2284 // Callers might care if the SELECT snapshot is safely fresh
2285 $this->lockedOwnTrx
= $makesTransaction;
2290 return $this->lockedOwnTrx
;
2294 * Decrement the lock reference count and end the atomic section if it reaches zero
2296 * This method should not be used outside of LocalFile/LocalFile*Batch
2298 * The commit and loc release will happen when no atomic sections are active, which
2299 * may happen immediately or at some point after calling this
2301 public function unlock() {
2302 if ( $this->locked
) {
2304 if ( !$this->locked
) {
2305 $dbw = $this->repo
->getMasterDB();
2306 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2307 $this->lockedOwnTrx
= false;
2315 protected function readOnlyFatalStatus() {
2316 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2317 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2321 * Clean up any dangling locks
2323 function __destruct() {
2326 } // LocalFile class
2328 # ------------------------------------------------------------------------------
2331 * Helper class for file deletion
2332 * @ingroup FileAbstraction
2334 class LocalFileDeleteBatch
{
2335 /** @var LocalFile */
2342 private $srcRels = [];
2345 private $archiveUrls = [];
2347 /** @var array Items to be processed in the deletion batch */
2348 private $deletionBatch;
2350 /** @var bool Whether to suppress all suppressable fields when deleting */
2361 * @param string $reason
2362 * @param bool $suppress
2363 * @param User|null $user
2365 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2366 $this->file
= $file;
2367 $this->reason
= $reason;
2368 $this->suppress
= $suppress;
2370 $this->user
= $user;
2373 $this->user
= $wgUser;
2375 $this->status
= $file->repo
->newGood();
2378 public function addCurrent() {
2379 $this->srcRels
['.'] = $this->file
->getRel();
2383 * @param string $oldName
2385 public function addOld( $oldName ) {
2386 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2387 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2391 * Add the old versions of the image to the batch
2392 * @return string[] List of archive names from old versions
2394 public function addOlds() {
2397 $dbw = $this->file
->repo
->getMasterDB();
2398 $result = $dbw->select( 'oldimage',
2399 [ 'oi_archive_name' ],
2400 [ 'oi_name' => $this->file
->getName() ],
2404 foreach ( $result as $row ) {
2405 $this->addOld( $row->oi_archive_name
);
2406 $archiveNames[] = $row->oi_archive_name
;
2409 return $archiveNames;
2415 protected function getOldRels() {
2416 if ( !isset( $this->srcRels
['.'] ) ) {
2417 $oldRels =& $this->srcRels
;
2418 $deleteCurrent = false;
2420 $oldRels = $this->srcRels
;
2421 unset( $oldRels['.'] );
2422 $deleteCurrent = true;
2425 return [ $oldRels, $deleteCurrent ];
2431 protected function getHashes() {
2433 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2435 if ( $deleteCurrent ) {
2436 $hashes['.'] = $this->file
->getSha1();
2439 if ( count( $oldRels ) ) {
2440 $dbw = $this->file
->repo
->getMasterDB();
2441 $res = $dbw->select(
2443 [ 'oi_archive_name', 'oi_sha1' ],
2444 [ 'oi_archive_name' => array_keys( $oldRels ),
2445 'oi_name' => $this->file
->getName() ], // performance
2449 foreach ( $res as $row ) {
2450 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2451 // Get the hash from the file
2452 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2453 $props = $this->file
->repo
->getFileProps( $oldUrl );
2455 if ( $props['fileExists'] ) {
2456 // Upgrade the oldimage row
2457 $dbw->update( 'oldimage',
2458 [ 'oi_sha1' => $props['sha1'] ],
2459 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2461 $hashes[$row->oi_archive_name
] = $props['sha1'];
2463 $hashes[$row->oi_archive_name
] = false;
2466 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2471 $missing = array_diff_key( $this->srcRels
, $hashes );
2473 foreach ( $missing as $name => $rel ) {
2474 $this->status
->error( 'filedelete-old-unregistered', $name );
2477 foreach ( $hashes as $name => $hash ) {
2479 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2480 unset( $hashes[$name] );
2487 protected function doDBInserts() {
2488 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
2491 $dbw = $this->file
->repo
->getMasterDB();
2493 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
2494 $actorMigration = ActorMigration
::newMigration();
2496 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2497 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2498 $encGroup = $dbw->addQuotes( 'deleted' );
2499 $ext = $this->file
->getExtension();
2500 $dotExt = $ext === '' ?
'' : ".$ext";
2501 $encExt = $dbw->addQuotes( $dotExt );
2502 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2504 // Bitfields to further suppress the content
2505 if ( $this->suppress
) {
2506 $bitfield = Revision
::SUPPRESSED_ALL
;
2508 $bitfield = 'oi_deleted';
2511 if ( $deleteCurrent ) {
2512 $tables = [ 'image' ];
2514 'fa_storage_group' => $encGroup,
2515 'fa_storage_key' => $dbw->conditional(
2516 [ 'img_sha1' => '' ],
2517 $dbw->addQuotes( '' ),
2518 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2520 'fa_deleted_user' => $encUserId,
2521 'fa_deleted_timestamp' => $encTimestamp,
2522 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2523 'fa_name' => 'img_name',
2524 'fa_archive_name' => 'NULL',
2525 'fa_size' => 'img_size',
2526 'fa_width' => 'img_width',
2527 'fa_height' => 'img_height',
2528 'fa_metadata' => 'img_metadata',
2529 'fa_bits' => 'img_bits',
2530 'fa_media_type' => 'img_media_type',
2531 'fa_major_mime' => 'img_major_mime',
2532 'fa_minor_mime' => 'img_minor_mime',
2533 'fa_timestamp' => 'img_timestamp',
2534 'fa_sha1' => 'img_sha1'
2538 $fields +
= array_map(
2539 [ $dbw, 'addQuotes' ],
2540 $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason
)
2543 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2544 $fields['fa_description'] = 'img_description';
2546 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2547 $tables[] = 'image_comment_temp';
2548 $fields['fa_description_id'] = 'CASE WHEN img_description_id = 0 '
2549 . 'THEN COALESCE(imgcomment_description_id, 0) ELSE img_description_id END';
2550 $joins['image_comment_temp'] = [
2551 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
2552 [ 'imgcomment_name = img_name' ]
2556 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
2557 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2559 // Upgrade any rows that are still old-style. Otherwise an upgrade
2560 // might be missed if a deletion happens while the migration script
2562 $res = $dbw->select(
2563 [ 'image', 'image_comment_temp' ],
2564 [ 'img_name', 'img_description' ],
2566 'img_name' => $this->file
->getName(),
2567 'imgcomment_name' => null,
2568 'img_description_id' => 0,
2572 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2574 foreach ( $res as $row ) {
2575 $imgFields = $commentStore->insert( $dbw, 'img_description', $row->img_description
);
2579 [ 'img_name' => $row->img_name
],
2585 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
) {
2586 $fields['fa_user'] = 'img_user';
2587 $fields['fa_user_text'] = 'img_user_text';
2589 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
2590 $fields['fa_actor'] = 'img_actor';
2594 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH
) === SCHEMA_COMPAT_WRITE_BOTH
2596 // Upgrade any rows that are still old-style. Otherwise an upgrade
2597 // might be missed if a deletion happens while the migration script
2599 $res = $dbw->select(
2601 [ 'img_name', 'img_user', 'img_user_text' ],
2602 [ 'img_name' => $this->file
->getName(), 'img_actor' => 0 ],
2605 foreach ( $res as $row ) {
2606 $actorId = User
::newFromAnyId( $row->img_user
, $row->img_user_text
, null )->getActorId( $dbw );
2609 [ 'img_actor' => $actorId ],
2610 [ 'img_name' => $row->img_name
, 'img_actor' => 0 ],
2616 $dbw->insertSelect( 'filearchive', $tables, $fields,
2617 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2620 if ( count( $oldRels ) ) {
2621 $fileQuery = OldLocalFile
::getQueryInfo();
2622 $res = $dbw->select(
2623 $fileQuery['tables'],
2624 $fileQuery['fields'],
2626 'oi_name' => $this->file
->getName(),
2627 'oi_archive_name' => array_keys( $oldRels )
2634 if ( $res->numRows() ) {
2635 $reason = $commentStore->createComment( $dbw, $this->reason
);
2636 foreach ( $res as $row ) {
2637 $comment = $commentStore->getComment( 'oi_description', $row );
2638 $user = User
::newFromAnyId( $row->oi_user
, $row->oi_user_text
, $row->oi_actor
);
2640 // Deletion-specific fields
2641 'fa_storage_group' => 'deleted',
2642 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2644 : "{$row->oi_sha1}{$dotExt}",
2645 'fa_deleted_user' => $this->user
->getId(),
2646 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2647 // Counterpart fields
2648 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2649 'fa_name' => $row->oi_name
,
2650 'fa_archive_name' => $row->oi_archive_name
,
2651 'fa_size' => $row->oi_size
,
2652 'fa_width' => $row->oi_width
,
2653 'fa_height' => $row->oi_height
,
2654 'fa_metadata' => $row->oi_metadata
,
2655 'fa_bits' => $row->oi_bits
,
2656 'fa_media_type' => $row->oi_media_type
,
2657 'fa_major_mime' => $row->oi_major_mime
,
2658 'fa_minor_mime' => $row->oi_minor_mime
,
2659 'fa_timestamp' => $row->oi_timestamp
,
2660 'fa_sha1' => $row->oi_sha1
2661 ] +
$commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2662 +
$commentStore->insert( $dbw, 'fa_description', $comment )
2663 +
$actorMigration->getInsertValues( $dbw, 'fa_user', $user );
2667 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2671 function doDBDeletes() {
2672 global $wgCommentTableSchemaMigrationStage;
2674 $dbw = $this->file
->repo
->getMasterDB();
2675 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2677 if ( count( $oldRels ) ) {
2678 $dbw->delete( 'oldimage',
2680 'oi_name' => $this->file
->getName(),
2681 'oi_archive_name' => array_keys( $oldRels )
2685 if ( $deleteCurrent ) {
2686 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2687 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2688 // Clear deprecated table row
2690 'image_comment_temp', [ 'imgcomment_name' => $this->file
->getName() ], __METHOD__
2697 * Run the transaction
2700 public function execute() {
2701 $repo = $this->file
->getRepo();
2702 $this->file
->lock();
2704 // Prepare deletion batch
2705 $hashes = $this->getHashes();
2706 $this->deletionBatch
= [];
2707 $ext = $this->file
->getExtension();
2708 $dotExt = $ext === '' ?
'' : ".$ext";
2710 foreach ( $this->srcRels
as $name => $srcRel ) {
2711 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2712 if ( isset( $hashes[$name] ) ) {
2713 $hash = $hashes[$name];
2714 $key = $hash . $dotExt;
2715 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2716 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2720 if ( !$repo->hasSha1Storage() ) {
2721 // Removes non-existent file from the batch, so we don't get errors.
2722 // This also handles files in the 'deleted' zone deleted via revision deletion.
2723 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2724 if ( !$checkStatus->isGood() ) {
2725 $this->status
->merge( $checkStatus );
2726 return $this->status
;
2728 $this->deletionBatch
= $checkStatus->value
;
2730 // Execute the file deletion batch
2731 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2732 if ( !$status->isGood() ) {
2733 $this->status
->merge( $status );
2737 if ( !$this->status
->isOK() ) {
2738 // Critical file deletion error; abort
2739 $this->file
->unlock();
2741 return $this->status
;
2744 // Copy the image/oldimage rows to filearchive
2745 $this->doDBInserts();
2746 // Delete image/oldimage rows
2747 $this->doDBDeletes();
2749 // Commit and return
2750 $this->file
->unlock();
2752 return $this->status
;
2756 * Removes non-existent files from a deletion batch.
2757 * @param array $batch
2760 protected function removeNonexistentFiles( $batch ) {
2761 $files = $newBatch = [];
2763 foreach ( $batch as $batchItem ) {
2764 list( $src, ) = $batchItem;
2765 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2768 $result = $this->file
->repo
->fileExistsBatch( $files );
2769 if ( in_array( null, $result, true ) ) {
2770 return Status
::newFatal( 'backend-fail-internal',
2771 $this->file
->repo
->getBackend()->getName() );
2774 foreach ( $batch as $batchItem ) {
2775 if ( $result[$batchItem[0]] ) {
2776 $newBatch[] = $batchItem;
2780 return Status
::newGood( $newBatch );
2784 # ------------------------------------------------------------------------------
2787 * Helper class for file undeletion
2788 * @ingroup FileAbstraction
2790 class LocalFileRestoreBatch
{
2791 /** @var LocalFile */
2794 /** @var string[] List of file IDs to restore */
2795 private $cleanupBatch;
2797 /** @var string[] List of file IDs to restore */
2800 /** @var bool Add all revisions of the file */
2803 /** @var bool Whether to remove all settings for suppressed fields */
2804 private $unsuppress = false;
2808 * @param bool $unsuppress
2810 function __construct( File
$file, $unsuppress = false ) {
2811 $this->file
= $file;
2812 $this->cleanupBatch
= [];
2814 $this->unsuppress
= $unsuppress;
2821 public function addId( $fa_id ) {
2822 $this->ids
[] = $fa_id;
2826 * Add a whole lot of files by ID
2829 public function addIds( $ids ) {
2830 $this->ids
= array_merge( $this->ids
, $ids );
2834 * Add all revisions of the file
2836 public function addAll() {
2841 * Run the transaction, except the cleanup batch.
2842 * The cleanup batch should be run in a separate transaction, because it locks different
2843 * rows and there's no need to keep the image row locked while it's acquiring those locks
2844 * The caller may have its own transaction open.
2845 * So we save the batch and let the caller call cleanup()
2848 public function execute() {
2849 /** @var Language */
2852 $repo = $this->file
->getRepo();
2853 if ( !$this->all
&& !$this->ids
) {
2855 return $repo->newGood();
2858 $lockOwnsTrx = $this->file
->lock();
2860 $dbw = $this->file
->repo
->getMasterDB();
2862 $commentStore = MediaWikiServices
::getInstance()->getCommentStore();
2863 $actorMigration = ActorMigration
::newMigration();
2865 $status = $this->file
->repo
->newGood();
2867 $exists = (bool)$dbw->selectField( 'image', '1',
2868 [ 'img_name' => $this->file
->getName() ],
2870 // The lock() should already prevents changes, but this still may need
2871 // to bypass any transaction snapshot. However, if lock() started the
2872 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2873 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2876 // Fetch all or selected archived revisions for the file,
2877 // sorted from the most recent to the oldest.
2878 $conditions = [ 'fa_name' => $this->file
->getName() ];
2880 if ( !$this->all
) {
2881 $conditions['fa_id'] = $this->ids
;
2884 $arFileQuery = ArchivedFile
::getQueryInfo();
2885 $result = $dbw->select(
2886 $arFileQuery['tables'],
2887 $arFileQuery['fields'],
2890 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2891 $arFileQuery['joins']
2897 $insertCurrent = false;
2902 foreach ( $result as $row ) {
2903 $idsPresent[] = $row->fa_id
;
2905 if ( $row->fa_name
!= $this->file
->getName() ) {
2906 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2907 $status->failCount++
;
2911 if ( $row->fa_storage_key
== '' ) {
2912 // Revision was missing pre-deletion
2913 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2914 $status->failCount++
;
2918 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2919 $row->fa_storage_key
;
2920 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2922 if ( isset( $row->fa_sha1
) ) {
2923 $sha1 = $row->fa_sha1
;
2925 // old row, populate from key
2926 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2930 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2931 $sha1 = substr( $sha1, 1 );
2934 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2935 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2936 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2937 ||
is_null( $row->fa_metadata
)
2939 // Refresh our metadata
2940 // Required for a new current revision; nice for older ones too. :)
2941 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2944 'minor_mime' => $row->fa_minor_mime
,
2945 'major_mime' => $row->fa_major_mime
,
2946 'media_type' => $row->fa_media_type
,
2947 'metadata' => $row->fa_metadata
2951 $comment = $commentStore->getComment( 'fa_description', $row );
2952 $user = User
::newFromAnyId( $row->fa_user
, $row->fa_user_text
, $row->fa_actor
);
2953 if ( $first && !$exists ) {
2954 // This revision will be published as the new current version
2955 $destRel = $this->file
->getRel();
2956 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
2957 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
2959 'img_name' => $row->fa_name
,
2960 'img_size' => $row->fa_size
,
2961 'img_width' => $row->fa_width
,
2962 'img_height' => $row->fa_height
,
2963 'img_metadata' => $props['metadata'],
2964 'img_bits' => $row->fa_bits
,
2965 'img_media_type' => $props['media_type'],
2966 'img_major_mime' => $props['major_mime'],
2967 'img_minor_mime' => $props['minor_mime'],
2968 'img_timestamp' => $row->fa_timestamp
,
2970 ] +
$commentFields +
$actorFields;
2972 // The live (current) version cannot be hidden!
2973 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2974 $status->fatal( 'undeleterevdel' );
2975 $this->file
->unlock();
2979 $archiveName = $row->fa_archive_name
;
2981 if ( $archiveName == '' ) {
2982 // This was originally a current version; we
2983 // have to devise a new archive name for it.
2984 // Format is <timestamp of archiving>!<name>
2985 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2988 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2990 } while ( isset( $archiveNames[$archiveName] ) );
2993 $archiveNames[$archiveName] = true;
2994 $destRel = $this->file
->getArchiveRel( $archiveName );
2996 'oi_name' => $row->fa_name
,
2997 'oi_archive_name' => $archiveName,
2998 'oi_size' => $row->fa_size
,
2999 'oi_width' => $row->fa_width
,
3000 'oi_height' => $row->fa_height
,
3001 'oi_bits' => $row->fa_bits
,
3002 'oi_timestamp' => $row->fa_timestamp
,
3003 'oi_metadata' => $props['metadata'],
3004 'oi_media_type' => $props['media_type'],
3005 'oi_major_mime' => $props['major_mime'],
3006 'oi_minor_mime' => $props['minor_mime'],
3007 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
3009 ] +
$commentStore->insert( $dbw, 'oi_description', $comment )
3010 +
$actorMigration->getInsertValues( $dbw, 'oi_user', $user );
3013 $deleteIds[] = $row->fa_id
;
3015 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
3016 // private files can stay where they are
3017 $status->successCount++
;
3019 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
3020 $this->cleanupBatch
[] = $row->fa_storage_key
;
3028 // Add a warning to the status object for missing IDs
3029 $missingIds = array_diff( $this->ids
, $idsPresent );
3031 foreach ( $missingIds as $id ) {
3032 $status->error( 'undelete-missing-filearchive', $id );
3035 if ( !$repo->hasSha1Storage() ) {
3036 // Remove missing files from batch, so we don't get errors when undeleting them
3037 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
3038 if ( !$checkStatus->isGood() ) {
3039 $status->merge( $checkStatus );
3042 $storeBatch = $checkStatus->value
;
3044 // Run the store batch
3045 // Use the OVERWRITE_SAME flag to smooth over a common error
3046 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
3047 $status->merge( $storeStatus );
3049 if ( !$status->isGood() ) {
3050 // Even if some files could be copied, fail entirely as that is the
3051 // easiest thing to do without data loss
3052 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
3053 $status->setOK( false );
3054 $this->file
->unlock();
3060 // Run the DB updates
3061 // Because we have locked the image row, key conflicts should be rare.
3062 // If they do occur, we can roll back the transaction at this time with
3063 // no data loss, but leaving unregistered files scattered throughout the
3065 // This is not ideal, which is why it's important to lock the image row.
3066 if ( $insertCurrent ) {
3067 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
3070 if ( $insertBatch ) {
3071 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
3075 $dbw->delete( 'filearchive',
3076 [ 'fa_id' => $deleteIds ],
3080 // If store batch is empty (all files are missing), deletion is to be considered successful
3081 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
3083 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
3085 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
3087 $this->file
->purgeEverything();
3089 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
3090 $this->file
->purgeDescription();
3094 $this->file
->unlock();
3100 * Removes non-existent files from a store batch.
3101 * @param array $triplets
3104 protected function removeNonexistentFiles( $triplets ) {
3105 $files = $filteredTriplets = [];
3106 foreach ( $triplets as $file ) {
3107 $files[$file[0]] = $file[0];
3110 $result = $this->file
->repo
->fileExistsBatch( $files );
3111 if ( in_array( null, $result, true ) ) {
3112 return Status
::newFatal( 'backend-fail-internal',
3113 $this->file
->repo
->getBackend()->getName() );
3116 foreach ( $triplets as $file ) {
3117 if ( $result[$file[0]] ) {
3118 $filteredTriplets[] = $file;
3122 return Status
::newGood( $filteredTriplets );
3126 * Removes non-existent files from a cleanup batch.
3127 * @param string[] $batch
3130 protected function removeNonexistentFromCleanup( $batch ) {
3131 $files = $newBatch = [];
3132 $repo = $this->file
->repo
;
3134 foreach ( $batch as $file ) {
3135 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3136 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3139 $result = $repo->fileExistsBatch( $files );
3141 foreach ( $batch as $file ) {
3142 if ( $result[$file] ) {
3143 $newBatch[] = $file;
3151 * Delete unused files in the deleted zone.
3152 * This should be called from outside the transaction in which execute() was called.
3155 public function cleanup() {
3156 if ( !$this->cleanupBatch
) {
3157 return $this->file
->repo
->newGood();
3160 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
3162 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
3168 * Cleanup a failed batch. The batch was only partially successful, so
3169 * rollback by removing all items that were successfully copied.
3171 * @param Status $storeStatus
3172 * @param array[] $storeBatch
3174 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3177 foreach ( $storeStatus->success
as $i => $success ) {
3178 // Check if this item of the batch was successfully copied
3180 // Item was successfully copied and needs to be removed again
3181 // Extract ($dstZone, $dstRel) from the batch
3182 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3185 $this->file
->repo
->cleanupBatch( $cleanupBatch );
3189 # ------------------------------------------------------------------------------
3192 * Helper class for file movement
3193 * @ingroup FileAbstraction
3195 class LocalFileMoveBatch
{
3196 /** @var LocalFile */
3206 protected $oldCount;
3210 /** @var IDatabase */
3215 * @param Title $target
3217 function __construct( File
$file, Title
$target ) {
3218 $this->file
= $file;
3219 $this->target
= $target;
3220 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
3221 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
3222 $this->oldName
= $this->file
->getName();
3223 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
3224 $this->oldRel
= $this->oldHash
. $this->oldName
;
3225 $this->newRel
= $this->newHash
. $this->newName
;
3226 $this->db
= $file->getRepo()->getMasterDB();
3230 * Add the current image to the batch
3232 public function addCurrent() {
3233 $this->cur
= [ $this->oldRel
, $this->newRel
];
3237 * Add the old versions of the image to the batch
3238 * @return string[] List of archive names from old versions
3240 public function addOlds() {
3241 $archiveBase = 'archive';
3243 $this->oldCount
= 0;
3246 $result = $this->db
->select( 'oldimage',
3247 [ 'oi_archive_name', 'oi_deleted' ],
3248 [ 'oi_name' => $this->oldName
],
3250 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3253 foreach ( $result as $row ) {
3254 $archiveNames[] = $row->oi_archive_name
;
3255 $oldName = $row->oi_archive_name
;
3256 $bits = explode( '!', $oldName, 2 );
3258 if ( count( $bits ) != 2 ) {
3259 wfDebug( "Old file name missing !: '$oldName' \n" );
3263 list( $timestamp, $filename ) = $bits;
3265 if ( $this->oldName
!= $filename ) {
3266 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3272 // Do we want to add those to oldCount?
3273 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3278 "{$archiveBase}/{$this->oldHash}{$oldName}",
3279 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3283 return $archiveNames;
3290 public function execute() {
3291 $repo = $this->file
->repo
;
3292 $status = $repo->newGood();
3293 $destFile = wfLocalFile( $this->target
);
3295 $this->file
->lock(); // begin
3296 $destFile->lock(); // quickly fail if destination is not available
3298 $triplets = $this->getMoveTriplets();
3299 $checkStatus = $this->removeNonexistentFiles( $triplets );
3300 if ( !$checkStatus->isGood() ) {
3301 $destFile->unlock();
3302 $this->file
->unlock();
3303 $status->merge( $checkStatus ); // couldn't talk to file backend
3306 $triplets = $checkStatus->value
;
3308 // Verify the file versions metadata in the DB.
3309 $statusDb = $this->verifyDBUpdates();
3310 if ( !$statusDb->isGood() ) {
3311 $destFile->unlock();
3312 $this->file
->unlock();
3313 $statusDb->setOK( false );
3318 if ( !$repo->hasSha1Storage() ) {
3319 // Copy the files into their new location.
3320 // If a prior process fataled copying or cleaning up files we tolerate any
3321 // of the existing files if they are identical to the ones being stored.
3322 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3323 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3324 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3325 if ( !$statusMove->isGood() ) {
3326 // Delete any files copied over (while the destination is still locked)
3327 $this->cleanupTarget( $triplets );
3328 $destFile->unlock();
3329 $this->file
->unlock();
3330 wfDebugLog( 'imagemove', "Error in moving files: "
3331 . $statusMove->getWikiText( false, false, 'en' ) );
3332 $statusMove->setOK( false );
3336 $status->merge( $statusMove );
3339 // Rename the file versions metadata in the DB.
3340 $this->doDBUpdates();
3342 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3343 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3345 $destFile->unlock();
3346 $this->file
->unlock(); // done
3348 // Everything went ok, remove the source files
3349 $this->cleanupSource( $triplets );
3351 $status->merge( $statusDb );
3357 * Verify the database updates and return a new Status indicating how
3358 * many rows would be updated.
3362 protected function verifyDBUpdates() {
3363 $repo = $this->file
->repo
;
3364 $status = $repo->newGood();
3367 $hasCurrent = $dbw->lockForUpdate(
3369 [ 'img_name' => $this->oldName
],
3372 $oldRowCount = $dbw->lockForUpdate(
3374 [ 'oi_name' => $this->oldName
],
3378 if ( $hasCurrent ) {
3379 $status->successCount++
;
3381 $status->failCount++
;
3383 $status->successCount +
= $oldRowCount;
3384 // T36934: oldCount is based on files that actually exist.
3385 // There may be more DB rows than such files, in which case $affected
3386 // can be greater than $total. We use max() to avoid negatives here.
3387 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3388 if ( $status->failCount
) {
3389 $status->error( 'imageinvalidfilename' );
3396 * Do the database updates and return a new Status indicating how
3397 * many rows where updated.
3399 protected function doDBUpdates() {
3400 global $wgCommentTableSchemaMigrationStage;
3404 // Update current image
3407 [ 'img_name' => $this->newName
],
3408 [ 'img_name' => $this->oldName
],
3411 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
3413 'image_comment_temp',
3414 [ 'imgcomment_name' => $this->newName
],
3415 [ 'imgcomment_name' => $this->oldName
],
3420 // Update old images
3424 'oi_name' => $this->newName
,
3425 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3426 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3428 [ 'oi_name' => $this->oldName
],
3434 * Generate triplets for FileRepo::storeBatch().
3437 protected function getMoveTriplets() {
3438 $moves = array_merge( [ $this->cur
], $this->olds
);
3439 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3441 foreach ( $moves as $move ) {
3442 // $move: (oldRelativePath, newRelativePath)
3443 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3444 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3447 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3455 * Removes non-existent files from move batch.
3456 * @param array $triplets
3459 protected function removeNonexistentFiles( $triplets ) {
3462 foreach ( $triplets as $file ) {
3463 $files[$file[0]] = $file[0];
3466 $result = $this->file
->repo
->fileExistsBatch( $files );
3467 if ( in_array( null, $result, true ) ) {
3468 return Status
::newFatal( 'backend-fail-internal',
3469 $this->file
->repo
->getBackend()->getName() );
3472 $filteredTriplets = [];
3473 foreach ( $triplets as $file ) {
3474 if ( $result[$file[0]] ) {
3475 $filteredTriplets[] = $file;
3477 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3481 return Status
::newGood( $filteredTriplets );
3485 * Cleanup a partially moved array of triplets by deleting the target
3486 * files. Called if something went wrong half way.
3487 * @param array[] $triplets
3489 protected function cleanupTarget( $triplets ) {
3490 // Create dest pairs from the triplets
3492 foreach ( $triplets as $triplet ) {
3493 // $triplet: (old source virtual URL, dst zone, dest rel)
3494 $pairs[] = [ $triplet[1], $triplet[2] ];
3497 $this->file
->repo
->cleanupBatch( $pairs );
3501 * Cleanup a fully moved array of triplets by deleting the source files.
3502 * Called at the end of the move process if everything else went ok.
3503 * @param array[] $triplets
3505 protected function cleanupSource( $triplets ) {
3506 // Create source file names from the triplets
3508 foreach ( $triplets as $triplet ) {
3509 $files[] = $triplet[0];
3512 $this->file
->repo
->cleanupBatch( $files );
3516 class LocalFileLockError
extends ErrorPageError
{
3517 public function __construct( Status
$status ) {
3518 parent
::__construct(
3520 $status->getMessage()
3524 public function report() {
3526 $wgOut->setStatusCode( 429 );