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
198 static function selectFields() {
218 * Do not call this except from inside a repo class.
219 * @param Title $title
220 * @param FileRepo $repo
222 function __construct( $title, $repo ) {
223 parent
::__construct( $title, $repo );
225 $this->metadata
= '';
226 $this->historyLine
= 0;
227 $this->historyRes
= null;
228 $this->dataLoaded
= false;
229 $this->extraDataLoaded
= false;
231 $this->assertRepoDefined();
232 $this->assertTitleDefined();
236 * Get the memcached key for the main data for this file, or false if
237 * there is no access to the shared cache.
238 * @return string|bool
240 function getCacheKey() {
241 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
245 * @param WANObjectCache $cache
249 public function getMutableCacheKeys( WANObjectCache
$cache ) {
250 return [ $this->getCacheKey() ];
254 * Try to load file metadata from memcached, falling back to the database
256 private function loadFromCache() {
257 $this->dataLoaded
= false;
258 $this->extraDataLoaded
= false;
260 $key = $this->getCacheKey();
262 $this->loadFromDB( self
::READ_NORMAL
);
267 $cache = ObjectCache
::getMainWANInstance();
268 $cachedValues = $cache->getWithSetCallback(
271 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
272 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
274 $this->loadFromDB( self
::READ_NORMAL
);
276 $fields = $this->getCacheFields( '' );
277 $cacheVal['fileExists'] = $this->fileExists
;
278 if ( $this->fileExists
) {
279 foreach ( $fields as $field ) {
280 $cacheVal[$field] = $this->$field;
283 // Strip off excessive entries from the subset of fields that can become large.
284 // If the cache value gets to large it will not fit in memcached and nothing will
285 // get cached at all, causing master queries for any file access.
286 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
287 if ( isset( $cacheVal[$field] )
288 && strlen( $cacheVal[$field] ) > 100 * 1024
290 unset( $cacheVal[$field] ); // don't let the value get too big
294 if ( $this->fileExists
) {
295 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
297 $ttl = $cache::TTL_DAY
;
302 [ 'version' => self
::VERSION
]
305 $this->fileExists
= $cachedValues['fileExists'];
306 if ( $this->fileExists
) {
307 $this->setProps( $cachedValues );
310 $this->dataLoaded
= true;
311 $this->extraDataLoaded
= true;
312 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
313 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
318 * Purge the file object/metadata cache
320 public function invalidateCache() {
321 $key = $this->getCacheKey();
326 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
327 function () use ( $key ) {
328 ObjectCache
::getMainWANInstance()->delete( $key );
335 * Load metadata from the file itself
337 function loadFromFile() {
338 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
339 $this->setProps( $props );
343 * @param string $prefix
346 function getCacheFields( $prefix = 'img_' ) {
347 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
348 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
349 'user_text', 'description' ];
350 static $results = [];
352 if ( $prefix == '' ) {
356 if ( !isset( $results[$prefix] ) ) {
357 $prefixedFields = [];
358 foreach ( $fields as $field ) {
359 $prefixedFields[] = $prefix . $field;
361 $results[$prefix] = $prefixedFields;
364 return $results[$prefix];
368 * @param string $prefix
371 function getLazyCacheFields( $prefix = 'img_' ) {
372 static $fields = [ 'metadata' ];
373 static $results = [];
375 if ( $prefix == '' ) {
379 if ( !isset( $results[$prefix] ) ) {
380 $prefixedFields = [];
381 foreach ( $fields as $field ) {
382 $prefixedFields[] = $prefix . $field;
384 $results[$prefix] = $prefixedFields;
387 return $results[$prefix];
391 * Load file metadata from the DB
394 function loadFromDB( $flags = 0 ) {
395 $fname = static::class . '::' . __FUNCTION__
;
397 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
398 $this->dataLoaded
= true;
399 $this->extraDataLoaded
= true;
401 $dbr = ( $flags & self
::READ_LATEST
)
402 ?
$this->repo
->getMasterDB()
403 : $this->repo
->getReplicaDB();
405 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
406 [ 'img_name' => $this->getName() ], $fname );
409 $this->loadFromRow( $row );
411 $this->fileExists
= false;
416 * Load lazy file metadata from the DB.
417 * This covers fields that are sometimes not cached.
419 protected function loadExtraFromDB() {
420 $fname = static::class . '::' . __FUNCTION__
;
422 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
423 $this->extraDataLoaded
= true;
425 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
427 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
431 foreach ( $fieldMap as $name => $value ) {
432 $this->$name = $value;
435 throw new MWException( "Could not find data for image '{$this->getName()}'." );
440 * @param IDatabase $dbr
441 * @param string $fname
444 private function loadFieldsWithTimestamp( $dbr, $fname ) {
447 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
448 'img_name' => $this->getName(),
449 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
452 $fieldMap = $this->unprefixRow( $row, 'img_' );
454 # File may have been uploaded over in the meantime; check the old versions
455 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
456 'oi_name' => $this->getName(),
457 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
460 $fieldMap = $this->unprefixRow( $row, 'oi_' );
468 * @param array|object $row
469 * @param string $prefix
470 * @throws MWException
473 protected function unprefixRow( $row, $prefix = 'img_' ) {
474 $array = (array)$row;
475 $prefixLength = strlen( $prefix );
477 // Sanity check prefix once
478 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
479 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
483 foreach ( $array as $name => $value ) {
484 $decoded[substr( $name, $prefixLength )] = $value;
491 * Decode a row from the database (either object or array) to an array
492 * with timestamps and MIME types decoded, and the field prefix removed.
494 * @param string $prefix
495 * @throws MWException
498 function decodeRow( $row, $prefix = 'img_' ) {
499 $decoded = $this->unprefixRow( $row, $prefix );
501 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
503 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
505 if ( empty( $decoded['major_mime'] ) ) {
506 $decoded['mime'] = 'unknown/unknown';
508 if ( !$decoded['minor_mime'] ) {
509 $decoded['minor_mime'] = 'unknown';
511 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
514 // Trim zero padding from char/binary field
515 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
517 // Normalize some fields to integer type, per their database definition.
518 // Use unary + so that overflows will be upgraded to double instead of
519 // being trucated as with intval(). This is important to allow >2GB
520 // files on 32-bit systems.
521 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
522 $decoded[$field] = +
$decoded[$field];
529 * Load file metadata from a DB result row
532 * @param string $prefix
534 function loadFromRow( $row, $prefix = 'img_' ) {
535 $this->dataLoaded
= true;
536 $this->extraDataLoaded
= true;
538 $array = $this->decodeRow( $row, $prefix );
540 foreach ( $array as $name => $value ) {
541 $this->$name = $value;
544 $this->fileExists
= true;
545 $this->maybeUpgradeRow();
549 * Load file metadata from cache or DB, unless already loaded
552 function load( $flags = 0 ) {
553 if ( !$this->dataLoaded
) {
554 if ( $flags & self
::READ_LATEST
) {
555 $this->loadFromDB( $flags );
557 $this->loadFromCache();
561 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
562 // @note: loads on name/timestamp to reduce race condition problems
563 $this->loadExtraFromDB();
568 * Upgrade a row if it needs it
570 function maybeUpgradeRow() {
571 global $wgUpdateCompatibleMetadata;
573 if ( wfReadOnly() ||
$this->upgrading
) {
578 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
581 $handler = $this->getHandler();
583 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
584 if ( $validity === MediaHandler
::METADATA_BAD
) {
586 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
587 $upgrade = $wgUpdateCompatibleMetadata;
593 $this->upgrading
= true;
594 // Defer updates unless in auto-commit CLI mode
595 DeferredUpdates
::addCallableUpdate( function () {
596 $this->upgrading
= false; // avoid duplicate updates
599 } catch ( LocalFileLockError
$e ) {
600 // let the other process handle it (or do it next time)
607 * @return bool Whether upgradeRow() ran for this object
609 function getUpgraded() {
610 return $this->upgraded
;
614 * Fix assorted version-related problems with the image row by reloading it from the file
616 function upgradeRow() {
617 $this->lock(); // begin
619 $this->loadFromFile();
621 # Don't destroy file info of missing files
622 if ( !$this->fileExists
) {
624 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
629 $dbw = $this->repo
->getMasterDB();
630 list( $major, $minor ) = self
::splitMime( $this->mime
);
632 if ( wfReadOnly() ) {
637 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
639 $dbw->update( 'image',
641 'img_size' => $this->size
, // sanity
642 'img_width' => $this->width
,
643 'img_height' => $this->height
,
644 'img_bits' => $this->bits
,
645 'img_media_type' => $this->media_type
,
646 'img_major_mime' => $major,
647 'img_minor_mime' => $minor,
648 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
649 'img_sha1' => $this->sha1
,
651 [ 'img_name' => $this->getName() ],
655 $this->invalidateCache();
657 $this->unlock(); // done
658 $this->upgraded
= true; // avoid rework/retries
662 * Set properties in this object to be equal to those given in the
663 * associative array $info. Only cacheable fields can be set.
664 * All fields *must* be set in $info except for getLazyCacheFields().
666 * If 'mime' is given, it will be split into major_mime/minor_mime.
667 * If major_mime/minor_mime are given, $this->mime will also be set.
671 function setProps( $info ) {
672 $this->dataLoaded
= true;
673 $fields = $this->getCacheFields( '' );
674 $fields[] = 'fileExists';
676 foreach ( $fields as $field ) {
677 if ( isset( $info[$field] ) ) {
678 $this->$field = $info[$field];
682 // Fix up mime fields
683 if ( isset( $info['major_mime'] ) ) {
684 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
685 } elseif ( isset( $info['mime'] ) ) {
686 $this->mime
= $info['mime'];
687 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
691 /** splitMime inherited */
692 /** getName inherited */
693 /** getTitle inherited */
694 /** getURL inherited */
695 /** getViewURL inherited */
696 /** getPath inherited */
697 /** isVisible inherited */
702 function isMissing() {
703 if ( $this->missing
=== null ) {
704 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
705 $this->missing
= !$fileExists;
708 return $this->missing
;
712 * Return the width of the image
717 public function getWidth( $page = 1 ) {
725 if ( $this->isMultipage() ) {
726 $handler = $this->getHandler();
730 $dim = $handler->getPageDimensions( $this, $page );
732 return $dim['width'];
734 // For non-paged media, the false goes through an
735 // intval, turning failure into 0, so do same here.
744 * Return the height of the image
749 public function getHeight( $page = 1 ) {
757 if ( $this->isMultipage() ) {
758 $handler = $this->getHandler();
762 $dim = $handler->getPageDimensions( $this, $page );
764 return $dim['height'];
766 // For non-paged media, the false goes through an
767 // intval, turning failure into 0, so do same here.
771 return $this->height
;
776 * Returns ID or name of user who uploaded the file
778 * @param string $type 'text' or 'id'
781 function getUser( $type = 'text' ) {
784 if ( $type == 'text' ) {
785 return $this->user_text
;
787 return (int)$this->user
;
792 * Get short description URL for a file based on the page ID.
794 * @return string|null
795 * @throws MWException
798 public function getDescriptionShortUrl() {
799 $pageId = $this->title
->getArticleID();
801 if ( $pageId !== null ) {
802 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
803 if ( $url !== false ) {
811 * Get handler-specific metadata
814 function getMetadata() {
815 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
816 return $this->metadata
;
822 function getBitDepth() {
825 return (int)$this->bits
;
829 * Returns the size of the image file, in bytes
832 public function getSize() {
839 * Returns the MIME type of the file.
842 function getMimeType() {
849 * Returns the type of the media in the file.
850 * Use the value returned by this function with the MEDIATYPE_xxx constants.
853 function getMediaType() {
856 return $this->media_type
;
859 /** canRender inherited */
860 /** mustRender inherited */
861 /** allowInlineDisplay inherited */
862 /** isSafeFile inherited */
863 /** isTrustedFile inherited */
866 * Returns true if the file exists on disk.
867 * @return bool Whether file exist on disk.
869 public function exists() {
872 return $this->fileExists
;
875 /** getTransformScript inherited */
876 /** getUnscaledThumb inherited */
877 /** thumbName inherited */
878 /** createThumb inherited */
879 /** transform inherited */
881 /** getHandler inherited */
882 /** iconThumb inherited */
883 /** getLastError inherited */
886 * Get all thumbnail names previously generated for this file
887 * @param string|bool $archiveName Name of an archive file, default false
888 * @return array First element is the base dir, then files in that base dir.
890 function getThumbnails( $archiveName = false ) {
891 if ( $archiveName ) {
892 $dir = $this->getArchiveThumbPath( $archiveName );
894 $dir = $this->getThumbPath();
897 $backend = $this->repo
->getBackend();
900 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
901 foreach ( $iterator as $file ) {
904 } catch ( FileBackendError
$e ) {
905 } // suppress (T56674)
911 * Refresh metadata in memcached, but don't touch thumbnails or CDN
913 function purgeMetadataCache() {
914 $this->invalidateCache();
918 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
920 * @param array $options An array potentially with the key forThumbRefresh.
922 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
924 function purgeCache( $options = [] ) {
925 // Refresh metadata cache
926 $this->purgeMetadataCache();
929 $this->purgeThumbnails( $options );
931 // Purge CDN cache for this file
932 DeferredUpdates
::addUpdate(
933 new CdnCacheUpdate( [ $this->getUrl() ] ),
934 DeferredUpdates
::PRESEND
939 * Delete cached transformed files for an archived version only.
940 * @param string $archiveName Name of the archived file
942 function purgeOldThumbnails( $archiveName ) {
943 // Get a list of old thumbnails and URLs
944 $files = $this->getThumbnails( $archiveName );
946 // Purge any custom thumbnail caches
947 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
950 $dir = array_shift( $files );
951 $this->purgeThumbList( $dir, $files );
955 foreach ( $files as $file ) {
956 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
958 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
962 * Delete cached transformed files for the current version only.
963 * @param array $options
965 public function purgeThumbnails( $options = [] ) {
966 $files = $this->getThumbnails();
967 // Always purge all files from CDN regardless of handler filters
969 foreach ( $files as $file ) {
970 $urls[] = $this->getThumbUrl( $file );
972 array_shift( $urls ); // don't purge directory
974 // Give media handler a chance to filter the file purge list
975 if ( !empty( $options['forThumbRefresh'] ) ) {
976 $handler = $this->getHandler();
978 $handler->filterThumbnailPurgeList( $files, $options );
982 // Purge any custom thumbnail caches
983 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
986 $dir = array_shift( $files );
987 $this->purgeThumbList( $dir, $files );
990 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
994 * Prerenders a configurable set of thumbnails
998 public function prerenderThumbnails() {
999 global $wgUploadThumbnailRenderMap;
1003 $sizes = $wgUploadThumbnailRenderMap;
1006 foreach ( $sizes as $size ) {
1007 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1008 $jobs[] = new ThumbnailRenderJob(
1010 [ 'transformParams' => [ 'width' => $size ] ]
1016 JobQueueGroup
::singleton()->lazyPush( $jobs );
1021 * Delete a list of thumbnails visible at urls
1022 * @param string $dir Base dir of the files.
1023 * @param array $files Array of strings: relative filenames (to $dir)
1025 protected function purgeThumbList( $dir, $files ) {
1026 $fileListDebug = strtr(
1027 var_export( $files, true ),
1030 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1033 foreach ( $files as $file ) {
1034 if ( $this->repo
->supportsSha1URLs() ) {
1035 $reference = $this->getSha1();
1037 $reference = $this->getName();
1040 # Check that the reference (filename or sha1) is part of the thumb name
1041 # This is a basic sanity check to avoid erasing unrelated directories
1042 if ( strpos( $file, $reference ) !== false
1043 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1045 $purgeList[] = "{$dir}/{$file}";
1049 # Delete the thumbnails
1050 $this->repo
->quickPurgeBatch( $purgeList );
1051 # Clear out the thumbnail directory if empty
1052 $this->repo
->quickCleanDir( $dir );
1055 /** purgeDescription inherited */
1056 /** purgeEverything inherited */
1059 * @param int $limit Optional: Limit to number of results
1060 * @param int $start Optional: Timestamp, start from
1061 * @param int $end Optional: Timestamp, end at
1063 * @return OldLocalFile[]
1065 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1066 $dbr = $this->repo
->getReplicaDB();
1067 $tables = [ 'oldimage' ];
1068 $fields = OldLocalFile
::selectFields();
1069 $conds = $opts = $join_conds = [];
1070 $eq = $inc ?
'=' : '';
1071 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1074 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1078 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1082 $opts['LIMIT'] = $limit;
1085 // Search backwards for time > x queries
1086 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1087 $opts['ORDER BY'] = "oi_timestamp $order";
1088 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1090 // Avoid PHP 7.1 warning from passing $this by reference
1092 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1093 &$conds, &$opts, &$join_conds ] );
1095 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1098 foreach ( $res as $row ) {
1099 $r[] = $this->repo
->newFileFromRow( $row );
1102 if ( $order == 'ASC' ) {
1103 $r = array_reverse( $r ); // make sure it ends up descending
1110 * Returns the history of this file, line by line.
1111 * starts with current version, then old versions.
1112 * uses $this->historyLine to check which line to return:
1113 * 0 return line for current version
1114 * 1 query for old versions, return first one
1115 * 2, ... return next old version from above query
1118 public function nextHistoryLine() {
1119 # Polymorphic function name to distinguish foreign and local fetches
1120 $fname = static::class . '::' . __FUNCTION__
;
1122 $dbr = $this->repo
->getReplicaDB();
1124 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1125 $this->historyRes
= $dbr->select( 'image',
1128 "'' AS oi_archive_name",
1132 [ 'img_name' => $this->title
->getDBkey() ],
1136 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1137 $this->historyRes
= null;
1141 } elseif ( $this->historyLine
== 1 ) {
1142 $this->historyRes
= $dbr->select( 'oldimage', '*',
1143 [ 'oi_name' => $this->title
->getDBkey() ],
1145 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1148 $this->historyLine++
;
1150 return $dbr->fetchObject( $this->historyRes
);
1154 * Reset the history pointer to the first element of the history
1156 public function resetHistory() {
1157 $this->historyLine
= 0;
1159 if ( !is_null( $this->historyRes
) ) {
1160 $this->historyRes
= null;
1164 /** getHashPath inherited */
1165 /** getRel inherited */
1166 /** getUrlRel inherited */
1167 /** getArchiveRel inherited */
1168 /** getArchivePath inherited */
1169 /** getThumbPath inherited */
1170 /** getArchiveUrl inherited */
1171 /** getThumbUrl inherited */
1172 /** getArchiveVirtualUrl inherited */
1173 /** getThumbVirtualUrl inherited */
1174 /** isHashed inherited */
1177 * Upload a file and record it in the DB
1178 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1179 * @param string $comment Upload description
1180 * @param string $pageText Text to use for the new description page,
1181 * if a new description page is created
1182 * @param int|bool $flags Flags for publish()
1183 * @param array|bool $props File properties, if known. This can be used to
1184 * reduce the upload time when uploading virtual URLs for which the file
1185 * info is already known
1186 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1188 * @param User|null $user User object or null to use $wgUser
1189 * @param string[] $tags Change tags to add to the log entry and page revision.
1190 * (This doesn't check $user's permissions.)
1191 * @return Status On success, the value member contains the
1192 * archive name, or an empty string if it was a new file.
1194 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1195 $timestamp = false, $user = null, $tags = []
1199 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1200 return $this->readOnlyFatalStatus();
1203 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1205 if ( $this->repo
->isVirtualUrl( $srcPath )
1206 || FileBackend
::isStoragePath( $srcPath )
1208 $props = $this->repo
->getFileProps( $srcPath );
1210 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1211 $props = $mwProps->getPropsFromPath( $srcPath, true );
1216 $handler = MediaHandler
::getHandler( $props['mime'] );
1218 $metadata = MediaWiki\
quietCall( 'unserialize', $props['metadata'] );
1220 if ( !is_array( $metadata ) ) {
1224 $options['headers'] = $handler->getContentHeaders( $metadata );
1226 $options['headers'] = [];
1229 // Trim spaces on user supplied text
1230 $comment = trim( $comment );
1232 // Truncate nicely or the DB will do it for us
1233 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1234 $comment = $wgContLang->truncate( $comment, 255 );
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 if ( is_null( $user ) ) {
1307 $dbw = $this->repo
->getMasterDB();
1309 # Imports or such might force a certain timestamp; otherwise we generate
1310 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1311 if ( $timestamp === false ) {
1312 $timestamp = $dbw->timestamp();
1313 $allowTimeKludge = true;
1315 $allowTimeKludge = false;
1318 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1319 $props['description'] = $comment;
1320 $props['user'] = $user->getId();
1321 $props['user_text'] = $user->getName();
1322 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1323 $this->setProps( $props );
1325 # Fail now if the file isn't there
1326 if ( !$this->fileExists
) {
1327 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1332 $dbw->startAtomic( __METHOD__
);
1334 # Test to see if the row exists using INSERT IGNORE
1335 # This avoids race conditions by locking the row until the commit, and also
1336 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1337 $dbw->insert( 'image',
1339 'img_name' => $this->getName(),
1340 'img_size' => $this->size
,
1341 'img_width' => intval( $this->width
),
1342 'img_height' => intval( $this->height
),
1343 'img_bits' => $this->bits
,
1344 'img_media_type' => $this->media_type
,
1345 'img_major_mime' => $this->major_mime
,
1346 'img_minor_mime' => $this->minor_mime
,
1347 'img_timestamp' => $timestamp,
1348 'img_description' => $comment,
1349 'img_user' => $user->getId(),
1350 'img_user_text' => $user->getName(),
1351 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1352 'img_sha1' => $this->sha1
1358 $reupload = ( $dbw->affectedRows() == 0 );
1360 if ( $allowTimeKludge ) {
1361 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1362 $ltimestamp = $dbw->selectField(
1365 [ 'img_name' => $this->getName() ],
1367 [ 'LOCK IN SHARE MODE' ]
1369 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1370 # Avoid a timestamp that is not newer than the last version
1371 # TODO: the image/oldimage tables should be like page/revision with an ID field
1372 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1373 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1374 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1375 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1379 # (T36993) Note: $oldver can be empty here, if the previous
1380 # version of the file was broken. Allow registration of the new
1381 # version to continue anyway, because that's better than having
1382 # an image that's not fixable by user operations.
1383 # Collision, this is an update of a file
1384 # Insert previous contents into oldimage
1385 $dbw->insertSelect( 'oldimage', 'image',
1387 'oi_name' => 'img_name',
1388 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1389 'oi_size' => 'img_size',
1390 'oi_width' => 'img_width',
1391 'oi_height' => 'img_height',
1392 'oi_bits' => 'img_bits',
1393 'oi_timestamp' => 'img_timestamp',
1394 'oi_description' => 'img_description',
1395 'oi_user' => 'img_user',
1396 'oi_user_text' => 'img_user_text',
1397 'oi_metadata' => 'img_metadata',
1398 'oi_media_type' => 'img_media_type',
1399 'oi_major_mime' => 'img_major_mime',
1400 'oi_minor_mime' => 'img_minor_mime',
1401 'oi_sha1' => 'img_sha1'
1403 [ 'img_name' => $this->getName() ],
1407 # Update the current image row
1408 $dbw->update( 'image',
1410 'img_size' => $this->size
,
1411 'img_width' => intval( $this->width
),
1412 'img_height' => intval( $this->height
),
1413 'img_bits' => $this->bits
,
1414 'img_media_type' => $this->media_type
,
1415 'img_major_mime' => $this->major_mime
,
1416 'img_minor_mime' => $this->minor_mime
,
1417 'img_timestamp' => $timestamp,
1418 'img_description' => $comment,
1419 'img_user' => $user->getId(),
1420 'img_user_text' => $user->getName(),
1421 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1422 'img_sha1' => $this->sha1
1424 [ 'img_name' => $this->getName() ],
1429 $descTitle = $this->getTitle();
1430 $descId = $descTitle->getArticleID();
1431 $wikiPage = new WikiFilePage( $descTitle );
1432 $wikiPage->setFile( $this );
1434 // Add the log entry...
1435 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1436 $logEntry->setTimestamp( $this->timestamp
);
1437 $logEntry->setPerformer( $user );
1438 $logEntry->setComment( $comment );
1439 $logEntry->setTarget( $descTitle );
1440 // Allow people using the api to associate log entries with the upload.
1441 // Log has a timestamp, but sometimes different from upload timestamp.
1442 $logEntry->setParameters(
1444 'img_sha1' => $this->sha1
,
1445 'img_timestamp' => $timestamp,
1448 // Note we keep $logId around since during new image
1449 // creation, page doesn't exist yet, so log_page = 0
1450 // but we want it to point to the page we're making,
1451 // so we later modify the log entry.
1452 // For a similar reason, we avoid making an RC entry
1453 // now and wait until the page exists.
1454 $logId = $logEntry->insert();
1456 if ( $descTitle->exists() ) {
1457 // Use own context to get the action text in content language
1458 $formatter = LogFormatter
::newFromEntry( $logEntry );
1459 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1460 $editSummary = $formatter->getPlainActionText();
1462 $nullRevision = Revision
::newNullRevision(
1469 if ( $nullRevision ) {
1470 $nullRevision->insertOn( $dbw );
1472 'NewRevisionFromEditComplete',
1473 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1475 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1476 // Associate null revision id
1477 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1480 $newPageContent = null;
1482 // Make the description page and RC log entry post-commit
1483 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1486 # Defer purges, page creation, and link updates in case they error out.
1487 # The most important thing is that files and the DB registry stay synced.
1488 $dbw->endAtomic( __METHOD__
);
1490 # Do some cache purges after final commit so that:
1491 # a) Changes are more likely to be seen post-purge
1492 # b) They won't cause rollback of the log publish/update above
1493 DeferredUpdates
::addUpdate(
1494 new AutoCommitUpdate(
1498 $reupload, $wikiPage, $newPageContent, $comment, $user,
1499 $logEntry, $logId, $descId, $tags
1501 # Update memcache after the commit
1502 $this->invalidateCache();
1504 $updateLogPage = false;
1505 if ( $newPageContent ) {
1506 # New file page; create the description page.
1507 # There's already a log entry, so don't make a second RC entry
1508 # CDN and file cache for the description page are purged by doEditContent.
1509 $status = $wikiPage->doEditContent(
1512 EDIT_NEW | EDIT_SUPPRESS_RC
,
1517 if ( isset( $status->value
['revision'] ) ) {
1518 /** @var $rev Revision */
1519 $rev = $status->value
['revision'];
1520 // Associate new page revision id
1521 $logEntry->setAssociatedRevId( $rev->getId() );
1523 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1524 // which is triggered on $descTitle by doEditContent() above.
1525 if ( isset( $status->value
['revision'] ) ) {
1526 /** @var $rev Revision */
1527 $rev = $status->value
['revision'];
1528 $updateLogPage = $rev->getPage();
1531 # Existing file page: invalidate description page cache
1532 $wikiPage->getTitle()->invalidateCache();
1533 $wikiPage->getTitle()->purgeSquid();
1534 # Allow the new file version to be patrolled from the page footer
1535 Article
::purgePatrolFooterCache( $descId );
1538 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1539 # but setAssociatedRevId() wasn't called at that point yet...
1540 $logParams = $logEntry->getParameters();
1541 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1542 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1543 if ( $updateLogPage ) {
1544 # Also log page, in case where we just created it above
1545 $update['log_page'] = $updateLogPage;
1547 $this->getRepo()->getMasterDB()->update(
1550 [ 'log_id' => $logId ],
1553 $this->getRepo()->getMasterDB()->insert(
1556 'ls_field' => 'associated_rev_id',
1557 'ls_value' => $logEntry->getAssociatedRevId(),
1558 'ls_log_id' => $logId,
1563 # Add change tags, if any
1565 $logEntry->setTags( $tags );
1568 # Uploads can be patrolled
1569 $logEntry->setIsPatrollable( true );
1571 # Now that the log entry is up-to-date, make an RC entry.
1572 $logEntry->publish( $logId );
1574 # Run hook for other updates (typically more cache purging)
1575 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1578 # Delete old thumbnails
1579 $this->purgeThumbnails();
1580 # Remove the old file from the CDN cache
1581 DeferredUpdates
::addUpdate(
1582 new CdnCacheUpdate( [ $this->getUrl() ] ),
1583 DeferredUpdates
::PRESEND
1586 # Update backlink pages pointing to this title if created
1587 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1590 $this->prerenderThumbnails();
1593 DeferredUpdates
::PRESEND
1597 # This is a new file, so update the image count
1598 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1601 # Invalidate cache for all pages using this file
1602 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1608 * Move or copy a file to its public location. If a file exists at the
1609 * destination, move it to an archive. Returns a Status object with
1610 * the archive name in the "value" member on success.
1612 * The archive name should be passed through to recordUpload for database
1615 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1616 * @param int $flags A bitwise combination of:
1617 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1618 * @param array $options Optional additional parameters
1619 * @return Status On success, the value member contains the
1620 * archive name, or an empty string if it was a new file.
1622 function publish( $src, $flags = 0, array $options = [] ) {
1623 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1627 * Move or copy a file to a specified location. Returns a Status
1628 * object with the archive name in the "value" member on success.
1630 * The archive name should be passed through to recordUpload for database
1633 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1634 * @param string $dstRel Target relative path
1635 * @param int $flags A bitwise combination of:
1636 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1637 * @param array $options Optional additional parameters
1638 * @return Status On success, the value member contains the
1639 * archive name, or an empty string if it was a new file.
1641 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1642 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1644 $repo = $this->getRepo();
1645 if ( $repo->getReadOnlyReason() !== false ) {
1646 return $this->readOnlyFatalStatus();
1649 $this->lock(); // begin
1651 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1652 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1654 if ( $repo->hasSha1Storage() ) {
1655 $sha1 = $repo->isVirtualUrl( $srcPath )
1656 ?
$repo->getFileSha1( $srcPath )
1657 : FSFile
::getSha1Base36FromPath( $srcPath );
1658 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1659 $wrapperBackend = $repo->getBackend();
1660 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1661 $status = $repo->quickImport( $src, $dst );
1662 if ( $flags & File
::DELETE_SOURCE
) {
1666 if ( $this->exists() ) {
1667 $status->value
= $archiveName;
1670 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1671 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1673 if ( $status->value
== 'new' ) {
1674 $status->value
= '';
1676 $status->value
= $archiveName;
1680 $this->unlock(); // done
1685 /** getLinksTo inherited */
1686 /** getExifData inherited */
1687 /** isLocal inherited */
1688 /** wasDeleted inherited */
1691 * Move file to the new title
1693 * Move current, old version and all thumbnails
1694 * to the new filename. Old file is deleted.
1696 * Cache purging is done; checks for validity
1697 * and logging are caller's responsibility
1699 * @param Title $target New file name
1702 function move( $target ) {
1703 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1704 return $this->readOnlyFatalStatus();
1707 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1708 $batch = new LocalFileMoveBatch( $this, $target );
1710 $this->lock(); // begin
1711 $batch->addCurrent();
1712 $archiveNames = $batch->addOlds();
1713 $status = $batch->execute();
1714 $this->unlock(); // done
1716 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1718 // Purge the source and target files...
1719 $oldTitleFile = wfLocalFile( $this->title
);
1720 $newTitleFile = wfLocalFile( $target );
1721 // To avoid slow purges in the transaction, move them outside...
1722 DeferredUpdates
::addUpdate(
1723 new AutoCommitUpdate(
1724 $this->getRepo()->getMasterDB(),
1726 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1727 $oldTitleFile->purgeEverything();
1728 foreach ( $archiveNames as $archiveName ) {
1729 $oldTitleFile->purgeOldThumbnails( $archiveName );
1731 $newTitleFile->purgeEverything();
1734 DeferredUpdates
::PRESEND
1737 if ( $status->isOK() ) {
1738 // Now switch the object
1739 $this->title
= $target;
1740 // Force regeneration of the name and hashpath
1741 unset( $this->name
);
1742 unset( $this->hashPath
);
1749 * Delete all versions of the file.
1751 * Moves the files into an archive directory (or deletes them)
1752 * and removes the database rows.
1754 * Cache purging is done; logging is caller's responsibility.
1756 * @param string $reason
1757 * @param bool $suppress
1758 * @param User|null $user
1761 function delete( $reason, $suppress = false, $user = null ) {
1762 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1763 return $this->readOnlyFatalStatus();
1766 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1768 $this->lock(); // begin
1769 $batch->addCurrent();
1770 // Get old version relative paths
1771 $archiveNames = $batch->addOlds();
1772 $status = $batch->execute();
1773 $this->unlock(); // done
1775 if ( $status->isOK() ) {
1776 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1779 // To avoid slow purges in the transaction, move them outside...
1780 DeferredUpdates
::addUpdate(
1781 new AutoCommitUpdate(
1782 $this->getRepo()->getMasterDB(),
1784 function () use ( $archiveNames ) {
1785 $this->purgeEverything();
1786 foreach ( $archiveNames as $archiveName ) {
1787 $this->purgeOldThumbnails( $archiveName );
1791 DeferredUpdates
::PRESEND
1796 foreach ( $archiveNames as $archiveName ) {
1797 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1799 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1805 * Delete an old version of the file.
1807 * Moves the file into an archive directory (or deletes it)
1808 * and removes the database row.
1810 * Cache purging is done; logging is caller's responsibility.
1812 * @param string $archiveName
1813 * @param string $reason
1814 * @param bool $suppress
1815 * @param User|null $user
1816 * @throws MWException Exception on database or file store failure
1819 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1820 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1821 return $this->readOnlyFatalStatus();
1824 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1826 $this->lock(); // begin
1827 $batch->addOld( $archiveName );
1828 $status = $batch->execute();
1829 $this->unlock(); // done
1831 $this->purgeOldThumbnails( $archiveName );
1832 if ( $status->isOK() ) {
1833 $this->purgeDescription();
1836 DeferredUpdates
::addUpdate(
1837 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1838 DeferredUpdates
::PRESEND
1845 * Restore all or specified deleted revisions to the given file.
1846 * Permissions and logging are left to the caller.
1848 * May throw database exceptions on error.
1850 * @param array $versions Set of record ids of deleted items to restore,
1851 * or empty to restore all revisions.
1852 * @param bool $unsuppress
1855 function restore( $versions = [], $unsuppress = false ) {
1856 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1857 return $this->readOnlyFatalStatus();
1860 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1862 $this->lock(); // begin
1866 $batch->addIds( $versions );
1868 $status = $batch->execute();
1869 if ( $status->isGood() ) {
1870 $cleanupStatus = $batch->cleanup();
1871 $cleanupStatus->successCount
= 0;
1872 $cleanupStatus->failCount
= 0;
1873 $status->merge( $cleanupStatus );
1875 $this->unlock(); // done
1880 /** isMultipage inherited */
1881 /** pageCount inherited */
1882 /** scaleHeight inherited */
1883 /** getImageSize inherited */
1886 * Get the URL of the file description page.
1889 function getDescriptionUrl() {
1890 return $this->title
->getLocalURL();
1894 * Get the HTML text of the description page
1895 * This is not used by ImagePage for local files, since (among other things)
1896 * it skips the parser cache.
1898 * @param Language $lang What language to get description in (Optional)
1899 * @return bool|mixed
1901 function getDescriptionText( $lang = null ) {
1902 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1906 $content = $revision->getContent();
1910 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1912 return $pout->getText();
1916 * @param int $audience
1920 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1922 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1924 } elseif ( $audience == self
::FOR_THIS_USER
1925 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1929 return $this->description
;
1934 * @return bool|string
1936 function getTimestamp() {
1939 return $this->timestamp
;
1943 * @return bool|string
1945 public function getDescriptionTouched() {
1946 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1947 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1948 // need to differentiate between null (uninitialized) and false (failed to load).
1949 if ( $this->descriptionTouched
=== null ) {
1951 'page_namespace' => $this->title
->getNamespace(),
1952 'page_title' => $this->title
->getDBkey()
1954 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1955 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1958 return $this->descriptionTouched
;
1964 function getSha1() {
1966 // Initialise now if necessary
1967 if ( $this->sha1
== '' && $this->fileExists
) {
1968 $this->lock(); // begin
1970 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1971 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1972 $dbw = $this->repo
->getMasterDB();
1973 $dbw->update( 'image',
1974 [ 'img_sha1' => $this->sha1
],
1975 [ 'img_name' => $this->getName() ],
1977 $this->invalidateCache();
1980 $this->unlock(); // done
1987 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1989 function isCacheable() {
1992 // If extra data (metadata) was not loaded then it must have been large
1993 return $this->extraDataLoaded
1994 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2001 public function acquireFileLock() {
2002 return $this->getRepo()->getBackend()->lockFiles(
2003 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2011 public function releaseFileLock() {
2012 return $this->getRepo()->getBackend()->unlockFiles(
2013 [ $this->getPath() ], LockManager
::LOCK_EX
2018 * Start an atomic DB section and lock the image for update
2019 * or increments a reference counter if the lock is already held
2021 * This method should not be used outside of LocalFile/LocalFile*Batch
2023 * @throws LocalFileLockError Throws an error if the lock was not acquired
2024 * @return bool Whether the file lock owns/spawned the DB transaction
2026 public function lock() {
2027 if ( !$this->locked
) {
2028 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2030 $dbw = $this->repo
->getMasterDB();
2031 $makesTransaction = !$dbw->trxLevel();
2032 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2033 // T56736: use simple lock to handle when the file does not exist.
2034 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2035 // Also, that would cause contention on INSERT of similarly named rows.
2036 $status = $this->acquireFileLock(); // represents all versions of the file
2037 if ( !$status->isGood() ) {
2038 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2039 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2041 throw new LocalFileLockError( $status );
2043 // Release the lock *after* commit to avoid row-level contention.
2044 // Make sure it triggers on rollback() as well as commit() (T132921).
2045 $dbw->onTransactionResolution(
2046 function () use ( $logger ) {
2047 $status = $this->releaseFileLock();
2048 if ( !$status->isGood() ) {
2049 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2054 // Callers might care if the SELECT snapshot is safely fresh
2055 $this->lockedOwnTrx
= $makesTransaction;
2060 return $this->lockedOwnTrx
;
2064 * Decrement the lock reference count and end the atomic section if it reaches zero
2066 * This method should not be used outside of LocalFile/LocalFile*Batch
2068 * The commit and loc release will happen when no atomic sections are active, which
2069 * may happen immediately or at some point after calling this
2071 public function unlock() {
2072 if ( $this->locked
) {
2074 if ( !$this->locked
) {
2075 $dbw = $this->repo
->getMasterDB();
2076 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2077 $this->lockedOwnTrx
= false;
2085 protected function readOnlyFatalStatus() {
2086 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2087 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2091 * Clean up any dangling locks
2093 function __destruct() {
2096 } // LocalFile class
2098 # ------------------------------------------------------------------------------
2101 * Helper class for file deletion
2102 * @ingroup FileAbstraction
2104 class LocalFileDeleteBatch
{
2105 /** @var LocalFile */
2112 private $srcRels = [];
2115 private $archiveUrls = [];
2117 /** @var array Items to be processed in the deletion batch */
2118 private $deletionBatch;
2120 /** @var bool Whether to suppress all suppressable fields when deleting */
2131 * @param string $reason
2132 * @param bool $suppress
2133 * @param User|null $user
2135 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2136 $this->file
= $file;
2137 $this->reason
= $reason;
2138 $this->suppress
= $suppress;
2140 $this->user
= $user;
2143 $this->user
= $wgUser;
2145 $this->status
= $file->repo
->newGood();
2148 public function addCurrent() {
2149 $this->srcRels
['.'] = $this->file
->getRel();
2153 * @param string $oldName
2155 public function addOld( $oldName ) {
2156 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2157 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2161 * Add the old versions of the image to the batch
2162 * @return array List of archive names from old versions
2164 public function addOlds() {
2167 $dbw = $this->file
->repo
->getMasterDB();
2168 $result = $dbw->select( 'oldimage',
2169 [ 'oi_archive_name' ],
2170 [ 'oi_name' => $this->file
->getName() ],
2174 foreach ( $result as $row ) {
2175 $this->addOld( $row->oi_archive_name
);
2176 $archiveNames[] = $row->oi_archive_name
;
2179 return $archiveNames;
2185 protected function getOldRels() {
2186 if ( !isset( $this->srcRels
['.'] ) ) {
2187 $oldRels =& $this->srcRels
;
2188 $deleteCurrent = false;
2190 $oldRels = $this->srcRels
;
2191 unset( $oldRels['.'] );
2192 $deleteCurrent = true;
2195 return [ $oldRels, $deleteCurrent ];
2201 protected function getHashes() {
2203 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2205 if ( $deleteCurrent ) {
2206 $hashes['.'] = $this->file
->getSha1();
2209 if ( count( $oldRels ) ) {
2210 $dbw = $this->file
->repo
->getMasterDB();
2211 $res = $dbw->select(
2213 [ 'oi_archive_name', 'oi_sha1' ],
2214 [ 'oi_archive_name' => array_keys( $oldRels ),
2215 'oi_name' => $this->file
->getName() ], // performance
2219 foreach ( $res as $row ) {
2220 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2221 // Get the hash from the file
2222 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2223 $props = $this->file
->repo
->getFileProps( $oldUrl );
2225 if ( $props['fileExists'] ) {
2226 // Upgrade the oldimage row
2227 $dbw->update( 'oldimage',
2228 [ 'oi_sha1' => $props['sha1'] ],
2229 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2231 $hashes[$row->oi_archive_name
] = $props['sha1'];
2233 $hashes[$row->oi_archive_name
] = false;
2236 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2241 $missing = array_diff_key( $this->srcRels
, $hashes );
2243 foreach ( $missing as $name => $rel ) {
2244 $this->status
->error( 'filedelete-old-unregistered', $name );
2247 foreach ( $hashes as $name => $hash ) {
2249 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2250 unset( $hashes[$name] );
2257 protected function doDBInserts() {
2259 $dbw = $this->file
->repo
->getMasterDB();
2260 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2261 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2262 $encReason = $dbw->addQuotes( $this->reason
);
2263 $encGroup = $dbw->addQuotes( 'deleted' );
2264 $ext = $this->file
->getExtension();
2265 $dotExt = $ext === '' ?
'' : ".$ext";
2266 $encExt = $dbw->addQuotes( $dotExt );
2267 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2269 // Bitfields to further suppress the content
2270 if ( $this->suppress
) {
2271 $bitfield = Revision
::SUPPRESSED_ALL
;
2273 $bitfield = 'oi_deleted';
2276 if ( $deleteCurrent ) {
2281 'fa_storage_group' => $encGroup,
2282 'fa_storage_key' => $dbw->conditional(
2283 [ 'img_sha1' => '' ],
2284 $dbw->addQuotes( '' ),
2285 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2287 'fa_deleted_user' => $encUserId,
2288 'fa_deleted_timestamp' => $encTimestamp,
2289 'fa_deleted_reason' => $encReason,
2290 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2291 'fa_name' => 'img_name',
2292 'fa_archive_name' => 'NULL',
2293 'fa_size' => 'img_size',
2294 'fa_width' => 'img_width',
2295 'fa_height' => 'img_height',
2296 'fa_metadata' => 'img_metadata',
2297 'fa_bits' => 'img_bits',
2298 'fa_media_type' => 'img_media_type',
2299 'fa_major_mime' => 'img_major_mime',
2300 'fa_minor_mime' => 'img_minor_mime',
2301 'fa_description' => 'img_description',
2302 'fa_user' => 'img_user',
2303 'fa_user_text' => 'img_user_text',
2304 'fa_timestamp' => 'img_timestamp',
2305 'fa_sha1' => 'img_sha1'
2307 [ 'img_name' => $this->file
->getName() ],
2312 if ( count( $oldRels ) ) {
2313 $res = $dbw->select(
2315 OldLocalFile
::selectFields(),
2317 'oi_name' => $this->file
->getName(),
2318 'oi_archive_name' => array_keys( $oldRels )
2324 foreach ( $res as $row ) {
2326 // Deletion-specific fields
2327 'fa_storage_group' => 'deleted',
2328 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2330 : "{$row->oi_sha1}{$dotExt}",
2331 'fa_deleted_user' => $this->user
->getId(),
2332 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2333 'fa_deleted_reason' => $this->reason
,
2334 // Counterpart fields
2335 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2336 'fa_name' => $row->oi_name
,
2337 'fa_archive_name' => $row->oi_archive_name
,
2338 'fa_size' => $row->oi_size
,
2339 'fa_width' => $row->oi_width
,
2340 'fa_height' => $row->oi_height
,
2341 'fa_metadata' => $row->oi_metadata
,
2342 'fa_bits' => $row->oi_bits
,
2343 'fa_media_type' => $row->oi_media_type
,
2344 'fa_major_mime' => $row->oi_major_mime
,
2345 'fa_minor_mime' => $row->oi_minor_mime
,
2346 'fa_description' => $row->oi_description
,
2347 'fa_user' => $row->oi_user
,
2348 'fa_user_text' => $row->oi_user_text
,
2349 'fa_timestamp' => $row->oi_timestamp
,
2350 'fa_sha1' => $row->oi_sha1
2354 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2358 function doDBDeletes() {
2359 $dbw = $this->file
->repo
->getMasterDB();
2360 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2362 if ( count( $oldRels ) ) {
2363 $dbw->delete( 'oldimage',
2365 'oi_name' => $this->file
->getName(),
2366 'oi_archive_name' => array_keys( $oldRels )
2370 if ( $deleteCurrent ) {
2371 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2376 * Run the transaction
2379 public function execute() {
2380 $repo = $this->file
->getRepo();
2381 $this->file
->lock();
2383 // Prepare deletion batch
2384 $hashes = $this->getHashes();
2385 $this->deletionBatch
= [];
2386 $ext = $this->file
->getExtension();
2387 $dotExt = $ext === '' ?
'' : ".$ext";
2389 foreach ( $this->srcRels
as $name => $srcRel ) {
2390 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2391 if ( isset( $hashes[$name] ) ) {
2392 $hash = $hashes[$name];
2393 $key = $hash . $dotExt;
2394 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2395 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2399 if ( !$repo->hasSha1Storage() ) {
2400 // Removes non-existent file from the batch, so we don't get errors.
2401 // This also handles files in the 'deleted' zone deleted via revision deletion.
2402 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2403 if ( !$checkStatus->isGood() ) {
2404 $this->status
->merge( $checkStatus );
2405 return $this->status
;
2407 $this->deletionBatch
= $checkStatus->value
;
2409 // Execute the file deletion batch
2410 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2411 if ( !$status->isGood() ) {
2412 $this->status
->merge( $status );
2416 if ( !$this->status
->isOK() ) {
2417 // Critical file deletion error; abort
2418 $this->file
->unlock();
2420 return $this->status
;
2423 // Copy the image/oldimage rows to filearchive
2424 $this->doDBInserts();
2425 // Delete image/oldimage rows
2426 $this->doDBDeletes();
2428 // Commit and return
2429 $this->file
->unlock();
2431 return $this->status
;
2435 * Removes non-existent files from a deletion batch.
2436 * @param array $batch
2439 protected function removeNonexistentFiles( $batch ) {
2440 $files = $newBatch = [];
2442 foreach ( $batch as $batchItem ) {
2443 list( $src, ) = $batchItem;
2444 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2447 $result = $this->file
->repo
->fileExistsBatch( $files );
2448 if ( in_array( null, $result, true ) ) {
2449 return Status
::newFatal( 'backend-fail-internal',
2450 $this->file
->repo
->getBackend()->getName() );
2453 foreach ( $batch as $batchItem ) {
2454 if ( $result[$batchItem[0]] ) {
2455 $newBatch[] = $batchItem;
2459 return Status
::newGood( $newBatch );
2463 # ------------------------------------------------------------------------------
2466 * Helper class for file undeletion
2467 * @ingroup FileAbstraction
2469 class LocalFileRestoreBatch
{
2470 /** @var LocalFile */
2473 /** @var array List of file IDs to restore */
2474 private $cleanupBatch;
2476 /** @var array List of file IDs to restore */
2479 /** @var bool Add all revisions of the file */
2482 /** @var bool Whether to remove all settings for suppressed fields */
2483 private $unsuppress = false;
2487 * @param bool $unsuppress
2489 function __construct( File
$file, $unsuppress = false ) {
2490 $this->file
= $file;
2491 $this->cleanupBatch
= $this->ids
= [];
2493 $this->unsuppress
= $unsuppress;
2500 public function addId( $fa_id ) {
2501 $this->ids
[] = $fa_id;
2505 * Add a whole lot of files by ID
2508 public function addIds( $ids ) {
2509 $this->ids
= array_merge( $this->ids
, $ids );
2513 * Add all revisions of the file
2515 public function addAll() {
2520 * Run the transaction, except the cleanup batch.
2521 * The cleanup batch should be run in a separate transaction, because it locks different
2522 * rows and there's no need to keep the image row locked while it's acquiring those locks
2523 * The caller may have its own transaction open.
2524 * So we save the batch and let the caller call cleanup()
2527 public function execute() {
2528 /** @var Language */
2531 $repo = $this->file
->getRepo();
2532 if ( !$this->all
&& !$this->ids
) {
2534 return $repo->newGood();
2537 $lockOwnsTrx = $this->file
->lock();
2539 $dbw = $this->file
->repo
->getMasterDB();
2540 $status = $this->file
->repo
->newGood();
2542 $exists = (bool)$dbw->selectField( 'image', '1',
2543 [ 'img_name' => $this->file
->getName() ],
2545 // The lock() should already prevents changes, but this still may need
2546 // to bypass any transaction snapshot. However, if lock() started the
2547 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2548 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2551 // Fetch all or selected archived revisions for the file,
2552 // sorted from the most recent to the oldest.
2553 $conditions = [ 'fa_name' => $this->file
->getName() ];
2555 if ( !$this->all
) {
2556 $conditions['fa_id'] = $this->ids
;
2559 $result = $dbw->select(
2561 ArchivedFile
::selectFields(),
2564 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2570 $insertCurrent = false;
2575 foreach ( $result as $row ) {
2576 $idsPresent[] = $row->fa_id
;
2578 if ( $row->fa_name
!= $this->file
->getName() ) {
2579 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2580 $status->failCount++
;
2584 if ( $row->fa_storage_key
== '' ) {
2585 // Revision was missing pre-deletion
2586 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2587 $status->failCount++
;
2591 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2592 $row->fa_storage_key
;
2593 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2595 if ( isset( $row->fa_sha1
) ) {
2596 $sha1 = $row->fa_sha1
;
2598 // old row, populate from key
2599 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2603 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2604 $sha1 = substr( $sha1, 1 );
2607 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2608 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2609 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2610 ||
is_null( $row->fa_metadata
)
2612 // Refresh our metadata
2613 // Required for a new current revision; nice for older ones too. :)
2614 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2617 'minor_mime' => $row->fa_minor_mime
,
2618 'major_mime' => $row->fa_major_mime
,
2619 'media_type' => $row->fa_media_type
,
2620 'metadata' => $row->fa_metadata
2624 if ( $first && !$exists ) {
2625 // This revision will be published as the new current version
2626 $destRel = $this->file
->getRel();
2628 'img_name' => $row->fa_name
,
2629 'img_size' => $row->fa_size
,
2630 'img_width' => $row->fa_width
,
2631 'img_height' => $row->fa_height
,
2632 'img_metadata' => $props['metadata'],
2633 'img_bits' => $row->fa_bits
,
2634 'img_media_type' => $props['media_type'],
2635 'img_major_mime' => $props['major_mime'],
2636 'img_minor_mime' => $props['minor_mime'],
2637 'img_description' => $row->fa_description
,
2638 'img_user' => $row->fa_user
,
2639 'img_user_text' => $row->fa_user_text
,
2640 'img_timestamp' => $row->fa_timestamp
,
2644 // The live (current) version cannot be hidden!
2645 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2646 $status->fatal( 'undeleterevdel' );
2647 $this->file
->unlock();
2651 $archiveName = $row->fa_archive_name
;
2653 if ( $archiveName == '' ) {
2654 // This was originally a current version; we
2655 // have to devise a new archive name for it.
2656 // Format is <timestamp of archiving>!<name>
2657 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2660 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2662 } while ( isset( $archiveNames[$archiveName] ) );
2665 $archiveNames[$archiveName] = true;
2666 $destRel = $this->file
->getArchiveRel( $archiveName );
2668 'oi_name' => $row->fa_name
,
2669 'oi_archive_name' => $archiveName,
2670 'oi_size' => $row->fa_size
,
2671 'oi_width' => $row->fa_width
,
2672 'oi_height' => $row->fa_height
,
2673 'oi_bits' => $row->fa_bits
,
2674 'oi_description' => $row->fa_description
,
2675 'oi_user' => $row->fa_user
,
2676 'oi_user_text' => $row->fa_user_text
,
2677 'oi_timestamp' => $row->fa_timestamp
,
2678 'oi_metadata' => $props['metadata'],
2679 'oi_media_type' => $props['media_type'],
2680 'oi_major_mime' => $props['major_mime'],
2681 'oi_minor_mime' => $props['minor_mime'],
2682 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2683 'oi_sha1' => $sha1 ];
2686 $deleteIds[] = $row->fa_id
;
2688 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2689 // private files can stay where they are
2690 $status->successCount++
;
2692 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2693 $this->cleanupBatch
[] = $row->fa_storage_key
;
2701 // Add a warning to the status object for missing IDs
2702 $missingIds = array_diff( $this->ids
, $idsPresent );
2704 foreach ( $missingIds as $id ) {
2705 $status->error( 'undelete-missing-filearchive', $id );
2708 if ( !$repo->hasSha1Storage() ) {
2709 // Remove missing files from batch, so we don't get errors when undeleting them
2710 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2711 if ( !$checkStatus->isGood() ) {
2712 $status->merge( $checkStatus );
2715 $storeBatch = $checkStatus->value
;
2717 // Run the store batch
2718 // Use the OVERWRITE_SAME flag to smooth over a common error
2719 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2720 $status->merge( $storeStatus );
2722 if ( !$status->isGood() ) {
2723 // Even if some files could be copied, fail entirely as that is the
2724 // easiest thing to do without data loss
2725 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2726 $status->setOK( false );
2727 $this->file
->unlock();
2733 // Run the DB updates
2734 // Because we have locked the image row, key conflicts should be rare.
2735 // If they do occur, we can roll back the transaction at this time with
2736 // no data loss, but leaving unregistered files scattered throughout the
2738 // This is not ideal, which is why it's important to lock the image row.
2739 if ( $insertCurrent ) {
2740 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2743 if ( $insertBatch ) {
2744 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2748 $dbw->delete( 'filearchive',
2749 [ 'fa_id' => $deleteIds ],
2753 // If store batch is empty (all files are missing), deletion is to be considered successful
2754 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2756 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2758 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2760 $this->file
->purgeEverything();
2762 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2763 $this->file
->purgeDescription();
2767 $this->file
->unlock();
2773 * Removes non-existent files from a store batch.
2774 * @param array $triplets
2777 protected function removeNonexistentFiles( $triplets ) {
2778 $files = $filteredTriplets = [];
2779 foreach ( $triplets as $file ) {
2780 $files[$file[0]] = $file[0];
2783 $result = $this->file
->repo
->fileExistsBatch( $files );
2784 if ( in_array( null, $result, true ) ) {
2785 return Status
::newFatal( 'backend-fail-internal',
2786 $this->file
->repo
->getBackend()->getName() );
2789 foreach ( $triplets as $file ) {
2790 if ( $result[$file[0]] ) {
2791 $filteredTriplets[] = $file;
2795 return Status
::newGood( $filteredTriplets );
2799 * Removes non-existent files from a cleanup batch.
2800 * @param array $batch
2803 protected function removeNonexistentFromCleanup( $batch ) {
2804 $files = $newBatch = [];
2805 $repo = $this->file
->repo
;
2807 foreach ( $batch as $file ) {
2808 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2809 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2812 $result = $repo->fileExistsBatch( $files );
2814 foreach ( $batch as $file ) {
2815 if ( $result[$file] ) {
2816 $newBatch[] = $file;
2824 * Delete unused files in the deleted zone.
2825 * This should be called from outside the transaction in which execute() was called.
2828 public function cleanup() {
2829 if ( !$this->cleanupBatch
) {
2830 return $this->file
->repo
->newGood();
2833 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2835 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2841 * Cleanup a failed batch. The batch was only partially successful, so
2842 * rollback by removing all items that were succesfully copied.
2844 * @param Status $storeStatus
2845 * @param array $storeBatch
2847 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2850 foreach ( $storeStatus->success
as $i => $success ) {
2851 // Check if this item of the batch was successfully copied
2853 // Item was successfully copied and needs to be removed again
2854 // Extract ($dstZone, $dstRel) from the batch
2855 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2858 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2862 # ------------------------------------------------------------------------------
2865 * Helper class for file movement
2866 * @ingroup FileAbstraction
2868 class LocalFileMoveBatch
{
2869 /** @var LocalFile */
2879 protected $oldCount;
2883 /** @var IDatabase */
2888 * @param Title $target
2890 function __construct( File
$file, Title
$target ) {
2891 $this->file
= $file;
2892 $this->target
= $target;
2893 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2894 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2895 $this->oldName
= $this->file
->getName();
2896 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2897 $this->oldRel
= $this->oldHash
. $this->oldName
;
2898 $this->newRel
= $this->newHash
. $this->newName
;
2899 $this->db
= $file->getRepo()->getMasterDB();
2903 * Add the current image to the batch
2905 public function addCurrent() {
2906 $this->cur
= [ $this->oldRel
, $this->newRel
];
2910 * Add the old versions of the image to the batch
2911 * @return array List of archive names from old versions
2913 public function addOlds() {
2914 $archiveBase = 'archive';
2916 $this->oldCount
= 0;
2919 $result = $this->db
->select( 'oldimage',
2920 [ 'oi_archive_name', 'oi_deleted' ],
2921 [ 'oi_name' => $this->oldName
],
2923 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2926 foreach ( $result as $row ) {
2927 $archiveNames[] = $row->oi_archive_name
;
2928 $oldName = $row->oi_archive_name
;
2929 $bits = explode( '!', $oldName, 2 );
2931 if ( count( $bits ) != 2 ) {
2932 wfDebug( "Old file name missing !: '$oldName' \n" );
2936 list( $timestamp, $filename ) = $bits;
2938 if ( $this->oldName
!= $filename ) {
2939 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2945 // Do we want to add those to oldCount?
2946 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2951 "{$archiveBase}/{$this->oldHash}{$oldName}",
2952 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2956 return $archiveNames;
2963 public function execute() {
2964 $repo = $this->file
->repo
;
2965 $status = $repo->newGood();
2966 $destFile = wfLocalFile( $this->target
);
2968 $this->file
->lock(); // begin
2969 $destFile->lock(); // quickly fail if destination is not available
2971 $triplets = $this->getMoveTriplets();
2972 $checkStatus = $this->removeNonexistentFiles( $triplets );
2973 if ( !$checkStatus->isGood() ) {
2974 $destFile->unlock();
2975 $this->file
->unlock();
2976 $status->merge( $checkStatus ); // couldn't talk to file backend
2979 $triplets = $checkStatus->value
;
2981 // Verify the file versions metadata in the DB.
2982 $statusDb = $this->verifyDBUpdates();
2983 if ( !$statusDb->isGood() ) {
2984 $destFile->unlock();
2985 $this->file
->unlock();
2986 $statusDb->setOK( false );
2991 if ( !$repo->hasSha1Storage() ) {
2992 // Copy the files into their new location.
2993 // If a prior process fataled copying or cleaning up files we tolerate any
2994 // of the existing files if they are identical to the ones being stored.
2995 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2996 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2997 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2998 if ( !$statusMove->isGood() ) {
2999 // Delete any files copied over (while the destination is still locked)
3000 $this->cleanupTarget( $triplets );
3001 $destFile->unlock();
3002 $this->file
->unlock();
3003 wfDebugLog( 'imagemove', "Error in moving files: "
3004 . $statusMove->getWikiText( false, false, 'en' ) );
3005 $statusMove->setOK( false );
3009 $status->merge( $statusMove );
3012 // Rename the file versions metadata in the DB.
3013 $this->doDBUpdates();
3015 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3016 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3018 $destFile->unlock();
3019 $this->file
->unlock(); // done
3021 // Everything went ok, remove the source files
3022 $this->cleanupSource( $triplets );
3024 $status->merge( $statusDb );
3030 * Verify the database updates and return a new Status indicating how
3031 * many rows would be updated.
3035 protected function verifyDBUpdates() {
3036 $repo = $this->file
->repo
;
3037 $status = $repo->newGood();
3040 $hasCurrent = $dbw->selectField(
3043 [ 'img_name' => $this->oldName
],
3047 $oldRowCount = $dbw->selectField(
3050 [ 'oi_name' => $this->oldName
],
3055 if ( $hasCurrent ) {
3056 $status->successCount++
;
3058 $status->failCount++
;
3060 $status->successCount +
= $oldRowCount;
3061 // T36934: oldCount is based on files that actually exist.
3062 // There may be more DB rows than such files, in which case $affected
3063 // can be greater than $total. We use max() to avoid negatives here.
3064 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3065 if ( $status->failCount
) {
3066 $status->error( 'imageinvalidfilename' );
3073 * Do the database updates and return a new Status indicating how
3074 * many rows where updated.
3076 protected function doDBUpdates() {
3079 // Update current image
3082 [ 'img_name' => $this->newName
],
3083 [ 'img_name' => $this->oldName
],
3086 // Update old images
3090 'oi_name' => $this->newName
,
3091 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3092 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3094 [ 'oi_name' => $this->oldName
],
3100 * Generate triplets for FileRepo::storeBatch().
3103 protected function getMoveTriplets() {
3104 $moves = array_merge( [ $this->cur
], $this->olds
);
3105 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3107 foreach ( $moves as $move ) {
3108 // $move: (oldRelativePath, newRelativePath)
3109 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3110 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3113 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3121 * Removes non-existent files from move batch.
3122 * @param array $triplets
3125 protected function removeNonexistentFiles( $triplets ) {
3128 foreach ( $triplets as $file ) {
3129 $files[$file[0]] = $file[0];
3132 $result = $this->file
->repo
->fileExistsBatch( $files );
3133 if ( in_array( null, $result, true ) ) {
3134 return Status
::newFatal( 'backend-fail-internal',
3135 $this->file
->repo
->getBackend()->getName() );
3138 $filteredTriplets = [];
3139 foreach ( $triplets as $file ) {
3140 if ( $result[$file[0]] ) {
3141 $filteredTriplets[] = $file;
3143 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3147 return Status
::newGood( $filteredTriplets );
3151 * Cleanup a partially moved array of triplets by deleting the target
3152 * files. Called if something went wrong half way.
3153 * @param array $triplets
3155 protected function cleanupTarget( $triplets ) {
3156 // Create dest pairs from the triplets
3158 foreach ( $triplets as $triplet ) {
3159 // $triplet: (old source virtual URL, dst zone, dest rel)
3160 $pairs[] = [ $triplet[1], $triplet[2] ];
3163 $this->file
->repo
->cleanupBatch( $pairs );
3167 * Cleanup a fully moved array of triplets by deleting the source files.
3168 * Called at the end of the move process if everything else went ok.
3169 * @param array $triplets
3171 protected function cleanupSource( $triplets ) {
3172 // Create source file names from the triplets
3174 foreach ( $triplets as $triplet ) {
3175 $files[] = $triplet[0];
3178 $this->file
->repo
->cleanupBatch( $files );
3182 class LocalFileLockError
extends ErrorPageError
{
3183 public function __construct( Status
$status ) {
3184 parent
::__construct(
3186 $status->getMessage()
3190 public function report() {
3192 $wgOut->setStatusCode( 429 );