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() {
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',
350 'user_text', 'description' ];
351 static $results = [];
353 if ( $prefix == '' ) {
357 if ( !isset( $results[$prefix] ) ) {
358 $prefixedFields = [];
359 foreach ( $fields as $field ) {
360 $prefixedFields[] = $prefix . $field;
362 $results[$prefix] = $prefixedFields;
365 return $results[$prefix];
369 * @param string $prefix
372 function getLazyCacheFields( $prefix = 'img_' ) {
373 static $fields = [ 'metadata' ];
374 static $results = [];
376 if ( $prefix == '' ) {
380 if ( !isset( $results[$prefix] ) ) {
381 $prefixedFields = [];
382 foreach ( $fields as $field ) {
383 $prefixedFields[] = $prefix . $field;
385 $results[$prefix] = $prefixedFields;
388 return $results[$prefix];
392 * Load file metadata from the DB
395 function loadFromDB( $flags = 0 ) {
396 $fname = static::class . '::' . __FUNCTION__
;
398 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
399 $this->dataLoaded
= true;
400 $this->extraDataLoaded
= true;
402 $dbr = ( $flags & self
::READ_LATEST
)
403 ?
$this->repo
->getMasterDB()
404 : $this->repo
->getReplicaDB();
406 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
407 [ 'img_name' => $this->getName() ], $fname );
410 $this->loadFromRow( $row );
412 $this->fileExists
= false;
417 * Load lazy file metadata from the DB.
418 * This covers fields that are sometimes not cached.
420 protected function loadExtraFromDB() {
421 $fname = static::class . '::' . __FUNCTION__
;
423 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
424 $this->extraDataLoaded
= true;
426 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
428 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
432 foreach ( $fieldMap as $name => $value ) {
433 $this->$name = $value;
436 throw new MWException( "Could not find data for image '{$this->getName()}'." );
441 * @param IDatabase $dbr
442 * @param string $fname
445 private function loadFieldsWithTimestamp( $dbr, $fname ) {
448 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
449 'img_name' => $this->getName(),
450 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
453 $fieldMap = $this->unprefixRow( $row, 'img_' );
455 # File may have been uploaded over in the meantime; check the old versions
456 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
457 'oi_name' => $this->getName(),
458 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
461 $fieldMap = $this->unprefixRow( $row, 'oi_' );
469 * @param array|object $row
470 * @param string $prefix
471 * @throws MWException
474 protected function unprefixRow( $row, $prefix = 'img_' ) {
475 $array = (array)$row;
476 $prefixLength = strlen( $prefix );
478 // Sanity check prefix once
479 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
480 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
484 foreach ( $array as $name => $value ) {
485 $decoded[substr( $name, $prefixLength )] = $value;
492 * Decode a row from the database (either object or array) to an array
493 * with timestamps and MIME types decoded, and the field prefix removed.
495 * @param string $prefix
496 * @throws MWException
499 function decodeRow( $row, $prefix = 'img_' ) {
500 $decoded = $this->unprefixRow( $row, $prefix );
502 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
504 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
506 if ( empty( $decoded['major_mime'] ) ) {
507 $decoded['mime'] = 'unknown/unknown';
509 if ( !$decoded['minor_mime'] ) {
510 $decoded['minor_mime'] = 'unknown';
512 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
515 // Trim zero padding from char/binary field
516 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
518 // Normalize some fields to integer type, per their database definition.
519 // Use unary + so that overflows will be upgraded to double instead of
520 // being trucated as with intval(). This is important to allow >2GB
521 // files on 32-bit systems.
522 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
523 $decoded[$field] = +
$decoded[$field];
530 * Load file metadata from a DB result row
533 * @param string $prefix
535 function loadFromRow( $row, $prefix = 'img_' ) {
536 $this->dataLoaded
= true;
537 $this->extraDataLoaded
= true;
539 $array = $this->decodeRow( $row, $prefix );
541 foreach ( $array as $name => $value ) {
542 $this->$name = $value;
545 $this->fileExists
= true;
546 $this->maybeUpgradeRow();
550 * Load file metadata from cache or DB, unless already loaded
553 function load( $flags = 0 ) {
554 if ( !$this->dataLoaded
) {
555 if ( $flags & self
::READ_LATEST
) {
556 $this->loadFromDB( $flags );
558 $this->loadFromCache();
562 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
563 // @note: loads on name/timestamp to reduce race condition problems
564 $this->loadExtraFromDB();
569 * Upgrade a row if it needs it
571 function maybeUpgradeRow() {
572 global $wgUpdateCompatibleMetadata;
574 if ( wfReadOnly() ||
$this->upgrading
) {
579 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
582 $handler = $this->getHandler();
584 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
585 if ( $validity === MediaHandler
::METADATA_BAD
) {
587 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
588 $upgrade = $wgUpdateCompatibleMetadata;
594 $this->upgrading
= true;
595 // Defer updates unless in auto-commit CLI mode
596 DeferredUpdates
::addCallableUpdate( function() {
597 $this->upgrading
= false; // avoid duplicate updates
600 } catch ( LocalFileLockError
$e ) {
601 // let the other process handle it (or do it next time)
608 * @return bool Whether upgradeRow() ran for this object
610 function getUpgraded() {
611 return $this->upgraded
;
615 * Fix assorted version-related problems with the image row by reloading it from the file
617 function upgradeRow() {
618 $this->lock(); // begin
620 $this->loadFromFile();
622 # Don't destroy file info of missing files
623 if ( !$this->fileExists
) {
625 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
630 $dbw = $this->repo
->getMasterDB();
631 list( $major, $minor ) = self
::splitMime( $this->mime
);
633 if ( wfReadOnly() ) {
638 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
640 $dbw->update( 'image',
642 'img_size' => $this->size
, // sanity
643 'img_width' => $this->width
,
644 'img_height' => $this->height
,
645 'img_bits' => $this->bits
,
646 'img_media_type' => $this->media_type
,
647 'img_major_mime' => $major,
648 'img_minor_mime' => $minor,
649 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
650 'img_sha1' => $this->sha1
,
652 [ 'img_name' => $this->getName() ],
656 $this->invalidateCache();
658 $this->unlock(); // done
659 $this->upgraded
= true; // avoid rework/retries
663 * Set properties in this object to be equal to those given in the
664 * associative array $info. Only cacheable fields can be set.
665 * All fields *must* be set in $info except for getLazyCacheFields().
667 * If 'mime' is given, it will be split into major_mime/minor_mime.
668 * If major_mime/minor_mime are given, $this->mime will also be set.
672 function setProps( $info ) {
673 $this->dataLoaded
= true;
674 $fields = $this->getCacheFields( '' );
675 $fields[] = 'fileExists';
677 foreach ( $fields as $field ) {
678 if ( isset( $info[$field] ) ) {
679 $this->$field = $info[$field];
683 // Fix up mime fields
684 if ( isset( $info['major_mime'] ) ) {
685 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
686 } elseif ( isset( $info['mime'] ) ) {
687 $this->mime
= $info['mime'];
688 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
692 /** splitMime inherited */
693 /** getName inherited */
694 /** getTitle inherited */
695 /** getURL inherited */
696 /** getViewURL inherited */
697 /** getPath inherited */
698 /** isVisible inherited */
703 function isMissing() {
704 if ( $this->missing
=== null ) {
705 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
706 $this->missing
= !$fileExists;
709 return $this->missing
;
713 * Return the width of the image
718 public function getWidth( $page = 1 ) {
721 if ( $this->isMultipage() ) {
722 $handler = $this->getHandler();
726 $dim = $handler->getPageDimensions( $this, $page );
728 return $dim['width'];
730 // For non-paged media, the false goes through an
731 // intval, turning failure into 0, so do same here.
740 * Return the height of the image
745 public function getHeight( $page = 1 ) {
748 if ( $this->isMultipage() ) {
749 $handler = $this->getHandler();
753 $dim = $handler->getPageDimensions( $this, $page );
755 return $dim['height'];
757 // For non-paged media, the false goes through an
758 // intval, turning failure into 0, so do same here.
762 return $this->height
;
767 * Returns ID or name of user who uploaded the file
769 * @param string $type 'text' or 'id'
772 function getUser( $type = 'text' ) {
775 if ( $type == 'text' ) {
776 return $this->user_text
;
778 return (int)$this->user
;
783 * Get short description URL for a file based on the page ID.
785 * @return string|null
786 * @throws MWException
789 public function getDescriptionShortUrl() {
790 $pageId = $this->title
->getArticleID();
792 if ( $pageId !== null ) {
793 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
794 if ( $url !== false ) {
802 * Get handler-specific metadata
805 function getMetadata() {
806 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
807 return $this->metadata
;
813 function getBitDepth() {
816 return (int)$this->bits
;
820 * Returns the size of the image file, in bytes
823 public function getSize() {
830 * Returns the MIME type of the file.
833 function getMimeType() {
840 * Returns the type of the media in the file.
841 * Use the value returned by this function with the MEDIATYPE_xxx constants.
844 function getMediaType() {
847 return $this->media_type
;
850 /** canRender inherited */
851 /** mustRender inherited */
852 /** allowInlineDisplay inherited */
853 /** isSafeFile inherited */
854 /** isTrustedFile inherited */
857 * Returns true if the file exists on disk.
858 * @return bool Whether file exist on disk.
860 public function exists() {
863 return $this->fileExists
;
866 /** getTransformScript inherited */
867 /** getUnscaledThumb inherited */
868 /** thumbName inherited */
869 /** createThumb inherited */
870 /** transform inherited */
872 /** getHandler inherited */
873 /** iconThumb inherited */
874 /** getLastError inherited */
877 * Get all thumbnail names previously generated for this file
878 * @param string|bool $archiveName Name of an archive file, default false
879 * @return array First element is the base dir, then files in that base dir.
881 function getThumbnails( $archiveName = false ) {
882 if ( $archiveName ) {
883 $dir = $this->getArchiveThumbPath( $archiveName );
885 $dir = $this->getThumbPath();
888 $backend = $this->repo
->getBackend();
891 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
892 foreach ( $iterator as $file ) {
895 } catch ( FileBackendError
$e ) {
896 } // suppress (T56674)
902 * Refresh metadata in memcached, but don't touch thumbnails or CDN
904 function purgeMetadataCache() {
905 $this->invalidateCache();
909 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
911 * @param array $options An array potentially with the key forThumbRefresh.
913 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
915 function purgeCache( $options = [] ) {
916 // Refresh metadata cache
917 $this->purgeMetadataCache();
920 $this->purgeThumbnails( $options );
922 // Purge CDN cache for this file
923 DeferredUpdates
::addUpdate(
924 new CdnCacheUpdate( [ $this->getUrl() ] ),
925 DeferredUpdates
::PRESEND
930 * Delete cached transformed files for an archived version only.
931 * @param string $archiveName Name of the archived file
933 function purgeOldThumbnails( $archiveName ) {
934 // Get a list of old thumbnails and URLs
935 $files = $this->getThumbnails( $archiveName );
937 // Purge any custom thumbnail caches
938 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
941 $dir = array_shift( $files );
942 $this->purgeThumbList( $dir, $files );
946 foreach ( $files as $file ) {
947 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
949 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
953 * Delete cached transformed files for the current version only.
954 * @param array $options
956 public function purgeThumbnails( $options = [] ) {
957 $files = $this->getThumbnails();
958 // Always purge all files from CDN regardless of handler filters
960 foreach ( $files as $file ) {
961 $urls[] = $this->getThumbUrl( $file );
963 array_shift( $urls ); // don't purge directory
965 // Give media handler a chance to filter the file purge list
966 if ( !empty( $options['forThumbRefresh'] ) ) {
967 $handler = $this->getHandler();
969 $handler->filterThumbnailPurgeList( $files, $options );
973 // Purge any custom thumbnail caches
974 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
977 $dir = array_shift( $files );
978 $this->purgeThumbList( $dir, $files );
981 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
985 * Prerenders a configurable set of thumbnails
989 public function prerenderThumbnails() {
990 global $wgUploadThumbnailRenderMap;
994 $sizes = $wgUploadThumbnailRenderMap;
997 foreach ( $sizes as $size ) {
998 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
999 $jobs[] = new ThumbnailRenderJob(
1001 [ 'transformParams' => [ 'width' => $size ] ]
1007 JobQueueGroup
::singleton()->lazyPush( $jobs );
1012 * Delete a list of thumbnails visible at urls
1013 * @param string $dir Base dir of the files.
1014 * @param array $files Array of strings: relative filenames (to $dir)
1016 protected function purgeThumbList( $dir, $files ) {
1017 $fileListDebug = strtr(
1018 var_export( $files, true ),
1021 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1024 foreach ( $files as $file ) {
1025 # Check that the base file name is part of the thumb name
1026 # This is a basic sanity check to avoid erasing unrelated directories
1027 if ( strpos( $file, $this->getName() ) !== false
1028 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1030 $purgeList[] = "{$dir}/{$file}";
1034 # Delete the thumbnails
1035 $this->repo
->quickPurgeBatch( $purgeList );
1036 # Clear out the thumbnail directory if empty
1037 $this->repo
->quickCleanDir( $dir );
1040 /** purgeDescription inherited */
1041 /** purgeEverything inherited */
1044 * @param int $limit Optional: Limit to number of results
1045 * @param int $start Optional: Timestamp, start from
1046 * @param int $end Optional: Timestamp, end at
1048 * @return OldLocalFile[]
1050 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1051 $dbr = $this->repo
->getReplicaDB();
1052 $tables = [ 'oldimage' ];
1053 $fields = OldLocalFile
::selectFields();
1054 $conds = $opts = $join_conds = [];
1055 $eq = $inc ?
'=' : '';
1056 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1059 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1063 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1067 $opts['LIMIT'] = $limit;
1070 // Search backwards for time > x queries
1071 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1072 $opts['ORDER BY'] = "oi_timestamp $order";
1073 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1075 // Avoid PHP 7.1 warning from passing $this by reference
1077 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1078 &$conds, &$opts, &$join_conds ] );
1080 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1083 foreach ( $res as $row ) {
1084 $r[] = $this->repo
->newFileFromRow( $row );
1087 if ( $order == 'ASC' ) {
1088 $r = array_reverse( $r ); // make sure it ends up descending
1095 * Returns the history of this file, line by line.
1096 * starts with current version, then old versions.
1097 * uses $this->historyLine to check which line to return:
1098 * 0 return line for current version
1099 * 1 query for old versions, return first one
1100 * 2, ... return next old version from above query
1103 public function nextHistoryLine() {
1104 # Polymorphic function name to distinguish foreign and local fetches
1105 $fname = static::class . '::' . __FUNCTION__
;
1107 $dbr = $this->repo
->getReplicaDB();
1109 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1110 $this->historyRes
= $dbr->select( 'image',
1113 "'' AS oi_archive_name",
1117 [ 'img_name' => $this->title
->getDBkey() ],
1121 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1122 $this->historyRes
= null;
1126 } elseif ( $this->historyLine
== 1 ) {
1127 $this->historyRes
= $dbr->select( 'oldimage', '*',
1128 [ 'oi_name' => $this->title
->getDBkey() ],
1130 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1133 $this->historyLine++
;
1135 return $dbr->fetchObject( $this->historyRes
);
1139 * Reset the history pointer to the first element of the history
1141 public function resetHistory() {
1142 $this->historyLine
= 0;
1144 if ( !is_null( $this->historyRes
) ) {
1145 $this->historyRes
= null;
1149 /** getHashPath inherited */
1150 /** getRel inherited */
1151 /** getUrlRel inherited */
1152 /** getArchiveRel inherited */
1153 /** getArchivePath inherited */
1154 /** getThumbPath inherited */
1155 /** getArchiveUrl inherited */
1156 /** getThumbUrl inherited */
1157 /** getArchiveVirtualUrl inherited */
1158 /** getThumbVirtualUrl inherited */
1159 /** isHashed inherited */
1162 * Upload a file and record it in the DB
1163 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1164 * @param string $comment Upload description
1165 * @param string $pageText Text to use for the new description page,
1166 * if a new description page is created
1167 * @param int|bool $flags Flags for publish()
1168 * @param array|bool $props File properties, if known. This can be used to
1169 * reduce the upload time when uploading virtual URLs for which the file
1170 * info is already known
1171 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1173 * @param User|null $user User object or null to use $wgUser
1174 * @param string[] $tags Change tags to add to the log entry and page revision.
1175 * (This doesn't check $user's permissions.)
1176 * @return Status On success, the value member contains the
1177 * archive name, or an empty string if it was a new file.
1179 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1180 $timestamp = false, $user = null, $tags = []
1184 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1185 return $this->readOnlyFatalStatus();
1188 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1190 if ( $this->repo
->isVirtualUrl( $srcPath )
1191 || FileBackend
::isStoragePath( $srcPath )
1193 $props = $this->repo
->getFileProps( $srcPath );
1195 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1196 $props = $mwProps->getPropsFromPath( $srcPath, true );
1201 $handler = MediaHandler
::getHandler( $props['mime'] );
1203 $metadata = MediaWiki\
quietCall( 'unserialize', $props['metadata'] );
1205 if ( !is_array( $metadata ) ) {
1209 $options['headers'] = $handler->getContentHeaders( $metadata );
1211 $options['headers'] = [];
1214 // Trim spaces on user supplied text
1215 $comment = trim( $comment );
1217 // Truncate nicely or the DB will do it for us
1218 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1219 $comment = $wgContLang->truncate( $comment, 255 );
1220 $this->lock(); // begin
1221 $status = $this->publish( $src, $flags, $options );
1223 if ( $status->successCount
>= 2 ) {
1224 // There will be a copy+(one of move,copy,store).
1225 // The first succeeding does not commit us to updating the DB
1226 // since it simply copied the current version to a timestamped file name.
1227 // It is only *preferable* to avoid leaving such files orphaned.
1228 // Once the second operation goes through, then the current version was
1229 // updated and we must therefore update the DB too.
1230 $oldver = $status->value
;
1231 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1232 $status->fatal( 'filenotfound', $srcPath );
1236 $this->unlock(); // done
1242 * Record a file upload in the upload log and the image table
1243 * @param string $oldver
1244 * @param string $desc
1245 * @param string $license
1246 * @param string $copyStatus
1247 * @param string $source
1248 * @param bool $watch
1249 * @param string|bool $timestamp
1250 * @param User|null $user User object or null to use $wgUser
1253 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1254 $watch = false, $timestamp = false, User
$user = null ) {
1260 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1262 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1267 $user->addWatch( $this->getTitle() );
1274 * Record a file upload in the upload log and the image table
1275 * @param string $oldver
1276 * @param string $comment
1277 * @param string $pageText
1278 * @param bool|array $props
1279 * @param string|bool $timestamp
1280 * @param null|User $user
1281 * @param string[] $tags
1284 function recordUpload2(
1285 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1287 if ( is_null( $user ) ) {
1292 $dbw = $this->repo
->getMasterDB();
1294 # Imports or such might force a certain timestamp; otherwise we generate
1295 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1296 if ( $timestamp === false ) {
1297 $timestamp = $dbw->timestamp();
1298 $allowTimeKludge = true;
1300 $allowTimeKludge = false;
1303 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1304 $props['description'] = $comment;
1305 $props['user'] = $user->getId();
1306 $props['user_text'] = $user->getName();
1307 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1308 $this->setProps( $props );
1310 # Fail now if the file isn't there
1311 if ( !$this->fileExists
) {
1312 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1317 $dbw->startAtomic( __METHOD__
);
1319 # Test to see if the row exists using INSERT IGNORE
1320 # This avoids race conditions by locking the row until the commit, and also
1321 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1322 $dbw->insert( 'image',
1324 'img_name' => $this->getName(),
1325 'img_size' => $this->size
,
1326 'img_width' => intval( $this->width
),
1327 'img_height' => intval( $this->height
),
1328 'img_bits' => $this->bits
,
1329 'img_media_type' => $this->media_type
,
1330 'img_major_mime' => $this->major_mime
,
1331 'img_minor_mime' => $this->minor_mime
,
1332 'img_timestamp' => $timestamp,
1333 'img_description' => $comment,
1334 'img_user' => $user->getId(),
1335 'img_user_text' => $user->getName(),
1336 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1337 'img_sha1' => $this->sha1
1343 $reupload = ( $dbw->affectedRows() == 0 );
1345 if ( $allowTimeKludge ) {
1346 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1347 $ltimestamp = $dbw->selectField(
1350 [ 'img_name' => $this->getName() ],
1352 [ 'LOCK IN SHARE MODE' ]
1354 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1355 # Avoid a timestamp that is not newer than the last version
1356 # TODO: the image/oldimage tables should be like page/revision with an ID field
1357 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1358 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1359 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1360 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1364 # (T36993) Note: $oldver can be empty here, if the previous
1365 # version of the file was broken. Allow registration of the new
1366 # version to continue anyway, because that's better than having
1367 # an image that's not fixable by user operations.
1368 # Collision, this is an update of a file
1369 # Insert previous contents into oldimage
1370 $dbw->insertSelect( 'oldimage', 'image',
1372 'oi_name' => 'img_name',
1373 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1374 'oi_size' => 'img_size',
1375 'oi_width' => 'img_width',
1376 'oi_height' => 'img_height',
1377 'oi_bits' => 'img_bits',
1378 'oi_timestamp' => 'img_timestamp',
1379 'oi_description' => 'img_description',
1380 'oi_user' => 'img_user',
1381 'oi_user_text' => 'img_user_text',
1382 'oi_metadata' => 'img_metadata',
1383 'oi_media_type' => 'img_media_type',
1384 'oi_major_mime' => 'img_major_mime',
1385 'oi_minor_mime' => 'img_minor_mime',
1386 'oi_sha1' => 'img_sha1'
1388 [ 'img_name' => $this->getName() ],
1392 # Update the current image row
1393 $dbw->update( 'image',
1395 'img_size' => $this->size
,
1396 'img_width' => intval( $this->width
),
1397 'img_height' => intval( $this->height
),
1398 'img_bits' => $this->bits
,
1399 'img_media_type' => $this->media_type
,
1400 'img_major_mime' => $this->major_mime
,
1401 'img_minor_mime' => $this->minor_mime
,
1402 'img_timestamp' => $timestamp,
1403 'img_description' => $comment,
1404 'img_user' => $user->getId(),
1405 'img_user_text' => $user->getName(),
1406 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1407 'img_sha1' => $this->sha1
1409 [ 'img_name' => $this->getName() ],
1414 $descTitle = $this->getTitle();
1415 $descId = $descTitle->getArticleID();
1416 $wikiPage = new WikiFilePage( $descTitle );
1417 $wikiPage->setFile( $this );
1419 // Add the log entry...
1420 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1421 $logEntry->setTimestamp( $this->timestamp
);
1422 $logEntry->setPerformer( $user );
1423 $logEntry->setComment( $comment );
1424 $logEntry->setTarget( $descTitle );
1425 // Allow people using the api to associate log entries with the upload.
1426 // Log has a timestamp, but sometimes different from upload timestamp.
1427 $logEntry->setParameters(
1429 'img_sha1' => $this->sha1
,
1430 'img_timestamp' => $timestamp,
1433 // Note we keep $logId around since during new image
1434 // creation, page doesn't exist yet, so log_page = 0
1435 // but we want it to point to the page we're making,
1436 // so we later modify the log entry.
1437 // For a similar reason, we avoid making an RC entry
1438 // now and wait until the page exists.
1439 $logId = $logEntry->insert();
1441 if ( $descTitle->exists() ) {
1442 // Use own context to get the action text in content language
1443 $formatter = LogFormatter
::newFromEntry( $logEntry );
1444 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1445 $editSummary = $formatter->getPlainActionText();
1447 $nullRevision = Revision
::newNullRevision(
1454 if ( $nullRevision ) {
1455 $nullRevision->insertOn( $dbw );
1457 'NewRevisionFromEditComplete',
1458 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1460 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1461 // Associate null revision id
1462 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1465 $newPageContent = null;
1467 // Make the description page and RC log entry post-commit
1468 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1471 # Defer purges, page creation, and link updates in case they error out.
1472 # The most important thing is that files and the DB registry stay synced.
1473 $dbw->endAtomic( __METHOD__
);
1475 # Do some cache purges after final commit so that:
1476 # a) Changes are more likely to be seen post-purge
1477 # b) They won't cause rollback of the log publish/update above
1478 DeferredUpdates
::addUpdate(
1479 new AutoCommitUpdate(
1483 $reupload, $wikiPage, $newPageContent, $comment, $user,
1484 $logEntry, $logId, $descId, $tags
1486 # Update memcache after the commit
1487 $this->invalidateCache();
1489 $updateLogPage = false;
1490 if ( $newPageContent ) {
1491 # New file page; create the description page.
1492 # There's already a log entry, so don't make a second RC entry
1493 # CDN and file cache for the description page are purged by doEditContent.
1494 $status = $wikiPage->doEditContent(
1497 EDIT_NEW | EDIT_SUPPRESS_RC
,
1502 if ( isset( $status->value
['revision'] ) ) {
1503 /** @var $rev Revision */
1504 $rev = $status->value
['revision'];
1505 // Associate new page revision id
1506 $logEntry->setAssociatedRevId( $rev->getId() );
1508 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1509 // which is triggered on $descTitle by doEditContent() above.
1510 if ( isset( $status->value
['revision'] ) ) {
1511 /** @var $rev Revision */
1512 $rev = $status->value
['revision'];
1513 $updateLogPage = $rev->getPage();
1516 # Existing file page: invalidate description page cache
1517 $wikiPage->getTitle()->invalidateCache();
1518 $wikiPage->getTitle()->purgeSquid();
1519 # Allow the new file version to be patrolled from the page footer
1520 Article
::purgePatrolFooterCache( $descId );
1523 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1524 # but setAssociatedRevId() wasn't called at that point yet...
1525 $logParams = $logEntry->getParameters();
1526 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1527 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1528 if ( $updateLogPage ) {
1529 # Also log page, in case where we just created it above
1530 $update['log_page'] = $updateLogPage;
1532 $this->getRepo()->getMasterDB()->update(
1535 [ 'log_id' => $logId ],
1538 $this->getRepo()->getMasterDB()->insert(
1541 'ls_field' => 'associated_rev_id',
1542 'ls_value' => $logEntry->getAssociatedRevId(),
1543 'ls_log_id' => $logId,
1548 # Add change tags, if any
1550 $logEntry->setTags( $tags );
1553 # Uploads can be patrolled
1554 $logEntry->setIsPatrollable( true );
1556 # Now that the log entry is up-to-date, make an RC entry.
1557 $logEntry->publish( $logId );
1559 # Run hook for other updates (typically more cache purging)
1560 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1563 # Delete old thumbnails
1564 $this->purgeThumbnails();
1565 # Remove the old file from the CDN cache
1566 DeferredUpdates
::addUpdate(
1567 new CdnCacheUpdate( [ $this->getUrl() ] ),
1568 DeferredUpdates
::PRESEND
1571 # Update backlink pages pointing to this title if created
1572 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1575 $this->prerenderThumbnails();
1578 DeferredUpdates
::PRESEND
1582 # This is a new file, so update the image count
1583 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1586 # Invalidate cache for all pages using this file
1587 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1593 * Move or copy a file to its public location. If a file exists at the
1594 * destination, move it to an archive. Returns a Status object with
1595 * the archive name in the "value" member on success.
1597 * The archive name should be passed through to recordUpload for database
1600 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1601 * @param int $flags A bitwise combination of:
1602 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1603 * @param array $options Optional additional parameters
1604 * @return Status On success, the value member contains the
1605 * archive name, or an empty string if it was a new file.
1607 function publish( $src, $flags = 0, array $options = [] ) {
1608 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1612 * Move or copy a file to a specified location. Returns a Status
1613 * object with the archive name in the "value" member on success.
1615 * The archive name should be passed through to recordUpload for database
1618 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1619 * @param string $dstRel Target relative path
1620 * @param int $flags A bitwise combination of:
1621 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1622 * @param array $options Optional additional parameters
1623 * @return Status On success, the value member contains the
1624 * archive name, or an empty string if it was a new file.
1626 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1627 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1629 $repo = $this->getRepo();
1630 if ( $repo->getReadOnlyReason() !== false ) {
1631 return $this->readOnlyFatalStatus();
1634 $this->lock(); // begin
1636 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1637 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1639 if ( $repo->hasSha1Storage() ) {
1640 $sha1 = $repo->isVirtualUrl( $srcPath )
1641 ?
$repo->getFileSha1( $srcPath )
1642 : FSFile
::getSha1Base36FromPath( $srcPath );
1643 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1644 $wrapperBackend = $repo->getBackend();
1645 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1646 $status = $repo->quickImport( $src, $dst );
1647 if ( $flags & File
::DELETE_SOURCE
) {
1651 if ( $this->exists() ) {
1652 $status->value
= $archiveName;
1655 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1656 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1658 if ( $status->value
== 'new' ) {
1659 $status->value
= '';
1661 $status->value
= $archiveName;
1665 $this->unlock(); // done
1670 /** getLinksTo inherited */
1671 /** getExifData inherited */
1672 /** isLocal inherited */
1673 /** wasDeleted inherited */
1676 * Move file to the new title
1678 * Move current, old version and all thumbnails
1679 * to the new filename. Old file is deleted.
1681 * Cache purging is done; checks for validity
1682 * and logging are caller's responsibility
1684 * @param Title $target New file name
1687 function move( $target ) {
1688 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1689 return $this->readOnlyFatalStatus();
1692 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1693 $batch = new LocalFileMoveBatch( $this, $target );
1695 $this->lock(); // begin
1696 $batch->addCurrent();
1697 $archiveNames = $batch->addOlds();
1698 $status = $batch->execute();
1699 $this->unlock(); // done
1701 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1703 // Purge the source and target files...
1704 $oldTitleFile = wfLocalFile( $this->title
);
1705 $newTitleFile = wfLocalFile( $target );
1706 // To avoid slow purges in the transaction, move them outside...
1707 DeferredUpdates
::addUpdate(
1708 new AutoCommitUpdate(
1709 $this->getRepo()->getMasterDB(),
1711 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1712 $oldTitleFile->purgeEverything();
1713 foreach ( $archiveNames as $archiveName ) {
1714 $oldTitleFile->purgeOldThumbnails( $archiveName );
1716 $newTitleFile->purgeEverything();
1719 DeferredUpdates
::PRESEND
1722 if ( $status->isOK() ) {
1723 // Now switch the object
1724 $this->title
= $target;
1725 // Force regeneration of the name and hashpath
1726 unset( $this->name
);
1727 unset( $this->hashPath
);
1734 * Delete all versions of the file.
1736 * Moves the files into an archive directory (or deletes them)
1737 * and removes the database rows.
1739 * Cache purging is done; logging is caller's responsibility.
1741 * @param string $reason
1742 * @param bool $suppress
1743 * @param User|null $user
1746 function delete( $reason, $suppress = false, $user = null ) {
1747 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1748 return $this->readOnlyFatalStatus();
1751 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1753 $this->lock(); // begin
1754 $batch->addCurrent();
1755 // Get old version relative paths
1756 $archiveNames = $batch->addOlds();
1757 $status = $batch->execute();
1758 $this->unlock(); // done
1760 if ( $status->isOK() ) {
1761 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1764 // To avoid slow purges in the transaction, move them outside...
1765 DeferredUpdates
::addUpdate(
1766 new AutoCommitUpdate(
1767 $this->getRepo()->getMasterDB(),
1769 function () use ( $archiveNames ) {
1770 $this->purgeEverything();
1771 foreach ( $archiveNames as $archiveName ) {
1772 $this->purgeOldThumbnails( $archiveName );
1776 DeferredUpdates
::PRESEND
1781 foreach ( $archiveNames as $archiveName ) {
1782 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1784 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1790 * Delete an old version of the file.
1792 * Moves the file into an archive directory (or deletes it)
1793 * and removes the database row.
1795 * Cache purging is done; logging is caller's responsibility.
1797 * @param string $archiveName
1798 * @param string $reason
1799 * @param bool $suppress
1800 * @param User|null $user
1801 * @throws MWException Exception on database or file store failure
1804 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1805 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1806 return $this->readOnlyFatalStatus();
1809 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1811 $this->lock(); // begin
1812 $batch->addOld( $archiveName );
1813 $status = $batch->execute();
1814 $this->unlock(); // done
1816 $this->purgeOldThumbnails( $archiveName );
1817 if ( $status->isOK() ) {
1818 $this->purgeDescription();
1821 DeferredUpdates
::addUpdate(
1822 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1823 DeferredUpdates
::PRESEND
1830 * Restore all or specified deleted revisions to the given file.
1831 * Permissions and logging are left to the caller.
1833 * May throw database exceptions on error.
1835 * @param array $versions Set of record ids of deleted items to restore,
1836 * or empty to restore all revisions.
1837 * @param bool $unsuppress
1840 function restore( $versions = [], $unsuppress = false ) {
1841 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1842 return $this->readOnlyFatalStatus();
1845 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1847 $this->lock(); // begin
1851 $batch->addIds( $versions );
1853 $status = $batch->execute();
1854 if ( $status->isGood() ) {
1855 $cleanupStatus = $batch->cleanup();
1856 $cleanupStatus->successCount
= 0;
1857 $cleanupStatus->failCount
= 0;
1858 $status->merge( $cleanupStatus );
1860 $this->unlock(); // done
1865 /** isMultipage inherited */
1866 /** pageCount inherited */
1867 /** scaleHeight inherited */
1868 /** getImageSize inherited */
1871 * Get the URL of the file description page.
1874 function getDescriptionUrl() {
1875 return $this->title
->getLocalURL();
1879 * Get the HTML text of the description page
1880 * This is not used by ImagePage for local files, since (among other things)
1881 * it skips the parser cache.
1883 * @param Language $lang What language to get description in (Optional)
1884 * @return bool|mixed
1886 function getDescriptionText( $lang = null ) {
1887 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1891 $content = $revision->getContent();
1895 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1897 return $pout->getText();
1901 * @param int $audience
1905 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1907 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1909 } elseif ( $audience == self
::FOR_THIS_USER
1910 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1914 return $this->description
;
1919 * @return bool|string
1921 function getTimestamp() {
1924 return $this->timestamp
;
1928 * @return bool|string
1930 public function getDescriptionTouched() {
1931 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1932 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1933 // need to differentiate between null (uninitialized) and false (failed to load).
1934 if ( $this->descriptionTouched
=== null ) {
1936 'page_namespace' => $this->title
->getNamespace(),
1937 'page_title' => $this->title
->getDBkey()
1939 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1940 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1943 return $this->descriptionTouched
;
1949 function getSha1() {
1951 // Initialise now if necessary
1952 if ( $this->sha1
== '' && $this->fileExists
) {
1953 $this->lock(); // begin
1955 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1956 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1957 $dbw = $this->repo
->getMasterDB();
1958 $dbw->update( 'image',
1959 [ 'img_sha1' => $this->sha1
],
1960 [ 'img_name' => $this->getName() ],
1962 $this->invalidateCache();
1965 $this->unlock(); // done
1972 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1974 function isCacheable() {
1977 // If extra data (metadata) was not loaded then it must have been large
1978 return $this->extraDataLoaded
1979 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1986 public function acquireFileLock() {
1987 return $this->getRepo()->getBackend()->lockFiles(
1988 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1996 public function releaseFileLock() {
1997 return $this->getRepo()->getBackend()->unlockFiles(
1998 [ $this->getPath() ], LockManager
::LOCK_EX
2003 * Start an atomic DB section and lock the image for update
2004 * or increments a reference counter if the lock is already held
2006 * This method should not be used outside of LocalFile/LocalFile*Batch
2008 * @throws LocalFileLockError Throws an error if the lock was not acquired
2009 * @return bool Whether the file lock owns/spawned the DB transaction
2011 public function lock() {
2012 if ( !$this->locked
) {
2013 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2015 $dbw = $this->repo
->getMasterDB();
2016 $makesTransaction = !$dbw->trxLevel();
2017 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2018 // T56736: use simple lock to handle when the file does not exist.
2019 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2020 // Also, that would cause contention on INSERT of similarly named rows.
2021 $status = $this->acquireFileLock(); // represents all versions of the file
2022 if ( !$status->isGood() ) {
2023 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2024 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2026 throw new LocalFileLockError( $status );
2028 // Release the lock *after* commit to avoid row-level contention.
2029 // Make sure it triggers on rollback() as well as commit() (T132921).
2030 $dbw->onTransactionResolution(
2031 function () use ( $logger ) {
2032 $status = $this->releaseFileLock();
2033 if ( !$status->isGood() ) {
2034 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2039 // Callers might care if the SELECT snapshot is safely fresh
2040 $this->lockedOwnTrx
= $makesTransaction;
2045 return $this->lockedOwnTrx
;
2049 * Decrement the lock reference count and end the atomic section if it reaches zero
2051 * This method should not be used outside of LocalFile/LocalFile*Batch
2053 * The commit and loc release will happen when no atomic sections are active, which
2054 * may happen immediately or at some point after calling this
2056 public function unlock() {
2057 if ( $this->locked
) {
2059 if ( !$this->locked
) {
2060 $dbw = $this->repo
->getMasterDB();
2061 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2062 $this->lockedOwnTrx
= false;
2070 protected function readOnlyFatalStatus() {
2071 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2072 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2076 * Clean up any dangling locks
2078 function __destruct() {
2081 } // LocalFile class
2083 # ------------------------------------------------------------------------------
2086 * Helper class for file deletion
2087 * @ingroup FileAbstraction
2089 class LocalFileDeleteBatch
{
2090 /** @var LocalFile */
2097 private $srcRels = [];
2100 private $archiveUrls = [];
2102 /** @var array Items to be processed in the deletion batch */
2103 private $deletionBatch;
2105 /** @var bool Whether to suppress all suppressable fields when deleting */
2116 * @param string $reason
2117 * @param bool $suppress
2118 * @param User|null $user
2120 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2121 $this->file
= $file;
2122 $this->reason
= $reason;
2123 $this->suppress
= $suppress;
2125 $this->user
= $user;
2128 $this->user
= $wgUser;
2130 $this->status
= $file->repo
->newGood();
2133 public function addCurrent() {
2134 $this->srcRels
['.'] = $this->file
->getRel();
2138 * @param string $oldName
2140 public function addOld( $oldName ) {
2141 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2142 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2146 * Add the old versions of the image to the batch
2147 * @return array List of archive names from old versions
2149 public function addOlds() {
2152 $dbw = $this->file
->repo
->getMasterDB();
2153 $result = $dbw->select( 'oldimage',
2154 [ 'oi_archive_name' ],
2155 [ 'oi_name' => $this->file
->getName() ],
2159 foreach ( $result as $row ) {
2160 $this->addOld( $row->oi_archive_name
);
2161 $archiveNames[] = $row->oi_archive_name
;
2164 return $archiveNames;
2170 protected function getOldRels() {
2171 if ( !isset( $this->srcRels
['.'] ) ) {
2172 $oldRels =& $this->srcRels
;
2173 $deleteCurrent = false;
2175 $oldRels = $this->srcRels
;
2176 unset( $oldRels['.'] );
2177 $deleteCurrent = true;
2180 return [ $oldRels, $deleteCurrent ];
2186 protected function getHashes() {
2188 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2190 if ( $deleteCurrent ) {
2191 $hashes['.'] = $this->file
->getSha1();
2194 if ( count( $oldRels ) ) {
2195 $dbw = $this->file
->repo
->getMasterDB();
2196 $res = $dbw->select(
2198 [ 'oi_archive_name', 'oi_sha1' ],
2199 [ 'oi_archive_name' => array_keys( $oldRels ),
2200 'oi_name' => $this->file
->getName() ], // performance
2204 foreach ( $res as $row ) {
2205 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2206 // Get the hash from the file
2207 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2208 $props = $this->file
->repo
->getFileProps( $oldUrl );
2210 if ( $props['fileExists'] ) {
2211 // Upgrade the oldimage row
2212 $dbw->update( 'oldimage',
2213 [ 'oi_sha1' => $props['sha1'] ],
2214 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2216 $hashes[$row->oi_archive_name
] = $props['sha1'];
2218 $hashes[$row->oi_archive_name
] = false;
2221 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2226 $missing = array_diff_key( $this->srcRels
, $hashes );
2228 foreach ( $missing as $name => $rel ) {
2229 $this->status
->error( 'filedelete-old-unregistered', $name );
2232 foreach ( $hashes as $name => $hash ) {
2234 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2235 unset( $hashes[$name] );
2242 protected function doDBInserts() {
2244 $dbw = $this->file
->repo
->getMasterDB();
2245 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2246 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2247 $encReason = $dbw->addQuotes( $this->reason
);
2248 $encGroup = $dbw->addQuotes( 'deleted' );
2249 $ext = $this->file
->getExtension();
2250 $dotExt = $ext === '' ?
'' : ".$ext";
2251 $encExt = $dbw->addQuotes( $dotExt );
2252 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2254 // Bitfields to further suppress the content
2255 if ( $this->suppress
) {
2256 $bitfield = Revision
::SUPPRESSED_ALL
;
2258 $bitfield = 'oi_deleted';
2261 if ( $deleteCurrent ) {
2266 'fa_storage_group' => $encGroup,
2267 'fa_storage_key' => $dbw->conditional(
2268 [ 'img_sha1' => '' ],
2269 $dbw->addQuotes( '' ),
2270 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2272 'fa_deleted_user' => $encUserId,
2273 'fa_deleted_timestamp' => $encTimestamp,
2274 'fa_deleted_reason' => $encReason,
2275 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2276 'fa_name' => 'img_name',
2277 'fa_archive_name' => 'NULL',
2278 'fa_size' => 'img_size',
2279 'fa_width' => 'img_width',
2280 'fa_height' => 'img_height',
2281 'fa_metadata' => 'img_metadata',
2282 'fa_bits' => 'img_bits',
2283 'fa_media_type' => 'img_media_type',
2284 'fa_major_mime' => 'img_major_mime',
2285 'fa_minor_mime' => 'img_minor_mime',
2286 'fa_description' => 'img_description',
2287 'fa_user' => 'img_user',
2288 'fa_user_text' => 'img_user_text',
2289 'fa_timestamp' => 'img_timestamp',
2290 'fa_sha1' => 'img_sha1'
2292 [ 'img_name' => $this->file
->getName() ],
2297 if ( count( $oldRels ) ) {
2298 $res = $dbw->select(
2300 OldLocalFile
::selectFields(),
2302 'oi_name' => $this->file
->getName(),
2303 'oi_archive_name' => array_keys( $oldRels )
2309 foreach ( $res as $row ) {
2311 // Deletion-specific fields
2312 'fa_storage_group' => 'deleted',
2313 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2315 : "{$row->oi_sha1}{$dotExt}",
2316 'fa_deleted_user' => $this->user
->getId(),
2317 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2318 'fa_deleted_reason' => $this->reason
,
2319 // Counterpart fields
2320 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2321 'fa_name' => $row->oi_name
,
2322 'fa_archive_name' => $row->oi_archive_name
,
2323 'fa_size' => $row->oi_size
,
2324 'fa_width' => $row->oi_width
,
2325 'fa_height' => $row->oi_height
,
2326 'fa_metadata' => $row->oi_metadata
,
2327 'fa_bits' => $row->oi_bits
,
2328 'fa_media_type' => $row->oi_media_type
,
2329 'fa_major_mime' => $row->oi_major_mime
,
2330 'fa_minor_mime' => $row->oi_minor_mime
,
2331 'fa_description' => $row->oi_description
,
2332 'fa_user' => $row->oi_user
,
2333 'fa_user_text' => $row->oi_user_text
,
2334 'fa_timestamp' => $row->oi_timestamp
,
2335 'fa_sha1' => $row->oi_sha1
2339 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2343 function doDBDeletes() {
2344 $dbw = $this->file
->repo
->getMasterDB();
2345 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2347 if ( count( $oldRels ) ) {
2348 $dbw->delete( 'oldimage',
2350 'oi_name' => $this->file
->getName(),
2351 'oi_archive_name' => array_keys( $oldRels )
2355 if ( $deleteCurrent ) {
2356 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2361 * Run the transaction
2364 public function execute() {
2365 $repo = $this->file
->getRepo();
2366 $this->file
->lock();
2368 // Prepare deletion batch
2369 $hashes = $this->getHashes();
2370 $this->deletionBatch
= [];
2371 $ext = $this->file
->getExtension();
2372 $dotExt = $ext === '' ?
'' : ".$ext";
2374 foreach ( $this->srcRels
as $name => $srcRel ) {
2375 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2376 if ( isset( $hashes[$name] ) ) {
2377 $hash = $hashes[$name];
2378 $key = $hash . $dotExt;
2379 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2380 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2384 if ( !$repo->hasSha1Storage() ) {
2385 // Removes non-existent file from the batch, so we don't get errors.
2386 // This also handles files in the 'deleted' zone deleted via revision deletion.
2387 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2388 if ( !$checkStatus->isGood() ) {
2389 $this->status
->merge( $checkStatus );
2390 return $this->status
;
2392 $this->deletionBatch
= $checkStatus->value
;
2394 // Execute the file deletion batch
2395 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2396 if ( !$status->isGood() ) {
2397 $this->status
->merge( $status );
2401 if ( !$this->status
->isOK() ) {
2402 // Critical file deletion error; abort
2403 $this->file
->unlock();
2405 return $this->status
;
2408 // Copy the image/oldimage rows to filearchive
2409 $this->doDBInserts();
2410 // Delete image/oldimage rows
2411 $this->doDBDeletes();
2413 // Commit and return
2414 $this->file
->unlock();
2416 return $this->status
;
2420 * Removes non-existent files from a deletion batch.
2421 * @param array $batch
2424 protected function removeNonexistentFiles( $batch ) {
2425 $files = $newBatch = [];
2427 foreach ( $batch as $batchItem ) {
2428 list( $src, ) = $batchItem;
2429 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2432 $result = $this->file
->repo
->fileExistsBatch( $files );
2433 if ( in_array( null, $result, true ) ) {
2434 return Status
::newFatal( 'backend-fail-internal',
2435 $this->file
->repo
->getBackend()->getName() );
2438 foreach ( $batch as $batchItem ) {
2439 if ( $result[$batchItem[0]] ) {
2440 $newBatch[] = $batchItem;
2444 return Status
::newGood( $newBatch );
2448 # ------------------------------------------------------------------------------
2451 * Helper class for file undeletion
2452 * @ingroup FileAbstraction
2454 class LocalFileRestoreBatch
{
2455 /** @var LocalFile */
2458 /** @var array List of file IDs to restore */
2459 private $cleanupBatch;
2461 /** @var array List of file IDs to restore */
2464 /** @var bool Add all revisions of the file */
2467 /** @var bool Whether to remove all settings for suppressed fields */
2468 private $unsuppress = false;
2472 * @param bool $unsuppress
2474 function __construct( File
$file, $unsuppress = false ) {
2475 $this->file
= $file;
2476 $this->cleanupBatch
= $this->ids
= [];
2478 $this->unsuppress
= $unsuppress;
2485 public function addId( $fa_id ) {
2486 $this->ids
[] = $fa_id;
2490 * Add a whole lot of files by ID
2493 public function addIds( $ids ) {
2494 $this->ids
= array_merge( $this->ids
, $ids );
2498 * Add all revisions of the file
2500 public function addAll() {
2505 * Run the transaction, except the cleanup batch.
2506 * The cleanup batch should be run in a separate transaction, because it locks different
2507 * rows and there's no need to keep the image row locked while it's acquiring those locks
2508 * The caller may have its own transaction open.
2509 * So we save the batch and let the caller call cleanup()
2512 public function execute() {
2513 /** @var Language */
2516 $repo = $this->file
->getRepo();
2517 if ( !$this->all
&& !$this->ids
) {
2519 return $repo->newGood();
2522 $lockOwnsTrx = $this->file
->lock();
2524 $dbw = $this->file
->repo
->getMasterDB();
2525 $status = $this->file
->repo
->newGood();
2527 $exists = (bool)$dbw->selectField( 'image', '1',
2528 [ 'img_name' => $this->file
->getName() ],
2530 // The lock() should already prevents changes, but this still may need
2531 // to bypass any transaction snapshot. However, if lock() started the
2532 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2533 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2536 // Fetch all or selected archived revisions for the file,
2537 // sorted from the most recent to the oldest.
2538 $conditions = [ 'fa_name' => $this->file
->getName() ];
2540 if ( !$this->all
) {
2541 $conditions['fa_id'] = $this->ids
;
2544 $result = $dbw->select(
2546 ArchivedFile
::selectFields(),
2549 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2555 $insertCurrent = false;
2560 foreach ( $result as $row ) {
2561 $idsPresent[] = $row->fa_id
;
2563 if ( $row->fa_name
!= $this->file
->getName() ) {
2564 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2565 $status->failCount++
;
2569 if ( $row->fa_storage_key
== '' ) {
2570 // Revision was missing pre-deletion
2571 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2572 $status->failCount++
;
2576 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2577 $row->fa_storage_key
;
2578 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2580 if ( isset( $row->fa_sha1
) ) {
2581 $sha1 = $row->fa_sha1
;
2583 // old row, populate from key
2584 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2588 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2589 $sha1 = substr( $sha1, 1 );
2592 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2593 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2594 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2595 ||
is_null( $row->fa_metadata
)
2597 // Refresh our metadata
2598 // Required for a new current revision; nice for older ones too. :)
2599 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2602 'minor_mime' => $row->fa_minor_mime
,
2603 'major_mime' => $row->fa_major_mime
,
2604 'media_type' => $row->fa_media_type
,
2605 'metadata' => $row->fa_metadata
2609 if ( $first && !$exists ) {
2610 // This revision will be published as the new current version
2611 $destRel = $this->file
->getRel();
2613 'img_name' => $row->fa_name
,
2614 'img_size' => $row->fa_size
,
2615 'img_width' => $row->fa_width
,
2616 'img_height' => $row->fa_height
,
2617 'img_metadata' => $props['metadata'],
2618 'img_bits' => $row->fa_bits
,
2619 'img_media_type' => $props['media_type'],
2620 'img_major_mime' => $props['major_mime'],
2621 'img_minor_mime' => $props['minor_mime'],
2622 'img_description' => $row->fa_description
,
2623 'img_user' => $row->fa_user
,
2624 'img_user_text' => $row->fa_user_text
,
2625 'img_timestamp' => $row->fa_timestamp
,
2629 // The live (current) version cannot be hidden!
2630 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2631 $status->fatal( 'undeleterevdel' );
2632 $this->file
->unlock();
2636 $archiveName = $row->fa_archive_name
;
2638 if ( $archiveName == '' ) {
2639 // This was originally a current version; we
2640 // have to devise a new archive name for it.
2641 // Format is <timestamp of archiving>!<name>
2642 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2645 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2647 } while ( isset( $archiveNames[$archiveName] ) );
2650 $archiveNames[$archiveName] = true;
2651 $destRel = $this->file
->getArchiveRel( $archiveName );
2653 'oi_name' => $row->fa_name
,
2654 'oi_archive_name' => $archiveName,
2655 'oi_size' => $row->fa_size
,
2656 'oi_width' => $row->fa_width
,
2657 'oi_height' => $row->fa_height
,
2658 'oi_bits' => $row->fa_bits
,
2659 'oi_description' => $row->fa_description
,
2660 'oi_user' => $row->fa_user
,
2661 'oi_user_text' => $row->fa_user_text
,
2662 'oi_timestamp' => $row->fa_timestamp
,
2663 'oi_metadata' => $props['metadata'],
2664 'oi_media_type' => $props['media_type'],
2665 'oi_major_mime' => $props['major_mime'],
2666 'oi_minor_mime' => $props['minor_mime'],
2667 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2668 'oi_sha1' => $sha1 ];
2671 $deleteIds[] = $row->fa_id
;
2673 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2674 // private files can stay where they are
2675 $status->successCount++
;
2677 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2678 $this->cleanupBatch
[] = $row->fa_storage_key
;
2686 // Add a warning to the status object for missing IDs
2687 $missingIds = array_diff( $this->ids
, $idsPresent );
2689 foreach ( $missingIds as $id ) {
2690 $status->error( 'undelete-missing-filearchive', $id );
2693 if ( !$repo->hasSha1Storage() ) {
2694 // Remove missing files from batch, so we don't get errors when undeleting them
2695 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2696 if ( !$checkStatus->isGood() ) {
2697 $status->merge( $checkStatus );
2700 $storeBatch = $checkStatus->value
;
2702 // Run the store batch
2703 // Use the OVERWRITE_SAME flag to smooth over a common error
2704 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2705 $status->merge( $storeStatus );
2707 if ( !$status->isGood() ) {
2708 // Even if some files could be copied, fail entirely as that is the
2709 // easiest thing to do without data loss
2710 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2711 $status->setOK( false );
2712 $this->file
->unlock();
2718 // Run the DB updates
2719 // Because we have locked the image row, key conflicts should be rare.
2720 // If they do occur, we can roll back the transaction at this time with
2721 // no data loss, but leaving unregistered files scattered throughout the
2723 // This is not ideal, which is why it's important to lock the image row.
2724 if ( $insertCurrent ) {
2725 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2728 if ( $insertBatch ) {
2729 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2733 $dbw->delete( 'filearchive',
2734 [ 'fa_id' => $deleteIds ],
2738 // If store batch is empty (all files are missing), deletion is to be considered successful
2739 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2741 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2743 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2745 $this->file
->purgeEverything();
2747 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2748 $this->file
->purgeDescription();
2752 $this->file
->unlock();
2758 * Removes non-existent files from a store batch.
2759 * @param array $triplets
2762 protected function removeNonexistentFiles( $triplets ) {
2763 $files = $filteredTriplets = [];
2764 foreach ( $triplets as $file ) {
2765 $files[$file[0]] = $file[0];
2768 $result = $this->file
->repo
->fileExistsBatch( $files );
2769 if ( in_array( null, $result, true ) ) {
2770 return Status
::newFatal( 'backend-fail-internal',
2771 $this->file
->repo
->getBackend()->getName() );
2774 foreach ( $triplets as $file ) {
2775 if ( $result[$file[0]] ) {
2776 $filteredTriplets[] = $file;
2780 return Status
::newGood( $filteredTriplets );
2784 * Removes non-existent files from a cleanup batch.
2785 * @param array $batch
2788 protected function removeNonexistentFromCleanup( $batch ) {
2789 $files = $newBatch = [];
2790 $repo = $this->file
->repo
;
2792 foreach ( $batch as $file ) {
2793 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2794 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2797 $result = $repo->fileExistsBatch( $files );
2799 foreach ( $batch as $file ) {
2800 if ( $result[$file] ) {
2801 $newBatch[] = $file;
2809 * Delete unused files in the deleted zone.
2810 * This should be called from outside the transaction in which execute() was called.
2813 public function cleanup() {
2814 if ( !$this->cleanupBatch
) {
2815 return $this->file
->repo
->newGood();
2818 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2820 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2826 * Cleanup a failed batch. The batch was only partially successful, so
2827 * rollback by removing all items that were succesfully copied.
2829 * @param Status $storeStatus
2830 * @param array $storeBatch
2832 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2835 foreach ( $storeStatus->success
as $i => $success ) {
2836 // Check if this item of the batch was successfully copied
2838 // Item was successfully copied and needs to be removed again
2839 // Extract ($dstZone, $dstRel) from the batch
2840 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2843 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2847 # ------------------------------------------------------------------------------
2850 * Helper class for file movement
2851 * @ingroup FileAbstraction
2853 class LocalFileMoveBatch
{
2854 /** @var LocalFile */
2864 protected $oldCount;
2868 /** @var IDatabase */
2873 * @param Title $target
2875 function __construct( File
$file, Title
$target ) {
2876 $this->file
= $file;
2877 $this->target
= $target;
2878 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2879 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2880 $this->oldName
= $this->file
->getName();
2881 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2882 $this->oldRel
= $this->oldHash
. $this->oldName
;
2883 $this->newRel
= $this->newHash
. $this->newName
;
2884 $this->db
= $file->getRepo()->getMasterDB();
2888 * Add the current image to the batch
2890 public function addCurrent() {
2891 $this->cur
= [ $this->oldRel
, $this->newRel
];
2895 * Add the old versions of the image to the batch
2896 * @return array List of archive names from old versions
2898 public function addOlds() {
2899 $archiveBase = 'archive';
2901 $this->oldCount
= 0;
2904 $result = $this->db
->select( 'oldimage',
2905 [ 'oi_archive_name', 'oi_deleted' ],
2906 [ 'oi_name' => $this->oldName
],
2908 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2911 foreach ( $result as $row ) {
2912 $archiveNames[] = $row->oi_archive_name
;
2913 $oldName = $row->oi_archive_name
;
2914 $bits = explode( '!', $oldName, 2 );
2916 if ( count( $bits ) != 2 ) {
2917 wfDebug( "Old file name missing !: '$oldName' \n" );
2921 list( $timestamp, $filename ) = $bits;
2923 if ( $this->oldName
!= $filename ) {
2924 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2930 // Do we want to add those to oldCount?
2931 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2936 "{$archiveBase}/{$this->oldHash}{$oldName}",
2937 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2941 return $archiveNames;
2948 public function execute() {
2949 $repo = $this->file
->repo
;
2950 $status = $repo->newGood();
2951 $destFile = wfLocalFile( $this->target
);
2953 $this->file
->lock(); // begin
2954 $destFile->lock(); // quickly fail if destination is not available
2956 $triplets = $this->getMoveTriplets();
2957 $checkStatus = $this->removeNonexistentFiles( $triplets );
2958 if ( !$checkStatus->isGood() ) {
2959 $destFile->unlock();
2960 $this->file
->unlock();
2961 $status->merge( $checkStatus ); // couldn't talk to file backend
2964 $triplets = $checkStatus->value
;
2966 // Verify the file versions metadata in the DB.
2967 $statusDb = $this->verifyDBUpdates();
2968 if ( !$statusDb->isGood() ) {
2969 $destFile->unlock();
2970 $this->file
->unlock();
2971 $statusDb->setOK( false );
2976 if ( !$repo->hasSha1Storage() ) {
2977 // Copy the files into their new location.
2978 // If a prior process fataled copying or cleaning up files we tolerate any
2979 // of the existing files if they are identical to the ones being stored.
2980 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2981 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2982 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2983 if ( !$statusMove->isGood() ) {
2984 // Delete any files copied over (while the destination is still locked)
2985 $this->cleanupTarget( $triplets );
2986 $destFile->unlock();
2987 $this->file
->unlock();
2988 wfDebugLog( 'imagemove', "Error in moving files: "
2989 . $statusMove->getWikiText( false, false, 'en' ) );
2990 $statusMove->setOK( false );
2994 $status->merge( $statusMove );
2997 // Rename the file versions metadata in the DB.
2998 $this->doDBUpdates();
3000 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3001 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3003 $destFile->unlock();
3004 $this->file
->unlock(); // done
3006 // Everything went ok, remove the source files
3007 $this->cleanupSource( $triplets );
3009 $status->merge( $statusDb );
3015 * Verify the database updates and return a new Status indicating how
3016 * many rows would be updated.
3020 protected function verifyDBUpdates() {
3021 $repo = $this->file
->repo
;
3022 $status = $repo->newGood();
3025 $hasCurrent = $dbw->selectField(
3028 [ 'img_name' => $this->oldName
],
3032 $oldRowCount = $dbw->selectField(
3035 [ 'oi_name' => $this->oldName
],
3040 if ( $hasCurrent ) {
3041 $status->successCount++
;
3043 $status->failCount++
;
3045 $status->successCount +
= $oldRowCount;
3046 // T36934: oldCount is based on files that actually exist.
3047 // There may be more DB rows than such files, in which case $affected
3048 // can be greater than $total. We use max() to avoid negatives here.
3049 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3050 if ( $status->failCount
) {
3051 $status->error( 'imageinvalidfilename' );
3058 * Do the database updates and return a new Status indicating how
3059 * many rows where updated.
3061 protected function doDBUpdates() {
3064 // Update current image
3067 [ 'img_name' => $this->newName
],
3068 [ 'img_name' => $this->oldName
],
3071 // Update old images
3075 'oi_name' => $this->newName
,
3076 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3077 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3079 [ 'oi_name' => $this->oldName
],
3085 * Generate triplets for FileRepo::storeBatch().
3088 protected function getMoveTriplets() {
3089 $moves = array_merge( [ $this->cur
], $this->olds
);
3090 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3092 foreach ( $moves as $move ) {
3093 // $move: (oldRelativePath, newRelativePath)
3094 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3095 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3098 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3106 * Removes non-existent files from move batch.
3107 * @param array $triplets
3110 protected function removeNonexistentFiles( $triplets ) {
3113 foreach ( $triplets as $file ) {
3114 $files[$file[0]] = $file[0];
3117 $result = $this->file
->repo
->fileExistsBatch( $files );
3118 if ( in_array( null, $result, true ) ) {
3119 return Status
::newFatal( 'backend-fail-internal',
3120 $this->file
->repo
->getBackend()->getName() );
3123 $filteredTriplets = [];
3124 foreach ( $triplets as $file ) {
3125 if ( $result[$file[0]] ) {
3126 $filteredTriplets[] = $file;
3128 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3132 return Status
::newGood( $filteredTriplets );
3136 * Cleanup a partially moved array of triplets by deleting the target
3137 * files. Called if something went wrong half way.
3138 * @param array $triplets
3140 protected function cleanupTarget( $triplets ) {
3141 // Create dest pairs from the triplets
3143 foreach ( $triplets as $triplet ) {
3144 // $triplet: (old source virtual URL, dst zone, dest rel)
3145 $pairs[] = [ $triplet[1], $triplet[2] ];
3148 $this->file
->repo
->cleanupBatch( $pairs );
3152 * Cleanup a fully moved array of triplets by deleting the source files.
3153 * Called at the end of the move process if everything else went ok.
3154 * @param array $triplets
3156 protected function cleanupSource( $triplets ) {
3157 // Create source file names from the triplets
3159 foreach ( $triplets as $triplet ) {
3160 $files[] = $triplet[0];
3163 $this->file
->repo
->cleanupBatch( $files );
3167 class LocalFileLockError
extends ErrorPageError
{
3168 public function __construct( Status
$status ) {
3169 parent
::__construct(
3171 $status->getMessage()
3175 public function report() {
3177 $wgOut->setStatusCode( 429 );