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
;
27 * Class to represent a local file in the wiki's own database
29 * Provides methods to retrieve paths (physical, logical, URL),
30 * to generate image thumbnails or for uploading.
32 * Note that only the repo object knows what its file class is called. You should
33 * never name a file class explictly outside of the repo class. Instead use the
34 * repo's factory functions to generate file objects, for example:
36 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
38 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
41 * @ingroup FileAbstraction
43 class LocalFile
extends File
{
44 const VERSION
= 10; // cache version
46 const CACHE_FIELD_MAX_LEN
= 1000;
48 /** @var bool Does the file exist on disk? (loadFromXxx) */
49 protected $fileExists;
51 /** @var int Image width */
54 /** @var int Image height */
57 /** @var int Returned by getimagesize (loadFromXxx) */
60 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
61 protected $media_type;
63 /** @var string MIME type, determined by MimeMagic::guessMimeType */
66 /** @var int Size in bytes (loadFromXxx) */
69 /** @var string Handler-specific metadata */
72 /** @var string SHA-1 base 36 content hash */
75 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
76 protected $dataLoaded;
78 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
79 protected $extraDataLoaded;
81 /** @var int Bitfield akin to rev_deleted */
85 protected $repoClass = 'LocalRepo';
87 /** @var int Number of line to return by nextHistoryLine() (constructor) */
90 /** @var int Result of the query for the file's history (nextHistoryLine) */
93 /** @var string Major MIME type */
96 /** @var string Minor MIME type */
99 /** @var string Upload timestamp */
102 /** @var int User ID of uploader */
105 /** @var string User name of uploader */
108 /** @var string Description of current revision of the file */
109 private $description;
111 /** @var string TS_MW timestamp of the last change of the file description */
112 private $descriptionTouched;
114 /** @var bool Whether the row was upgraded on load */
117 /** @var bool Whether the row was scheduled to upgrade on load */
120 /** @var bool True if the image row is locked */
123 /** @var bool True if the image row is locked with a lock initiated transaction */
124 private $lockedOwnTrx;
126 /** @var bool True if file is not present in file system. Not to be cached in memcached */
129 // @note: higher than IDBAccessObject constants
130 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
132 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
135 * Create a LocalFile from a title
136 * Do not call this except from inside a repo class.
138 * Note: $unused param is only here to avoid an E_STRICT
140 * @param Title $title
141 * @param FileRepo $repo
142 * @param null $unused
146 static function newFromTitle( $title, $repo, $unused = null ) {
147 return new self( $title, $repo );
151 * Create a LocalFile from a title
152 * Do not call this except from inside a repo class.
154 * @param stdClass $row
155 * @param FileRepo $repo
159 static function newFromRow( $row, $repo ) {
160 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
161 $file = new self( $title, $repo );
162 $file->loadFromRow( $row );
168 * Create a LocalFile from a SHA-1 key
169 * Do not call this except from inside a repo class.
171 * @param string $sha1 Base-36 SHA-1
172 * @param LocalRepo $repo
173 * @param string|bool $timestamp MW_timestamp (optional)
174 * @return bool|LocalFile
176 static function newFromKey( $sha1, $repo, $timestamp = false ) {
177 $dbr = $repo->getReplicaDB();
179 $conds = [ 'img_sha1' => $sha1 ];
181 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
184 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
186 return self
::newFromRow( $row, $repo );
193 * Fields in the image table
196 static function selectFields() {
217 * Do not call this except from inside a repo class.
218 * @param Title $title
219 * @param FileRepo $repo
221 function __construct( $title, $repo ) {
222 parent
::__construct( $title, $repo );
224 $this->metadata
= '';
225 $this->historyLine
= 0;
226 $this->historyRes
= null;
227 $this->dataLoaded
= false;
228 $this->extraDataLoaded
= false;
230 $this->assertRepoDefined();
231 $this->assertTitleDefined();
235 * Get the memcached key for the main data for this file, or false if
236 * there is no access to the shared cache.
237 * @return string|bool
239 function getCacheKey() {
240 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
244 * @param WANObjectCache $cache
248 public function getMutableCacheKeys( WANObjectCache
$cache ) {
249 return [ $this->getCacheKey() ];
253 * Try to load file metadata from memcached, falling back to the database
255 private function loadFromCache() {
256 $this->dataLoaded
= false;
257 $this->extraDataLoaded
= false;
259 $key = $this->getCacheKey();
261 $this->loadFromDB( self
::READ_NORMAL
);
266 $cache = ObjectCache
::getMainWANInstance();
267 $cachedValues = $cache->getWithSetCallback(
270 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
271 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
273 $this->loadFromDB( self
::READ_NORMAL
);
275 $fields = $this->getCacheFields( '' );
276 $cacheVal['fileExists'] = $this->fileExists
;
277 if ( $this->fileExists
) {
278 foreach ( $fields as $field ) {
279 $cacheVal[$field] = $this->$field;
282 // Strip off excessive entries from the subset of fields that can become large.
283 // If the cache value gets to large it will not fit in memcached and nothing will
284 // get cached at all, causing master queries for any file access.
285 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
286 if ( isset( $cacheVal[$field] )
287 && strlen( $cacheVal[$field] ) > 100 * 1024
289 unset( $cacheVal[$field] ); // don't let the value get too big
293 if ( $this->fileExists
) {
294 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
296 $ttl = $cache::TTL_DAY
;
301 [ 'version' => self
::VERSION
]
304 $this->fileExists
= $cachedValues['fileExists'];
305 if ( $this->fileExists
) {
306 $this->setProps( $cachedValues );
309 $this->dataLoaded
= true;
310 $this->extraDataLoaded
= true;
311 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
312 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
317 * Purge the file object/metadata cache
319 public function invalidateCache() {
320 $key = $this->getCacheKey();
325 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
326 function () use ( $key ) {
327 ObjectCache
::getMainWANInstance()->delete( $key );
334 * Load metadata from the file itself
336 function loadFromFile() {
337 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
338 $this->setProps( $props );
342 * @param string $prefix
345 function getCacheFields( $prefix = 'img_' ) {
346 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
347 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
348 'user_text', 'description' ];
349 static $results = [];
351 if ( $prefix == '' ) {
355 if ( !isset( $results[$prefix] ) ) {
356 $prefixedFields = [];
357 foreach ( $fields as $field ) {
358 $prefixedFields[] = $prefix . $field;
360 $results[$prefix] = $prefixedFields;
363 return $results[$prefix];
367 * @param string $prefix
370 function getLazyCacheFields( $prefix = 'img_' ) {
371 static $fields = [ 'metadata' ];
372 static $results = [];
374 if ( $prefix == '' ) {
378 if ( !isset( $results[$prefix] ) ) {
379 $prefixedFields = [];
380 foreach ( $fields as $field ) {
381 $prefixedFields[] = $prefix . $field;
383 $results[$prefix] = $prefixedFields;
386 return $results[$prefix];
390 * Load file metadata from the DB
393 function loadFromDB( $flags = 0 ) {
394 $fname = get_class( $this ) . '::' . __FUNCTION__
;
396 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
397 $this->dataLoaded
= true;
398 $this->extraDataLoaded
= true;
400 $dbr = ( $flags & self
::READ_LATEST
)
401 ?
$this->repo
->getMasterDB()
402 : $this->repo
->getReplicaDB();
404 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
405 [ 'img_name' => $this->getName() ], $fname );
408 $this->loadFromRow( $row );
410 $this->fileExists
= false;
415 * Load lazy file metadata from the DB.
416 * This covers fields that are sometimes not cached.
418 protected function loadExtraFromDB() {
419 $fname = get_class( $this ) . '::' . __FUNCTION__
;
421 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
422 $this->extraDataLoaded
= true;
424 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
426 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
430 foreach ( $fieldMap as $name => $value ) {
431 $this->$name = $value;
434 throw new MWException( "Could not find data for image '{$this->getName()}'." );
439 * @param IDatabase $dbr
440 * @param string $fname
443 private function loadFieldsWithTimestamp( $dbr, $fname ) {
446 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
447 'img_name' => $this->getName(),
448 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
451 $fieldMap = $this->unprefixRow( $row, 'img_' );
453 # File may have been uploaded over in the meantime; check the old versions
454 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
455 'oi_name' => $this->getName(),
456 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
459 $fieldMap = $this->unprefixRow( $row, 'oi_' );
467 * @param array|object $row
468 * @param string $prefix
469 * @throws MWException
472 protected function unprefixRow( $row, $prefix = 'img_' ) {
473 $array = (array)$row;
474 $prefixLength = strlen( $prefix );
476 // Sanity check prefix once
477 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
478 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
482 foreach ( $array as $name => $value ) {
483 $decoded[substr( $name, $prefixLength )] = $value;
490 * Decode a row from the database (either object or array) to an array
491 * with timestamps and MIME types decoded, and the field prefix removed.
493 * @param string $prefix
494 * @throws MWException
497 function decodeRow( $row, $prefix = 'img_' ) {
498 $decoded = $this->unprefixRow( $row, $prefix );
500 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
502 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
504 if ( empty( $decoded['major_mime'] ) ) {
505 $decoded['mime'] = 'unknown/unknown';
507 if ( !$decoded['minor_mime'] ) {
508 $decoded['minor_mime'] = 'unknown';
510 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
513 // Trim zero padding from char/binary field
514 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
516 // Normalize some fields to integer type, per their database definition.
517 // Use unary + so that overflows will be upgraded to double instead of
518 // being trucated as with intval(). This is important to allow >2GB
519 // files on 32-bit systems.
520 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
521 $decoded[$field] = +
$decoded[$field];
528 * Load file metadata from a DB result row
531 * @param string $prefix
533 function loadFromRow( $row, $prefix = 'img_' ) {
534 $this->dataLoaded
= true;
535 $this->extraDataLoaded
= true;
537 $array = $this->decodeRow( $row, $prefix );
539 foreach ( $array as $name => $value ) {
540 $this->$name = $value;
543 $this->fileExists
= true;
544 $this->maybeUpgradeRow();
548 * Load file metadata from cache or DB, unless already loaded
551 function load( $flags = 0 ) {
552 if ( !$this->dataLoaded
) {
553 if ( $flags & self
::READ_LATEST
) {
554 $this->loadFromDB( $flags );
556 $this->loadFromCache();
560 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
561 // @note: loads on name/timestamp to reduce race condition problems
562 $this->loadExtraFromDB();
567 * Upgrade a row if it needs it
569 function maybeUpgradeRow() {
570 global $wgUpdateCompatibleMetadata;
572 if ( wfReadOnly() ||
$this->upgrading
) {
577 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
580 $handler = $this->getHandler();
582 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
583 if ( $validity === MediaHandler
::METADATA_BAD
) {
585 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
586 $upgrade = $wgUpdateCompatibleMetadata;
592 $this->upgrading
= true;
593 // Defer updates unless in auto-commit CLI mode
594 DeferredUpdates
::addCallableUpdate( function() {
595 $this->upgrading
= false; // avoid duplicate updates
598 } catch ( LocalFileLockError
$e ) {
599 // let the other process handle it (or do it next time)
606 * @return bool Whether upgradeRow() ran for this object
608 function getUpgraded() {
609 return $this->upgraded
;
613 * Fix assorted version-related problems with the image row by reloading it from the file
615 function upgradeRow() {
616 $this->lock(); // begin
618 $this->loadFromFile();
620 # Don't destroy file info of missing files
621 if ( !$this->fileExists
) {
623 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
628 $dbw = $this->repo
->getMasterDB();
629 list( $major, $minor ) = self
::splitMime( $this->mime
);
631 if ( wfReadOnly() ) {
636 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
638 $dbw->update( 'image',
640 'img_size' => $this->size
, // sanity
641 'img_width' => $this->width
,
642 'img_height' => $this->height
,
643 'img_bits' => $this->bits
,
644 'img_media_type' => $this->media_type
,
645 'img_major_mime' => $major,
646 'img_minor_mime' => $minor,
647 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
648 'img_sha1' => $this->sha1
,
650 [ 'img_name' => $this->getName() ],
654 $this->invalidateCache();
656 $this->unlock(); // done
657 $this->upgraded
= true; // avoid rework/retries
661 * Set properties in this object to be equal to those given in the
662 * associative array $info. Only cacheable fields can be set.
663 * All fields *must* be set in $info except for getLazyCacheFields().
665 * If 'mime' is given, it will be split into major_mime/minor_mime.
666 * If major_mime/minor_mime are given, $this->mime will also be set.
670 function setProps( $info ) {
671 $this->dataLoaded
= true;
672 $fields = $this->getCacheFields( '' );
673 $fields[] = 'fileExists';
675 foreach ( $fields as $field ) {
676 if ( isset( $info[$field] ) ) {
677 $this->$field = $info[$field];
681 // Fix up mime fields
682 if ( isset( $info['major_mime'] ) ) {
683 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
684 } elseif ( isset( $info['mime'] ) ) {
685 $this->mime
= $info['mime'];
686 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
690 /** splitMime inherited */
691 /** getName inherited */
692 /** getTitle inherited */
693 /** getURL inherited */
694 /** getViewURL inherited */
695 /** getPath inherited */
696 /** isVisible inherited */
701 function isMissing() {
702 if ( $this->missing
=== null ) {
703 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
704 $this->missing
= !$fileExists;
707 return $this->missing
;
711 * Return the width of the image
716 public function getWidth( $page = 1 ) {
719 if ( $this->isMultipage() ) {
720 $handler = $this->getHandler();
724 $dim = $handler->getPageDimensions( $this, $page );
726 return $dim['width'];
728 // For non-paged media, the false goes through an
729 // intval, turning failure into 0, so do same here.
738 * Return the height of the image
743 public function getHeight( $page = 1 ) {
746 if ( $this->isMultipage() ) {
747 $handler = $this->getHandler();
751 $dim = $handler->getPageDimensions( $this, $page );
753 return $dim['height'];
755 // For non-paged media, the false goes through an
756 // intval, turning failure into 0, so do same here.
760 return $this->height
;
765 * Returns ID or name of user who uploaded the file
767 * @param string $type 'text' or 'id'
770 function getUser( $type = 'text' ) {
773 if ( $type == 'text' ) {
774 return $this->user_text
;
776 return (int)$this->user
;
781 * Get short description URL for a file based on the page ID.
783 * @return string|null
784 * @throws MWException
787 public function getDescriptionShortUrl() {
788 $pageId = $this->title
->getArticleID();
790 if ( $pageId !== null ) {
791 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
792 if ( $url !== false ) {
800 * Get handler-specific metadata
803 function getMetadata() {
804 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
805 return $this->metadata
;
811 function getBitDepth() {
814 return (int)$this->bits
;
818 * Returns the size of the image file, in bytes
821 public function getSize() {
828 * Returns the MIME type of the file.
831 function getMimeType() {
838 * Returns the type of the media in the file.
839 * Use the value returned by this function with the MEDIATYPE_xxx constants.
842 function getMediaType() {
845 return $this->media_type
;
848 /** canRender inherited */
849 /** mustRender inherited */
850 /** allowInlineDisplay inherited */
851 /** isSafeFile inherited */
852 /** isTrustedFile inherited */
855 * Returns true if the file exists on disk.
856 * @return bool Whether file exist on disk.
858 public function exists() {
861 return $this->fileExists
;
864 /** getTransformScript inherited */
865 /** getUnscaledThumb inherited */
866 /** thumbName inherited */
867 /** createThumb inherited */
868 /** transform inherited */
870 /** getHandler inherited */
871 /** iconThumb inherited */
872 /** getLastError inherited */
875 * Get all thumbnail names previously generated for this file
876 * @param string|bool $archiveName Name of an archive file, default false
877 * @return array First element is the base dir, then files in that base dir.
879 function getThumbnails( $archiveName = false ) {
880 if ( $archiveName ) {
881 $dir = $this->getArchiveThumbPath( $archiveName );
883 $dir = $this->getThumbPath();
886 $backend = $this->repo
->getBackend();
889 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
890 foreach ( $iterator as $file ) {
893 } catch ( FileBackendError
$e ) {
894 } // suppress (bug 54674)
900 * Refresh metadata in memcached, but don't touch thumbnails or CDN
902 function purgeMetadataCache() {
903 $this->invalidateCache();
907 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
909 * @param array $options An array potentially with the key forThumbRefresh.
911 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
913 function purgeCache( $options = [] ) {
914 // Refresh metadata cache
915 $this->purgeMetadataCache();
918 $this->purgeThumbnails( $options );
920 // Purge CDN cache for this file
921 DeferredUpdates
::addUpdate(
922 new CdnCacheUpdate( [ $this->getUrl() ] ),
923 DeferredUpdates
::PRESEND
928 * Delete cached transformed files for an archived version only.
929 * @param string $archiveName Name of the archived file
931 function purgeOldThumbnails( $archiveName ) {
932 // Get a list of old thumbnails and URLs
933 $files = $this->getThumbnails( $archiveName );
935 // Purge any custom thumbnail caches
936 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
939 $dir = array_shift( $files );
940 $this->purgeThumbList( $dir, $files );
944 foreach ( $files as $file ) {
945 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
947 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
951 * Delete cached transformed files for the current version only.
952 * @param array $options
954 public function purgeThumbnails( $options = [] ) {
955 $files = $this->getThumbnails();
956 // Always purge all files from CDN regardless of handler filters
958 foreach ( $files as $file ) {
959 $urls[] = $this->getThumbUrl( $file );
961 array_shift( $urls ); // don't purge directory
963 // Give media handler a chance to filter the file purge list
964 if ( !empty( $options['forThumbRefresh'] ) ) {
965 $handler = $this->getHandler();
967 $handler->filterThumbnailPurgeList( $files, $options );
971 // Purge any custom thumbnail caches
972 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
975 $dir = array_shift( $files );
976 $this->purgeThumbList( $dir, $files );
979 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
983 * Prerenders a configurable set of thumbnails
987 public function prerenderThumbnails() {
988 global $wgUploadThumbnailRenderMap;
992 $sizes = $wgUploadThumbnailRenderMap;
995 foreach ( $sizes as $size ) {
996 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
997 $jobs[] = new ThumbnailRenderJob(
999 [ 'transformParams' => [ 'width' => $size ] ]
1005 JobQueueGroup
::singleton()->lazyPush( $jobs );
1010 * Delete a list of thumbnails visible at urls
1011 * @param string $dir Base dir of the files.
1012 * @param array $files Array of strings: relative filenames (to $dir)
1014 protected function purgeThumbList( $dir, $files ) {
1015 $fileListDebug = strtr(
1016 var_export( $files, true ),
1019 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1022 foreach ( $files as $file ) {
1023 # Check that the base file name is part of the thumb name
1024 # This is a basic sanity check to avoid erasing unrelated directories
1025 if ( strpos( $file, $this->getName() ) !== false
1026 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1028 $purgeList[] = "{$dir}/{$file}";
1032 # Delete the thumbnails
1033 $this->repo
->quickPurgeBatch( $purgeList );
1034 # Clear out the thumbnail directory if empty
1035 $this->repo
->quickCleanDir( $dir );
1038 /** purgeDescription inherited */
1039 /** purgeEverything inherited */
1042 * @param int $limit Optional: Limit to number of results
1043 * @param int $start Optional: Timestamp, start from
1044 * @param int $end Optional: Timestamp, end at
1046 * @return OldLocalFile[]
1048 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1049 $dbr = $this->repo
->getReplicaDB();
1050 $tables = [ 'oldimage' ];
1051 $fields = OldLocalFile
::selectFields();
1052 $conds = $opts = $join_conds = [];
1053 $eq = $inc ?
'=' : '';
1054 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1057 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1061 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1065 $opts['LIMIT'] = $limit;
1068 // Search backwards for time > x queries
1069 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1070 $opts['ORDER BY'] = "oi_timestamp $order";
1071 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1073 // Avoid PHP 7.1 warning from passing $this by reference
1075 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1076 &$conds, &$opts, &$join_conds ] );
1078 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1081 foreach ( $res as $row ) {
1082 $r[] = $this->repo
->newFileFromRow( $row );
1085 if ( $order == 'ASC' ) {
1086 $r = array_reverse( $r ); // make sure it ends up descending
1093 * Returns the history of this file, line by line.
1094 * starts with current version, then old versions.
1095 * uses $this->historyLine to check which line to return:
1096 * 0 return line for current version
1097 * 1 query for old versions, return first one
1098 * 2, ... return next old version from above query
1101 public function nextHistoryLine() {
1102 # Polymorphic function name to distinguish foreign and local fetches
1103 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1105 $dbr = $this->repo
->getReplicaDB();
1107 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1108 $this->historyRes
= $dbr->select( 'image',
1111 "'' AS oi_archive_name",
1115 [ 'img_name' => $this->title
->getDBkey() ],
1119 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1120 $this->historyRes
= null;
1124 } elseif ( $this->historyLine
== 1 ) {
1125 $this->historyRes
= $dbr->select( 'oldimage', '*',
1126 [ 'oi_name' => $this->title
->getDBkey() ],
1128 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1131 $this->historyLine++
;
1133 return $dbr->fetchObject( $this->historyRes
);
1137 * Reset the history pointer to the first element of the history
1139 public function resetHistory() {
1140 $this->historyLine
= 0;
1142 if ( !is_null( $this->historyRes
) ) {
1143 $this->historyRes
= null;
1147 /** getHashPath inherited */
1148 /** getRel inherited */
1149 /** getUrlRel inherited */
1150 /** getArchiveRel inherited */
1151 /** getArchivePath inherited */
1152 /** getThumbPath inherited */
1153 /** getArchiveUrl inherited */
1154 /** getThumbUrl inherited */
1155 /** getArchiveVirtualUrl inherited */
1156 /** getThumbVirtualUrl inherited */
1157 /** isHashed inherited */
1160 * Upload a file and record it in the DB
1161 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1162 * @param string $comment Upload description
1163 * @param string $pageText Text to use for the new description page,
1164 * if a new description page is created
1165 * @param int|bool $flags Flags for publish()
1166 * @param array|bool $props File properties, if known. This can be used to
1167 * reduce the upload time when uploading virtual URLs for which the file
1168 * info is already known
1169 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1171 * @param User|null $user User object or null to use $wgUser
1172 * @param string[] $tags Change tags to add to the log entry and page revision.
1173 * (This doesn't check $user's permissions.)
1174 * @return Status On success, the value member contains the
1175 * archive name, or an empty string if it was a new file.
1177 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1178 $timestamp = false, $user = null, $tags = []
1182 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1183 return $this->readOnlyFatalStatus();
1186 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1188 if ( $this->repo
->isVirtualUrl( $srcPath )
1189 || FileBackend
::isStoragePath( $srcPath )
1191 $props = $this->repo
->getFileProps( $srcPath );
1193 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1194 $props = $mwProps->getPropsFromPath( $srcPath, true );
1199 $handler = MediaHandler
::getHandler( $props['mime'] );
1201 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1203 $options['headers'] = [];
1206 // Trim spaces on user supplied text
1207 $comment = trim( $comment );
1209 // Truncate nicely or the DB will do it for us
1210 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1211 $comment = $wgContLang->truncate( $comment, 255 );
1212 $this->lock(); // begin
1213 $status = $this->publish( $src, $flags, $options );
1215 if ( $status->successCount
>= 2 ) {
1216 // There will be a copy+(one of move,copy,store).
1217 // The first succeeding does not commit us to updating the DB
1218 // since it simply copied the current version to a timestamped file name.
1219 // It is only *preferable* to avoid leaving such files orphaned.
1220 // Once the second operation goes through, then the current version was
1221 // updated and we must therefore update the DB too.
1222 $oldver = $status->value
;
1223 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1224 $status->fatal( 'filenotfound', $srcPath );
1228 $this->unlock(); // done
1234 * Record a file upload in the upload log and the image table
1235 * @param string $oldver
1236 * @param string $desc
1237 * @param string $license
1238 * @param string $copyStatus
1239 * @param string $source
1240 * @param bool $watch
1241 * @param string|bool $timestamp
1242 * @param User|null $user User object or null to use $wgUser
1245 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1246 $watch = false, $timestamp = false, User
$user = null ) {
1252 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1254 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1259 $user->addWatch( $this->getTitle() );
1266 * Record a file upload in the upload log and the image table
1267 * @param string $oldver
1268 * @param string $comment
1269 * @param string $pageText
1270 * @param bool|array $props
1271 * @param string|bool $timestamp
1272 * @param null|User $user
1273 * @param string[] $tags
1276 function recordUpload2(
1277 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1279 if ( is_null( $user ) ) {
1284 $dbw = $this->repo
->getMasterDB();
1286 # Imports or such might force a certain timestamp; otherwise we generate
1287 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1288 if ( $timestamp === false ) {
1289 $timestamp = $dbw->timestamp();
1290 $allowTimeKludge = true;
1292 $allowTimeKludge = false;
1295 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1296 $props['description'] = $comment;
1297 $props['user'] = $user->getId();
1298 $props['user_text'] = $user->getName();
1299 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1300 $this->setProps( $props );
1302 # Fail now if the file isn't there
1303 if ( !$this->fileExists
) {
1304 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1309 $dbw->startAtomic( __METHOD__
);
1311 # Test to see if the row exists using INSERT IGNORE
1312 # This avoids race conditions by locking the row until the commit, and also
1313 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1314 $dbw->insert( 'image',
1316 'img_name' => $this->getName(),
1317 'img_size' => $this->size
,
1318 'img_width' => intval( $this->width
),
1319 'img_height' => intval( $this->height
),
1320 'img_bits' => $this->bits
,
1321 'img_media_type' => $this->media_type
,
1322 'img_major_mime' => $this->major_mime
,
1323 'img_minor_mime' => $this->minor_mime
,
1324 'img_timestamp' => $timestamp,
1325 'img_description' => $comment,
1326 'img_user' => $user->getId(),
1327 'img_user_text' => $user->getName(),
1328 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1329 'img_sha1' => $this->sha1
1335 $reupload = ( $dbw->affectedRows() == 0 );
1337 if ( $allowTimeKludge ) {
1338 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1339 $ltimestamp = $dbw->selectField(
1342 [ 'img_name' => $this->getName() ],
1344 [ 'LOCK IN SHARE MODE' ]
1346 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1347 # Avoid a timestamp that is not newer than the last version
1348 # TODO: the image/oldimage tables should be like page/revision with an ID field
1349 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1350 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1351 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1352 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1356 # (bug 34993) Note: $oldver can be empty here, if the previous
1357 # version of the file was broken. Allow registration of the new
1358 # version to continue anyway, because that's better than having
1359 # an image that's not fixable by user operations.
1360 # Collision, this is an update of a file
1361 # Insert previous contents into oldimage
1362 $dbw->insertSelect( 'oldimage', 'image',
1364 'oi_name' => 'img_name',
1365 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1366 'oi_size' => 'img_size',
1367 'oi_width' => 'img_width',
1368 'oi_height' => 'img_height',
1369 'oi_bits' => 'img_bits',
1370 'oi_timestamp' => 'img_timestamp',
1371 'oi_description' => 'img_description',
1372 'oi_user' => 'img_user',
1373 'oi_user_text' => 'img_user_text',
1374 'oi_metadata' => 'img_metadata',
1375 'oi_media_type' => 'img_media_type',
1376 'oi_major_mime' => 'img_major_mime',
1377 'oi_minor_mime' => 'img_minor_mime',
1378 'oi_sha1' => 'img_sha1'
1380 [ 'img_name' => $this->getName() ],
1384 # Update the current image row
1385 $dbw->update( 'image',
1387 'img_size' => $this->size
,
1388 'img_width' => intval( $this->width
),
1389 'img_height' => intval( $this->height
),
1390 'img_bits' => $this->bits
,
1391 'img_media_type' => $this->media_type
,
1392 'img_major_mime' => $this->major_mime
,
1393 'img_minor_mime' => $this->minor_mime
,
1394 'img_timestamp' => $timestamp,
1395 'img_description' => $comment,
1396 'img_user' => $user->getId(),
1397 'img_user_text' => $user->getName(),
1398 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1399 'img_sha1' => $this->sha1
1401 [ 'img_name' => $this->getName() ],
1406 $descTitle = $this->getTitle();
1407 $descId = $descTitle->getArticleID();
1408 $wikiPage = new WikiFilePage( $descTitle );
1409 $wikiPage->setFile( $this );
1411 // Add the log entry...
1412 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1413 $logEntry->setTimestamp( $this->timestamp
);
1414 $logEntry->setPerformer( $user );
1415 $logEntry->setComment( $comment );
1416 $logEntry->setTarget( $descTitle );
1417 // Allow people using the api to associate log entries with the upload.
1418 // Log has a timestamp, but sometimes different from upload timestamp.
1419 $logEntry->setParameters(
1421 'img_sha1' => $this->sha1
,
1422 'img_timestamp' => $timestamp,
1425 // Note we keep $logId around since during new image
1426 // creation, page doesn't exist yet, so log_page = 0
1427 // but we want it to point to the page we're making,
1428 // so we later modify the log entry.
1429 // For a similar reason, we avoid making an RC entry
1430 // now and wait until the page exists.
1431 $logId = $logEntry->insert();
1433 if ( $descTitle->exists() ) {
1434 // Use own context to get the action text in content language
1435 $formatter = LogFormatter
::newFromEntry( $logEntry );
1436 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1437 $editSummary = $formatter->getPlainActionText();
1439 $nullRevision = Revision
::newNullRevision(
1446 if ( $nullRevision ) {
1447 $nullRevision->insertOn( $dbw );
1449 'NewRevisionFromEditComplete',
1450 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1452 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1453 // Associate null revision id
1454 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1457 $newPageContent = null;
1459 // Make the description page and RC log entry post-commit
1460 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1463 # Defer purges, page creation, and link updates in case they error out.
1464 # The most important thing is that files and the DB registry stay synced.
1465 $dbw->endAtomic( __METHOD__
);
1467 # Do some cache purges after final commit so that:
1468 # a) Changes are more likely to be seen post-purge
1469 # b) They won't cause rollback of the log publish/update above
1470 DeferredUpdates
::addUpdate(
1471 new AutoCommitUpdate(
1475 $reupload, $wikiPage, $newPageContent, $comment, $user,
1476 $logEntry, $logId, $descId, $tags
1478 # Update memcache after the commit
1479 $this->invalidateCache();
1481 $updateLogPage = false;
1482 if ( $newPageContent ) {
1483 # New file page; create the description page.
1484 # There's already a log entry, so don't make a second RC entry
1485 # CDN and file cache for the description page are purged by doEditContent.
1486 $status = $wikiPage->doEditContent(
1489 EDIT_NEW | EDIT_SUPPRESS_RC
,
1494 if ( isset( $status->value
['revision'] ) ) {
1495 /** @var $rev Revision */
1496 $rev = $status->value
['revision'];
1497 // Associate new page revision id
1498 $logEntry->setAssociatedRevId( $rev->getId() );
1500 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1501 // which is triggered on $descTitle by doEditContent() above.
1502 if ( isset( $status->value
['revision'] ) ) {
1503 /** @var $rev Revision */
1504 $rev = $status->value
['revision'];
1505 $updateLogPage = $rev->getPage();
1508 # Existing file page: invalidate description page cache
1509 $wikiPage->getTitle()->invalidateCache();
1510 $wikiPage->getTitle()->purgeSquid();
1511 # Allow the new file version to be patrolled from the page footer
1512 Article
::purgePatrolFooterCache( $descId );
1515 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1516 # but setAssociatedRevId() wasn't called at that point yet...
1517 $logParams = $logEntry->getParameters();
1518 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1519 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1520 if ( $updateLogPage ) {
1521 # Also log page, in case where we just created it above
1522 $update['log_page'] = $updateLogPage;
1524 $this->getRepo()->getMasterDB()->update(
1527 [ 'log_id' => $logId ],
1530 $this->getRepo()->getMasterDB()->insert(
1533 'ls_field' => 'associated_rev_id',
1534 'ls_value' => $logEntry->getAssociatedRevId(),
1535 'ls_log_id' => $logId,
1540 # Add change tags, if any
1542 $logEntry->setTags( $tags );
1545 # Uploads can be patrolled
1546 $logEntry->setIsPatrollable( true );
1548 # Now that the log entry is up-to-date, make an RC entry.
1549 $logEntry->publish( $logId );
1551 # Run hook for other updates (typically more cache purging)
1552 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1555 # Delete old thumbnails
1556 $this->purgeThumbnails();
1557 # Remove the old file from the CDN cache
1558 DeferredUpdates
::addUpdate(
1559 new CdnCacheUpdate( [ $this->getUrl() ] ),
1560 DeferredUpdates
::PRESEND
1563 # Update backlink pages pointing to this title if created
1564 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1567 $this->prerenderThumbnails();
1570 DeferredUpdates
::PRESEND
1574 # This is a new file, so update the image count
1575 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1578 # Invalidate cache for all pages using this file
1579 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1585 * Move or copy a file to its public location. If a file exists at the
1586 * destination, move it to an archive. Returns a Status object with
1587 * the archive name in the "value" member on success.
1589 * The archive name should be passed through to recordUpload for database
1592 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1593 * @param int $flags A bitwise combination of:
1594 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1595 * @param array $options Optional additional parameters
1596 * @return Status On success, the value member contains the
1597 * archive name, or an empty string if it was a new file.
1599 function publish( $src, $flags = 0, array $options = [] ) {
1600 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1604 * Move or copy a file to a specified location. Returns a Status
1605 * object with the archive name in the "value" member on success.
1607 * The archive name should be passed through to recordUpload for database
1610 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1611 * @param string $dstRel Target relative path
1612 * @param int $flags A bitwise combination of:
1613 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1614 * @param array $options Optional additional parameters
1615 * @return Status On success, the value member contains the
1616 * archive name, or an empty string if it was a new file.
1618 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1619 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1621 $repo = $this->getRepo();
1622 if ( $repo->getReadOnlyReason() !== false ) {
1623 return $this->readOnlyFatalStatus();
1626 $this->lock(); // begin
1628 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1629 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1631 if ( $repo->hasSha1Storage() ) {
1632 $sha1 = $repo->isVirtualUrl( $srcPath )
1633 ?
$repo->getFileSha1( $srcPath )
1634 : FSFile
::getSha1Base36FromPath( $srcPath );
1635 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1636 $wrapperBackend = $repo->getBackend();
1637 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1638 $status = $repo->quickImport( $src, $dst );
1639 if ( $flags & File
::DELETE_SOURCE
) {
1643 if ( $this->exists() ) {
1644 $status->value
= $archiveName;
1647 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1648 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1650 if ( $status->value
== 'new' ) {
1651 $status->value
= '';
1653 $status->value
= $archiveName;
1657 $this->unlock(); // done
1662 /** getLinksTo inherited */
1663 /** getExifData inherited */
1664 /** isLocal inherited */
1665 /** wasDeleted inherited */
1668 * Move file to the new title
1670 * Move current, old version and all thumbnails
1671 * to the new filename. Old file is deleted.
1673 * Cache purging is done; checks for validity
1674 * and logging are caller's responsibility
1676 * @param Title $target New file name
1679 function move( $target ) {
1680 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1681 return $this->readOnlyFatalStatus();
1684 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1685 $batch = new LocalFileMoveBatch( $this, $target );
1687 $this->lock(); // begin
1688 $batch->addCurrent();
1689 $archiveNames = $batch->addOlds();
1690 $status = $batch->execute();
1691 $this->unlock(); // done
1693 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1695 // Purge the source and target files...
1696 $oldTitleFile = wfLocalFile( $this->title
);
1697 $newTitleFile = wfLocalFile( $target );
1698 // To avoid slow purges in the transaction, move them outside...
1699 DeferredUpdates
::addUpdate(
1700 new AutoCommitUpdate(
1701 $this->getRepo()->getMasterDB(),
1703 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1704 $oldTitleFile->purgeEverything();
1705 foreach ( $archiveNames as $archiveName ) {
1706 $oldTitleFile->purgeOldThumbnails( $archiveName );
1708 $newTitleFile->purgeEverything();
1711 DeferredUpdates
::PRESEND
1714 if ( $status->isOK() ) {
1715 // Now switch the object
1716 $this->title
= $target;
1717 // Force regeneration of the name and hashpath
1718 unset( $this->name
);
1719 unset( $this->hashPath
);
1726 * Delete all versions of the file.
1728 * Moves the files into an archive directory (or deletes them)
1729 * and removes the database rows.
1731 * Cache purging is done; logging is caller's responsibility.
1733 * @param string $reason
1734 * @param bool $suppress
1735 * @param User|null $user
1738 function delete( $reason, $suppress = false, $user = null ) {
1739 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1740 return $this->readOnlyFatalStatus();
1743 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1745 $this->lock(); // begin
1746 $batch->addCurrent();
1747 // Get old version relative paths
1748 $archiveNames = $batch->addOlds();
1749 $status = $batch->execute();
1750 $this->unlock(); // done
1752 if ( $status->isOK() ) {
1753 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1756 // To avoid slow purges in the transaction, move them outside...
1757 DeferredUpdates
::addUpdate(
1758 new AutoCommitUpdate(
1759 $this->getRepo()->getMasterDB(),
1761 function () use ( $archiveNames ) {
1762 $this->purgeEverything();
1763 foreach ( $archiveNames as $archiveName ) {
1764 $this->purgeOldThumbnails( $archiveName );
1768 DeferredUpdates
::PRESEND
1773 foreach ( $archiveNames as $archiveName ) {
1774 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1776 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1782 * Delete an old version of the file.
1784 * Moves the file into an archive directory (or deletes it)
1785 * and removes the database row.
1787 * Cache purging is done; logging is caller's responsibility.
1789 * @param string $archiveName
1790 * @param string $reason
1791 * @param bool $suppress
1792 * @param User|null $user
1793 * @throws MWException Exception on database or file store failure
1796 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1797 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1798 return $this->readOnlyFatalStatus();
1801 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1803 $this->lock(); // begin
1804 $batch->addOld( $archiveName );
1805 $status = $batch->execute();
1806 $this->unlock(); // done
1808 $this->purgeOldThumbnails( $archiveName );
1809 if ( $status->isOK() ) {
1810 $this->purgeDescription();
1813 DeferredUpdates
::addUpdate(
1814 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1815 DeferredUpdates
::PRESEND
1822 * Restore all or specified deleted revisions to the given file.
1823 * Permissions and logging are left to the caller.
1825 * May throw database exceptions on error.
1827 * @param array $versions Set of record ids of deleted items to restore,
1828 * or empty to restore all revisions.
1829 * @param bool $unsuppress
1832 function restore( $versions = [], $unsuppress = false ) {
1833 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1834 return $this->readOnlyFatalStatus();
1837 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1839 $this->lock(); // begin
1843 $batch->addIds( $versions );
1845 $status = $batch->execute();
1846 if ( $status->isGood() ) {
1847 $cleanupStatus = $batch->cleanup();
1848 $cleanupStatus->successCount
= 0;
1849 $cleanupStatus->failCount
= 0;
1850 $status->merge( $cleanupStatus );
1852 $this->unlock(); // done
1857 /** isMultipage inherited */
1858 /** pageCount inherited */
1859 /** scaleHeight inherited */
1860 /** getImageSize inherited */
1863 * Get the URL of the file description page.
1866 function getDescriptionUrl() {
1867 return $this->title
->getLocalURL();
1871 * Get the HTML text of the description page
1872 * This is not used by ImagePage for local files, since (among other things)
1873 * it skips the parser cache.
1875 * @param Language $lang What language to get description in (Optional)
1876 * @return bool|mixed
1878 function getDescriptionText( $lang = null ) {
1879 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1883 $content = $revision->getContent();
1887 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1889 return $pout->getText();
1893 * @param int $audience
1897 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1899 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1901 } elseif ( $audience == self
::FOR_THIS_USER
1902 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1906 return $this->description
;
1911 * @return bool|string
1913 function getTimestamp() {
1916 return $this->timestamp
;
1920 * @return bool|string
1922 public function getDescriptionTouched() {
1923 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1924 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1925 // need to differentiate between null (uninitialized) and false (failed to load).
1926 if ( $this->descriptionTouched
=== null ) {
1928 'page_namespace' => $this->title
->getNamespace(),
1929 'page_title' => $this->title
->getDBkey()
1931 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1932 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1935 return $this->descriptionTouched
;
1941 function getSha1() {
1943 // Initialise now if necessary
1944 if ( $this->sha1
== '' && $this->fileExists
) {
1945 $this->lock(); // begin
1947 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1948 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1949 $dbw = $this->repo
->getMasterDB();
1950 $dbw->update( 'image',
1951 [ 'img_sha1' => $this->sha1
],
1952 [ 'img_name' => $this->getName() ],
1954 $this->invalidateCache();
1957 $this->unlock(); // done
1964 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1966 function isCacheable() {
1969 // If extra data (metadata) was not loaded then it must have been large
1970 return $this->extraDataLoaded
1971 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1978 public function acquireFileLock() {
1979 return $this->getRepo()->getBackend()->lockFiles(
1980 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1988 public function releaseFileLock() {
1989 return $this->getRepo()->getBackend()->unlockFiles(
1990 [ $this->getPath() ], LockManager
::LOCK_EX
1995 * Start an atomic DB section and lock the image for update
1996 * or increments a reference counter if the lock is already held
1998 * This method should not be used outside of LocalFile/LocalFile*Batch
2000 * @throws LocalFileLockError Throws an error if the lock was not acquired
2001 * @return bool Whether the file lock owns/spawned the DB transaction
2003 public function lock() {
2004 if ( !$this->locked
) {
2005 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2007 $dbw = $this->repo
->getMasterDB();
2008 $makesTransaction = !$dbw->trxLevel();
2009 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2010 // Bug 54736: use simple lock to handle when the file does not exist.
2011 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2012 // Also, that would cause contention on INSERT of similarly named rows.
2013 $status = $this->acquireFileLock(); // represents all versions of the file
2014 if ( !$status->isGood() ) {
2015 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2016 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2018 throw new LocalFileLockError( $status );
2020 // Release the lock *after* commit to avoid row-level contention.
2021 // Make sure it triggers on rollback() as well as commit() (T132921).
2022 $dbw->onTransactionResolution(
2023 function () use ( $logger ) {
2024 $status = $this->releaseFileLock();
2025 if ( !$status->isGood() ) {
2026 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2031 // Callers might care if the SELECT snapshot is safely fresh
2032 $this->lockedOwnTrx
= $makesTransaction;
2037 return $this->lockedOwnTrx
;
2041 * Decrement the lock reference count and end the atomic section if it reaches zero
2043 * This method should not be used outside of LocalFile/LocalFile*Batch
2045 * The commit and loc release will happen when no atomic sections are active, which
2046 * may happen immediately or at some point after calling this
2048 public function unlock() {
2049 if ( $this->locked
) {
2051 if ( !$this->locked
) {
2052 $dbw = $this->repo
->getMasterDB();
2053 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2054 $this->lockedOwnTrx
= false;
2062 protected function readOnlyFatalStatus() {
2063 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2064 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2068 * Clean up any dangling locks
2070 function __destruct() {
2073 } // LocalFile class
2075 # ------------------------------------------------------------------------------
2078 * Helper class for file deletion
2079 * @ingroup FileAbstraction
2081 class LocalFileDeleteBatch
{
2082 /** @var LocalFile */
2089 private $srcRels = [];
2092 private $archiveUrls = [];
2094 /** @var array Items to be processed in the deletion batch */
2095 private $deletionBatch;
2097 /** @var bool Whether to suppress all suppressable fields when deleting */
2108 * @param string $reason
2109 * @param bool $suppress
2110 * @param User|null $user
2112 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2113 $this->file
= $file;
2114 $this->reason
= $reason;
2115 $this->suppress
= $suppress;
2117 $this->user
= $user;
2120 $this->user
= $wgUser;
2122 $this->status
= $file->repo
->newGood();
2125 public function addCurrent() {
2126 $this->srcRels
['.'] = $this->file
->getRel();
2130 * @param string $oldName
2132 public function addOld( $oldName ) {
2133 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2134 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2138 * Add the old versions of the image to the batch
2139 * @return array List of archive names from old versions
2141 public function addOlds() {
2144 $dbw = $this->file
->repo
->getMasterDB();
2145 $result = $dbw->select( 'oldimage',
2146 [ 'oi_archive_name' ],
2147 [ 'oi_name' => $this->file
->getName() ],
2151 foreach ( $result as $row ) {
2152 $this->addOld( $row->oi_archive_name
);
2153 $archiveNames[] = $row->oi_archive_name
;
2156 return $archiveNames;
2162 protected function getOldRels() {
2163 if ( !isset( $this->srcRels
['.'] ) ) {
2164 $oldRels =& $this->srcRels
;
2165 $deleteCurrent = false;
2167 $oldRels = $this->srcRels
;
2168 unset( $oldRels['.'] );
2169 $deleteCurrent = true;
2172 return [ $oldRels, $deleteCurrent ];
2178 protected function getHashes() {
2180 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2182 if ( $deleteCurrent ) {
2183 $hashes['.'] = $this->file
->getSha1();
2186 if ( count( $oldRels ) ) {
2187 $dbw = $this->file
->repo
->getMasterDB();
2188 $res = $dbw->select(
2190 [ 'oi_archive_name', 'oi_sha1' ],
2191 [ 'oi_archive_name' => array_keys( $oldRels ),
2192 'oi_name' => $this->file
->getName() ], // performance
2196 foreach ( $res as $row ) {
2197 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2198 // Get the hash from the file
2199 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2200 $props = $this->file
->repo
->getFileProps( $oldUrl );
2202 if ( $props['fileExists'] ) {
2203 // Upgrade the oldimage row
2204 $dbw->update( 'oldimage',
2205 [ 'oi_sha1' => $props['sha1'] ],
2206 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2208 $hashes[$row->oi_archive_name
] = $props['sha1'];
2210 $hashes[$row->oi_archive_name
] = false;
2213 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2218 $missing = array_diff_key( $this->srcRels
, $hashes );
2220 foreach ( $missing as $name => $rel ) {
2221 $this->status
->error( 'filedelete-old-unregistered', $name );
2224 foreach ( $hashes as $name => $hash ) {
2226 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2227 unset( $hashes[$name] );
2234 protected function doDBInserts() {
2236 $dbw = $this->file
->repo
->getMasterDB();
2237 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2238 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2239 $encReason = $dbw->addQuotes( $this->reason
);
2240 $encGroup = $dbw->addQuotes( 'deleted' );
2241 $ext = $this->file
->getExtension();
2242 $dotExt = $ext === '' ?
'' : ".$ext";
2243 $encExt = $dbw->addQuotes( $dotExt );
2244 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2246 // Bitfields to further suppress the content
2247 if ( $this->suppress
) {
2248 $bitfield = Revision
::SUPPRESSED_ALL
;
2250 $bitfield = 'oi_deleted';
2253 if ( $deleteCurrent ) {
2258 'fa_storage_group' => $encGroup,
2259 'fa_storage_key' => $dbw->conditional(
2260 [ 'img_sha1' => '' ],
2261 $dbw->addQuotes( '' ),
2262 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2264 'fa_deleted_user' => $encUserId,
2265 'fa_deleted_timestamp' => $encTimestamp,
2266 'fa_deleted_reason' => $encReason,
2267 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2268 'fa_name' => 'img_name',
2269 'fa_archive_name' => 'NULL',
2270 'fa_size' => 'img_size',
2271 'fa_width' => 'img_width',
2272 'fa_height' => 'img_height',
2273 'fa_metadata' => 'img_metadata',
2274 'fa_bits' => 'img_bits',
2275 'fa_media_type' => 'img_media_type',
2276 'fa_major_mime' => 'img_major_mime',
2277 'fa_minor_mime' => 'img_minor_mime',
2278 'fa_description' => 'img_description',
2279 'fa_user' => 'img_user',
2280 'fa_user_text' => 'img_user_text',
2281 'fa_timestamp' => 'img_timestamp',
2282 'fa_sha1' => 'img_sha1'
2284 [ 'img_name' => $this->file
->getName() ],
2289 if ( count( $oldRels ) ) {
2290 $res = $dbw->select(
2292 OldLocalFile
::selectFields(),
2294 'oi_name' => $this->file
->getName(),
2295 'oi_archive_name' => array_keys( $oldRels )
2301 foreach ( $res as $row ) {
2303 // Deletion-specific fields
2304 'fa_storage_group' => 'deleted',
2305 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2307 : "{$row->oi_sha1}{$dotExt}",
2308 'fa_deleted_user' => $this->user
->getId(),
2309 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2310 'fa_deleted_reason' => $this->reason
,
2311 // Counterpart fields
2312 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2313 'fa_name' => $row->oi_name
,
2314 'fa_archive_name' => $row->oi_archive_name
,
2315 'fa_size' => $row->oi_size
,
2316 'fa_width' => $row->oi_width
,
2317 'fa_height' => $row->oi_height
,
2318 'fa_metadata' => $row->oi_metadata
,
2319 'fa_bits' => $row->oi_bits
,
2320 'fa_media_type' => $row->oi_media_type
,
2321 'fa_major_mime' => $row->oi_major_mime
,
2322 'fa_minor_mime' => $row->oi_minor_mime
,
2323 'fa_description' => $row->oi_description
,
2324 'fa_user' => $row->oi_user
,
2325 'fa_user_text' => $row->oi_user_text
,
2326 'fa_timestamp' => $row->oi_timestamp
,
2327 'fa_sha1' => $row->oi_sha1
2331 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2335 function doDBDeletes() {
2336 $dbw = $this->file
->repo
->getMasterDB();
2337 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2339 if ( count( $oldRels ) ) {
2340 $dbw->delete( 'oldimage',
2342 'oi_name' => $this->file
->getName(),
2343 'oi_archive_name' => array_keys( $oldRels )
2347 if ( $deleteCurrent ) {
2348 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2353 * Run the transaction
2356 public function execute() {
2357 $repo = $this->file
->getRepo();
2358 $this->file
->lock();
2360 // Prepare deletion batch
2361 $hashes = $this->getHashes();
2362 $this->deletionBatch
= [];
2363 $ext = $this->file
->getExtension();
2364 $dotExt = $ext === '' ?
'' : ".$ext";
2366 foreach ( $this->srcRels
as $name => $srcRel ) {
2367 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2368 if ( isset( $hashes[$name] ) ) {
2369 $hash = $hashes[$name];
2370 $key = $hash . $dotExt;
2371 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2372 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2376 if ( !$repo->hasSha1Storage() ) {
2377 // Removes non-existent file from the batch, so we don't get errors.
2378 // This also handles files in the 'deleted' zone deleted via revision deletion.
2379 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2380 if ( !$checkStatus->isGood() ) {
2381 $this->status
->merge( $checkStatus );
2382 return $this->status
;
2384 $this->deletionBatch
= $checkStatus->value
;
2386 // Execute the file deletion batch
2387 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2388 if ( !$status->isGood() ) {
2389 $this->status
->merge( $status );
2393 if ( !$this->status
->isOK() ) {
2394 // Critical file deletion error; abort
2395 $this->file
->unlock();
2397 return $this->status
;
2400 // Copy the image/oldimage rows to filearchive
2401 $this->doDBInserts();
2402 // Delete image/oldimage rows
2403 $this->doDBDeletes();
2405 // Commit and return
2406 $this->file
->unlock();
2408 return $this->status
;
2412 * Removes non-existent files from a deletion batch.
2413 * @param array $batch
2416 protected function removeNonexistentFiles( $batch ) {
2417 $files = $newBatch = [];
2419 foreach ( $batch as $batchItem ) {
2420 list( $src, ) = $batchItem;
2421 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2424 $result = $this->file
->repo
->fileExistsBatch( $files );
2425 if ( in_array( null, $result, true ) ) {
2426 return Status
::newFatal( 'backend-fail-internal',
2427 $this->file
->repo
->getBackend()->getName() );
2430 foreach ( $batch as $batchItem ) {
2431 if ( $result[$batchItem[0]] ) {
2432 $newBatch[] = $batchItem;
2436 return Status
::newGood( $newBatch );
2440 # ------------------------------------------------------------------------------
2443 * Helper class for file undeletion
2444 * @ingroup FileAbstraction
2446 class LocalFileRestoreBatch
{
2447 /** @var LocalFile */
2450 /** @var array List of file IDs to restore */
2451 private $cleanupBatch;
2453 /** @var array List of file IDs to restore */
2456 /** @var bool Add all revisions of the file */
2459 /** @var bool Whether to remove all settings for suppressed fields */
2460 private $unsuppress = false;
2464 * @param bool $unsuppress
2466 function __construct( File
$file, $unsuppress = false ) {
2467 $this->file
= $file;
2468 $this->cleanupBatch
= $this->ids
= [];
2470 $this->unsuppress
= $unsuppress;
2477 public function addId( $fa_id ) {
2478 $this->ids
[] = $fa_id;
2482 * Add a whole lot of files by ID
2485 public function addIds( $ids ) {
2486 $this->ids
= array_merge( $this->ids
, $ids );
2490 * Add all revisions of the file
2492 public function addAll() {
2497 * Run the transaction, except the cleanup batch.
2498 * The cleanup batch should be run in a separate transaction, because it locks different
2499 * rows and there's no need to keep the image row locked while it's acquiring those locks
2500 * The caller may have its own transaction open.
2501 * So we save the batch and let the caller call cleanup()
2504 public function execute() {
2505 /** @var Language */
2508 $repo = $this->file
->getRepo();
2509 if ( !$this->all
&& !$this->ids
) {
2511 return $repo->newGood();
2514 $lockOwnsTrx = $this->file
->lock();
2516 $dbw = $this->file
->repo
->getMasterDB();
2517 $status = $this->file
->repo
->newGood();
2519 $exists = (bool)$dbw->selectField( 'image', '1',
2520 [ 'img_name' => $this->file
->getName() ],
2522 // The lock() should already prevents changes, but this still may need
2523 // to bypass any transaction snapshot. However, if lock() started the
2524 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2525 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2528 // Fetch all or selected archived revisions for the file,
2529 // sorted from the most recent to the oldest.
2530 $conditions = [ 'fa_name' => $this->file
->getName() ];
2532 if ( !$this->all
) {
2533 $conditions['fa_id'] = $this->ids
;
2536 $result = $dbw->select(
2538 ArchivedFile
::selectFields(),
2541 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2547 $insertCurrent = false;
2552 foreach ( $result as $row ) {
2553 $idsPresent[] = $row->fa_id
;
2555 if ( $row->fa_name
!= $this->file
->getName() ) {
2556 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2557 $status->failCount++
;
2561 if ( $row->fa_storage_key
== '' ) {
2562 // Revision was missing pre-deletion
2563 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2564 $status->failCount++
;
2568 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2569 $row->fa_storage_key
;
2570 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2572 if ( isset( $row->fa_sha1
) ) {
2573 $sha1 = $row->fa_sha1
;
2575 // old row, populate from key
2576 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2580 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2581 $sha1 = substr( $sha1, 1 );
2584 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2585 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2586 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2587 ||
is_null( $row->fa_metadata
)
2589 // Refresh our metadata
2590 // Required for a new current revision; nice for older ones too. :)
2591 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2594 'minor_mime' => $row->fa_minor_mime
,
2595 'major_mime' => $row->fa_major_mime
,
2596 'media_type' => $row->fa_media_type
,
2597 'metadata' => $row->fa_metadata
2601 if ( $first && !$exists ) {
2602 // This revision will be published as the new current version
2603 $destRel = $this->file
->getRel();
2605 'img_name' => $row->fa_name
,
2606 'img_size' => $row->fa_size
,
2607 'img_width' => $row->fa_width
,
2608 'img_height' => $row->fa_height
,
2609 'img_metadata' => $props['metadata'],
2610 'img_bits' => $row->fa_bits
,
2611 'img_media_type' => $props['media_type'],
2612 'img_major_mime' => $props['major_mime'],
2613 'img_minor_mime' => $props['minor_mime'],
2614 'img_description' => $row->fa_description
,
2615 'img_user' => $row->fa_user
,
2616 'img_user_text' => $row->fa_user_text
,
2617 'img_timestamp' => $row->fa_timestamp
,
2621 // The live (current) version cannot be hidden!
2622 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2623 $status->fatal( 'undeleterevdel' );
2624 $this->file
->unlock();
2628 $archiveName = $row->fa_archive_name
;
2630 if ( $archiveName == '' ) {
2631 // This was originally a current version; we
2632 // have to devise a new archive name for it.
2633 // Format is <timestamp of archiving>!<name>
2634 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2637 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2639 } while ( isset( $archiveNames[$archiveName] ) );
2642 $archiveNames[$archiveName] = true;
2643 $destRel = $this->file
->getArchiveRel( $archiveName );
2645 'oi_name' => $row->fa_name
,
2646 'oi_archive_name' => $archiveName,
2647 'oi_size' => $row->fa_size
,
2648 'oi_width' => $row->fa_width
,
2649 'oi_height' => $row->fa_height
,
2650 'oi_bits' => $row->fa_bits
,
2651 'oi_description' => $row->fa_description
,
2652 'oi_user' => $row->fa_user
,
2653 'oi_user_text' => $row->fa_user_text
,
2654 'oi_timestamp' => $row->fa_timestamp
,
2655 'oi_metadata' => $props['metadata'],
2656 'oi_media_type' => $props['media_type'],
2657 'oi_major_mime' => $props['major_mime'],
2658 'oi_minor_mime' => $props['minor_mime'],
2659 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2660 'oi_sha1' => $sha1 ];
2663 $deleteIds[] = $row->fa_id
;
2665 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2666 // private files can stay where they are
2667 $status->successCount++
;
2669 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2670 $this->cleanupBatch
[] = $row->fa_storage_key
;
2678 // Add a warning to the status object for missing IDs
2679 $missingIds = array_diff( $this->ids
, $idsPresent );
2681 foreach ( $missingIds as $id ) {
2682 $status->error( 'undelete-missing-filearchive', $id );
2685 if ( !$repo->hasSha1Storage() ) {
2686 // Remove missing files from batch, so we don't get errors when undeleting them
2687 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2688 if ( !$checkStatus->isGood() ) {
2689 $status->merge( $checkStatus );
2692 $storeBatch = $checkStatus->value
;
2694 // Run the store batch
2695 // Use the OVERWRITE_SAME flag to smooth over a common error
2696 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2697 $status->merge( $storeStatus );
2699 if ( !$status->isGood() ) {
2700 // Even if some files could be copied, fail entirely as that is the
2701 // easiest thing to do without data loss
2702 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2703 $status->setOK( false );
2704 $this->file
->unlock();
2710 // Run the DB updates
2711 // Because we have locked the image row, key conflicts should be rare.
2712 // If they do occur, we can roll back the transaction at this time with
2713 // no data loss, but leaving unregistered files scattered throughout the
2715 // This is not ideal, which is why it's important to lock the image row.
2716 if ( $insertCurrent ) {
2717 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2720 if ( $insertBatch ) {
2721 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2725 $dbw->delete( 'filearchive',
2726 [ 'fa_id' => $deleteIds ],
2730 // If store batch is empty (all files are missing), deletion is to be considered successful
2731 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2733 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2735 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2737 $this->file
->purgeEverything();
2739 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2740 $this->file
->purgeDescription();
2744 $this->file
->unlock();
2750 * Removes non-existent files from a store batch.
2751 * @param array $triplets
2754 protected function removeNonexistentFiles( $triplets ) {
2755 $files = $filteredTriplets = [];
2756 foreach ( $triplets as $file ) {
2757 $files[$file[0]] = $file[0];
2760 $result = $this->file
->repo
->fileExistsBatch( $files );
2761 if ( in_array( null, $result, true ) ) {
2762 return Status
::newFatal( 'backend-fail-internal',
2763 $this->file
->repo
->getBackend()->getName() );
2766 foreach ( $triplets as $file ) {
2767 if ( $result[$file[0]] ) {
2768 $filteredTriplets[] = $file;
2772 return Status
::newGood( $filteredTriplets );
2776 * Removes non-existent files from a cleanup batch.
2777 * @param array $batch
2780 protected function removeNonexistentFromCleanup( $batch ) {
2781 $files = $newBatch = [];
2782 $repo = $this->file
->repo
;
2784 foreach ( $batch as $file ) {
2785 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2786 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2789 $result = $repo->fileExistsBatch( $files );
2791 foreach ( $batch as $file ) {
2792 if ( $result[$file] ) {
2793 $newBatch[] = $file;
2801 * Delete unused files in the deleted zone.
2802 * This should be called from outside the transaction in which execute() was called.
2805 public function cleanup() {
2806 if ( !$this->cleanupBatch
) {
2807 return $this->file
->repo
->newGood();
2810 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2812 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2818 * Cleanup a failed batch. The batch was only partially successful, so
2819 * rollback by removing all items that were succesfully copied.
2821 * @param Status $storeStatus
2822 * @param array $storeBatch
2824 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2827 foreach ( $storeStatus->success
as $i => $success ) {
2828 // Check if this item of the batch was successfully copied
2830 // Item was successfully copied and needs to be removed again
2831 // Extract ($dstZone, $dstRel) from the batch
2832 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2835 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2839 # ------------------------------------------------------------------------------
2842 * Helper class for file movement
2843 * @ingroup FileAbstraction
2845 class LocalFileMoveBatch
{
2846 /** @var LocalFile */
2856 protected $oldCount;
2860 /** @var IDatabase */
2865 * @param Title $target
2867 function __construct( File
$file, Title
$target ) {
2868 $this->file
= $file;
2869 $this->target
= $target;
2870 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2871 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2872 $this->oldName
= $this->file
->getName();
2873 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2874 $this->oldRel
= $this->oldHash
. $this->oldName
;
2875 $this->newRel
= $this->newHash
. $this->newName
;
2876 $this->db
= $file->getRepo()->getMasterDB();
2880 * Add the current image to the batch
2882 public function addCurrent() {
2883 $this->cur
= [ $this->oldRel
, $this->newRel
];
2887 * Add the old versions of the image to the batch
2888 * @return array List of archive names from old versions
2890 public function addOlds() {
2891 $archiveBase = 'archive';
2893 $this->oldCount
= 0;
2896 $result = $this->db
->select( 'oldimage',
2897 [ 'oi_archive_name', 'oi_deleted' ],
2898 [ 'oi_name' => $this->oldName
],
2900 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2903 foreach ( $result as $row ) {
2904 $archiveNames[] = $row->oi_archive_name
;
2905 $oldName = $row->oi_archive_name
;
2906 $bits = explode( '!', $oldName, 2 );
2908 if ( count( $bits ) != 2 ) {
2909 wfDebug( "Old file name missing !: '$oldName' \n" );
2913 list( $timestamp, $filename ) = $bits;
2915 if ( $this->oldName
!= $filename ) {
2916 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2922 // Do we want to add those to oldCount?
2923 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2928 "{$archiveBase}/{$this->oldHash}{$oldName}",
2929 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2933 return $archiveNames;
2940 public function execute() {
2941 $repo = $this->file
->repo
;
2942 $status = $repo->newGood();
2943 $destFile = wfLocalFile( $this->target
);
2945 $this->file
->lock(); // begin
2946 $destFile->lock(); // quickly fail if destination is not available
2948 $triplets = $this->getMoveTriplets();
2949 $checkStatus = $this->removeNonexistentFiles( $triplets );
2950 if ( !$checkStatus->isGood() ) {
2951 $destFile->unlock();
2952 $this->file
->unlock();
2953 $status->merge( $checkStatus ); // couldn't talk to file backend
2956 $triplets = $checkStatus->value
;
2958 // Verify the file versions metadata in the DB.
2959 $statusDb = $this->verifyDBUpdates();
2960 if ( !$statusDb->isGood() ) {
2961 $destFile->unlock();
2962 $this->file
->unlock();
2963 $statusDb->setOK( false );
2968 if ( !$repo->hasSha1Storage() ) {
2969 // Copy the files into their new location.
2970 // If a prior process fataled copying or cleaning up files we tolerate any
2971 // of the existing files if they are identical to the ones being stored.
2972 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2973 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2974 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2975 if ( !$statusMove->isGood() ) {
2976 // Delete any files copied over (while the destination is still locked)
2977 $this->cleanupTarget( $triplets );
2978 $destFile->unlock();
2979 $this->file
->unlock();
2980 wfDebugLog( 'imagemove', "Error in moving files: "
2981 . $statusMove->getWikiText( false, false, 'en' ) );
2982 $statusMove->setOK( false );
2986 $status->merge( $statusMove );
2989 // Rename the file versions metadata in the DB.
2990 $this->doDBUpdates();
2992 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2993 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2995 $destFile->unlock();
2996 $this->file
->unlock(); // done
2998 // Everything went ok, remove the source files
2999 $this->cleanupSource( $triplets );
3001 $status->merge( $statusDb );
3007 * Verify the database updates and return a new Status indicating how
3008 * many rows would be updated.
3012 protected function verifyDBUpdates() {
3013 $repo = $this->file
->repo
;
3014 $status = $repo->newGood();
3017 $hasCurrent = $dbw->selectField(
3020 [ 'img_name' => $this->oldName
],
3024 $oldRowCount = $dbw->selectField(
3027 [ 'oi_name' => $this->oldName
],
3032 if ( $hasCurrent ) {
3033 $status->successCount++
;
3035 $status->failCount++
;
3037 $status->successCount +
= $oldRowCount;
3038 // Bug 34934: oldCount is based on files that actually exist.
3039 // There may be more DB rows than such files, in which case $affected
3040 // can be greater than $total. We use max() to avoid negatives here.
3041 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3042 if ( $status->failCount
) {
3043 $status->error( 'imageinvalidfilename' );
3050 * Do the database updates and return a new Status indicating how
3051 * many rows where updated.
3053 protected function doDBUpdates() {
3056 // Update current image
3059 [ 'img_name' => $this->newName
],
3060 [ 'img_name' => $this->oldName
],
3063 // Update old images
3067 'oi_name' => $this->newName
,
3068 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3069 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3071 [ 'oi_name' => $this->oldName
],
3077 * Generate triplets for FileRepo::storeBatch().
3080 protected function getMoveTriplets() {
3081 $moves = array_merge( [ $this->cur
], $this->olds
);
3082 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3084 foreach ( $moves as $move ) {
3085 // $move: (oldRelativePath, newRelativePath)
3086 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3087 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3090 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3098 * Removes non-existent files from move batch.
3099 * @param array $triplets
3102 protected function removeNonexistentFiles( $triplets ) {
3105 foreach ( $triplets as $file ) {
3106 $files[$file[0]] = $file[0];
3109 $result = $this->file
->repo
->fileExistsBatch( $files );
3110 if ( in_array( null, $result, true ) ) {
3111 return Status
::newFatal( 'backend-fail-internal',
3112 $this->file
->repo
->getBackend()->getName() );
3115 $filteredTriplets = [];
3116 foreach ( $triplets as $file ) {
3117 if ( $result[$file[0]] ) {
3118 $filteredTriplets[] = $file;
3120 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3124 return Status
::newGood( $filteredTriplets );
3128 * Cleanup a partially moved array of triplets by deleting the target
3129 * files. Called if something went wrong half way.
3130 * @param array $triplets
3132 protected function cleanupTarget( $triplets ) {
3133 // Create dest pairs from the triplets
3135 foreach ( $triplets as $triplet ) {
3136 // $triplet: (old source virtual URL, dst zone, dest rel)
3137 $pairs[] = [ $triplet[1], $triplet[2] ];
3140 $this->file
->repo
->cleanupBatch( $pairs );
3144 * Cleanup a fully moved array of triplets by deleting the source files.
3145 * Called at the end of the move process if everything else went ok.
3146 * @param array $triplets
3148 protected function cleanupSource( $triplets ) {
3149 // Create source file names from the triplets
3151 foreach ( $triplets as $triplet ) {
3152 $files[] = $triplet[0];
3155 $this->file
->repo
->cleanupBatch( $files );
3159 class LocalFileLockError
extends ErrorPageError
{
3160 public function __construct( Status
$status ) {
3161 parent
::__construct(
3163 $status->getMessage()
3167 public function report() {
3169 $wgOut->setStatusCode( 429 );