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 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1074 &$conds, &$opts, &$join_conds ] );
1076 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1079 foreach ( $res as $row ) {
1080 $r[] = $this->repo
->newFileFromRow( $row );
1083 if ( $order == 'ASC' ) {
1084 $r = array_reverse( $r ); // make sure it ends up descending
1091 * Returns the history of this file, line by line.
1092 * starts with current version, then old versions.
1093 * uses $this->historyLine to check which line to return:
1094 * 0 return line for current version
1095 * 1 query for old versions, return first one
1096 * 2, ... return next old version from above query
1099 public function nextHistoryLine() {
1100 # Polymorphic function name to distinguish foreign and local fetches
1101 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1103 $dbr = $this->repo
->getReplicaDB();
1105 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1106 $this->historyRes
= $dbr->select( 'image',
1109 "'' AS oi_archive_name",
1113 [ 'img_name' => $this->title
->getDBkey() ],
1117 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1118 $this->historyRes
= null;
1122 } elseif ( $this->historyLine
== 1 ) {
1123 $this->historyRes
= $dbr->select( 'oldimage', '*',
1124 [ 'oi_name' => $this->title
->getDBkey() ],
1126 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1129 $this->historyLine++
;
1131 return $dbr->fetchObject( $this->historyRes
);
1135 * Reset the history pointer to the first element of the history
1137 public function resetHistory() {
1138 $this->historyLine
= 0;
1140 if ( !is_null( $this->historyRes
) ) {
1141 $this->historyRes
= null;
1145 /** getHashPath inherited */
1146 /** getRel inherited */
1147 /** getUrlRel inherited */
1148 /** getArchiveRel inherited */
1149 /** getArchivePath inherited */
1150 /** getThumbPath inherited */
1151 /** getArchiveUrl inherited */
1152 /** getThumbUrl inherited */
1153 /** getArchiveVirtualUrl inherited */
1154 /** getThumbVirtualUrl inherited */
1155 /** isHashed inherited */
1158 * Upload a file and record it in the DB
1159 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1160 * @param string $comment Upload description
1161 * @param string $pageText Text to use for the new description page,
1162 * if a new description page is created
1163 * @param int|bool $flags Flags for publish()
1164 * @param array|bool $props File properties, if known. This can be used to
1165 * reduce the upload time when uploading virtual URLs for which the file
1166 * info is already known
1167 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1169 * @param User|null $user User object or null to use $wgUser
1170 * @param string[] $tags Change tags to add to the log entry and page revision.
1171 * (This doesn't check $user's permissions.)
1172 * @return Status On success, the value member contains the
1173 * archive name, or an empty string if it was a new file.
1175 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1176 $timestamp = false, $user = null, $tags = []
1180 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1181 return $this->readOnlyFatalStatus();
1184 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1186 if ( $this->repo
->isVirtualUrl( $srcPath )
1187 || FileBackend
::isStoragePath( $srcPath )
1189 $props = $this->repo
->getFileProps( $srcPath );
1191 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1192 $props = $mwProps->getPropsFromPath( $srcPath, true );
1197 $handler = MediaHandler
::getHandler( $props['mime'] );
1199 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1201 $options['headers'] = [];
1204 // Trim spaces on user supplied text
1205 $comment = trim( $comment );
1207 // Truncate nicely or the DB will do it for us
1208 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1209 $comment = $wgContLang->truncate( $comment, 255 );
1210 $this->lock(); // begin
1211 $status = $this->publish( $src, $flags, $options );
1213 if ( $status->successCount
>= 2 ) {
1214 // There will be a copy+(one of move,copy,store).
1215 // The first succeeding does not commit us to updating the DB
1216 // since it simply copied the current version to a timestamped file name.
1217 // It is only *preferable* to avoid leaving such files orphaned.
1218 // Once the second operation goes through, then the current version was
1219 // updated and we must therefore update the DB too.
1220 $oldver = $status->value
;
1221 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1222 $status->fatal( 'filenotfound', $srcPath );
1226 $this->unlock(); // done
1232 * Record a file upload in the upload log and the image table
1233 * @param string $oldver
1234 * @param string $desc
1235 * @param string $license
1236 * @param string $copyStatus
1237 * @param string $source
1238 * @param bool $watch
1239 * @param string|bool $timestamp
1240 * @param User|null $user User object or null to use $wgUser
1243 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1244 $watch = false, $timestamp = false, User
$user = null ) {
1250 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1252 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1257 $user->addWatch( $this->getTitle() );
1264 * Record a file upload in the upload log and the image table
1265 * @param string $oldver
1266 * @param string $comment
1267 * @param string $pageText
1268 * @param bool|array $props
1269 * @param string|bool $timestamp
1270 * @param null|User $user
1271 * @param string[] $tags
1274 function recordUpload2(
1275 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1277 if ( is_null( $user ) ) {
1282 $dbw = $this->repo
->getMasterDB();
1284 # Imports or such might force a certain timestamp; otherwise we generate
1285 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1286 if ( $timestamp === false ) {
1287 $timestamp = $dbw->timestamp();
1288 $allowTimeKludge = true;
1290 $allowTimeKludge = false;
1293 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1294 $props['description'] = $comment;
1295 $props['user'] = $user->getId();
1296 $props['user_text'] = $user->getName();
1297 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1298 $this->setProps( $props );
1300 # Fail now if the file isn't there
1301 if ( !$this->fileExists
) {
1302 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1307 $dbw->startAtomic( __METHOD__
);
1309 # Test to see if the row exists using INSERT IGNORE
1310 # This avoids race conditions by locking the row until the commit, and also
1311 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1312 $dbw->insert( 'image',
1314 'img_name' => $this->getName(),
1315 'img_size' => $this->size
,
1316 'img_width' => intval( $this->width
),
1317 'img_height' => intval( $this->height
),
1318 'img_bits' => $this->bits
,
1319 'img_media_type' => $this->media_type
,
1320 'img_major_mime' => $this->major_mime
,
1321 'img_minor_mime' => $this->minor_mime
,
1322 'img_timestamp' => $timestamp,
1323 'img_description' => $comment,
1324 'img_user' => $user->getId(),
1325 'img_user_text' => $user->getName(),
1326 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1327 'img_sha1' => $this->sha1
1333 $reupload = ( $dbw->affectedRows() == 0 );
1335 if ( $allowTimeKludge ) {
1336 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1337 $ltimestamp = $dbw->selectField(
1340 [ 'img_name' => $this->getName() ],
1342 [ 'LOCK IN SHARE MODE' ]
1344 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1345 # Avoid a timestamp that is not newer than the last version
1346 # TODO: the image/oldimage tables should be like page/revision with an ID field
1347 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1348 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1349 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1350 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1354 # (bug 34993) Note: $oldver can be empty here, if the previous
1355 # version of the file was broken. Allow registration of the new
1356 # version to continue anyway, because that's better than having
1357 # an image that's not fixable by user operations.
1358 # Collision, this is an update of a file
1359 # Insert previous contents into oldimage
1360 $dbw->insertSelect( 'oldimage', 'image',
1362 'oi_name' => 'img_name',
1363 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1364 'oi_size' => 'img_size',
1365 'oi_width' => 'img_width',
1366 'oi_height' => 'img_height',
1367 'oi_bits' => 'img_bits',
1368 'oi_timestamp' => 'img_timestamp',
1369 'oi_description' => 'img_description',
1370 'oi_user' => 'img_user',
1371 'oi_user_text' => 'img_user_text',
1372 'oi_metadata' => 'img_metadata',
1373 'oi_media_type' => 'img_media_type',
1374 'oi_major_mime' => 'img_major_mime',
1375 'oi_minor_mime' => 'img_minor_mime',
1376 'oi_sha1' => 'img_sha1'
1378 [ 'img_name' => $this->getName() ],
1382 # Update the current image row
1383 $dbw->update( 'image',
1385 'img_size' => $this->size
,
1386 'img_width' => intval( $this->width
),
1387 'img_height' => intval( $this->height
),
1388 'img_bits' => $this->bits
,
1389 'img_media_type' => $this->media_type
,
1390 'img_major_mime' => $this->major_mime
,
1391 'img_minor_mime' => $this->minor_mime
,
1392 'img_timestamp' => $timestamp,
1393 'img_description' => $comment,
1394 'img_user' => $user->getId(),
1395 'img_user_text' => $user->getName(),
1396 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1397 'img_sha1' => $this->sha1
1399 [ 'img_name' => $this->getName() ],
1404 $descTitle = $this->getTitle();
1405 $descId = $descTitle->getArticleID();
1406 $wikiPage = new WikiFilePage( $descTitle );
1407 $wikiPage->setFile( $this );
1409 // Add the log entry...
1410 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1411 $logEntry->setTimestamp( $this->timestamp
);
1412 $logEntry->setPerformer( $user );
1413 $logEntry->setComment( $comment );
1414 $logEntry->setTarget( $descTitle );
1415 // Allow people using the api to associate log entries with the upload.
1416 // Log has a timestamp, but sometimes different from upload timestamp.
1417 $logEntry->setParameters(
1419 'img_sha1' => $this->sha1
,
1420 'img_timestamp' => $timestamp,
1423 // Note we keep $logId around since during new image
1424 // creation, page doesn't exist yet, so log_page = 0
1425 // but we want it to point to the page we're making,
1426 // so we later modify the log entry.
1427 // For a similar reason, we avoid making an RC entry
1428 // now and wait until the page exists.
1429 $logId = $logEntry->insert();
1431 if ( $descTitle->exists() ) {
1432 // Use own context to get the action text in content language
1433 $formatter = LogFormatter
::newFromEntry( $logEntry );
1434 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1435 $editSummary = $formatter->getPlainActionText();
1437 $nullRevision = Revision
::newNullRevision(
1444 if ( $nullRevision ) {
1445 $nullRevision->insertOn( $dbw );
1447 'NewRevisionFromEditComplete',
1448 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1450 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1451 // Associate null revision id
1452 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1455 $newPageContent = null;
1457 // Make the description page and RC log entry post-commit
1458 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1461 # Defer purges, page creation, and link updates in case they error out.
1462 # The most important thing is that files and the DB registry stay synced.
1463 $dbw->endAtomic( __METHOD__
);
1465 # Do some cache purges after final commit so that:
1466 # a) Changes are more likely to be seen post-purge
1467 # b) They won't cause rollback of the log publish/update above
1468 DeferredUpdates
::addUpdate(
1469 new AutoCommitUpdate(
1473 $reupload, $wikiPage, $newPageContent, $comment, $user,
1474 $logEntry, $logId, $descId, $tags
1476 # Update memcache after the commit
1477 $this->invalidateCache();
1479 $updateLogPage = false;
1480 if ( $newPageContent ) {
1481 # New file page; create the description page.
1482 # There's already a log entry, so don't make a second RC entry
1483 # CDN and file cache for the description page are purged by doEditContent.
1484 $status = $wikiPage->doEditContent(
1487 EDIT_NEW | EDIT_SUPPRESS_RC
,
1492 if ( isset( $status->value
['revision'] ) ) {
1493 /** @var $rev Revision */
1494 $rev = $status->value
['revision'];
1495 // Associate new page revision id
1496 $logEntry->setAssociatedRevId( $rev->getId() );
1498 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1499 // which is triggered on $descTitle by doEditContent() above.
1500 if ( isset( $status->value
['revision'] ) ) {
1501 /** @var $rev Revision */
1502 $rev = $status->value
['revision'];
1503 $updateLogPage = $rev->getPage();
1506 # Existing file page: invalidate description page cache
1507 $wikiPage->getTitle()->invalidateCache();
1508 $wikiPage->getTitle()->purgeSquid();
1509 # Allow the new file version to be patrolled from the page footer
1510 Article
::purgePatrolFooterCache( $descId );
1513 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1514 # but setAssociatedRevId() wasn't called at that point yet...
1515 $logParams = $logEntry->getParameters();
1516 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1517 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1518 if ( $updateLogPage ) {
1519 # Also log page, in case where we just created it above
1520 $update['log_page'] = $updateLogPage;
1522 $this->getRepo()->getMasterDB()->update(
1525 [ 'log_id' => $logId ],
1528 $this->getRepo()->getMasterDB()->insert(
1531 'ls_field' => 'associated_rev_id',
1532 'ls_value' => $logEntry->getAssociatedRevId(),
1533 'ls_log_id' => $logId,
1538 # Add change tags, if any
1540 $logEntry->setTags( $tags );
1543 # Uploads can be patrolled
1544 $logEntry->setIsPatrollable( true );
1546 # Now that the log entry is up-to-date, make an RC entry.
1547 $logEntry->publish( $logId );
1549 # Run hook for other updates (typically more cache purging)
1550 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1553 # Delete old thumbnails
1554 $this->purgeThumbnails();
1555 # Remove the old file from the CDN cache
1556 DeferredUpdates
::addUpdate(
1557 new CdnCacheUpdate( [ $this->getUrl() ] ),
1558 DeferredUpdates
::PRESEND
1561 # Update backlink pages pointing to this title if created
1562 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1565 $this->prerenderThumbnails();
1568 DeferredUpdates
::PRESEND
1572 # This is a new file, so update the image count
1573 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1576 # Invalidate cache for all pages using this file
1577 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1583 * Move or copy a file to its public location. If a file exists at the
1584 * destination, move it to an archive. Returns a Status object with
1585 * the archive name in the "value" member on success.
1587 * The archive name should be passed through to recordUpload for database
1590 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1591 * @param int $flags A bitwise combination of:
1592 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1593 * @param array $options Optional additional parameters
1594 * @return Status On success, the value member contains the
1595 * archive name, or an empty string if it was a new file.
1597 function publish( $src, $flags = 0, array $options = [] ) {
1598 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1602 * Move or copy a file to a specified location. Returns a Status
1603 * object with the archive name in the "value" member on success.
1605 * The archive name should be passed through to recordUpload for database
1608 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1609 * @param string $dstRel Target relative path
1610 * @param int $flags A bitwise combination of:
1611 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1612 * @param array $options Optional additional parameters
1613 * @return Status On success, the value member contains the
1614 * archive name, or an empty string if it was a new file.
1616 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1617 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1619 $repo = $this->getRepo();
1620 if ( $repo->getReadOnlyReason() !== false ) {
1621 return $this->readOnlyFatalStatus();
1624 $this->lock(); // begin
1626 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1627 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1629 if ( $repo->hasSha1Storage() ) {
1630 $sha1 = $repo->isVirtualUrl( $srcPath )
1631 ?
$repo->getFileSha1( $srcPath )
1632 : FSFile
::getSha1Base36FromPath( $srcPath );
1633 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1634 $wrapperBackend = $repo->getBackend();
1635 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1636 $status = $repo->quickImport( $src, $dst );
1637 if ( $flags & File
::DELETE_SOURCE
) {
1641 if ( $this->exists() ) {
1642 $status->value
= $archiveName;
1645 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1646 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1648 if ( $status->value
== 'new' ) {
1649 $status->value
= '';
1651 $status->value
= $archiveName;
1655 $this->unlock(); // done
1660 /** getLinksTo inherited */
1661 /** getExifData inherited */
1662 /** isLocal inherited */
1663 /** wasDeleted inherited */
1666 * Move file to the new title
1668 * Move current, old version and all thumbnails
1669 * to the new filename. Old file is deleted.
1671 * Cache purging is done; checks for validity
1672 * and logging are caller's responsibility
1674 * @param Title $target New file name
1677 function move( $target ) {
1678 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1679 return $this->readOnlyFatalStatus();
1682 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1683 $batch = new LocalFileMoveBatch( $this, $target );
1685 $this->lock(); // begin
1686 $batch->addCurrent();
1687 $archiveNames = $batch->addOlds();
1688 $status = $batch->execute();
1689 $this->unlock(); // done
1691 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1693 // Purge the source and target files...
1694 $oldTitleFile = wfLocalFile( $this->title
);
1695 $newTitleFile = wfLocalFile( $target );
1696 // To avoid slow purges in the transaction, move them outside...
1697 DeferredUpdates
::addUpdate(
1698 new AutoCommitUpdate(
1699 $this->getRepo()->getMasterDB(),
1701 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1702 $oldTitleFile->purgeEverything();
1703 foreach ( $archiveNames as $archiveName ) {
1704 $oldTitleFile->purgeOldThumbnails( $archiveName );
1706 $newTitleFile->purgeEverything();
1709 DeferredUpdates
::PRESEND
1712 if ( $status->isOK() ) {
1713 // Now switch the object
1714 $this->title
= $target;
1715 // Force regeneration of the name and hashpath
1716 unset( $this->name
);
1717 unset( $this->hashPath
);
1724 * Delete all versions of the file.
1726 * Moves the files into an archive directory (or deletes them)
1727 * and removes the database rows.
1729 * Cache purging is done; logging is caller's responsibility.
1731 * @param string $reason
1732 * @param bool $suppress
1733 * @param User|null $user
1736 function delete( $reason, $suppress = false, $user = null ) {
1737 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1738 return $this->readOnlyFatalStatus();
1741 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1743 $this->lock(); // begin
1744 $batch->addCurrent();
1745 // Get old version relative paths
1746 $archiveNames = $batch->addOlds();
1747 $status = $batch->execute();
1748 $this->unlock(); // done
1750 if ( $status->isOK() ) {
1751 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1754 // To avoid slow purges in the transaction, move them outside...
1755 DeferredUpdates
::addUpdate(
1756 new AutoCommitUpdate(
1757 $this->getRepo()->getMasterDB(),
1759 function () use ( $archiveNames ) {
1760 $this->purgeEverything();
1761 foreach ( $archiveNames as $archiveName ) {
1762 $this->purgeOldThumbnails( $archiveName );
1766 DeferredUpdates
::PRESEND
1771 foreach ( $archiveNames as $archiveName ) {
1772 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1774 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1780 * Delete an old version of the file.
1782 * Moves the file into an archive directory (or deletes it)
1783 * and removes the database row.
1785 * Cache purging is done; logging is caller's responsibility.
1787 * @param string $archiveName
1788 * @param string $reason
1789 * @param bool $suppress
1790 * @param User|null $user
1791 * @throws MWException Exception on database or file store failure
1794 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1795 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1796 return $this->readOnlyFatalStatus();
1799 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1801 $this->lock(); // begin
1802 $batch->addOld( $archiveName );
1803 $status = $batch->execute();
1804 $this->unlock(); // done
1806 $this->purgeOldThumbnails( $archiveName );
1807 if ( $status->isOK() ) {
1808 $this->purgeDescription();
1811 DeferredUpdates
::addUpdate(
1812 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1813 DeferredUpdates
::PRESEND
1820 * Restore all or specified deleted revisions to the given file.
1821 * Permissions and logging are left to the caller.
1823 * May throw database exceptions on error.
1825 * @param array $versions Set of record ids of deleted items to restore,
1826 * or empty to restore all revisions.
1827 * @param bool $unsuppress
1830 function restore( $versions = [], $unsuppress = false ) {
1831 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1832 return $this->readOnlyFatalStatus();
1835 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1837 $this->lock(); // begin
1841 $batch->addIds( $versions );
1843 $status = $batch->execute();
1844 if ( $status->isGood() ) {
1845 $cleanupStatus = $batch->cleanup();
1846 $cleanupStatus->successCount
= 0;
1847 $cleanupStatus->failCount
= 0;
1848 $status->merge( $cleanupStatus );
1850 $this->unlock(); // done
1855 /** isMultipage inherited */
1856 /** pageCount inherited */
1857 /** scaleHeight inherited */
1858 /** getImageSize inherited */
1861 * Get the URL of the file description page.
1864 function getDescriptionUrl() {
1865 return $this->title
->getLocalURL();
1869 * Get the HTML text of the description page
1870 * This is not used by ImagePage for local files, since (among other things)
1871 * it skips the parser cache.
1873 * @param Language $lang What language to get description in (Optional)
1874 * @return bool|mixed
1876 function getDescriptionText( $lang = null ) {
1877 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1881 $content = $revision->getContent();
1885 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1887 return $pout->getText();
1891 * @param int $audience
1895 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1897 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1899 } elseif ( $audience == self
::FOR_THIS_USER
1900 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1904 return $this->description
;
1909 * @return bool|string
1911 function getTimestamp() {
1914 return $this->timestamp
;
1918 * @return bool|string
1920 public function getDescriptionTouched() {
1921 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1922 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1923 // need to differentiate between null (uninitialized) and false (failed to load).
1924 if ( $this->descriptionTouched
=== null ) {
1926 'page_namespace' => $this->title
->getNamespace(),
1927 'page_title' => $this->title
->getDBkey()
1929 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1930 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1933 return $this->descriptionTouched
;
1939 function getSha1() {
1941 // Initialise now if necessary
1942 if ( $this->sha1
== '' && $this->fileExists
) {
1943 $this->lock(); // begin
1945 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1946 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1947 $dbw = $this->repo
->getMasterDB();
1948 $dbw->update( 'image',
1949 [ 'img_sha1' => $this->sha1
],
1950 [ 'img_name' => $this->getName() ],
1952 $this->invalidateCache();
1955 $this->unlock(); // done
1962 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1964 function isCacheable() {
1967 // If extra data (metadata) was not loaded then it must have been large
1968 return $this->extraDataLoaded
1969 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1976 public function acquireFileLock() {
1977 return $this->getRepo()->getBackend()->lockFiles(
1978 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1986 public function releaseFileLock() {
1987 return $this->getRepo()->getBackend()->unlockFiles(
1988 [ $this->getPath() ], LockManager
::LOCK_EX
1993 * Start an atomic DB section and lock the image for update
1994 * or increments a reference counter if the lock is already held
1996 * This method should not be used outside of LocalFile/LocalFile*Batch
1998 * @throws LocalFileLockError Throws an error if the lock was not acquired
1999 * @return bool Whether the file lock owns/spawned the DB transaction
2001 public function lock() {
2002 if ( !$this->locked
) {
2003 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2005 $dbw = $this->repo
->getMasterDB();
2006 $makesTransaction = !$dbw->trxLevel();
2007 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2008 // Bug 54736: use simple lock to handle when the file does not exist.
2009 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2010 // Also, that would cause contention on INSERT of similarly named rows.
2011 $status = $this->acquireFileLock(); // represents all versions of the file
2012 if ( !$status->isGood() ) {
2013 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2014 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2016 throw new LocalFileLockError( $status );
2018 // Release the lock *after* commit to avoid row-level contention.
2019 // Make sure it triggers on rollback() as well as commit() (T132921).
2020 $dbw->onTransactionResolution(
2021 function () use ( $logger ) {
2022 $status = $this->releaseFileLock();
2023 if ( !$status->isGood() ) {
2024 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2029 // Callers might care if the SELECT snapshot is safely fresh
2030 $this->lockedOwnTrx
= $makesTransaction;
2035 return $this->lockedOwnTrx
;
2039 * Decrement the lock reference count and end the atomic section if it reaches zero
2041 * This method should not be used outside of LocalFile/LocalFile*Batch
2043 * The commit and loc release will happen when no atomic sections are active, which
2044 * may happen immediately or at some point after calling this
2046 public function unlock() {
2047 if ( $this->locked
) {
2049 if ( !$this->locked
) {
2050 $dbw = $this->repo
->getMasterDB();
2051 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2052 $this->lockedOwnTrx
= false;
2060 protected function readOnlyFatalStatus() {
2061 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2062 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2066 * Clean up any dangling locks
2068 function __destruct() {
2071 } // LocalFile class
2073 # ------------------------------------------------------------------------------
2076 * Helper class for file deletion
2077 * @ingroup FileAbstraction
2079 class LocalFileDeleteBatch
{
2080 /** @var LocalFile */
2087 private $srcRels = [];
2090 private $archiveUrls = [];
2092 /** @var array Items to be processed in the deletion batch */
2093 private $deletionBatch;
2095 /** @var bool Whether to suppress all suppressable fields when deleting */
2106 * @param string $reason
2107 * @param bool $suppress
2108 * @param User|null $user
2110 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2111 $this->file
= $file;
2112 $this->reason
= $reason;
2113 $this->suppress
= $suppress;
2115 $this->user
= $user;
2118 $this->user
= $wgUser;
2120 $this->status
= $file->repo
->newGood();
2123 public function addCurrent() {
2124 $this->srcRels
['.'] = $this->file
->getRel();
2128 * @param string $oldName
2130 public function addOld( $oldName ) {
2131 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2132 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2136 * Add the old versions of the image to the batch
2137 * @return array List of archive names from old versions
2139 public function addOlds() {
2142 $dbw = $this->file
->repo
->getMasterDB();
2143 $result = $dbw->select( 'oldimage',
2144 [ 'oi_archive_name' ],
2145 [ 'oi_name' => $this->file
->getName() ],
2149 foreach ( $result as $row ) {
2150 $this->addOld( $row->oi_archive_name
);
2151 $archiveNames[] = $row->oi_archive_name
;
2154 return $archiveNames;
2160 protected function getOldRels() {
2161 if ( !isset( $this->srcRels
['.'] ) ) {
2162 $oldRels =& $this->srcRels
;
2163 $deleteCurrent = false;
2165 $oldRels = $this->srcRels
;
2166 unset( $oldRels['.'] );
2167 $deleteCurrent = true;
2170 return [ $oldRels, $deleteCurrent ];
2176 protected function getHashes() {
2178 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2180 if ( $deleteCurrent ) {
2181 $hashes['.'] = $this->file
->getSha1();
2184 if ( count( $oldRels ) ) {
2185 $dbw = $this->file
->repo
->getMasterDB();
2186 $res = $dbw->select(
2188 [ 'oi_archive_name', 'oi_sha1' ],
2189 [ 'oi_archive_name' => array_keys( $oldRels ),
2190 'oi_name' => $this->file
->getName() ], // performance
2194 foreach ( $res as $row ) {
2195 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2196 // Get the hash from the file
2197 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2198 $props = $this->file
->repo
->getFileProps( $oldUrl );
2200 if ( $props['fileExists'] ) {
2201 // Upgrade the oldimage row
2202 $dbw->update( 'oldimage',
2203 [ 'oi_sha1' => $props['sha1'] ],
2204 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2206 $hashes[$row->oi_archive_name
] = $props['sha1'];
2208 $hashes[$row->oi_archive_name
] = false;
2211 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2216 $missing = array_diff_key( $this->srcRels
, $hashes );
2218 foreach ( $missing as $name => $rel ) {
2219 $this->status
->error( 'filedelete-old-unregistered', $name );
2222 foreach ( $hashes as $name => $hash ) {
2224 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2225 unset( $hashes[$name] );
2232 protected function doDBInserts() {
2234 $dbw = $this->file
->repo
->getMasterDB();
2235 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2236 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2237 $encReason = $dbw->addQuotes( $this->reason
);
2238 $encGroup = $dbw->addQuotes( 'deleted' );
2239 $ext = $this->file
->getExtension();
2240 $dotExt = $ext === '' ?
'' : ".$ext";
2241 $encExt = $dbw->addQuotes( $dotExt );
2242 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2244 // Bitfields to further suppress the content
2245 if ( $this->suppress
) {
2246 $bitfield = Revision
::SUPPRESSED_ALL
;
2248 $bitfield = 'oi_deleted';
2251 if ( $deleteCurrent ) {
2256 'fa_storage_group' => $encGroup,
2257 'fa_storage_key' => $dbw->conditional(
2258 [ 'img_sha1' => '' ],
2259 $dbw->addQuotes( '' ),
2260 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2262 'fa_deleted_user' => $encUserId,
2263 'fa_deleted_timestamp' => $encTimestamp,
2264 'fa_deleted_reason' => $encReason,
2265 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2266 'fa_name' => 'img_name',
2267 'fa_archive_name' => 'NULL',
2268 'fa_size' => 'img_size',
2269 'fa_width' => 'img_width',
2270 'fa_height' => 'img_height',
2271 'fa_metadata' => 'img_metadata',
2272 'fa_bits' => 'img_bits',
2273 'fa_media_type' => 'img_media_type',
2274 'fa_major_mime' => 'img_major_mime',
2275 'fa_minor_mime' => 'img_minor_mime',
2276 'fa_description' => 'img_description',
2277 'fa_user' => 'img_user',
2278 'fa_user_text' => 'img_user_text',
2279 'fa_timestamp' => 'img_timestamp',
2280 'fa_sha1' => 'img_sha1'
2282 [ 'img_name' => $this->file
->getName() ],
2287 if ( count( $oldRels ) ) {
2288 $res = $dbw->select(
2290 OldLocalFile
::selectFields(),
2292 'oi_name' => $this->file
->getName(),
2293 'oi_archive_name' => array_keys( $oldRels )
2299 foreach ( $res as $row ) {
2301 // Deletion-specific fields
2302 'fa_storage_group' => 'deleted',
2303 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2305 : "{$row->oi_sha1}{$dotExt}",
2306 'fa_deleted_user' => $this->user
->getId(),
2307 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2308 'fa_deleted_reason' => $this->reason
,
2309 // Counterpart fields
2310 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2311 'fa_name' => $row->oi_name
,
2312 'fa_archive_name' => $row->oi_archive_name
,
2313 'fa_size' => $row->oi_size
,
2314 'fa_width' => $row->oi_width
,
2315 'fa_height' => $row->oi_height
,
2316 'fa_metadata' => $row->oi_metadata
,
2317 'fa_bits' => $row->oi_bits
,
2318 'fa_media_type' => $row->oi_media_type
,
2319 'fa_major_mime' => $row->oi_major_mime
,
2320 'fa_minor_mime' => $row->oi_minor_mime
,
2321 'fa_description' => $row->oi_description
,
2322 'fa_user' => $row->oi_user
,
2323 'fa_user_text' => $row->oi_user_text
,
2324 'fa_timestamp' => $row->oi_timestamp
,
2325 'fa_sha1' => $row->oi_sha1
2329 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2333 function doDBDeletes() {
2334 $dbw = $this->file
->repo
->getMasterDB();
2335 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2337 if ( count( $oldRels ) ) {
2338 $dbw->delete( 'oldimage',
2340 'oi_name' => $this->file
->getName(),
2341 'oi_archive_name' => array_keys( $oldRels )
2345 if ( $deleteCurrent ) {
2346 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2351 * Run the transaction
2354 public function execute() {
2355 $repo = $this->file
->getRepo();
2356 $this->file
->lock();
2358 // Prepare deletion batch
2359 $hashes = $this->getHashes();
2360 $this->deletionBatch
= [];
2361 $ext = $this->file
->getExtension();
2362 $dotExt = $ext === '' ?
'' : ".$ext";
2364 foreach ( $this->srcRels
as $name => $srcRel ) {
2365 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2366 if ( isset( $hashes[$name] ) ) {
2367 $hash = $hashes[$name];
2368 $key = $hash . $dotExt;
2369 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2370 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2374 if ( !$repo->hasSha1Storage() ) {
2375 // Removes non-existent file from the batch, so we don't get errors.
2376 // This also handles files in the 'deleted' zone deleted via revision deletion.
2377 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2378 if ( !$checkStatus->isGood() ) {
2379 $this->status
->merge( $checkStatus );
2380 return $this->status
;
2382 $this->deletionBatch
= $checkStatus->value
;
2384 // Execute the file deletion batch
2385 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2386 if ( !$status->isGood() ) {
2387 $this->status
->merge( $status );
2391 if ( !$this->status
->isOK() ) {
2392 // Critical file deletion error; abort
2393 $this->file
->unlock();
2395 return $this->status
;
2398 // Copy the image/oldimage rows to filearchive
2399 $this->doDBInserts();
2400 // Delete image/oldimage rows
2401 $this->doDBDeletes();
2403 // Commit and return
2404 $this->file
->unlock();
2406 return $this->status
;
2410 * Removes non-existent files from a deletion batch.
2411 * @param array $batch
2414 protected function removeNonexistentFiles( $batch ) {
2415 $files = $newBatch = [];
2417 foreach ( $batch as $batchItem ) {
2418 list( $src, ) = $batchItem;
2419 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2422 $result = $this->file
->repo
->fileExistsBatch( $files );
2423 if ( in_array( null, $result, true ) ) {
2424 return Status
::newFatal( 'backend-fail-internal',
2425 $this->file
->repo
->getBackend()->getName() );
2428 foreach ( $batch as $batchItem ) {
2429 if ( $result[$batchItem[0]] ) {
2430 $newBatch[] = $batchItem;
2434 return Status
::newGood( $newBatch );
2438 # ------------------------------------------------------------------------------
2441 * Helper class for file undeletion
2442 * @ingroup FileAbstraction
2444 class LocalFileRestoreBatch
{
2445 /** @var LocalFile */
2448 /** @var array List of file IDs to restore */
2449 private $cleanupBatch;
2451 /** @var array List of file IDs to restore */
2454 /** @var bool Add all revisions of the file */
2457 /** @var bool Whether to remove all settings for suppressed fields */
2458 private $unsuppress = false;
2462 * @param bool $unsuppress
2464 function __construct( File
$file, $unsuppress = false ) {
2465 $this->file
= $file;
2466 $this->cleanupBatch
= $this->ids
= [];
2468 $this->unsuppress
= $unsuppress;
2475 public function addId( $fa_id ) {
2476 $this->ids
[] = $fa_id;
2480 * Add a whole lot of files by ID
2483 public function addIds( $ids ) {
2484 $this->ids
= array_merge( $this->ids
, $ids );
2488 * Add all revisions of the file
2490 public function addAll() {
2495 * Run the transaction, except the cleanup batch.
2496 * The cleanup batch should be run in a separate transaction, because it locks different
2497 * rows and there's no need to keep the image row locked while it's acquiring those locks
2498 * The caller may have its own transaction open.
2499 * So we save the batch and let the caller call cleanup()
2502 public function execute() {
2503 /** @var Language */
2506 $repo = $this->file
->getRepo();
2507 if ( !$this->all
&& !$this->ids
) {
2509 return $repo->newGood();
2512 $lockOwnsTrx = $this->file
->lock();
2514 $dbw = $this->file
->repo
->getMasterDB();
2515 $status = $this->file
->repo
->newGood();
2517 $exists = (bool)$dbw->selectField( 'image', '1',
2518 [ 'img_name' => $this->file
->getName() ],
2520 // The lock() should already prevents changes, but this still may need
2521 // to bypass any transaction snapshot. However, if lock() started the
2522 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2523 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2526 // Fetch all or selected archived revisions for the file,
2527 // sorted from the most recent to the oldest.
2528 $conditions = [ 'fa_name' => $this->file
->getName() ];
2530 if ( !$this->all
) {
2531 $conditions['fa_id'] = $this->ids
;
2534 $result = $dbw->select(
2536 ArchivedFile
::selectFields(),
2539 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2545 $insertCurrent = false;
2550 foreach ( $result as $row ) {
2551 $idsPresent[] = $row->fa_id
;
2553 if ( $row->fa_name
!= $this->file
->getName() ) {
2554 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2555 $status->failCount++
;
2559 if ( $row->fa_storage_key
== '' ) {
2560 // Revision was missing pre-deletion
2561 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2562 $status->failCount++
;
2566 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2567 $row->fa_storage_key
;
2568 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2570 if ( isset( $row->fa_sha1
) ) {
2571 $sha1 = $row->fa_sha1
;
2573 // old row, populate from key
2574 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2578 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2579 $sha1 = substr( $sha1, 1 );
2582 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2583 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2584 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2585 ||
is_null( $row->fa_metadata
)
2587 // Refresh our metadata
2588 // Required for a new current revision; nice for older ones too. :)
2589 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2592 'minor_mime' => $row->fa_minor_mime
,
2593 'major_mime' => $row->fa_major_mime
,
2594 'media_type' => $row->fa_media_type
,
2595 'metadata' => $row->fa_metadata
2599 if ( $first && !$exists ) {
2600 // This revision will be published as the new current version
2601 $destRel = $this->file
->getRel();
2603 'img_name' => $row->fa_name
,
2604 'img_size' => $row->fa_size
,
2605 'img_width' => $row->fa_width
,
2606 'img_height' => $row->fa_height
,
2607 'img_metadata' => $props['metadata'],
2608 'img_bits' => $row->fa_bits
,
2609 'img_media_type' => $props['media_type'],
2610 'img_major_mime' => $props['major_mime'],
2611 'img_minor_mime' => $props['minor_mime'],
2612 'img_description' => $row->fa_description
,
2613 'img_user' => $row->fa_user
,
2614 'img_user_text' => $row->fa_user_text
,
2615 'img_timestamp' => $row->fa_timestamp
,
2619 // The live (current) version cannot be hidden!
2620 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2621 $status->fatal( 'undeleterevdel' );
2622 $this->file
->unlock();
2626 $archiveName = $row->fa_archive_name
;
2628 if ( $archiveName == '' ) {
2629 // This was originally a current version; we
2630 // have to devise a new archive name for it.
2631 // Format is <timestamp of archiving>!<name>
2632 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2635 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2637 } while ( isset( $archiveNames[$archiveName] ) );
2640 $archiveNames[$archiveName] = true;
2641 $destRel = $this->file
->getArchiveRel( $archiveName );
2643 'oi_name' => $row->fa_name
,
2644 'oi_archive_name' => $archiveName,
2645 'oi_size' => $row->fa_size
,
2646 'oi_width' => $row->fa_width
,
2647 'oi_height' => $row->fa_height
,
2648 'oi_bits' => $row->fa_bits
,
2649 'oi_description' => $row->fa_description
,
2650 'oi_user' => $row->fa_user
,
2651 'oi_user_text' => $row->fa_user_text
,
2652 'oi_timestamp' => $row->fa_timestamp
,
2653 'oi_metadata' => $props['metadata'],
2654 'oi_media_type' => $props['media_type'],
2655 'oi_major_mime' => $props['major_mime'],
2656 'oi_minor_mime' => $props['minor_mime'],
2657 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2658 'oi_sha1' => $sha1 ];
2661 $deleteIds[] = $row->fa_id
;
2663 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2664 // private files can stay where they are
2665 $status->successCount++
;
2667 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2668 $this->cleanupBatch
[] = $row->fa_storage_key
;
2676 // Add a warning to the status object for missing IDs
2677 $missingIds = array_diff( $this->ids
, $idsPresent );
2679 foreach ( $missingIds as $id ) {
2680 $status->error( 'undelete-missing-filearchive', $id );
2683 if ( !$repo->hasSha1Storage() ) {
2684 // Remove missing files from batch, so we don't get errors when undeleting them
2685 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2686 if ( !$checkStatus->isGood() ) {
2687 $status->merge( $checkStatus );
2690 $storeBatch = $checkStatus->value
;
2692 // Run the store batch
2693 // Use the OVERWRITE_SAME flag to smooth over a common error
2694 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2695 $status->merge( $storeStatus );
2697 if ( !$status->isGood() ) {
2698 // Even if some files could be copied, fail entirely as that is the
2699 // easiest thing to do without data loss
2700 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2701 $status->setOK( false );
2702 $this->file
->unlock();
2708 // Run the DB updates
2709 // Because we have locked the image row, key conflicts should be rare.
2710 // If they do occur, we can roll back the transaction at this time with
2711 // no data loss, but leaving unregistered files scattered throughout the
2713 // This is not ideal, which is why it's important to lock the image row.
2714 if ( $insertCurrent ) {
2715 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2718 if ( $insertBatch ) {
2719 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2723 $dbw->delete( 'filearchive',
2724 [ 'fa_id' => $deleteIds ],
2728 // If store batch is empty (all files are missing), deletion is to be considered successful
2729 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2731 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2733 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2735 $this->file
->purgeEverything();
2737 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2738 $this->file
->purgeDescription();
2742 $this->file
->unlock();
2748 * Removes non-existent files from a store batch.
2749 * @param array $triplets
2752 protected function removeNonexistentFiles( $triplets ) {
2753 $files = $filteredTriplets = [];
2754 foreach ( $triplets as $file ) {
2755 $files[$file[0]] = $file[0];
2758 $result = $this->file
->repo
->fileExistsBatch( $files );
2759 if ( in_array( null, $result, true ) ) {
2760 return Status
::newFatal( 'backend-fail-internal',
2761 $this->file
->repo
->getBackend()->getName() );
2764 foreach ( $triplets as $file ) {
2765 if ( $result[$file[0]] ) {
2766 $filteredTriplets[] = $file;
2770 return Status
::newGood( $filteredTriplets );
2774 * Removes non-existent files from a cleanup batch.
2775 * @param array $batch
2778 protected function removeNonexistentFromCleanup( $batch ) {
2779 $files = $newBatch = [];
2780 $repo = $this->file
->repo
;
2782 foreach ( $batch as $file ) {
2783 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2784 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2787 $result = $repo->fileExistsBatch( $files );
2789 foreach ( $batch as $file ) {
2790 if ( $result[$file] ) {
2791 $newBatch[] = $file;
2799 * Delete unused files in the deleted zone.
2800 * This should be called from outside the transaction in which execute() was called.
2803 public function cleanup() {
2804 if ( !$this->cleanupBatch
) {
2805 return $this->file
->repo
->newGood();
2808 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2810 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2816 * Cleanup a failed batch. The batch was only partially successful, so
2817 * rollback by removing all items that were succesfully copied.
2819 * @param Status $storeStatus
2820 * @param array $storeBatch
2822 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2825 foreach ( $storeStatus->success
as $i => $success ) {
2826 // Check if this item of the batch was successfully copied
2828 // Item was successfully copied and needs to be removed again
2829 // Extract ($dstZone, $dstRel) from the batch
2830 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2833 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2837 # ------------------------------------------------------------------------------
2840 * Helper class for file movement
2841 * @ingroup FileAbstraction
2843 class LocalFileMoveBatch
{
2844 /** @var LocalFile */
2854 protected $oldCount;
2858 /** @var IDatabase */
2863 * @param Title $target
2865 function __construct( File
$file, Title
$target ) {
2866 $this->file
= $file;
2867 $this->target
= $target;
2868 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2869 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2870 $this->oldName
= $this->file
->getName();
2871 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2872 $this->oldRel
= $this->oldHash
. $this->oldName
;
2873 $this->newRel
= $this->newHash
. $this->newName
;
2874 $this->db
= $file->getRepo()->getMasterDB();
2878 * Add the current image to the batch
2880 public function addCurrent() {
2881 $this->cur
= [ $this->oldRel
, $this->newRel
];
2885 * Add the old versions of the image to the batch
2886 * @return array List of archive names from old versions
2888 public function addOlds() {
2889 $archiveBase = 'archive';
2891 $this->oldCount
= 0;
2894 $result = $this->db
->select( 'oldimage',
2895 [ 'oi_archive_name', 'oi_deleted' ],
2896 [ 'oi_name' => $this->oldName
],
2898 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2901 foreach ( $result as $row ) {
2902 $archiveNames[] = $row->oi_archive_name
;
2903 $oldName = $row->oi_archive_name
;
2904 $bits = explode( '!', $oldName, 2 );
2906 if ( count( $bits ) != 2 ) {
2907 wfDebug( "Old file name missing !: '$oldName' \n" );
2911 list( $timestamp, $filename ) = $bits;
2913 if ( $this->oldName
!= $filename ) {
2914 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2920 // Do we want to add those to oldCount?
2921 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2926 "{$archiveBase}/{$this->oldHash}{$oldName}",
2927 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2931 return $archiveNames;
2938 public function execute() {
2939 $repo = $this->file
->repo
;
2940 $status = $repo->newGood();
2941 $destFile = wfLocalFile( $this->target
);
2943 $this->file
->lock(); // begin
2944 $destFile->lock(); // quickly fail if destination is not available
2946 $triplets = $this->getMoveTriplets();
2947 $checkStatus = $this->removeNonexistentFiles( $triplets );
2948 if ( !$checkStatus->isGood() ) {
2949 $destFile->unlock();
2950 $this->file
->unlock();
2951 $status->merge( $checkStatus ); // couldn't talk to file backend
2954 $triplets = $checkStatus->value
;
2956 // Verify the file versions metadata in the DB.
2957 $statusDb = $this->verifyDBUpdates();
2958 if ( !$statusDb->isGood() ) {
2959 $destFile->unlock();
2960 $this->file
->unlock();
2961 $statusDb->setOK( false );
2966 if ( !$repo->hasSha1Storage() ) {
2967 // Copy the files into their new location.
2968 // If a prior process fataled copying or cleaning up files we tolerate any
2969 // of the existing files if they are identical to the ones being stored.
2970 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2971 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2972 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2973 if ( !$statusMove->isGood() ) {
2974 // Delete any files copied over (while the destination is still locked)
2975 $this->cleanupTarget( $triplets );
2976 $destFile->unlock();
2977 $this->file
->unlock();
2978 wfDebugLog( 'imagemove', "Error in moving files: "
2979 . $statusMove->getWikiText( false, false, 'en' ) );
2980 $statusMove->setOK( false );
2984 $status->merge( $statusMove );
2987 // Rename the file versions metadata in the DB.
2988 $this->doDBUpdates();
2990 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2991 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2993 $destFile->unlock();
2994 $this->file
->unlock(); // done
2996 // Everything went ok, remove the source files
2997 $this->cleanupSource( $triplets );
2999 $status->merge( $statusDb );
3005 * Verify the database updates and return a new Status indicating how
3006 * many rows would be updated.
3010 protected function verifyDBUpdates() {
3011 $repo = $this->file
->repo
;
3012 $status = $repo->newGood();
3015 $hasCurrent = $dbw->selectField(
3018 [ 'img_name' => $this->oldName
],
3022 $oldRowCount = $dbw->selectField(
3025 [ 'oi_name' => $this->oldName
],
3030 if ( $hasCurrent ) {
3031 $status->successCount++
;
3033 $status->failCount++
;
3035 $status->successCount +
= $oldRowCount;
3036 // Bug 34934: oldCount is based on files that actually exist.
3037 // There may be more DB rows than such files, in which case $affected
3038 // can be greater than $total. We use max() to avoid negatives here.
3039 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3040 if ( $status->failCount
) {
3041 $status->error( 'imageinvalidfilename' );
3048 * Do the database updates and return a new Status indicating how
3049 * many rows where updated.
3051 protected function doDBUpdates() {
3054 // Update current image
3057 [ 'img_name' => $this->newName
],
3058 [ 'img_name' => $this->oldName
],
3061 // Update old images
3065 'oi_name' => $this->newName
,
3066 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3067 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3069 [ 'oi_name' => $this->oldName
],
3075 * Generate triplets for FileRepo::storeBatch().
3078 protected function getMoveTriplets() {
3079 $moves = array_merge( [ $this->cur
], $this->olds
);
3080 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3082 foreach ( $moves as $move ) {
3083 // $move: (oldRelativePath, newRelativePath)
3084 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3085 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3088 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3096 * Removes non-existent files from move batch.
3097 * @param array $triplets
3100 protected function removeNonexistentFiles( $triplets ) {
3103 foreach ( $triplets as $file ) {
3104 $files[$file[0]] = $file[0];
3107 $result = $this->file
->repo
->fileExistsBatch( $files );
3108 if ( in_array( null, $result, true ) ) {
3109 return Status
::newFatal( 'backend-fail-internal',
3110 $this->file
->repo
->getBackend()->getName() );
3113 $filteredTriplets = [];
3114 foreach ( $triplets as $file ) {
3115 if ( $result[$file[0]] ) {
3116 $filteredTriplets[] = $file;
3118 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3122 return Status
::newGood( $filteredTriplets );
3126 * Cleanup a partially moved array of triplets by deleting the target
3127 * files. Called if something went wrong half way.
3128 * @param array $triplets
3130 protected function cleanupTarget( $triplets ) {
3131 // Create dest pairs from the triplets
3133 foreach ( $triplets as $triplet ) {
3134 // $triplet: (old source virtual URL, dst zone, dest rel)
3135 $pairs[] = [ $triplet[1], $triplet[2] ];
3138 $this->file
->repo
->cleanupBatch( $pairs );
3142 * Cleanup a fully moved array of triplets by deleting the source files.
3143 * Called at the end of the move process if everything else went ok.
3144 * @param array $triplets
3146 protected function cleanupSource( $triplets ) {
3147 // Create source file names from the triplets
3149 foreach ( $triplets as $triplet ) {
3150 $files[] = $triplet[0];
3153 $this->file
->repo
->cleanupBatch( $files );
3157 class LocalFileLockError
extends ErrorPageError
{
3158 public function __construct( Status
$status ) {
3159 parent
::__construct(
3161 $status->getMessage()
3165 public function report() {
3167 $wgOut->setStatusCode( 429 );