3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use MediaWiki\Logger\LoggerFactory
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
29 * Class to represent a local file in the wiki's own database
31 * Provides methods to retrieve paths (physical, logical, URL),
32 * to generate image thumbnails or for uploading.
34 * Note that only the repo object knows what its file class is called. You should
35 * never name a file class explictly outside of the repo class. Instead use the
36 * repo's factory functions to generate file objects, for example:
38 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
40 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
43 * @ingroup FileAbstraction
45 class LocalFile
extends File
{
46 const VERSION
= 10; // cache version
48 const CACHE_FIELD_MAX_LEN
= 1000;
50 /** @var bool Does the file exist on disk? (loadFromXxx) */
51 protected $fileExists;
53 /** @var int Image width */
56 /** @var int Image height */
59 /** @var int Returned by getimagesize (loadFromXxx) */
62 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
63 protected $media_type;
65 /** @var string MIME type, determined by MimeMagic::guessMimeType */
68 /** @var int Size in bytes (loadFromXxx) */
71 /** @var string Handler-specific metadata */
74 /** @var string SHA-1 base 36 content hash */
77 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
78 protected $dataLoaded;
80 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
81 protected $extraDataLoaded;
83 /** @var int Bitfield akin to rev_deleted */
87 protected $repoClass = 'LocalRepo';
89 /** @var int Number of line to return by nextHistoryLine() (constructor) */
92 /** @var int Result of the query for the file's history (nextHistoryLine) */
95 /** @var string Major MIME type */
98 /** @var string Minor MIME type */
101 /** @var string Upload timestamp */
104 /** @var int User ID of uploader */
107 /** @var string User name of uploader */
110 /** @var string Description of current revision of the file */
111 private $description;
113 /** @var string TS_MW timestamp of the last change of the file description */
114 private $descriptionTouched;
116 /** @var bool Whether the row was upgraded on load */
119 /** @var bool Whether the row was scheduled to upgrade on load */
122 /** @var bool True if the image row is locked */
125 /** @var bool True if the image row is locked with a lock initiated transaction */
126 private $lockedOwnTrx;
128 /** @var bool True if file is not present in file system. Not to be cached in memcached */
131 // @note: higher than IDBAccessObject constants
132 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
134 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
137 * Create a LocalFile from a title
138 * Do not call this except from inside a repo class.
140 * Note: $unused param is only here to avoid an E_STRICT
142 * @param Title $title
143 * @param FileRepo $repo
144 * @param null $unused
148 static function newFromTitle( $title, $repo, $unused = null ) {
149 return new self( $title, $repo );
153 * Create a LocalFile from a title
154 * Do not call this except from inside a repo class.
156 * @param stdClass $row
157 * @param FileRepo $repo
161 static function newFromRow( $row, $repo ) {
162 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
163 $file = new self( $title, $repo );
164 $file->loadFromRow( $row );
170 * Create a LocalFile from a SHA-1 key
171 * Do not call this except from inside a repo class.
173 * @param string $sha1 Base-36 SHA-1
174 * @param LocalRepo $repo
175 * @param string|bool $timestamp MW_timestamp (optional)
176 * @return bool|LocalFile
178 static function newFromKey( $sha1, $repo, $timestamp = false ) {
179 $dbr = $repo->getReplicaDB();
181 $conds = [ 'img_sha1' => $sha1 ];
183 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
186 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
188 return self
::newFromRow( $row, $repo );
195 * Fields in the image table
196 * @todo Deprecate this in favor of a method that returns tables and joins
197 * as well, and use CommentStore::getJoin().
200 static function selectFields() {
215 ] + CommentStore
::newKey( 'img_description' )->getFields();
219 * Do not call this except from inside a repo class.
220 * @param Title $title
221 * @param FileRepo $repo
223 function __construct( $title, $repo ) {
224 parent
::__construct( $title, $repo );
226 $this->metadata
= '';
227 $this->historyLine
= 0;
228 $this->historyRes
= null;
229 $this->dataLoaded
= false;
230 $this->extraDataLoaded
= false;
232 $this->assertRepoDefined();
233 $this->assertTitleDefined();
237 * Get the memcached key for the main data for this file, or false if
238 * there is no access to the shared cache.
239 * @return string|bool
241 function getCacheKey() {
242 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
246 * @param WANObjectCache $cache
250 public function getMutableCacheKeys( WANObjectCache
$cache ) {
251 return [ $this->getCacheKey() ];
255 * Try to load file metadata from memcached, falling back to the database
257 private function loadFromCache() {
258 $this->dataLoaded
= false;
259 $this->extraDataLoaded
= false;
261 $key = $this->getCacheKey();
263 $this->loadFromDB( self
::READ_NORMAL
);
268 $cache = ObjectCache
::getMainWANInstance();
269 $cachedValues = $cache->getWithSetCallback(
272 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
273 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
275 $this->loadFromDB( self
::READ_NORMAL
);
277 $fields = $this->getCacheFields( '' );
278 $cacheVal['fileExists'] = $this->fileExists
;
279 if ( $this->fileExists
) {
280 foreach ( $fields as $field ) {
281 $cacheVal[$field] = $this->$field;
284 // Strip off excessive entries from the subset of fields that can become large.
285 // If the cache value gets to large it will not fit in memcached and nothing will
286 // get cached at all, causing master queries for any file access.
287 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
288 if ( isset( $cacheVal[$field] )
289 && strlen( $cacheVal[$field] ) > 100 * 1024
291 unset( $cacheVal[$field] ); // don't let the value get too big
295 if ( $this->fileExists
) {
296 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
298 $ttl = $cache::TTL_DAY
;
303 [ 'version' => self
::VERSION
]
306 $this->fileExists
= $cachedValues['fileExists'];
307 if ( $this->fileExists
) {
308 $this->setProps( $cachedValues );
311 $this->dataLoaded
= true;
312 $this->extraDataLoaded
= true;
313 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
314 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
319 * Purge the file object/metadata cache
321 public function invalidateCache() {
322 $key = $this->getCacheKey();
327 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
328 function () use ( $key ) {
329 ObjectCache
::getMainWANInstance()->delete( $key );
336 * Load metadata from the file itself
338 function loadFromFile() {
339 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
340 $this->setProps( $props );
344 * @param string $prefix
347 function getCacheFields( $prefix = 'img_' ) {
348 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
349 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
351 static $results = [];
353 if ( $prefix == '' ) {
357 if ( !isset( $results[$prefix] ) ) {
358 $prefixedFields = [];
359 foreach ( $fields as $field ) {
360 $prefixedFields[] = $prefix . $field;
362 $prefixedFields +
= CommentStore
::newKey( "{$prefix}description" )->getFields();
363 $results[$prefix] = $prefixedFields;
366 return $results[$prefix];
370 * @param string $prefix
373 function getLazyCacheFields( $prefix = 'img_' ) {
374 static $fields = [ 'metadata' ];
375 static $results = [];
377 if ( $prefix == '' ) {
381 if ( !isset( $results[$prefix] ) ) {
382 $prefixedFields = [];
383 foreach ( $fields as $field ) {
384 $prefixedFields[] = $prefix . $field;
386 $results[$prefix] = $prefixedFields;
389 return $results[$prefix];
393 * Load file metadata from the DB
396 function loadFromDB( $flags = 0 ) {
397 $fname = static::class . '::' . __FUNCTION__
;
399 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
400 $this->dataLoaded
= true;
401 $this->extraDataLoaded
= true;
403 $dbr = ( $flags & self
::READ_LATEST
)
404 ?
$this->repo
->getMasterDB()
405 : $this->repo
->getReplicaDB();
407 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
408 [ 'img_name' => $this->getName() ], $fname );
411 $this->loadFromRow( $row );
413 $this->fileExists
= false;
418 * Load lazy file metadata from the DB.
419 * This covers fields that are sometimes not cached.
421 protected function loadExtraFromDB() {
422 $fname = static::class . '::' . __FUNCTION__
;
424 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
425 $this->extraDataLoaded
= true;
427 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
429 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
433 foreach ( $fieldMap as $name => $value ) {
434 $this->$name = $value;
437 throw new MWException( "Could not find data for image '{$this->getName()}'." );
442 * @param IDatabase $dbr
443 * @param string $fname
446 private function loadFieldsWithTimestamp( $dbr, $fname ) {
449 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
450 'img_name' => $this->getName(),
451 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
454 $fieldMap = $this->unprefixRow( $row, 'img_' );
456 # File may have been uploaded over in the meantime; check the old versions
457 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
458 'oi_name' => $this->getName(),
459 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
462 $fieldMap = $this->unprefixRow( $row, 'oi_' );
470 * @param array|object $row
471 * @param string $prefix
472 * @throws MWException
475 protected function unprefixRow( $row, $prefix = 'img_' ) {
476 $array = (array)$row;
477 $prefixLength = strlen( $prefix );
479 // Sanity check prefix once
480 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
481 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
485 foreach ( $array as $name => $value ) {
486 $decoded[substr( $name, $prefixLength )] = $value;
493 * Decode a row from the database (either object or array) to an array
494 * with timestamps and MIME types decoded, and the field prefix removed.
496 * @param string $prefix
497 * @throws MWException
500 function decodeRow( $row, $prefix = 'img_' ) {
501 $decoded = $this->unprefixRow( $row, $prefix );
503 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
505 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
507 if ( empty( $decoded['major_mime'] ) ) {
508 $decoded['mime'] = 'unknown/unknown';
510 if ( !$decoded['minor_mime'] ) {
511 $decoded['minor_mime'] = 'unknown';
513 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
516 // Trim zero padding from char/binary field
517 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
519 // Normalize some fields to integer type, per their database definition.
520 // Use unary + so that overflows will be upgraded to double instead of
521 // being trucated as with intval(). This is important to allow >2GB
522 // files on 32-bit systems.
523 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
524 $decoded[$field] = +
$decoded[$field];
531 * Load file metadata from a DB result row
534 * @param string $prefix
536 function loadFromRow( $row, $prefix = 'img_' ) {
537 $this->dataLoaded
= true;
538 $this->extraDataLoaded
= true;
540 $this->description
= CommentStore
::newKey( "{$prefix}description" )
541 ->getComment( $row )->text
;
543 $array = $this->decodeRow( $row, $prefix );
545 foreach ( $array as $name => $value ) {
546 $this->$name = $value;
549 $this->fileExists
= true;
550 $this->maybeUpgradeRow();
554 * Load file metadata from cache or DB, unless already loaded
557 function load( $flags = 0 ) {
558 if ( !$this->dataLoaded
) {
559 if ( $flags & self
::READ_LATEST
) {
560 $this->loadFromDB( $flags );
562 $this->loadFromCache();
566 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
567 // @note: loads on name/timestamp to reduce race condition problems
568 $this->loadExtraFromDB();
573 * Upgrade a row if it needs it
575 function maybeUpgradeRow() {
576 global $wgUpdateCompatibleMetadata;
578 if ( wfReadOnly() ||
$this->upgrading
) {
583 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
586 $handler = $this->getHandler();
588 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
589 if ( $validity === MediaHandler
::METADATA_BAD
) {
591 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
592 $upgrade = $wgUpdateCompatibleMetadata;
598 $this->upgrading
= true;
599 // Defer updates unless in auto-commit CLI mode
600 DeferredUpdates
::addCallableUpdate( function () {
601 $this->upgrading
= false; // avoid duplicate updates
604 } catch ( LocalFileLockError
$e ) {
605 // let the other process handle it (or do it next time)
612 * @return bool Whether upgradeRow() ran for this object
614 function getUpgraded() {
615 return $this->upgraded
;
619 * Fix assorted version-related problems with the image row by reloading it from the file
621 function upgradeRow() {
622 $this->lock(); // begin
624 $this->loadFromFile();
626 # Don't destroy file info of missing files
627 if ( !$this->fileExists
) {
629 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
634 $dbw = $this->repo
->getMasterDB();
635 list( $major, $minor ) = self
::splitMime( $this->mime
);
637 if ( wfReadOnly() ) {
642 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
644 $dbw->update( 'image',
646 'img_size' => $this->size
, // sanity
647 'img_width' => $this->width
,
648 'img_height' => $this->height
,
649 'img_bits' => $this->bits
,
650 'img_media_type' => $this->media_type
,
651 'img_major_mime' => $major,
652 'img_minor_mime' => $minor,
653 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
654 'img_sha1' => $this->sha1
,
656 [ 'img_name' => $this->getName() ],
660 $this->invalidateCache();
662 $this->unlock(); // done
663 $this->upgraded
= true; // avoid rework/retries
667 * Set properties in this object to be equal to those given in the
668 * associative array $info. Only cacheable fields can be set.
669 * All fields *must* be set in $info except for getLazyCacheFields().
671 * If 'mime' is given, it will be split into major_mime/minor_mime.
672 * If major_mime/minor_mime are given, $this->mime will also be set.
676 function setProps( $info ) {
677 $this->dataLoaded
= true;
678 $fields = $this->getCacheFields( '' );
679 $fields[] = 'fileExists';
681 foreach ( $fields as $field ) {
682 if ( isset( $info[$field] ) ) {
683 $this->$field = $info[$field];
687 // Fix up mime fields
688 if ( isset( $info['major_mime'] ) ) {
689 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
690 } elseif ( isset( $info['mime'] ) ) {
691 $this->mime
= $info['mime'];
692 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
696 /** splitMime inherited */
697 /** getName inherited */
698 /** getTitle inherited */
699 /** getURL inherited */
700 /** getViewURL inherited */
701 /** getPath inherited */
702 /** isVisible inherited */
707 function isMissing() {
708 if ( $this->missing
=== null ) {
709 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
710 $this->missing
= !$fileExists;
713 return $this->missing
;
717 * Return the width of the image
722 public function getWidth( $page = 1 ) {
730 if ( $this->isMultipage() ) {
731 $handler = $this->getHandler();
735 $dim = $handler->getPageDimensions( $this, $page );
737 return $dim['width'];
739 // For non-paged media, the false goes through an
740 // intval, turning failure into 0, so do same here.
749 * Return the height of the image
754 public function getHeight( $page = 1 ) {
762 if ( $this->isMultipage() ) {
763 $handler = $this->getHandler();
767 $dim = $handler->getPageDimensions( $this, $page );
769 return $dim['height'];
771 // For non-paged media, the false goes through an
772 // intval, turning failure into 0, so do same here.
776 return $this->height
;
781 * Returns ID or name of user who uploaded the file
783 * @param string $type 'text' or 'id'
786 function getUser( $type = 'text' ) {
789 if ( $type == 'text' ) {
790 return $this->user_text
;
792 return (int)$this->user
;
797 * Get short description URL for a file based on the page ID.
799 * @return string|null
800 * @throws MWException
803 public function getDescriptionShortUrl() {
804 $pageId = $this->title
->getArticleID();
806 if ( $pageId !== null ) {
807 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
808 if ( $url !== false ) {
816 * Get handler-specific metadata
819 function getMetadata() {
820 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
821 return $this->metadata
;
827 function getBitDepth() {
830 return (int)$this->bits
;
834 * Returns the size of the image file, in bytes
837 public function getSize() {
844 * Returns the MIME type of the file.
847 function getMimeType() {
854 * Returns the type of the media in the file.
855 * Use the value returned by this function with the MEDIATYPE_xxx constants.
858 function getMediaType() {
861 return $this->media_type
;
864 /** canRender inherited */
865 /** mustRender inherited */
866 /** allowInlineDisplay inherited */
867 /** isSafeFile inherited */
868 /** isTrustedFile inherited */
871 * Returns true if the file exists on disk.
872 * @return bool Whether file exist on disk.
874 public function exists() {
877 return $this->fileExists
;
880 /** getTransformScript inherited */
881 /** getUnscaledThumb inherited */
882 /** thumbName inherited */
883 /** createThumb inherited */
884 /** transform inherited */
886 /** getHandler inherited */
887 /** iconThumb inherited */
888 /** getLastError inherited */
891 * Get all thumbnail names previously generated for this file
892 * @param string|bool $archiveName Name of an archive file, default false
893 * @return array First element is the base dir, then files in that base dir.
895 function getThumbnails( $archiveName = false ) {
896 if ( $archiveName ) {
897 $dir = $this->getArchiveThumbPath( $archiveName );
899 $dir = $this->getThumbPath();
902 $backend = $this->repo
->getBackend();
905 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
906 foreach ( $iterator as $file ) {
909 } catch ( FileBackendError
$e ) {
910 } // suppress (T56674)
916 * Refresh metadata in memcached, but don't touch thumbnails or CDN
918 function purgeMetadataCache() {
919 $this->invalidateCache();
923 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
925 * @param array $options An array potentially with the key forThumbRefresh.
927 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
929 function purgeCache( $options = [] ) {
930 // Refresh metadata cache
931 $this->purgeMetadataCache();
934 $this->purgeThumbnails( $options );
936 // Purge CDN cache for this file
937 DeferredUpdates
::addUpdate(
938 new CdnCacheUpdate( [ $this->getUrl() ] ),
939 DeferredUpdates
::PRESEND
944 * Delete cached transformed files for an archived version only.
945 * @param string $archiveName Name of the archived file
947 function purgeOldThumbnails( $archiveName ) {
948 // Get a list of old thumbnails and URLs
949 $files = $this->getThumbnails( $archiveName );
951 // Purge any custom thumbnail caches
952 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
955 $dir = array_shift( $files );
956 $this->purgeThumbList( $dir, $files );
960 foreach ( $files as $file ) {
961 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
963 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
967 * Delete cached transformed files for the current version only.
968 * @param array $options
970 public function purgeThumbnails( $options = [] ) {
971 $files = $this->getThumbnails();
972 // Always purge all files from CDN regardless of handler filters
974 foreach ( $files as $file ) {
975 $urls[] = $this->getThumbUrl( $file );
977 array_shift( $urls ); // don't purge directory
979 // Give media handler a chance to filter the file purge list
980 if ( !empty( $options['forThumbRefresh'] ) ) {
981 $handler = $this->getHandler();
983 $handler->filterThumbnailPurgeList( $files, $options );
987 // Purge any custom thumbnail caches
988 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
991 $dir = array_shift( $files );
992 $this->purgeThumbList( $dir, $files );
995 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
999 * Prerenders a configurable set of thumbnails
1003 public function prerenderThumbnails() {
1004 global $wgUploadThumbnailRenderMap;
1008 $sizes = $wgUploadThumbnailRenderMap;
1011 foreach ( $sizes as $size ) {
1012 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1013 $jobs[] = new ThumbnailRenderJob(
1015 [ 'transformParams' => [ 'width' => $size ] ]
1021 JobQueueGroup
::singleton()->lazyPush( $jobs );
1026 * Delete a list of thumbnails visible at urls
1027 * @param string $dir Base dir of the files.
1028 * @param array $files Array of strings: relative filenames (to $dir)
1030 protected function purgeThumbList( $dir, $files ) {
1031 $fileListDebug = strtr(
1032 var_export( $files, true ),
1035 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1038 foreach ( $files as $file ) {
1039 if ( $this->repo
->supportsSha1URLs() ) {
1040 $reference = $this->getSha1();
1042 $reference = $this->getName();
1045 # Check that the reference (filename or sha1) is part of the thumb name
1046 # This is a basic sanity check to avoid erasing unrelated directories
1047 if ( strpos( $file, $reference ) !== false
1048 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1050 $purgeList[] = "{$dir}/{$file}";
1054 # Delete the thumbnails
1055 $this->repo
->quickPurgeBatch( $purgeList );
1056 # Clear out the thumbnail directory if empty
1057 $this->repo
->quickCleanDir( $dir );
1060 /** purgeDescription inherited */
1061 /** purgeEverything inherited */
1064 * @param int $limit Optional: Limit to number of results
1065 * @param int $start Optional: Timestamp, start from
1066 * @param int $end Optional: Timestamp, end at
1068 * @return OldLocalFile[]
1070 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1071 $dbr = $this->repo
->getReplicaDB();
1072 $tables = [ 'oldimage' ];
1073 $fields = OldLocalFile
::selectFields();
1074 $conds = $opts = $join_conds = [];
1075 $eq = $inc ?
'=' : '';
1076 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1079 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1083 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1087 $opts['LIMIT'] = $limit;
1090 // Search backwards for time > x queries
1091 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1092 $opts['ORDER BY'] = "oi_timestamp $order";
1093 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1095 // Avoid PHP 7.1 warning from passing $this by reference
1097 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1098 &$conds, &$opts, &$join_conds ] );
1100 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1103 foreach ( $res as $row ) {
1104 $r[] = $this->repo
->newFileFromRow( $row );
1107 if ( $order == 'ASC' ) {
1108 $r = array_reverse( $r ); // make sure it ends up descending
1115 * Returns the history of this file, line by line.
1116 * starts with current version, then old versions.
1117 * uses $this->historyLine to check which line to return:
1118 * 0 return line for current version
1119 * 1 query for old versions, return first one
1120 * 2, ... return next old version from above query
1123 public function nextHistoryLine() {
1124 # Polymorphic function name to distinguish foreign and local fetches
1125 $fname = static::class . '::' . __FUNCTION__
;
1127 $dbr = $this->repo
->getReplicaDB();
1129 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1130 $this->historyRes
= $dbr->select( 'image',
1133 "'' AS oi_archive_name",
1137 [ 'img_name' => $this->title
->getDBkey() ],
1141 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1142 $this->historyRes
= null;
1146 } elseif ( $this->historyLine
== 1 ) {
1147 $this->historyRes
= $dbr->select( 'oldimage', '*',
1148 [ 'oi_name' => $this->title
->getDBkey() ],
1150 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1153 $this->historyLine++
;
1155 return $dbr->fetchObject( $this->historyRes
);
1159 * Reset the history pointer to the first element of the history
1161 public function resetHistory() {
1162 $this->historyLine
= 0;
1164 if ( !is_null( $this->historyRes
) ) {
1165 $this->historyRes
= null;
1169 /** getHashPath inherited */
1170 /** getRel inherited */
1171 /** getUrlRel inherited */
1172 /** getArchiveRel inherited */
1173 /** getArchivePath inherited */
1174 /** getThumbPath inherited */
1175 /** getArchiveUrl inherited */
1176 /** getThumbUrl inherited */
1177 /** getArchiveVirtualUrl inherited */
1178 /** getThumbVirtualUrl inherited */
1179 /** isHashed inherited */
1182 * Upload a file and record it in the DB
1183 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1184 * @param string $comment Upload description
1185 * @param string $pageText Text to use for the new description page,
1186 * if a new description page is created
1187 * @param int|bool $flags Flags for publish()
1188 * @param array|bool $props File properties, if known. This can be used to
1189 * reduce the upload time when uploading virtual URLs for which the file
1190 * info is already known
1191 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1193 * @param User|null $user User object or null to use $wgUser
1194 * @param string[] $tags Change tags to add to the log entry and page revision.
1195 * (This doesn't check $user's permissions.)
1196 * @return Status On success, the value member contains the
1197 * archive name, or an empty string if it was a new file.
1199 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1200 $timestamp = false, $user = null, $tags = []
1202 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1203 return $this->readOnlyFatalStatus();
1206 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1208 if ( $this->repo
->isVirtualUrl( $srcPath )
1209 || FileBackend
::isStoragePath( $srcPath )
1211 $props = $this->repo
->getFileProps( $srcPath );
1213 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1214 $props = $mwProps->getPropsFromPath( $srcPath, true );
1219 $handler = MediaHandler
::getHandler( $props['mime'] );
1221 $metadata = MediaWiki\
quietCall( 'unserialize', $props['metadata'] );
1223 if ( !is_array( $metadata ) ) {
1227 $options['headers'] = $handler->getContentHeaders( $metadata );
1229 $options['headers'] = [];
1232 // Trim spaces on user supplied text
1233 $comment = trim( $comment );
1235 $this->lock(); // begin
1236 $status = $this->publish( $src, $flags, $options );
1238 if ( $status->successCount
>= 2 ) {
1239 // There will be a copy+(one of move,copy,store).
1240 // The first succeeding does not commit us to updating the DB
1241 // since it simply copied the current version to a timestamped file name.
1242 // It is only *preferable* to avoid leaving such files orphaned.
1243 // Once the second operation goes through, then the current version was
1244 // updated and we must therefore update the DB too.
1245 $oldver = $status->value
;
1246 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1247 $status->fatal( 'filenotfound', $srcPath );
1251 $this->unlock(); // done
1257 * Record a file upload in the upload log and the image table
1258 * @param string $oldver
1259 * @param string $desc
1260 * @param string $license
1261 * @param string $copyStatus
1262 * @param string $source
1263 * @param bool $watch
1264 * @param string|bool $timestamp
1265 * @param User|null $user User object or null to use $wgUser
1268 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1269 $watch = false, $timestamp = false, User
$user = null ) {
1275 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1277 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1282 $user->addWatch( $this->getTitle() );
1289 * Record a file upload in the upload log and the image table
1290 * @param string $oldver
1291 * @param string $comment
1292 * @param string $pageText
1293 * @param bool|array $props
1294 * @param string|bool $timestamp
1295 * @param null|User $user
1296 * @param string[] $tags
1299 function recordUpload2(
1300 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1302 global $wgCommentTableSchemaMigrationStage;
1304 if ( is_null( $user ) ) {
1309 $dbw = $this->repo
->getMasterDB();
1311 # Imports or such might force a certain timestamp; otherwise we generate
1312 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1313 if ( $timestamp === false ) {
1314 $timestamp = $dbw->timestamp();
1315 $allowTimeKludge = true;
1317 $allowTimeKludge = false;
1320 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1321 $props['description'] = $comment;
1322 $props['user'] = $user->getId();
1323 $props['user_text'] = $user->getName();
1324 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1325 $this->setProps( $props );
1327 # Fail now if the file isn't there
1328 if ( !$this->fileExists
) {
1329 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1334 $dbw->startAtomic( __METHOD__
);
1336 # Test to see if the row exists using INSERT IGNORE
1337 # This avoids race conditions by locking the row until the commit, and also
1338 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1339 $commentStore = new CommentStore( 'img_description' );
1340 list( $commentFields, $commentCallback ) =
1341 $commentStore->insertWithTempTable( $dbw, $comment );
1342 $dbw->insert( 'image',
1344 'img_name' => $this->getName(),
1345 'img_size' => $this->size
,
1346 'img_width' => intval( $this->width
),
1347 'img_height' => intval( $this->height
),
1348 'img_bits' => $this->bits
,
1349 'img_media_type' => $this->media_type
,
1350 'img_major_mime' => $this->major_mime
,
1351 'img_minor_mime' => $this->minor_mime
,
1352 'img_timestamp' => $timestamp,
1353 'img_user' => $user->getId(),
1354 'img_user_text' => $user->getName(),
1355 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1356 'img_sha1' => $this->sha1
1361 $reupload = ( $dbw->affectedRows() == 0 );
1364 if ( $allowTimeKludge ) {
1365 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1366 $ltimestamp = $dbw->selectField(
1369 [ 'img_name' => $this->getName() ],
1371 [ 'LOCK IN SHARE MODE' ]
1373 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1374 # Avoid a timestamp that is not newer than the last version
1375 # TODO: the image/oldimage tables should be like page/revision with an ID field
1376 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1377 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1378 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1379 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1383 $tables = [ 'image' ];
1385 'oi_name' => 'img_name',
1386 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1387 'oi_size' => 'img_size',
1388 'oi_width' => 'img_width',
1389 'oi_height' => 'img_height',
1390 'oi_bits' => 'img_bits',
1391 'oi_timestamp' => 'img_timestamp',
1392 'oi_user' => 'img_user',
1393 'oi_user_text' => 'img_user_text',
1394 'oi_metadata' => 'img_metadata',
1395 'oi_media_type' => 'img_media_type',
1396 'oi_major_mime' => 'img_major_mime',
1397 'oi_minor_mime' => 'img_minor_mime',
1398 'oi_sha1' => 'img_sha1',
1402 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1403 $fields['oi_description'] = 'img_description';
1405 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1406 $tables[] = 'image_comment_temp';
1407 $fields['oi_description_id'] = 'imgcomment_description_id';
1408 $joins['image_comment_temp'] = [
1409 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
1410 [ 'imgcomment_name = img_name' ]
1414 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
1415 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1417 // Upgrade any rows that are still old-style. Otherwise an upgrade
1418 // might be missed if a deletion happens while the migration script
1420 $res = $dbw->select(
1421 [ 'image', 'image_comment_temp' ],
1422 [ 'img_name', 'img_description' ],
1423 [ 'img_name' => $this->getName(), 'imgcomment_name' => null ],
1426 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1428 foreach ( $res as $row ) {
1429 list( , $callback ) = $commentStore->insertWithTempTable( $dbw, $row->img_description
);
1430 $callback( $row->img_name
);
1434 # (T36993) Note: $oldver can be empty here, if the previous
1435 # version of the file was broken. Allow registration of the new
1436 # version to continue anyway, because that's better than having
1437 # an image that's not fixable by user operations.
1438 # Collision, this is an update of a file
1439 # Insert previous contents into oldimage
1440 $dbw->insertSelect( 'oldimage', $tables, $fields,
1441 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1443 # Update the current image row
1444 $dbw->update( 'image',
1446 'img_size' => $this->size
,
1447 'img_width' => intval( $this->width
),
1448 'img_height' => intval( $this->height
),
1449 'img_bits' => $this->bits
,
1450 'img_media_type' => $this->media_type
,
1451 'img_major_mime' => $this->major_mime
,
1452 'img_minor_mime' => $this->minor_mime
,
1453 'img_timestamp' => $timestamp,
1454 'img_user' => $user->getId(),
1455 'img_user_text' => $user->getName(),
1456 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1457 'img_sha1' => $this->sha1
1459 [ 'img_name' => $this->getName() ],
1462 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
1463 // So $commentCallback can insert the new row
1464 $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__
);
1467 $commentCallback( $this->getName() );
1469 $descTitle = $this->getTitle();
1470 $descId = $descTitle->getArticleID();
1471 $wikiPage = new WikiFilePage( $descTitle );
1472 $wikiPage->setFile( $this );
1474 // Add the log entry...
1475 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1476 $logEntry->setTimestamp( $this->timestamp
);
1477 $logEntry->setPerformer( $user );
1478 $logEntry->setComment( $comment );
1479 $logEntry->setTarget( $descTitle );
1480 // Allow people using the api to associate log entries with the upload.
1481 // Log has a timestamp, but sometimes different from upload timestamp.
1482 $logEntry->setParameters(
1484 'img_sha1' => $this->sha1
,
1485 'img_timestamp' => $timestamp,
1488 // Note we keep $logId around since during new image
1489 // creation, page doesn't exist yet, so log_page = 0
1490 // but we want it to point to the page we're making,
1491 // so we later modify the log entry.
1492 // For a similar reason, we avoid making an RC entry
1493 // now and wait until the page exists.
1494 $logId = $logEntry->insert();
1496 if ( $descTitle->exists() ) {
1497 // Use own context to get the action text in content language
1498 $formatter = LogFormatter
::newFromEntry( $logEntry );
1499 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1500 $editSummary = $formatter->getPlainActionText();
1502 $nullRevision = Revision
::newNullRevision(
1509 if ( $nullRevision ) {
1510 $nullRevision->insertOn( $dbw );
1512 'NewRevisionFromEditComplete',
1513 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1515 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1516 // Associate null revision id
1517 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1520 $newPageContent = null;
1522 // Make the description page and RC log entry post-commit
1523 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1526 # Defer purges, page creation, and link updates in case they error out.
1527 # The most important thing is that files and the DB registry stay synced.
1528 $dbw->endAtomic( __METHOD__
);
1530 # Do some cache purges after final commit so that:
1531 # a) Changes are more likely to be seen post-purge
1532 # b) They won't cause rollback of the log publish/update above
1533 DeferredUpdates
::addUpdate(
1534 new AutoCommitUpdate(
1538 $reupload, $wikiPage, $newPageContent, $comment, $user,
1539 $logEntry, $logId, $descId, $tags
1541 # Update memcache after the commit
1542 $this->invalidateCache();
1544 $updateLogPage = false;
1545 if ( $newPageContent ) {
1546 # New file page; create the description page.
1547 # There's already a log entry, so don't make a second RC entry
1548 # CDN and file cache for the description page are purged by doEditContent.
1549 $status = $wikiPage->doEditContent(
1552 EDIT_NEW | EDIT_SUPPRESS_RC
,
1557 if ( isset( $status->value
['revision'] ) ) {
1558 /** @var Revision $rev */
1559 $rev = $status->value
['revision'];
1560 // Associate new page revision id
1561 $logEntry->setAssociatedRevId( $rev->getId() );
1563 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1564 // which is triggered on $descTitle by doEditContent() above.
1565 if ( isset( $status->value
['revision'] ) ) {
1566 /** @var Revision $rev */
1567 $rev = $status->value
['revision'];
1568 $updateLogPage = $rev->getPage();
1571 # Existing file page: invalidate description page cache
1572 $wikiPage->getTitle()->invalidateCache();
1573 $wikiPage->getTitle()->purgeSquid();
1574 # Allow the new file version to be patrolled from the page footer
1575 Article
::purgePatrolFooterCache( $descId );
1578 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1579 # but setAssociatedRevId() wasn't called at that point yet...
1580 $logParams = $logEntry->getParameters();
1581 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1582 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1583 if ( $updateLogPage ) {
1584 # Also log page, in case where we just created it above
1585 $update['log_page'] = $updateLogPage;
1587 $this->getRepo()->getMasterDB()->update(
1590 [ 'log_id' => $logId ],
1593 $this->getRepo()->getMasterDB()->insert(
1596 'ls_field' => 'associated_rev_id',
1597 'ls_value' => $logEntry->getAssociatedRevId(),
1598 'ls_log_id' => $logId,
1603 # Add change tags, if any
1605 $logEntry->setTags( $tags );
1608 # Uploads can be patrolled
1609 $logEntry->setIsPatrollable( true );
1611 # Now that the log entry is up-to-date, make an RC entry.
1612 $logEntry->publish( $logId );
1614 # Run hook for other updates (typically more cache purging)
1615 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1618 # Delete old thumbnails
1619 $this->purgeThumbnails();
1620 # Remove the old file from the CDN cache
1621 DeferredUpdates
::addUpdate(
1622 new CdnCacheUpdate( [ $this->getUrl() ] ),
1623 DeferredUpdates
::PRESEND
1626 # Update backlink pages pointing to this title if created
1627 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1630 $this->prerenderThumbnails();
1633 DeferredUpdates
::PRESEND
1637 # This is a new file, so update the image count
1638 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1641 # Invalidate cache for all pages using this file
1642 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1648 * Move or copy a file to its public location. If a file exists at the
1649 * destination, move it to an archive. Returns a Status object with
1650 * the archive name in the "value" member on success.
1652 * The archive name should be passed through to recordUpload for database
1655 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1656 * @param int $flags A bitwise combination of:
1657 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1658 * @param array $options Optional additional parameters
1659 * @return Status On success, the value member contains the
1660 * archive name, or an empty string if it was a new file.
1662 function publish( $src, $flags = 0, array $options = [] ) {
1663 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1667 * Move or copy a file to a specified location. Returns a Status
1668 * object with the archive name in the "value" member on success.
1670 * The archive name should be passed through to recordUpload for database
1673 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1674 * @param string $dstRel Target relative path
1675 * @param int $flags A bitwise combination of:
1676 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1677 * @param array $options Optional additional parameters
1678 * @return Status On success, the value member contains the
1679 * archive name, or an empty string if it was a new file.
1681 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1682 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1684 $repo = $this->getRepo();
1685 if ( $repo->getReadOnlyReason() !== false ) {
1686 return $this->readOnlyFatalStatus();
1689 $this->lock(); // begin
1691 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1692 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1694 if ( $repo->hasSha1Storage() ) {
1695 $sha1 = $repo->isVirtualUrl( $srcPath )
1696 ?
$repo->getFileSha1( $srcPath )
1697 : FSFile
::getSha1Base36FromPath( $srcPath );
1698 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1699 $wrapperBackend = $repo->getBackend();
1700 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1701 $status = $repo->quickImport( $src, $dst );
1702 if ( $flags & File
::DELETE_SOURCE
) {
1706 if ( $this->exists() ) {
1707 $status->value
= $archiveName;
1710 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1711 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1713 if ( $status->value
== 'new' ) {
1714 $status->value
= '';
1716 $status->value
= $archiveName;
1720 $this->unlock(); // done
1725 /** getLinksTo inherited */
1726 /** getExifData inherited */
1727 /** isLocal inherited */
1728 /** wasDeleted inherited */
1731 * Move file to the new title
1733 * Move current, old version and all thumbnails
1734 * to the new filename. Old file is deleted.
1736 * Cache purging is done; checks for validity
1737 * and logging are caller's responsibility
1739 * @param Title $target New file name
1742 function move( $target ) {
1743 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1744 return $this->readOnlyFatalStatus();
1747 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1748 $batch = new LocalFileMoveBatch( $this, $target );
1750 $this->lock(); // begin
1751 $batch->addCurrent();
1752 $archiveNames = $batch->addOlds();
1753 $status = $batch->execute();
1754 $this->unlock(); // done
1756 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1758 // Purge the source and target files...
1759 $oldTitleFile = wfLocalFile( $this->title
);
1760 $newTitleFile = wfLocalFile( $target );
1761 // To avoid slow purges in the transaction, move them outside...
1762 DeferredUpdates
::addUpdate(
1763 new AutoCommitUpdate(
1764 $this->getRepo()->getMasterDB(),
1766 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1767 $oldTitleFile->purgeEverything();
1768 foreach ( $archiveNames as $archiveName ) {
1769 $oldTitleFile->purgeOldThumbnails( $archiveName );
1771 $newTitleFile->purgeEverything();
1774 DeferredUpdates
::PRESEND
1777 if ( $status->isOK() ) {
1778 // Now switch the object
1779 $this->title
= $target;
1780 // Force regeneration of the name and hashpath
1781 unset( $this->name
);
1782 unset( $this->hashPath
);
1789 * Delete all versions of the file.
1791 * Moves the files into an archive directory (or deletes them)
1792 * and removes the database rows.
1794 * Cache purging is done; logging is caller's responsibility.
1796 * @param string $reason
1797 * @param bool $suppress
1798 * @param User|null $user
1801 function delete( $reason, $suppress = false, $user = null ) {
1802 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1803 return $this->readOnlyFatalStatus();
1806 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1808 $this->lock(); // begin
1809 $batch->addCurrent();
1810 // Get old version relative paths
1811 $archiveNames = $batch->addOlds();
1812 $status = $batch->execute();
1813 $this->unlock(); // done
1815 if ( $status->isOK() ) {
1816 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1819 // To avoid slow purges in the transaction, move them outside...
1820 DeferredUpdates
::addUpdate(
1821 new AutoCommitUpdate(
1822 $this->getRepo()->getMasterDB(),
1824 function () use ( $archiveNames ) {
1825 $this->purgeEverything();
1826 foreach ( $archiveNames as $archiveName ) {
1827 $this->purgeOldThumbnails( $archiveName );
1831 DeferredUpdates
::PRESEND
1836 foreach ( $archiveNames as $archiveName ) {
1837 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1839 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1845 * Delete an old version of the file.
1847 * Moves the file into an archive directory (or deletes it)
1848 * and removes the database row.
1850 * Cache purging is done; logging is caller's responsibility.
1852 * @param string $archiveName
1853 * @param string $reason
1854 * @param bool $suppress
1855 * @param User|null $user
1856 * @throws MWException Exception on database or file store failure
1859 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1860 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1861 return $this->readOnlyFatalStatus();
1864 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1866 $this->lock(); // begin
1867 $batch->addOld( $archiveName );
1868 $status = $batch->execute();
1869 $this->unlock(); // done
1871 $this->purgeOldThumbnails( $archiveName );
1872 if ( $status->isOK() ) {
1873 $this->purgeDescription();
1876 DeferredUpdates
::addUpdate(
1877 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1878 DeferredUpdates
::PRESEND
1885 * Restore all or specified deleted revisions to the given file.
1886 * Permissions and logging are left to the caller.
1888 * May throw database exceptions on error.
1890 * @param array $versions Set of record ids of deleted items to restore,
1891 * or empty to restore all revisions.
1892 * @param bool $unsuppress
1895 function restore( $versions = [], $unsuppress = false ) {
1896 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1897 return $this->readOnlyFatalStatus();
1900 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1902 $this->lock(); // begin
1906 $batch->addIds( $versions );
1908 $status = $batch->execute();
1909 if ( $status->isGood() ) {
1910 $cleanupStatus = $batch->cleanup();
1911 $cleanupStatus->successCount
= 0;
1912 $cleanupStatus->failCount
= 0;
1913 $status->merge( $cleanupStatus );
1915 $this->unlock(); // done
1920 /** isMultipage inherited */
1921 /** pageCount inherited */
1922 /** scaleHeight inherited */
1923 /** getImageSize inherited */
1926 * Get the URL of the file description page.
1929 function getDescriptionUrl() {
1930 return $this->title
->getLocalURL();
1934 * Get the HTML text of the description page
1935 * This is not used by ImagePage for local files, since (among other things)
1936 * it skips the parser cache.
1938 * @param Language $lang What language to get description in (Optional)
1939 * @return bool|mixed
1941 function getDescriptionText( $lang = null ) {
1942 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1946 $content = $revision->getContent();
1950 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1952 return $pout->getText();
1956 * @param int $audience
1960 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1962 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1964 } elseif ( $audience == self
::FOR_THIS_USER
1965 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1969 return $this->description
;
1974 * @return bool|string
1976 function getTimestamp() {
1979 return $this->timestamp
;
1983 * @return bool|string
1985 public function getDescriptionTouched() {
1986 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1987 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1988 // need to differentiate between null (uninitialized) and false (failed to load).
1989 if ( $this->descriptionTouched
=== null ) {
1991 'page_namespace' => $this->title
->getNamespace(),
1992 'page_title' => $this->title
->getDBkey()
1994 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1995 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1998 return $this->descriptionTouched
;
2004 function getSha1() {
2006 // Initialise now if necessary
2007 if ( $this->sha1
== '' && $this->fileExists
) {
2008 $this->lock(); // begin
2010 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2011 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2012 $dbw = $this->repo
->getMasterDB();
2013 $dbw->update( 'image',
2014 [ 'img_sha1' => $this->sha1
],
2015 [ 'img_name' => $this->getName() ],
2017 $this->invalidateCache();
2020 $this->unlock(); // done
2027 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2029 function isCacheable() {
2032 // If extra data (metadata) was not loaded then it must have been large
2033 return $this->extraDataLoaded
2034 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2041 public function acquireFileLock() {
2042 return $this->getRepo()->getBackend()->lockFiles(
2043 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2051 public function releaseFileLock() {
2052 return $this->getRepo()->getBackend()->unlockFiles(
2053 [ $this->getPath() ], LockManager
::LOCK_EX
2058 * Start an atomic DB section and lock the image for update
2059 * or increments a reference counter if the lock is already held
2061 * This method should not be used outside of LocalFile/LocalFile*Batch
2063 * @throws LocalFileLockError Throws an error if the lock was not acquired
2064 * @return bool Whether the file lock owns/spawned the DB transaction
2066 public function lock() {
2067 if ( !$this->locked
) {
2068 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2070 $dbw = $this->repo
->getMasterDB();
2071 $makesTransaction = !$dbw->trxLevel();
2072 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2073 // T56736: use simple lock to handle when the file does not exist.
2074 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2075 // Also, that would cause contention on INSERT of similarly named rows.
2076 $status = $this->acquireFileLock(); // represents all versions of the file
2077 if ( !$status->isGood() ) {
2078 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2079 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2081 throw new LocalFileLockError( $status );
2083 // Release the lock *after* commit to avoid row-level contention.
2084 // Make sure it triggers on rollback() as well as commit() (T132921).
2085 $dbw->onTransactionResolution(
2086 function () use ( $logger ) {
2087 $status = $this->releaseFileLock();
2088 if ( !$status->isGood() ) {
2089 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2094 // Callers might care if the SELECT snapshot is safely fresh
2095 $this->lockedOwnTrx
= $makesTransaction;
2100 return $this->lockedOwnTrx
;
2104 * Decrement the lock reference count and end the atomic section if it reaches zero
2106 * This method should not be used outside of LocalFile/LocalFile*Batch
2108 * The commit and loc release will happen when no atomic sections are active, which
2109 * may happen immediately or at some point after calling this
2111 public function unlock() {
2112 if ( $this->locked
) {
2114 if ( !$this->locked
) {
2115 $dbw = $this->repo
->getMasterDB();
2116 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2117 $this->lockedOwnTrx
= false;
2125 protected function readOnlyFatalStatus() {
2126 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2127 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2131 * Clean up any dangling locks
2133 function __destruct() {
2136 } // LocalFile class
2138 # ------------------------------------------------------------------------------
2141 * Helper class for file deletion
2142 * @ingroup FileAbstraction
2144 class LocalFileDeleteBatch
{
2145 /** @var LocalFile */
2152 private $srcRels = [];
2155 private $archiveUrls = [];
2157 /** @var array Items to be processed in the deletion batch */
2158 private $deletionBatch;
2160 /** @var bool Whether to suppress all suppressable fields when deleting */
2171 * @param string $reason
2172 * @param bool $suppress
2173 * @param User|null $user
2175 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2176 $this->file
= $file;
2177 $this->reason
= $reason;
2178 $this->suppress
= $suppress;
2180 $this->user
= $user;
2183 $this->user
= $wgUser;
2185 $this->status
= $file->repo
->newGood();
2188 public function addCurrent() {
2189 $this->srcRels
['.'] = $this->file
->getRel();
2193 * @param string $oldName
2195 public function addOld( $oldName ) {
2196 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2197 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2201 * Add the old versions of the image to the batch
2202 * @return array List of archive names from old versions
2204 public function addOlds() {
2207 $dbw = $this->file
->repo
->getMasterDB();
2208 $result = $dbw->select( 'oldimage',
2209 [ 'oi_archive_name' ],
2210 [ 'oi_name' => $this->file
->getName() ],
2214 foreach ( $result as $row ) {
2215 $this->addOld( $row->oi_archive_name
);
2216 $archiveNames[] = $row->oi_archive_name
;
2219 return $archiveNames;
2225 protected function getOldRels() {
2226 if ( !isset( $this->srcRels
['.'] ) ) {
2227 $oldRels =& $this->srcRels
;
2228 $deleteCurrent = false;
2230 $oldRels = $this->srcRels
;
2231 unset( $oldRels['.'] );
2232 $deleteCurrent = true;
2235 return [ $oldRels, $deleteCurrent ];
2241 protected function getHashes() {
2243 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2245 if ( $deleteCurrent ) {
2246 $hashes['.'] = $this->file
->getSha1();
2249 if ( count( $oldRels ) ) {
2250 $dbw = $this->file
->repo
->getMasterDB();
2251 $res = $dbw->select(
2253 [ 'oi_archive_name', 'oi_sha1' ],
2254 [ 'oi_archive_name' => array_keys( $oldRels ),
2255 'oi_name' => $this->file
->getName() ], // performance
2259 foreach ( $res as $row ) {
2260 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2261 // Get the hash from the file
2262 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2263 $props = $this->file
->repo
->getFileProps( $oldUrl );
2265 if ( $props['fileExists'] ) {
2266 // Upgrade the oldimage row
2267 $dbw->update( 'oldimage',
2268 [ 'oi_sha1' => $props['sha1'] ],
2269 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2271 $hashes[$row->oi_archive_name
] = $props['sha1'];
2273 $hashes[$row->oi_archive_name
] = false;
2276 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2281 $missing = array_diff_key( $this->srcRels
, $hashes );
2283 foreach ( $missing as $name => $rel ) {
2284 $this->status
->error( 'filedelete-old-unregistered', $name );
2287 foreach ( $hashes as $name => $hash ) {
2289 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2290 unset( $hashes[$name] );
2297 protected function doDBInserts() {
2298 global $wgCommentTableSchemaMigrationStage;
2301 $dbw = $this->file
->repo
->getMasterDB();
2303 $commentStoreImgDesc = new CommentStore( 'img_description' );
2304 $commentStoreOiDesc = new CommentStore( 'oi_description' );
2305 $commentStoreFaDesc = new CommentStore( 'fa_description' );
2306 $commentStoreFaReason = new CommentStore( 'fa_deleted_reason' );
2308 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2309 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2310 $encReason = $dbw->addQuotes( $this->reason
);
2311 $encGroup = $dbw->addQuotes( 'deleted' );
2312 $ext = $this->file
->getExtension();
2313 $dotExt = $ext === '' ?
'' : ".$ext";
2314 $encExt = $dbw->addQuotes( $dotExt );
2315 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2317 // Bitfields to further suppress the content
2318 if ( $this->suppress
) {
2319 $bitfield = Revision
::SUPPRESSED_ALL
;
2321 $bitfield = 'oi_deleted';
2324 if ( $deleteCurrent ) {
2325 $tables = [ 'image' ];
2327 'fa_storage_group' => $encGroup,
2328 'fa_storage_key' => $dbw->conditional(
2329 [ 'img_sha1' => '' ],
2330 $dbw->addQuotes( '' ),
2331 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2333 'fa_deleted_user' => $encUserId,
2334 'fa_deleted_timestamp' => $encTimestamp,
2335 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2336 'fa_name' => 'img_name',
2337 'fa_archive_name' => 'NULL',
2338 'fa_size' => 'img_size',
2339 'fa_width' => 'img_width',
2340 'fa_height' => 'img_height',
2341 'fa_metadata' => 'img_metadata',
2342 'fa_bits' => 'img_bits',
2343 'fa_media_type' => 'img_media_type',
2344 'fa_major_mime' => 'img_major_mime',
2345 'fa_minor_mime' => 'img_minor_mime',
2346 'fa_user' => 'img_user',
2347 'fa_user_text' => 'img_user_text',
2348 'fa_timestamp' => 'img_timestamp',
2349 'fa_sha1' => 'img_sha1'
2353 $fields +
= $commentStoreFaReason->insert( $dbw, $encReason );
2355 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2356 $fields['fa_description'] = 'img_description';
2358 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2359 $tables[] = 'image_comment_temp';
2360 $fields['fa_description_id'] = 'imgcomment_description_id';
2361 $joins['image_comment_temp'] = [
2362 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
2363 [ 'imgcomment_name = img_name' ]
2367 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
2368 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2370 // Upgrade any rows that are still old-style. Otherwise an upgrade
2371 // might be missed if a deletion happens while the migration script
2373 $res = $dbw->select(
2374 [ 'image', 'image_comment_temp' ],
2375 [ 'img_name', 'img_description' ],
2376 [ 'img_name' => $this->file
->getName(), 'imgcomment_name' => null ],
2379 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2381 foreach ( $res as $row ) {
2382 list( , $callback ) = $commentStoreImgDesc->insertWithTempTable( $dbw, $row->img_description
);
2383 $callback( $row->img_name
);
2387 $dbw->insertSelect( 'filearchive', $tables, $fields,
2388 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2391 if ( count( $oldRels ) ) {
2392 $res = $dbw->select(
2394 OldLocalFile
::selectFields(),
2396 'oi_name' => $this->file
->getName(),
2397 'oi_archive_name' => array_keys( $oldRels )
2403 if ( $res->numRows() ) {
2404 $reason = $commentStoreFaReason->createComment( $dbw, $this->reason
);
2405 foreach ( $res as $row ) {
2406 // Legacy from OldLocalFile::selectFields() just above
2407 $comment = $commentStoreOiDesc->getCommentLegacy( $dbw, $row );
2409 // Deletion-specific fields
2410 'fa_storage_group' => 'deleted',
2411 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2413 : "{$row->oi_sha1}{$dotExt}",
2414 'fa_deleted_user' => $this->user
->getId(),
2415 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2416 // Counterpart fields
2417 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2418 'fa_name' => $row->oi_name
,
2419 'fa_archive_name' => $row->oi_archive_name
,
2420 'fa_size' => $row->oi_size
,
2421 'fa_width' => $row->oi_width
,
2422 'fa_height' => $row->oi_height
,
2423 'fa_metadata' => $row->oi_metadata
,
2424 'fa_bits' => $row->oi_bits
,
2425 'fa_media_type' => $row->oi_media_type
,
2426 'fa_major_mime' => $row->oi_major_mime
,
2427 'fa_minor_mime' => $row->oi_minor_mime
,
2428 'fa_user' => $row->oi_user
,
2429 'fa_user_text' => $row->oi_user_text
,
2430 'fa_timestamp' => $row->oi_timestamp
,
2431 'fa_sha1' => $row->oi_sha1
2432 ] +
$commentStoreFaReason->insert( $dbw, $reason )
2433 +
$commentStoreFaDesc->insert( $dbw, $comment );
2437 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2441 function doDBDeletes() {
2442 global $wgUpdateCompatibleMetadata;
2444 $dbw = $this->file
->repo
->getMasterDB();
2445 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2447 if ( count( $oldRels ) ) {
2448 $dbw->delete( 'oldimage',
2450 'oi_name' => $this->file
->getName(),
2451 'oi_archive_name' => array_keys( $oldRels )
2455 if ( $deleteCurrent ) {
2456 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2457 if ( $wgUpdateCompatibleMetadata > MIGRATION_OLD
) {
2459 'image_comment_temp', [ 'imgcomment_name' => $this->file
->getName() ], __METHOD__
2466 * Run the transaction
2469 public function execute() {
2470 $repo = $this->file
->getRepo();
2471 $this->file
->lock();
2473 // Prepare deletion batch
2474 $hashes = $this->getHashes();
2475 $this->deletionBatch
= [];
2476 $ext = $this->file
->getExtension();
2477 $dotExt = $ext === '' ?
'' : ".$ext";
2479 foreach ( $this->srcRels
as $name => $srcRel ) {
2480 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2481 if ( isset( $hashes[$name] ) ) {
2482 $hash = $hashes[$name];
2483 $key = $hash . $dotExt;
2484 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2485 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2489 if ( !$repo->hasSha1Storage() ) {
2490 // Removes non-existent file from the batch, so we don't get errors.
2491 // This also handles files in the 'deleted' zone deleted via revision deletion.
2492 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2493 if ( !$checkStatus->isGood() ) {
2494 $this->status
->merge( $checkStatus );
2495 return $this->status
;
2497 $this->deletionBatch
= $checkStatus->value
;
2499 // Execute the file deletion batch
2500 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2501 if ( !$status->isGood() ) {
2502 $this->status
->merge( $status );
2506 if ( !$this->status
->isOK() ) {
2507 // Critical file deletion error; abort
2508 $this->file
->unlock();
2510 return $this->status
;
2513 // Copy the image/oldimage rows to filearchive
2514 $this->doDBInserts();
2515 // Delete image/oldimage rows
2516 $this->doDBDeletes();
2518 // Commit and return
2519 $this->file
->unlock();
2521 return $this->status
;
2525 * Removes non-existent files from a deletion batch.
2526 * @param array $batch
2529 protected function removeNonexistentFiles( $batch ) {
2530 $files = $newBatch = [];
2532 foreach ( $batch as $batchItem ) {
2533 list( $src, ) = $batchItem;
2534 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2537 $result = $this->file
->repo
->fileExistsBatch( $files );
2538 if ( in_array( null, $result, true ) ) {
2539 return Status
::newFatal( 'backend-fail-internal',
2540 $this->file
->repo
->getBackend()->getName() );
2543 foreach ( $batch as $batchItem ) {
2544 if ( $result[$batchItem[0]] ) {
2545 $newBatch[] = $batchItem;
2549 return Status
::newGood( $newBatch );
2553 # ------------------------------------------------------------------------------
2556 * Helper class for file undeletion
2557 * @ingroup FileAbstraction
2559 class LocalFileRestoreBatch
{
2560 /** @var LocalFile */
2563 /** @var array List of file IDs to restore */
2564 private $cleanupBatch;
2566 /** @var array List of file IDs to restore */
2569 /** @var bool Add all revisions of the file */
2572 /** @var bool Whether to remove all settings for suppressed fields */
2573 private $unsuppress = false;
2577 * @param bool $unsuppress
2579 function __construct( File
$file, $unsuppress = false ) {
2580 $this->file
= $file;
2581 $this->cleanupBatch
= $this->ids
= [];
2583 $this->unsuppress
= $unsuppress;
2590 public function addId( $fa_id ) {
2591 $this->ids
[] = $fa_id;
2595 * Add a whole lot of files by ID
2598 public function addIds( $ids ) {
2599 $this->ids
= array_merge( $this->ids
, $ids );
2603 * Add all revisions of the file
2605 public function addAll() {
2610 * Run the transaction, except the cleanup batch.
2611 * The cleanup batch should be run in a separate transaction, because it locks different
2612 * rows and there's no need to keep the image row locked while it's acquiring those locks
2613 * The caller may have its own transaction open.
2614 * So we save the batch and let the caller call cleanup()
2617 public function execute() {
2618 /** @var Language */
2621 $repo = $this->file
->getRepo();
2622 if ( !$this->all
&& !$this->ids
) {
2624 return $repo->newGood();
2627 $lockOwnsTrx = $this->file
->lock();
2629 $dbw = $this->file
->repo
->getMasterDB();
2631 $commentStoreImgDesc = new CommentStore( 'img_description' );
2632 $commentStoreOiDesc = new CommentStore( 'oi_description' );
2633 $commentStoreFaDesc = new CommentStore( 'fa_description' );
2635 $status = $this->file
->repo
->newGood();
2637 $exists = (bool)$dbw->selectField( 'image', '1',
2638 [ 'img_name' => $this->file
->getName() ],
2640 // The lock() should already prevents changes, but this still may need
2641 // to bypass any transaction snapshot. However, if lock() started the
2642 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2643 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2646 // Fetch all or selected archived revisions for the file,
2647 // sorted from the most recent to the oldest.
2648 $conditions = [ 'fa_name' => $this->file
->getName() ];
2650 if ( !$this->all
) {
2651 $conditions['fa_id'] = $this->ids
;
2654 $result = $dbw->select(
2656 ArchivedFile
::selectFields(),
2659 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2665 $insertCurrent = false;
2670 foreach ( $result as $row ) {
2671 $idsPresent[] = $row->fa_id
;
2673 if ( $row->fa_name
!= $this->file
->getName() ) {
2674 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2675 $status->failCount++
;
2679 if ( $row->fa_storage_key
== '' ) {
2680 // Revision was missing pre-deletion
2681 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2682 $status->failCount++
;
2686 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2687 $row->fa_storage_key
;
2688 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2690 if ( isset( $row->fa_sha1
) ) {
2691 $sha1 = $row->fa_sha1
;
2693 // old row, populate from key
2694 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2698 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2699 $sha1 = substr( $sha1, 1 );
2702 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2703 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2704 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2705 ||
is_null( $row->fa_metadata
)
2707 // Refresh our metadata
2708 // Required for a new current revision; nice for older ones too. :)
2709 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2712 'minor_mime' => $row->fa_minor_mime
,
2713 'major_mime' => $row->fa_major_mime
,
2714 'media_type' => $row->fa_media_type
,
2715 'metadata' => $row->fa_metadata
2719 // Legacy from ArchivedFile::selectFields() just above
2720 $comment = $commentStoreFaDesc->getCommentLegacy( $dbw, $row );
2721 if ( $first && !$exists ) {
2722 // This revision will be published as the new current version
2723 $destRel = $this->file
->getRel();
2724 list( $commentFields, $commentCallback ) =
2725 $commentStoreImgDesc->insertWithTempTable( $dbw, $comment );
2727 'img_name' => $row->fa_name
,
2728 'img_size' => $row->fa_size
,
2729 'img_width' => $row->fa_width
,
2730 'img_height' => $row->fa_height
,
2731 'img_metadata' => $props['metadata'],
2732 'img_bits' => $row->fa_bits
,
2733 'img_media_type' => $props['media_type'],
2734 'img_major_mime' => $props['major_mime'],
2735 'img_minor_mime' => $props['minor_mime'],
2736 'img_user' => $row->fa_user
,
2737 'img_user_text' => $row->fa_user_text
,
2738 'img_timestamp' => $row->fa_timestamp
,
2742 // The live (current) version cannot be hidden!
2743 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2744 $status->fatal( 'undeleterevdel' );
2745 $this->file
->unlock();
2749 $archiveName = $row->fa_archive_name
;
2751 if ( $archiveName == '' ) {
2752 // This was originally a current version; we
2753 // have to devise a new archive name for it.
2754 // Format is <timestamp of archiving>!<name>
2755 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2758 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2760 } while ( isset( $archiveNames[$archiveName] ) );
2763 $archiveNames[$archiveName] = true;
2764 $destRel = $this->file
->getArchiveRel( $archiveName );
2766 'oi_name' => $row->fa_name
,
2767 'oi_archive_name' => $archiveName,
2768 'oi_size' => $row->fa_size
,
2769 'oi_width' => $row->fa_width
,
2770 'oi_height' => $row->fa_height
,
2771 'oi_bits' => $row->fa_bits
,
2772 'oi_user' => $row->fa_user
,
2773 'oi_user_text' => $row->fa_user_text
,
2774 'oi_timestamp' => $row->fa_timestamp
,
2775 'oi_metadata' => $props['metadata'],
2776 'oi_media_type' => $props['media_type'],
2777 'oi_major_mime' => $props['major_mime'],
2778 'oi_minor_mime' => $props['minor_mime'],
2779 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2781 ] +
$commentStoreOiDesc->insert( $dbw, $comment );
2784 $deleteIds[] = $row->fa_id
;
2786 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2787 // private files can stay where they are
2788 $status->successCount++
;
2790 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2791 $this->cleanupBatch
[] = $row->fa_storage_key
;
2799 // Add a warning to the status object for missing IDs
2800 $missingIds = array_diff( $this->ids
, $idsPresent );
2802 foreach ( $missingIds as $id ) {
2803 $status->error( 'undelete-missing-filearchive', $id );
2806 if ( !$repo->hasSha1Storage() ) {
2807 // Remove missing files from batch, so we don't get errors when undeleting them
2808 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2809 if ( !$checkStatus->isGood() ) {
2810 $status->merge( $checkStatus );
2813 $storeBatch = $checkStatus->value
;
2815 // Run the store batch
2816 // Use the OVERWRITE_SAME flag to smooth over a common error
2817 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2818 $status->merge( $storeStatus );
2820 if ( !$status->isGood() ) {
2821 // Even if some files could be copied, fail entirely as that is the
2822 // easiest thing to do without data loss
2823 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2824 $status->setOK( false );
2825 $this->file
->unlock();
2831 // Run the DB updates
2832 // Because we have locked the image row, key conflicts should be rare.
2833 // If they do occur, we can roll back the transaction at this time with
2834 // no data loss, but leaving unregistered files scattered throughout the
2836 // This is not ideal, which is why it's important to lock the image row.
2837 if ( $insertCurrent ) {
2838 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2839 $commentCallback( $insertCurrent['img_name'] );
2842 if ( $insertBatch ) {
2843 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2847 $dbw->delete( 'filearchive',
2848 [ 'fa_id' => $deleteIds ],
2852 // If store batch is empty (all files are missing), deletion is to be considered successful
2853 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2855 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2857 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2859 $this->file
->purgeEverything();
2861 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2862 $this->file
->purgeDescription();
2866 $this->file
->unlock();
2872 * Removes non-existent files from a store batch.
2873 * @param array $triplets
2876 protected function removeNonexistentFiles( $triplets ) {
2877 $files = $filteredTriplets = [];
2878 foreach ( $triplets as $file ) {
2879 $files[$file[0]] = $file[0];
2882 $result = $this->file
->repo
->fileExistsBatch( $files );
2883 if ( in_array( null, $result, true ) ) {
2884 return Status
::newFatal( 'backend-fail-internal',
2885 $this->file
->repo
->getBackend()->getName() );
2888 foreach ( $triplets as $file ) {
2889 if ( $result[$file[0]] ) {
2890 $filteredTriplets[] = $file;
2894 return Status
::newGood( $filteredTriplets );
2898 * Removes non-existent files from a cleanup batch.
2899 * @param array $batch
2902 protected function removeNonexistentFromCleanup( $batch ) {
2903 $files = $newBatch = [];
2904 $repo = $this->file
->repo
;
2906 foreach ( $batch as $file ) {
2907 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2908 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2911 $result = $repo->fileExistsBatch( $files );
2913 foreach ( $batch as $file ) {
2914 if ( $result[$file] ) {
2915 $newBatch[] = $file;
2923 * Delete unused files in the deleted zone.
2924 * This should be called from outside the transaction in which execute() was called.
2927 public function cleanup() {
2928 if ( !$this->cleanupBatch
) {
2929 return $this->file
->repo
->newGood();
2932 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2934 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2940 * Cleanup a failed batch. The batch was only partially successful, so
2941 * rollback by removing all items that were succesfully copied.
2943 * @param Status $storeStatus
2944 * @param array $storeBatch
2946 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2949 foreach ( $storeStatus->success
as $i => $success ) {
2950 // Check if this item of the batch was successfully copied
2952 // Item was successfully copied and needs to be removed again
2953 // Extract ($dstZone, $dstRel) from the batch
2954 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2957 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2961 # ------------------------------------------------------------------------------
2964 * Helper class for file movement
2965 * @ingroup FileAbstraction
2967 class LocalFileMoveBatch
{
2968 /** @var LocalFile */
2978 protected $oldCount;
2982 /** @var IDatabase */
2987 * @param Title $target
2989 function __construct( File
$file, Title
$target ) {
2990 $this->file
= $file;
2991 $this->target
= $target;
2992 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2993 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2994 $this->oldName
= $this->file
->getName();
2995 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2996 $this->oldRel
= $this->oldHash
. $this->oldName
;
2997 $this->newRel
= $this->newHash
. $this->newName
;
2998 $this->db
= $file->getRepo()->getMasterDB();
3002 * Add the current image to the batch
3004 public function addCurrent() {
3005 $this->cur
= [ $this->oldRel
, $this->newRel
];
3009 * Add the old versions of the image to the batch
3010 * @return array List of archive names from old versions
3012 public function addOlds() {
3013 $archiveBase = 'archive';
3015 $this->oldCount
= 0;
3018 $result = $this->db
->select( 'oldimage',
3019 [ 'oi_archive_name', 'oi_deleted' ],
3020 [ 'oi_name' => $this->oldName
],
3022 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3025 foreach ( $result as $row ) {
3026 $archiveNames[] = $row->oi_archive_name
;
3027 $oldName = $row->oi_archive_name
;
3028 $bits = explode( '!', $oldName, 2 );
3030 if ( count( $bits ) != 2 ) {
3031 wfDebug( "Old file name missing !: '$oldName' \n" );
3035 list( $timestamp, $filename ) = $bits;
3037 if ( $this->oldName
!= $filename ) {
3038 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3044 // Do we want to add those to oldCount?
3045 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3050 "{$archiveBase}/{$this->oldHash}{$oldName}",
3051 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3055 return $archiveNames;
3062 public function execute() {
3063 $repo = $this->file
->repo
;
3064 $status = $repo->newGood();
3065 $destFile = wfLocalFile( $this->target
);
3067 $this->file
->lock(); // begin
3068 $destFile->lock(); // quickly fail if destination is not available
3070 $triplets = $this->getMoveTriplets();
3071 $checkStatus = $this->removeNonexistentFiles( $triplets );
3072 if ( !$checkStatus->isGood() ) {
3073 $destFile->unlock();
3074 $this->file
->unlock();
3075 $status->merge( $checkStatus ); // couldn't talk to file backend
3078 $triplets = $checkStatus->value
;
3080 // Verify the file versions metadata in the DB.
3081 $statusDb = $this->verifyDBUpdates();
3082 if ( !$statusDb->isGood() ) {
3083 $destFile->unlock();
3084 $this->file
->unlock();
3085 $statusDb->setOK( false );
3090 if ( !$repo->hasSha1Storage() ) {
3091 // Copy the files into their new location.
3092 // If a prior process fataled copying or cleaning up files we tolerate any
3093 // of the existing files if they are identical to the ones being stored.
3094 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3095 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3096 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3097 if ( !$statusMove->isGood() ) {
3098 // Delete any files copied over (while the destination is still locked)
3099 $this->cleanupTarget( $triplets );
3100 $destFile->unlock();
3101 $this->file
->unlock();
3102 wfDebugLog( 'imagemove', "Error in moving files: "
3103 . $statusMove->getWikiText( false, false, 'en' ) );
3104 $statusMove->setOK( false );
3108 $status->merge( $statusMove );
3111 // Rename the file versions metadata in the DB.
3112 $this->doDBUpdates();
3114 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3115 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3117 $destFile->unlock();
3118 $this->file
->unlock(); // done
3120 // Everything went ok, remove the source files
3121 $this->cleanupSource( $triplets );
3123 $status->merge( $statusDb );
3129 * Verify the database updates and return a new Status indicating how
3130 * many rows would be updated.
3134 protected function verifyDBUpdates() {
3135 $repo = $this->file
->repo
;
3136 $status = $repo->newGood();
3139 $hasCurrent = $dbw->selectField(
3142 [ 'img_name' => $this->oldName
],
3146 $oldRowCount = $dbw->selectField(
3149 [ 'oi_name' => $this->oldName
],
3154 if ( $hasCurrent ) {
3155 $status->successCount++
;
3157 $status->failCount++
;
3159 $status->successCount +
= $oldRowCount;
3160 // T36934: oldCount is based on files that actually exist.
3161 // There may be more DB rows than such files, in which case $affected
3162 // can be greater than $total. We use max() to avoid negatives here.
3163 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3164 if ( $status->failCount
) {
3165 $status->error( 'imageinvalidfilename' );
3172 * Do the database updates and return a new Status indicating how
3173 * many rows where updated.
3175 protected function doDBUpdates() {
3178 // Update current image
3181 [ 'img_name' => $this->newName
],
3182 [ 'img_name' => $this->oldName
],
3185 // Update old images
3189 'oi_name' => $this->newName
,
3190 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3191 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3193 [ 'oi_name' => $this->oldName
],
3199 * Generate triplets for FileRepo::storeBatch().
3202 protected function getMoveTriplets() {
3203 $moves = array_merge( [ $this->cur
], $this->olds
);
3204 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3206 foreach ( $moves as $move ) {
3207 // $move: (oldRelativePath, newRelativePath)
3208 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3209 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3212 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3220 * Removes non-existent files from move batch.
3221 * @param array $triplets
3224 protected function removeNonexistentFiles( $triplets ) {
3227 foreach ( $triplets as $file ) {
3228 $files[$file[0]] = $file[0];
3231 $result = $this->file
->repo
->fileExistsBatch( $files );
3232 if ( in_array( null, $result, true ) ) {
3233 return Status
::newFatal( 'backend-fail-internal',
3234 $this->file
->repo
->getBackend()->getName() );
3237 $filteredTriplets = [];
3238 foreach ( $triplets as $file ) {
3239 if ( $result[$file[0]] ) {
3240 $filteredTriplets[] = $file;
3242 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3246 return Status
::newGood( $filteredTriplets );
3250 * Cleanup a partially moved array of triplets by deleting the target
3251 * files. Called if something went wrong half way.
3252 * @param array $triplets
3254 protected function cleanupTarget( $triplets ) {
3255 // Create dest pairs from the triplets
3257 foreach ( $triplets as $triplet ) {
3258 // $triplet: (old source virtual URL, dst zone, dest rel)
3259 $pairs[] = [ $triplet[1], $triplet[2] ];
3262 $this->file
->repo
->cleanupBatch( $pairs );
3266 * Cleanup a fully moved array of triplets by deleting the source files.
3267 * Called at the end of the move process if everything else went ok.
3268 * @param array $triplets
3270 protected function cleanupSource( $triplets ) {
3271 // Create source file names from the triplets
3273 foreach ( $triplets as $triplet ) {
3274 $files[] = $triplet[0];
3277 $this->file
->repo
->cleanupBatch( $files );
3281 class LocalFileLockError
extends ErrorPageError
{
3282 public function __construct( Status
$status ) {
3283 parent
::__construct(
3285 $status->getMessage()
3289 public function report() {
3291 $wgOut->setStatusCode( 429 );