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 * Bump this number when serialized cache records may be incompatible.
29 define( 'MW_FILE_VERSION', 9 );
32 * Class to represent a local file in the wiki's own database
34 * Provides methods to retrieve paths (physical, logical, URL),
35 * to generate image thumbnails or for uploading.
37 * Note that only the repo object knows what its file class is called. You should
38 * never name a file class explictly outside of the repo class. Instead use the
39 * repo's factory functions to generate file objects, for example:
41 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
43 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
46 * @ingroup FileAbstraction
48 class LocalFile
extends File
{
49 const CACHE_FIELD_MAX_LEN
= 1000;
51 /** @var bool Does the file exist on disk? (loadFromXxx) */
52 protected $fileExists;
54 /** @var int Image width */
57 /** @var int Image height */
60 /** @var int Returned by getimagesize (loadFromXxx) */
63 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
64 protected $media_type;
66 /** @var string MIME type, determined by MimeMagic::guessMimeType */
69 /** @var int Size in bytes (loadFromXxx) */
72 /** @var string Handler-specific metadata */
75 /** @var string SHA-1 base 36 content hash */
78 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
79 protected $dataLoaded;
81 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
82 protected $extraDataLoaded;
84 /** @var int Bitfield akin to rev_deleted */
88 protected $repoClass = 'LocalRepo';
90 /** @var int Number of line to return by nextHistoryLine() (constructor) */
93 /** @var int Result of the query for the file's history (nextHistoryLine) */
96 /** @var string Major MIME type */
99 /** @var string Minor MIME type */
102 /** @var string Upload timestamp */
105 /** @var int User ID of uploader */
108 /** @var string User name of uploader */
111 /** @var string Description of current revision of the file */
112 private $description;
114 /** @var string TS_MW timestamp of the last change of the file description */
115 private $descriptionTouched;
117 /** @var bool Whether the row was upgraded on load */
120 /** @var bool Whether the row was scheduled to upgrade on load */
123 /** @var bool True if the image row is locked */
126 /** @var bool True if the image row is locked with a lock initiated transaction */
127 private $lockedOwnTrx;
129 /** @var bool True if file is not present in file system. Not to be cached in memcached */
132 // @note: higher than IDBAccessObject constants
133 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
135 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
138 * Create a LocalFile from a title
139 * Do not call this except from inside a repo class.
141 * Note: $unused param is only here to avoid an E_STRICT
143 * @param Title $title
144 * @param FileRepo $repo
145 * @param null $unused
149 static function newFromTitle( $title, $repo, $unused = null ) {
150 return new self( $title, $repo );
154 * Create a LocalFile from a title
155 * Do not call this except from inside a repo class.
157 * @param stdClass $row
158 * @param FileRepo $repo
162 static function newFromRow( $row, $repo ) {
163 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
164 $file = new self( $title, $repo );
165 $file->loadFromRow( $row );
171 * Create a LocalFile from a SHA-1 key
172 * Do not call this except from inside a repo class.
174 * @param string $sha1 Base-36 SHA-1
175 * @param LocalRepo $repo
176 * @param string|bool $timestamp MW_timestamp (optional)
177 * @return bool|LocalFile
179 static function newFromKey( $sha1, $repo, $timestamp = false ) {
180 $dbr = $repo->getSlaveDB();
182 $conds = [ 'img_sha1' => $sha1 ];
184 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
187 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
189 return self
::newFromRow( $row, $repo );
196 * Fields in the image table
199 static function selectFields() {
220 * Do not call this except from inside a repo class.
221 * @param Title $title
222 * @param FileRepo $repo
224 function __construct( $title, $repo ) {
225 parent
::__construct( $title, $repo );
227 $this->metadata
= '';
228 $this->historyLine
= 0;
229 $this->historyRes
= null;
230 $this->dataLoaded
= false;
231 $this->extraDataLoaded
= false;
233 $this->assertRepoDefined();
234 $this->assertTitleDefined();
238 * Get the memcached key for the main data for this file, or false if
239 * there is no access to the shared cache.
240 * @return string|bool
242 function getCacheKey() {
243 $hashedName = md5( $this->getName() );
245 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
249 * Try to load file metadata from memcached. Returns true on success.
252 private function loadFromCache() {
253 $this->dataLoaded
= false;
254 $this->extraDataLoaded
= false;
255 $key = $this->getCacheKey();
261 $cache = ObjectCache
::getMainWANInstance();
262 $cachedValues = $cache->get( $key );
264 // Check if the key existed and belongs to this version of MediaWiki
265 if ( is_array( $cachedValues ) && $cachedValues['version'] == MW_FILE_VERSION
) {
266 $this->fileExists
= $cachedValues['fileExists'];
267 if ( $this->fileExists
) {
268 $this->setProps( $cachedValues );
270 $this->dataLoaded
= true;
271 $this->extraDataLoaded
= true;
272 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
273 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
277 return $this->dataLoaded
;
281 * Save the file metadata to memcached
283 private function saveToCache() {
286 $key = $this->getCacheKey();
291 $fields = $this->getCacheFields( '' );
292 $cacheVal = [ 'version' => MW_FILE_VERSION
];
293 $cacheVal['fileExists'] = $this->fileExists
;
295 if ( $this->fileExists
) {
296 foreach ( $fields as $field ) {
297 $cacheVal[$field] = $this->$field;
301 // Strip off excessive entries from the subset of fields that can become large.
302 // If the cache value gets to large it will not fit in memcached and nothing will
303 // get cached at all, causing master queries for any file access.
304 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
305 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
306 unset( $cacheVal[$field] ); // don't let the value get too big
310 // Cache presence for 1 week and negatives for 1 day
311 $ttl = $this->fileExists ?
86400 * 7 : 86400;
312 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
313 ObjectCache
::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
317 * Purge the file object/metadata cache
319 public function invalidateCache() {
320 $key = $this->getCacheKey();
325 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
326 ObjectCache
::getMainWANInstance()->delete( $key );
331 * Load metadata from the file itself
333 function loadFromFile() {
334 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
335 $this->setProps( $props );
339 * @param string $prefix
342 function getCacheFields( $prefix = 'img_' ) {
343 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
344 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
345 'user_text', 'description' ];
346 static $results = [];
348 if ( $prefix == '' ) {
352 if ( !isset( $results[$prefix] ) ) {
353 $prefixedFields = [];
354 foreach ( $fields as $field ) {
355 $prefixedFields[] = $prefix . $field;
357 $results[$prefix] = $prefixedFields;
360 return $results[$prefix];
364 * @param string $prefix
367 function getLazyCacheFields( $prefix = 'img_' ) {
368 static $fields = [ 'metadata' ];
369 static $results = [];
371 if ( $prefix == '' ) {
375 if ( !isset( $results[$prefix] ) ) {
376 $prefixedFields = [];
377 foreach ( $fields as $field ) {
378 $prefixedFields[] = $prefix . $field;
380 $results[$prefix] = $prefixedFields;
383 return $results[$prefix];
387 * Load file metadata from the DB
390 function loadFromDB( $flags = 0 ) {
391 $fname = get_class( $this ) . '::' . __FUNCTION__
;
393 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
394 $this->dataLoaded
= true;
395 $this->extraDataLoaded
= true;
397 $dbr = ( $flags & self
::READ_LATEST
)
398 ?
$this->repo
->getMasterDB()
399 : $this->repo
->getSlaveDB();
401 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
402 [ 'img_name' => $this->getName() ], $fname );
405 $this->loadFromRow( $row );
407 $this->fileExists
= false;
412 * Load lazy file metadata from the DB.
413 * This covers fields that are sometimes not cached.
415 protected function loadExtraFromDB() {
416 $fname = get_class( $this ) . '::' . __FUNCTION__
;
418 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
419 $this->extraDataLoaded
= true;
421 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
423 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
427 foreach ( $fieldMap as $name => $value ) {
428 $this->$name = $value;
431 throw new MWException( "Could not find data for image '{$this->getName()}'." );
436 * @param IDatabase $dbr
437 * @param string $fname
440 private function loadFieldsWithTimestamp( $dbr, $fname ) {
443 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
444 [ 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ],
447 $fieldMap = $this->unprefixRow( $row, 'img_' );
449 # File may have been uploaded over in the meantime; check the old versions
450 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
451 [ 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ],
454 $fieldMap = $this->unprefixRow( $row, 'oi_' );
462 * @param array|object $row
463 * @param string $prefix
464 * @throws MWException
467 protected function unprefixRow( $row, $prefix = 'img_' ) {
468 $array = (array)$row;
469 $prefixLength = strlen( $prefix );
471 // Sanity check prefix once
472 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
473 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
477 foreach ( $array as $name => $value ) {
478 $decoded[substr( $name, $prefixLength )] = $value;
485 * Decode a row from the database (either object or array) to an array
486 * with timestamps and MIME types decoded, and the field prefix removed.
488 * @param string $prefix
489 * @throws MWException
492 function decodeRow( $row, $prefix = 'img_' ) {
493 $decoded = $this->unprefixRow( $row, $prefix );
495 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
497 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
499 if ( empty( $decoded['major_mime'] ) ) {
500 $decoded['mime'] = 'unknown/unknown';
502 if ( !$decoded['minor_mime'] ) {
503 $decoded['minor_mime'] = 'unknown';
505 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
508 // Trim zero padding from char/binary field
509 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
511 // Normalize some fields to integer type, per their database definition.
512 // Use unary + so that overflows will be upgraded to double instead of
513 // being trucated as with intval(). This is important to allow >2GB
514 // files on 32-bit systems.
515 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
516 $decoded[$field] = +
$decoded[$field];
523 * Load file metadata from a DB result row
526 * @param string $prefix
528 function loadFromRow( $row, $prefix = 'img_' ) {
529 $this->dataLoaded
= true;
530 $this->extraDataLoaded
= true;
532 $array = $this->decodeRow( $row, $prefix );
534 foreach ( $array as $name => $value ) {
535 $this->$name = $value;
538 $this->fileExists
= true;
539 $this->maybeUpgradeRow();
543 * Load file metadata from cache or DB, unless already loaded
546 function load( $flags = 0 ) {
547 if ( !$this->dataLoaded
) {
548 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
549 $this->loadFromDB( $flags );
550 $this->saveToCache();
552 $this->dataLoaded
= true;
554 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
555 // @note: loads on name/timestamp to reduce race condition problems
556 $this->loadExtraFromDB();
561 * Upgrade a row if it needs it
563 function maybeUpgradeRow() {
564 global $wgUpdateCompatibleMetadata;
566 if ( wfReadOnly() ||
$this->upgrading
) {
571 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
574 $handler = $this->getHandler();
576 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
577 if ( $validity === MediaHandler
::METADATA_BAD
) {
579 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
580 $upgrade = $wgUpdateCompatibleMetadata;
586 $this->upgrading
= true;
587 // Defer updates unless in auto-commit CLI mode
588 DeferredUpdates
::addCallableUpdate( function() {
589 $this->upgrading
= false; // avoid duplicate updates
592 } catch ( LocalFileLockError
$e ) {
593 // let the other process handle it (or do it next time)
600 * @return bool Whether upgradeRow() ran for this object
602 function getUpgraded() {
603 return $this->upgraded
;
607 * Fix assorted version-related problems with the image row by reloading it from the file
609 function upgradeRow() {
610 $this->lock(); // begin
612 $this->loadFromFile();
614 # Don't destroy file info of missing files
615 if ( !$this->fileExists
) {
617 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
622 $dbw = $this->repo
->getMasterDB();
623 list( $major, $minor ) = self
::splitMime( $this->mime
);
625 if ( wfReadOnly() ) {
630 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
632 $dbw->update( 'image',
634 'img_size' => $this->size
, // sanity
635 'img_width' => $this->width
,
636 'img_height' => $this->height
,
637 'img_bits' => $this->bits
,
638 'img_media_type' => $this->media_type
,
639 'img_major_mime' => $major,
640 'img_minor_mime' => $minor,
641 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
642 'img_sha1' => $this->sha1
,
644 [ 'img_name' => $this->getName() ],
648 $this->invalidateCache();
650 $this->unlock(); // done
651 $this->upgraded
= true; // avoid rework/retries
655 * Set properties in this object to be equal to those given in the
656 * associative array $info. Only cacheable fields can be set.
657 * All fields *must* be set in $info except for getLazyCacheFields().
659 * If 'mime' is given, it will be split into major_mime/minor_mime.
660 * If major_mime/minor_mime are given, $this->mime will also be set.
664 function setProps( $info ) {
665 $this->dataLoaded
= true;
666 $fields = $this->getCacheFields( '' );
667 $fields[] = 'fileExists';
669 foreach ( $fields as $field ) {
670 if ( isset( $info[$field] ) ) {
671 $this->$field = $info[$field];
675 // Fix up mime fields
676 if ( isset( $info['major_mime'] ) ) {
677 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
678 } elseif ( isset( $info['mime'] ) ) {
679 $this->mime
= $info['mime'];
680 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
684 /** splitMime inherited */
685 /** getName inherited */
686 /** getTitle inherited */
687 /** getURL inherited */
688 /** getViewURL inherited */
689 /** getPath inherited */
690 /** isVisible inherited */
695 function isMissing() {
696 if ( $this->missing
=== null ) {
697 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
698 $this->missing
= !$fileExists;
701 return $this->missing
;
705 * Return the width of the image
710 public function getWidth( $page = 1 ) {
713 if ( $this->isMultipage() ) {
714 $handler = $this->getHandler();
718 $dim = $handler->getPageDimensions( $this, $page );
720 return $dim['width'];
722 // For non-paged media, the false goes through an
723 // intval, turning failure into 0, so do same here.
732 * Return the height of the image
737 public function getHeight( $page = 1 ) {
740 if ( $this->isMultipage() ) {
741 $handler = $this->getHandler();
745 $dim = $handler->getPageDimensions( $this, $page );
747 return $dim['height'];
749 // For non-paged media, the false goes through an
750 // intval, turning failure into 0, so do same here.
754 return $this->height
;
759 * Returns ID or name of user who uploaded the file
761 * @param string $type 'text' or 'id'
764 function getUser( $type = 'text' ) {
767 if ( $type == 'text' ) {
768 return $this->user_text
;
769 } elseif ( $type == 'id' ) {
770 return (int)$this->user
;
775 * Get short description URL for a file based on the page ID.
777 * @return string|null
778 * @throws MWException
781 public function getDescriptionShortUrl() {
782 $pageId = $this->title
->getArticleID();
784 if ( $pageId !== null ) {
785 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
786 if ( $url !== false ) {
794 * Get handler-specific metadata
797 function getMetadata() {
798 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
799 return $this->metadata
;
805 function getBitDepth() {
808 return (int)$this->bits
;
812 * Returns the size of the image file, in bytes
815 public function getSize() {
822 * Returns the MIME type of the file.
825 function getMimeType() {
832 * Returns the type of the media in the file.
833 * Use the value returned by this function with the MEDIATYPE_xxx constants.
836 function getMediaType() {
839 return $this->media_type
;
842 /** canRender inherited */
843 /** mustRender inherited */
844 /** allowInlineDisplay inherited */
845 /** isSafeFile inherited */
846 /** isTrustedFile inherited */
849 * Returns true if the file exists on disk.
850 * @return bool Whether file exist on disk.
852 public function exists() {
855 return $this->fileExists
;
858 /** getTransformScript inherited */
859 /** getUnscaledThumb inherited */
860 /** thumbName inherited */
861 /** createThumb inherited */
862 /** transform inherited */
864 /** getHandler inherited */
865 /** iconThumb inherited */
866 /** getLastError inherited */
869 * Get all thumbnail names previously generated for this file
870 * @param string|bool $archiveName Name of an archive file, default false
871 * @return array First element is the base dir, then files in that base dir.
873 function getThumbnails( $archiveName = false ) {
874 if ( $archiveName ) {
875 $dir = $this->getArchiveThumbPath( $archiveName );
877 $dir = $this->getThumbPath();
880 $backend = $this->repo
->getBackend();
883 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
884 foreach ( $iterator as $file ) {
887 } catch ( FileBackendError
$e ) {
888 } // suppress (bug 54674)
894 * Refresh metadata in memcached, but don't touch thumbnails or CDN
896 function purgeMetadataCache() {
897 $this->invalidateCache();
901 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
903 * @param array $options An array potentially with the key forThumbRefresh.
905 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
907 function purgeCache( $options = [] ) {
908 // Refresh metadata cache
909 $this->purgeMetadataCache();
912 $this->purgeThumbnails( $options );
914 // Purge CDN cache for this file
915 DeferredUpdates
::addUpdate(
916 new CdnCacheUpdate( [ $this->getUrl() ] ),
917 DeferredUpdates
::PRESEND
922 * Delete cached transformed files for an archived version only.
923 * @param string $archiveName Name of the archived file
925 function purgeOldThumbnails( $archiveName ) {
926 // Get a list of old thumbnails and URLs
927 $files = $this->getThumbnails( $archiveName );
929 // Purge any custom thumbnail caches
930 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
933 $dir = array_shift( $files );
934 $this->purgeThumbList( $dir, $files );
938 foreach ( $files as $file ) {
939 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
941 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
945 * Delete cached transformed files for the current version only.
946 * @param array $options
948 public function purgeThumbnails( $options = [] ) {
949 $files = $this->getThumbnails();
950 // Always purge all files from CDN regardless of handler filters
952 foreach ( $files as $file ) {
953 $urls[] = $this->getThumbUrl( $file );
955 array_shift( $urls ); // don't purge directory
957 // Give media handler a chance to filter the file purge list
958 if ( !empty( $options['forThumbRefresh'] ) ) {
959 $handler = $this->getHandler();
961 $handler->filterThumbnailPurgeList( $files, $options );
965 // Purge any custom thumbnail caches
966 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
969 $dir = array_shift( $files );
970 $this->purgeThumbList( $dir, $files );
973 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
977 * Prerenders a configurable set of thumbnails
981 public function prerenderThumbnails() {
982 global $wgUploadThumbnailRenderMap;
986 $sizes = $wgUploadThumbnailRenderMap;
989 foreach ( $sizes as $size ) {
990 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
991 $jobs[] = new ThumbnailRenderJob(
993 [ 'transformParams' => [ 'width' => $size ] ]
999 JobQueueGroup
::singleton()->lazyPush( $jobs );
1004 * Delete a list of thumbnails visible at urls
1005 * @param string $dir Base dir of the files.
1006 * @param array $files Array of strings: relative filenames (to $dir)
1008 protected function purgeThumbList( $dir, $files ) {
1009 $fileListDebug = strtr(
1010 var_export( $files, true ),
1013 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1016 foreach ( $files as $file ) {
1017 # Check that the base file name is part of the thumb name
1018 # This is a basic sanity check to avoid erasing unrelated directories
1019 if ( strpos( $file, $this->getName() ) !== false
1020 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1022 $purgeList[] = "{$dir}/{$file}";
1026 # Delete the thumbnails
1027 $this->repo
->quickPurgeBatch( $purgeList );
1028 # Clear out the thumbnail directory if empty
1029 $this->repo
->quickCleanDir( $dir );
1032 /** purgeDescription inherited */
1033 /** purgeEverything inherited */
1036 * @param int $limit Optional: Limit to number of results
1037 * @param int $start Optional: Timestamp, start from
1038 * @param int $end Optional: Timestamp, end at
1040 * @return OldLocalFile[]
1042 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1043 $dbr = $this->repo
->getSlaveDB();
1044 $tables = [ 'oldimage' ];
1045 $fields = OldLocalFile
::selectFields();
1046 $conds = $opts = $join_conds = [];
1047 $eq = $inc ?
'=' : '';
1048 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1051 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1055 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1059 $opts['LIMIT'] = $limit;
1062 // Search backwards for time > x queries
1063 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1064 $opts['ORDER BY'] = "oi_timestamp $order";
1065 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1067 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1068 &$conds, &$opts, &$join_conds ] );
1070 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1073 foreach ( $res as $row ) {
1074 $r[] = $this->repo
->newFileFromRow( $row );
1077 if ( $order == 'ASC' ) {
1078 $r = array_reverse( $r ); // make sure it ends up descending
1085 * Returns the history of this file, line by line.
1086 * starts with current version, then old versions.
1087 * uses $this->historyLine to check which line to return:
1088 * 0 return line for current version
1089 * 1 query for old versions, return first one
1090 * 2, ... return next old version from above query
1093 public function nextHistoryLine() {
1094 # Polymorphic function name to distinguish foreign and local fetches
1095 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1097 $dbr = $this->repo
->getSlaveDB();
1099 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1100 $this->historyRes
= $dbr->select( 'image',
1103 "'' AS oi_archive_name",
1107 [ 'img_name' => $this->title
->getDBkey() ],
1111 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1112 $this->historyRes
= null;
1116 } elseif ( $this->historyLine
== 1 ) {
1117 $this->historyRes
= $dbr->select( 'oldimage', '*',
1118 [ 'oi_name' => $this->title
->getDBkey() ],
1120 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1123 $this->historyLine++
;
1125 return $dbr->fetchObject( $this->historyRes
);
1129 * Reset the history pointer to the first element of the history
1131 public function resetHistory() {
1132 $this->historyLine
= 0;
1134 if ( !is_null( $this->historyRes
) ) {
1135 $this->historyRes
= null;
1139 /** getHashPath inherited */
1140 /** getRel inherited */
1141 /** getUrlRel inherited */
1142 /** getArchiveRel inherited */
1143 /** getArchivePath inherited */
1144 /** getThumbPath inherited */
1145 /** getArchiveUrl inherited */
1146 /** getThumbUrl inherited */
1147 /** getArchiveVirtualUrl inherited */
1148 /** getThumbVirtualUrl inherited */
1149 /** isHashed inherited */
1152 * Upload a file and record it in the DB
1153 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1154 * @param string $comment Upload description
1155 * @param string $pageText Text to use for the new description page,
1156 * if a new description page is created
1157 * @param int|bool $flags Flags for publish()
1158 * @param array|bool $props File properties, if known. This can be used to
1159 * reduce the upload time when uploading virtual URLs for which the file
1160 * info is already known
1161 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1163 * @param User|null $user User object or null to use $wgUser
1164 * @param string[] $tags Change tags to add to the log entry and page revision.
1165 * (This doesn't check $user's permissions.)
1166 * @return FileRepoStatus On success, the value member contains the
1167 * archive name, or an empty string if it was a new file.
1169 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1170 $timestamp = false, $user = null, $tags = []
1174 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1175 return $this->readOnlyFatalStatus();
1178 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1180 if ( $this->repo
->isVirtualUrl( $srcPath )
1181 || FileBackend
::isStoragePath( $srcPath )
1183 $props = $this->repo
->getFileProps( $srcPath );
1185 $props = FSFile
::getPropsFromPath( $srcPath );
1190 $handler = MediaHandler
::getHandler( $props['mime'] );
1192 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1194 $options['headers'] = [];
1197 // Trim spaces on user supplied text
1198 $comment = trim( $comment );
1200 // Truncate nicely or the DB will do it for us
1201 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1202 $comment = $wgContLang->truncate( $comment, 255 );
1203 $this->lock(); // begin
1204 $status = $this->publish( $src, $flags, $options );
1206 if ( $status->successCount
>= 2 ) {
1207 // There will be a copy+(one of move,copy,store).
1208 // The first succeeding does not commit us to updating the DB
1209 // since it simply copied the current version to a timestamped file name.
1210 // It is only *preferable* to avoid leaving such files orphaned.
1211 // Once the second operation goes through, then the current version was
1212 // updated and we must therefore update the DB too.
1213 $oldver = $status->value
;
1214 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1215 $status->fatal( 'filenotfound', $srcPath );
1219 $this->unlock(); // done
1225 * Record a file upload in the upload log and the image table
1226 * @param string $oldver
1227 * @param string $desc
1228 * @param string $license
1229 * @param string $copyStatus
1230 * @param string $source
1231 * @param bool $watch
1232 * @param string|bool $timestamp
1233 * @param User|null $user User object or null to use $wgUser
1236 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1237 $watch = false, $timestamp = false, User
$user = null ) {
1243 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1245 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1250 $user->addWatch( $this->getTitle() );
1257 * Record a file upload in the upload log and the image table
1258 * @param string $oldver
1259 * @param string $comment
1260 * @param string $pageText
1261 * @param bool|array $props
1262 * @param string|bool $timestamp
1263 * @param null|User $user
1264 * @param string[] $tags
1267 function recordUpload2(
1268 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1270 if ( is_null( $user ) ) {
1275 $dbw = $this->repo
->getMasterDB();
1277 # Imports or such might force a certain timestamp; otherwise we generate
1278 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1279 if ( $timestamp === false ) {
1280 $timestamp = $dbw->timestamp();
1281 $allowTimeKludge = true;
1283 $allowTimeKludge = false;
1286 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1287 $props['description'] = $comment;
1288 $props['user'] = $user->getId();
1289 $props['user_text'] = $user->getName();
1290 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1291 $this->setProps( $props );
1293 # Fail now if the file isn't there
1294 if ( !$this->fileExists
) {
1295 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1300 $dbw->startAtomic( __METHOD__
);
1302 # Test to see if the row exists using INSERT IGNORE
1303 # This avoids race conditions by locking the row until the commit, and also
1304 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1305 $dbw->insert( 'image',
1307 'img_name' => $this->getName(),
1308 'img_size' => $this->size
,
1309 'img_width' => intval( $this->width
),
1310 'img_height' => intval( $this->height
),
1311 'img_bits' => $this->bits
,
1312 'img_media_type' => $this->media_type
,
1313 'img_major_mime' => $this->major_mime
,
1314 'img_minor_mime' => $this->minor_mime
,
1315 'img_timestamp' => $timestamp,
1316 'img_description' => $comment,
1317 'img_user' => $user->getId(),
1318 'img_user_text' => $user->getName(),
1319 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1320 'img_sha1' => $this->sha1
1326 $reupload = ( $dbw->affectedRows() == 0 );
1328 if ( $allowTimeKludge ) {
1329 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1330 $ltimestamp = $dbw->selectField(
1333 [ 'img_name' => $this->getName() ],
1335 [ 'LOCK IN SHARE MODE' ]
1337 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1338 # Avoid a timestamp that is not newer than the last version
1339 # TODO: the image/oldimage tables should be like page/revision with an ID field
1340 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1341 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1342 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1343 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1347 # (bug 34993) Note: $oldver can be empty here, if the previous
1348 # version of the file was broken. Allow registration of the new
1349 # version to continue anyway, because that's better than having
1350 # an image that's not fixable by user operations.
1351 # Collision, this is an update of a file
1352 # Insert previous contents into oldimage
1353 $dbw->insertSelect( 'oldimage', 'image',
1355 'oi_name' => 'img_name',
1356 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1357 'oi_size' => 'img_size',
1358 'oi_width' => 'img_width',
1359 'oi_height' => 'img_height',
1360 'oi_bits' => 'img_bits',
1361 'oi_timestamp' => 'img_timestamp',
1362 'oi_description' => 'img_description',
1363 'oi_user' => 'img_user',
1364 'oi_user_text' => 'img_user_text',
1365 'oi_metadata' => 'img_metadata',
1366 'oi_media_type' => 'img_media_type',
1367 'oi_major_mime' => 'img_major_mime',
1368 'oi_minor_mime' => 'img_minor_mime',
1369 'oi_sha1' => 'img_sha1'
1371 [ 'img_name' => $this->getName() ],
1375 # Update the current image row
1376 $dbw->update( 'image',
1378 'img_size' => $this->size
,
1379 'img_width' => intval( $this->width
),
1380 'img_height' => intval( $this->height
),
1381 'img_bits' => $this->bits
,
1382 'img_media_type' => $this->media_type
,
1383 'img_major_mime' => $this->major_mime
,
1384 'img_minor_mime' => $this->minor_mime
,
1385 'img_timestamp' => $timestamp,
1386 'img_description' => $comment,
1387 'img_user' => $user->getId(),
1388 'img_user_text' => $user->getName(),
1389 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1390 'img_sha1' => $this->sha1
1392 [ 'img_name' => $this->getName() ],
1397 $descTitle = $this->getTitle();
1398 $descId = $descTitle->getArticleID();
1399 $wikiPage = new WikiFilePage( $descTitle );
1400 $wikiPage->setFile( $this );
1402 // Add the log entry...
1403 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1404 $logEntry->setTimestamp( $this->timestamp
);
1405 $logEntry->setPerformer( $user );
1406 $logEntry->setComment( $comment );
1407 $logEntry->setTarget( $descTitle );
1408 // Allow people using the api to associate log entries with the upload.
1409 // Log has a timestamp, but sometimes different from upload timestamp.
1410 $logEntry->setParameters(
1412 'img_sha1' => $this->sha1
,
1413 'img_timestamp' => $timestamp,
1416 // Note we keep $logId around since during new image
1417 // creation, page doesn't exist yet, so log_page = 0
1418 // but we want it to point to the page we're making,
1419 // so we later modify the log entry.
1420 // For a similar reason, we avoid making an RC entry
1421 // now and wait until the page exists.
1422 $logId = $logEntry->insert();
1424 if ( $descTitle->exists() ) {
1425 // Use own context to get the action text in content language
1426 $formatter = LogFormatter
::newFromEntry( $logEntry );
1427 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1428 $editSummary = $formatter->getPlainActionText();
1430 $nullRevision = Revision
::newNullRevision(
1437 if ( $nullRevision ) {
1438 $nullRevision->insertOn( $dbw );
1440 'NewRevisionFromEditComplete',
1441 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1443 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1444 // Associate null revision id
1445 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1448 $newPageContent = null;
1450 // Make the description page and RC log entry post-commit
1451 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1454 # Defer purges, page creation, and link updates in case they error out.
1455 # The most important thing is that files and the DB registry stay synced.
1456 $dbw->endAtomic( __METHOD__
);
1458 # Do some cache purges after final commit so that:
1459 # a) Changes are more likely to be seen post-purge
1460 # b) They won't cause rollback of the log publish/update above
1461 DeferredUpdates
::addUpdate(
1462 new AutoCommitUpdate(
1466 $reupload, $wikiPage, $newPageContent, $comment, $user,
1467 $logEntry, $logId, $descId, $tags
1469 # Update memcache after the commit
1470 $this->invalidateCache();
1472 $updateLogPage = false;
1473 if ( $newPageContent ) {
1474 # New file page; create the description page.
1475 # There's already a log entry, so don't make a second RC entry
1476 # CDN and file cache for the description page are purged by doEditContent.
1477 $status = $wikiPage->doEditContent(
1480 EDIT_NEW | EDIT_SUPPRESS_RC
,
1485 if ( isset( $status->value
['revision'] ) ) {
1486 // Associate new page revision id
1487 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1489 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1490 // which is triggered on $descTitle by doEditContent() above.
1491 if ( isset( $status->value
['revision'] ) ) {
1492 /** @var $rev Revision */
1493 $rev = $status->value
['revision'];
1494 $updateLogPage = $rev->getPage();
1497 # Existing file page: invalidate description page cache
1498 $wikiPage->getTitle()->invalidateCache();
1499 $wikiPage->getTitle()->purgeSquid();
1500 # Allow the new file version to be patrolled from the page footer
1501 Article
::purgePatrolFooterCache( $descId );
1504 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1505 # but setAssociatedRevId() wasn't called at that point yet...
1506 $logParams = $logEntry->getParameters();
1507 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1508 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1509 if ( $updateLogPage ) {
1510 # Also log page, in case where we just created it above
1511 $update['log_page'] = $updateLogPage;
1513 $this->getRepo()->getMasterDB()->update(
1516 [ 'log_id' => $logId ],
1519 $this->getRepo()->getMasterDB()->insert(
1522 'ls_field' => 'associated_rev_id',
1523 'ls_value' => $logEntry->getAssociatedRevId(),
1524 'ls_log_id' => $logId,
1529 # Add change tags, if any
1531 $logEntry->setTags( $tags );
1534 # Uploads can be patrolled
1535 $logEntry->setIsPatrollable( true );
1537 # Now that the log entry is up-to-date, make an RC entry.
1538 $logEntry->publish( $logId );
1540 # Run hook for other updates (typically more cache purging)
1541 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1544 # Delete old thumbnails
1545 $this->purgeThumbnails();
1546 # Remove the old file from the CDN cache
1547 DeferredUpdates
::addUpdate(
1548 new CdnCacheUpdate( [ $this->getUrl() ] ),
1549 DeferredUpdates
::PRESEND
1552 # Update backlink pages pointing to this title if created
1553 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1556 $this->prerenderThumbnails();
1559 DeferredUpdates
::PRESEND
1563 # This is a new file, so update the image count
1564 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1567 # Invalidate cache for all pages using this file
1568 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1574 * Move or copy a file to its public location. If a file exists at the
1575 * destination, move it to an archive. Returns a FileRepoStatus object with
1576 * the archive name in the "value" member on success.
1578 * The archive name should be passed through to recordUpload for database
1581 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1582 * @param int $flags A bitwise combination of:
1583 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1584 * @param array $options Optional additional parameters
1585 * @return FileRepoStatus On success, the value member contains the
1586 * archive name, or an empty string if it was a new file.
1588 function publish( $src, $flags = 0, array $options = [] ) {
1589 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1593 * Move or copy a file to a specified location. Returns a FileRepoStatus
1594 * object with the archive name in the "value" member on success.
1596 * The archive name should be passed through to recordUpload for database
1599 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1600 * @param string $dstRel Target relative path
1601 * @param int $flags A bitwise combination of:
1602 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1603 * @param array $options Optional additional parameters
1604 * @return FileRepoStatus On success, the value member contains the
1605 * archive name, or an empty string if it was a new file.
1607 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1608 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1610 $repo = $this->getRepo();
1611 if ( $repo->getReadOnlyReason() !== false ) {
1612 return $this->readOnlyFatalStatus();
1615 $this->lock(); // begin
1617 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1618 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1620 if ( $repo->hasSha1Storage() ) {
1621 $sha1 = $repo->isVirtualUrl( $srcPath )
1622 ?
$repo->getFileSha1( $srcPath )
1623 : FSFile
::getSha1Base36FromPath( $srcPath );
1624 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1625 $status = $repo->quickImport( $src, $dst );
1626 if ( $flags & File
::DELETE_SOURCE
) {
1630 if ( $this->exists() ) {
1631 $status->value
= $archiveName;
1634 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1635 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1637 if ( $status->value
== 'new' ) {
1638 $status->value
= '';
1640 $status->value
= $archiveName;
1644 $this->unlock(); // done
1649 /** getLinksTo inherited */
1650 /** getExifData inherited */
1651 /** isLocal inherited */
1652 /** wasDeleted inherited */
1655 * Move file to the new title
1657 * Move current, old version and all thumbnails
1658 * to the new filename. Old file is deleted.
1660 * Cache purging is done; checks for validity
1661 * and logging are caller's responsibility
1663 * @param Title $target New file name
1664 * @return FileRepoStatus
1666 function move( $target ) {
1667 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1668 return $this->readOnlyFatalStatus();
1671 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1672 $batch = new LocalFileMoveBatch( $this, $target );
1674 $this->lock(); // begin
1675 $batch->addCurrent();
1676 $archiveNames = $batch->addOlds();
1677 $status = $batch->execute();
1678 $this->unlock(); // done
1680 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1682 // Purge the source and target files...
1683 $oldTitleFile = wfLocalFile( $this->title
);
1684 $newTitleFile = wfLocalFile( $target );
1685 // To avoid slow purges in the transaction, move them outside...
1686 DeferredUpdates
::addUpdate(
1687 new AutoCommitUpdate(
1688 $this->getRepo()->getMasterDB(),
1690 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1691 $oldTitleFile->purgeEverything();
1692 foreach ( $archiveNames as $archiveName ) {
1693 $oldTitleFile->purgeOldThumbnails( $archiveName );
1695 $newTitleFile->purgeEverything();
1698 DeferredUpdates
::PRESEND
1701 if ( $status->isOK() ) {
1702 // Now switch the object
1703 $this->title
= $target;
1704 // Force regeneration of the name and hashpath
1705 unset( $this->name
);
1706 unset( $this->hashPath
);
1713 * Delete all versions of the file.
1715 * Moves the files into an archive directory (or deletes them)
1716 * and removes the database rows.
1718 * Cache purging is done; logging is caller's responsibility.
1720 * @param string $reason
1721 * @param bool $suppress
1722 * @param User|null $user
1723 * @return FileRepoStatus
1725 function delete( $reason, $suppress = false, $user = null ) {
1726 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1727 return $this->readOnlyFatalStatus();
1730 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1732 $this->lock(); // begin
1733 $batch->addCurrent();
1734 // Get old version relative paths
1735 $archiveNames = $batch->addOlds();
1736 $status = $batch->execute();
1737 $this->unlock(); // done
1739 if ( $status->isOK() ) {
1740 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1743 // To avoid slow purges in the transaction, move them outside...
1744 DeferredUpdates
::addUpdate(
1745 new AutoCommitUpdate(
1746 $this->getRepo()->getMasterDB(),
1748 function () use ( $archiveNames ) {
1749 $this->purgeEverything();
1750 foreach ( $archiveNames as $archiveName ) {
1751 $this->purgeOldThumbnails( $archiveName );
1755 DeferredUpdates
::PRESEND
1760 foreach ( $archiveNames as $archiveName ) {
1761 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1763 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1769 * Delete an old version of the file.
1771 * Moves the file into an archive directory (or deletes it)
1772 * and removes the database row.
1774 * Cache purging is done; logging is caller's responsibility.
1776 * @param string $archiveName
1777 * @param string $reason
1778 * @param bool $suppress
1779 * @param User|null $user
1780 * @throws MWException Exception on database or file store failure
1781 * @return FileRepoStatus
1783 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1784 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1785 return $this->readOnlyFatalStatus();
1788 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1790 $this->lock(); // begin
1791 $batch->addOld( $archiveName );
1792 $status = $batch->execute();
1793 $this->unlock(); // done
1795 $this->purgeOldThumbnails( $archiveName );
1796 if ( $status->isOK() ) {
1797 $this->purgeDescription();
1800 DeferredUpdates
::addUpdate(
1801 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1802 DeferredUpdates
::PRESEND
1809 * Restore all or specified deleted revisions to the given file.
1810 * Permissions and logging are left to the caller.
1812 * May throw database exceptions on error.
1814 * @param array $versions Set of record ids of deleted items to restore,
1815 * or empty to restore all revisions.
1816 * @param bool $unsuppress
1817 * @return FileRepoStatus
1819 function restore( $versions = [], $unsuppress = false ) {
1820 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1821 return $this->readOnlyFatalStatus();
1824 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1826 $this->lock(); // begin
1830 $batch->addIds( $versions );
1832 $status = $batch->execute();
1833 if ( $status->isGood() ) {
1834 $cleanupStatus = $batch->cleanup();
1835 $cleanupStatus->successCount
= 0;
1836 $cleanupStatus->failCount
= 0;
1837 $status->merge( $cleanupStatus );
1839 $this->unlock(); // done
1844 /** isMultipage inherited */
1845 /** pageCount inherited */
1846 /** scaleHeight inherited */
1847 /** getImageSize inherited */
1850 * Get the URL of the file description page.
1853 function getDescriptionUrl() {
1854 return $this->title
->getLocalURL();
1858 * Get the HTML text of the description page
1859 * This is not used by ImagePage for local files, since (among other things)
1860 * it skips the parser cache.
1862 * @param Language $lang What language to get description in (Optional)
1863 * @return bool|mixed
1865 function getDescriptionText( $lang = null ) {
1866 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1870 $content = $revision->getContent();
1874 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1876 return $pout->getText();
1880 * @param int $audience
1884 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1886 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1888 } elseif ( $audience == self
::FOR_THIS_USER
1889 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1893 return $this->description
;
1898 * @return bool|string
1900 function getTimestamp() {
1903 return $this->timestamp
;
1907 * @return bool|string
1909 public function getDescriptionTouched() {
1910 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1911 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1912 // need to differentiate between null (uninitialized) and false (failed to load).
1913 if ( $this->descriptionTouched
=== null ) {
1915 'page_namespace' => $this->title
->getNamespace(),
1916 'page_title' => $this->title
->getDBkey()
1918 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1919 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1922 return $this->descriptionTouched
;
1928 function getSha1() {
1930 // Initialise now if necessary
1931 if ( $this->sha1
== '' && $this->fileExists
) {
1932 $this->lock(); // begin
1934 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1935 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1936 $dbw = $this->repo
->getMasterDB();
1937 $dbw->update( 'image',
1938 [ 'img_sha1' => $this->sha1
],
1939 [ 'img_name' => $this->getName() ],
1941 $this->invalidateCache();
1944 $this->unlock(); // done
1951 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1953 function isCacheable() {
1956 // If extra data (metadata) was not loaded then it must have been large
1957 return $this->extraDataLoaded
1958 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1965 public function acquireFileLock() {
1966 return $this->getRepo()->getBackend()->lockFiles(
1967 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1975 public function releaseFileLock() {
1976 return $this->getRepo()->getBackend()->unlockFiles(
1977 [ $this->getPath() ], LockManager
::LOCK_EX
1982 * Start an atomic DB section and lock the image for update
1983 * or increments a reference counter if the lock is already held
1985 * This method should not be used outside of LocalFile/LocalFile*Batch
1987 * @throws LocalFileLockError Throws an error if the lock was not acquired
1988 * @return bool Whether the file lock owns/spawned the DB transaction
1990 public function lock() {
1991 if ( !$this->locked
) {
1992 $logger = LoggerFactory
::getInstance( 'LocalFile' );
1994 $dbw = $this->repo
->getMasterDB();
1995 $makesTransaction = !$dbw->trxLevel();
1996 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
1997 // Bug 54736: use simple lock to handle when the file does not exist.
1998 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1999 // Also, that would cause contention on INSERT of similarly named rows.
2000 $status = $this->acquireFileLock(); // represents all versions of the file
2001 if ( !$status->isGood() ) {
2002 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2003 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2005 throw new LocalFileLockError( $status );
2007 // Release the lock *after* commit to avoid row-level contention.
2008 // Make sure it triggers on rollback() as well as commit() (T132921).
2009 $dbw->onTransactionResolution( function () use ( $logger ) {
2010 $status = $this->releaseFileLock();
2011 if ( !$status->isGood() ) {
2012 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2015 // Callers might care if the SELECT snapshot is safely fresh
2016 $this->lockedOwnTrx
= $makesTransaction;
2021 return $this->lockedOwnTrx
;
2025 * Decrement the lock reference count and end the atomic section if it reaches zero
2027 * This method should not be used outside of LocalFile/LocalFile*Batch
2029 * The commit and loc release will happen when no atomic sections are active, which
2030 * may happen immediately or at some point after calling this
2032 public function unlock() {
2033 if ( $this->locked
) {
2035 if ( !$this->locked
) {
2036 $dbw = $this->repo
->getMasterDB();
2037 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2038 $this->lockedOwnTrx
= false;
2046 protected function readOnlyFatalStatus() {
2047 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2048 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2052 * Clean up any dangling locks
2054 function __destruct() {
2057 } // LocalFile class
2059 # ------------------------------------------------------------------------------
2062 * Helper class for file deletion
2063 * @ingroup FileAbstraction
2065 class LocalFileDeleteBatch
{
2066 /** @var LocalFile */
2073 private $srcRels = [];
2076 private $archiveUrls = [];
2078 /** @var array Items to be processed in the deletion batch */
2079 private $deletionBatch;
2081 /** @var bool Whether to suppress all suppressable fields when deleting */
2084 /** @var FileRepoStatus */
2092 * @param string $reason
2093 * @param bool $suppress
2094 * @param User|null $user
2096 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2097 $this->file
= $file;
2098 $this->reason
= $reason;
2099 $this->suppress
= $suppress;
2101 $this->user
= $user;
2104 $this->user
= $wgUser;
2106 $this->status
= $file->repo
->newGood();
2109 public function addCurrent() {
2110 $this->srcRels
['.'] = $this->file
->getRel();
2114 * @param string $oldName
2116 public function addOld( $oldName ) {
2117 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2118 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2122 * Add the old versions of the image to the batch
2123 * @return array List of archive names from old versions
2125 public function addOlds() {
2128 $dbw = $this->file
->repo
->getMasterDB();
2129 $result = $dbw->select( 'oldimage',
2130 [ 'oi_archive_name' ],
2131 [ 'oi_name' => $this->file
->getName() ],
2135 foreach ( $result as $row ) {
2136 $this->addOld( $row->oi_archive_name
);
2137 $archiveNames[] = $row->oi_archive_name
;
2140 return $archiveNames;
2146 protected function getOldRels() {
2147 if ( !isset( $this->srcRels
['.'] ) ) {
2148 $oldRels =& $this->srcRels
;
2149 $deleteCurrent = false;
2151 $oldRels = $this->srcRels
;
2152 unset( $oldRels['.'] );
2153 $deleteCurrent = true;
2156 return [ $oldRels, $deleteCurrent ];
2162 protected function getHashes() {
2164 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2166 if ( $deleteCurrent ) {
2167 $hashes['.'] = $this->file
->getSha1();
2170 if ( count( $oldRels ) ) {
2171 $dbw = $this->file
->repo
->getMasterDB();
2172 $res = $dbw->select(
2174 [ 'oi_archive_name', 'oi_sha1' ],
2175 [ 'oi_archive_name' => array_keys( $oldRels ),
2176 'oi_name' => $this->file
->getName() ], // performance
2180 foreach ( $res as $row ) {
2181 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2182 // Get the hash from the file
2183 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2184 $props = $this->file
->repo
->getFileProps( $oldUrl );
2186 if ( $props['fileExists'] ) {
2187 // Upgrade the oldimage row
2188 $dbw->update( 'oldimage',
2189 [ 'oi_sha1' => $props['sha1'] ],
2190 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2192 $hashes[$row->oi_archive_name
] = $props['sha1'];
2194 $hashes[$row->oi_archive_name
] = false;
2197 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2202 $missing = array_diff_key( $this->srcRels
, $hashes );
2204 foreach ( $missing as $name => $rel ) {
2205 $this->status
->error( 'filedelete-old-unregistered', $name );
2208 foreach ( $hashes as $name => $hash ) {
2210 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2211 unset( $hashes[$name] );
2218 protected function doDBInserts() {
2219 $dbw = $this->file
->repo
->getMasterDB();
2220 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2221 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2222 $encReason = $dbw->addQuotes( $this->reason
);
2223 $encGroup = $dbw->addQuotes( 'deleted' );
2224 $ext = $this->file
->getExtension();
2225 $dotExt = $ext === '' ?
'' : ".$ext";
2226 $encExt = $dbw->addQuotes( $dotExt );
2227 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2229 // Bitfields to further suppress the content
2230 if ( $this->suppress
) {
2232 // This should be 15...
2233 $bitfield |
= Revision
::DELETED_TEXT
;
2234 $bitfield |
= Revision
::DELETED_COMMENT
;
2235 $bitfield |
= Revision
::DELETED_USER
;
2236 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2238 $bitfield = 'oi_deleted';
2241 if ( $deleteCurrent ) {
2242 $concat = $dbw->buildConcat( [ "img_sha1", $encExt ] );
2243 $where = [ 'img_name' => $this->file
->getName() ];
2244 $dbw->insertSelect( 'filearchive', 'image',
2246 'fa_storage_group' => $encGroup,
2247 'fa_storage_key' => $dbw->conditional(
2248 [ 'img_sha1' => '' ],
2249 $dbw->addQuotes( '' ),
2252 'fa_deleted_user' => $encUserId,
2253 'fa_deleted_timestamp' => $encTimestamp,
2254 'fa_deleted_reason' => $encReason,
2255 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2257 'fa_name' => 'img_name',
2258 'fa_archive_name' => 'NULL',
2259 'fa_size' => 'img_size',
2260 'fa_width' => 'img_width',
2261 'fa_height' => 'img_height',
2262 'fa_metadata' => 'img_metadata',
2263 'fa_bits' => 'img_bits',
2264 'fa_media_type' => 'img_media_type',
2265 'fa_major_mime' => 'img_major_mime',
2266 'fa_minor_mime' => 'img_minor_mime',
2267 'fa_description' => 'img_description',
2268 'fa_user' => 'img_user',
2269 'fa_user_text' => 'img_user_text',
2270 'fa_timestamp' => 'img_timestamp',
2271 'fa_sha1' => 'img_sha1',
2272 ], $where, __METHOD__
);
2275 if ( count( $oldRels ) ) {
2276 $concat = $dbw->buildConcat( [ "oi_sha1", $encExt ] );
2278 'oi_name' => $this->file
->getName(),
2279 'oi_archive_name' => array_keys( $oldRels ) ];
2280 $dbw->insertSelect( 'filearchive', 'oldimage',
2282 'fa_storage_group' => $encGroup,
2283 'fa_storage_key' => $dbw->conditional(
2284 [ 'oi_sha1' => '' ],
2285 $dbw->addQuotes( '' ),
2288 'fa_deleted_user' => $encUserId,
2289 'fa_deleted_timestamp' => $encTimestamp,
2290 'fa_deleted_reason' => $encReason,
2291 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2293 'fa_name' => 'oi_name',
2294 'fa_archive_name' => 'oi_archive_name',
2295 'fa_size' => 'oi_size',
2296 'fa_width' => 'oi_width',
2297 'fa_height' => 'oi_height',
2298 'fa_metadata' => 'oi_metadata',
2299 'fa_bits' => 'oi_bits',
2300 'fa_media_type' => 'oi_media_type',
2301 'fa_major_mime' => 'oi_major_mime',
2302 'fa_minor_mime' => 'oi_minor_mime',
2303 'fa_description' => 'oi_description',
2304 'fa_user' => 'oi_user',
2305 'fa_user_text' => 'oi_user_text',
2306 'fa_timestamp' => 'oi_timestamp',
2307 'fa_sha1' => 'oi_sha1',
2308 ], $where, __METHOD__
);
2312 function doDBDeletes() {
2313 $dbw = $this->file
->repo
->getMasterDB();
2314 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2316 if ( count( $oldRels ) ) {
2317 $dbw->delete( 'oldimage',
2319 'oi_name' => $this->file
->getName(),
2320 'oi_archive_name' => array_keys( $oldRels )
2324 if ( $deleteCurrent ) {
2325 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2330 * Run the transaction
2331 * @return FileRepoStatus
2333 public function execute() {
2334 $repo = $this->file
->getRepo();
2335 $this->file
->lock();
2337 // Prepare deletion batch
2338 $hashes = $this->getHashes();
2339 $this->deletionBatch
= [];
2340 $ext = $this->file
->getExtension();
2341 $dotExt = $ext === '' ?
'' : ".$ext";
2343 foreach ( $this->srcRels
as $name => $srcRel ) {
2344 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2345 if ( isset( $hashes[$name] ) ) {
2346 $hash = $hashes[$name];
2347 $key = $hash . $dotExt;
2348 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2349 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2353 if ( !$repo->hasSha1Storage() ) {
2354 // Removes non-existent file from the batch, so we don't get errors.
2355 // This also handles files in the 'deleted' zone deleted via revision deletion.
2356 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2357 if ( !$checkStatus->isGood() ) {
2358 $this->status
->merge( $checkStatus );
2359 return $this->status
;
2361 $this->deletionBatch
= $checkStatus->value
;
2363 // Execute the file deletion batch
2364 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2365 if ( !$status->isGood() ) {
2366 $this->status
->merge( $status );
2370 if ( !$this->status
->isOK() ) {
2371 // Critical file deletion error; abort
2372 $this->file
->unlock();
2374 return $this->status
;
2377 // Copy the image/oldimage rows to filearchive
2378 $this->doDBInserts();
2379 // Delete image/oldimage rows
2380 $this->doDBDeletes();
2382 // Commit and return
2383 $this->file
->unlock();
2385 return $this->status
;
2389 * Removes non-existent files from a deletion batch.
2390 * @param array $batch
2393 protected function removeNonexistentFiles( $batch ) {
2394 $files = $newBatch = [];
2396 foreach ( $batch as $batchItem ) {
2397 list( $src, ) = $batchItem;
2398 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2401 $result = $this->file
->repo
->fileExistsBatch( $files );
2402 if ( in_array( null, $result, true ) ) {
2403 return Status
::newFatal( 'backend-fail-internal',
2404 $this->file
->repo
->getBackend()->getName() );
2407 foreach ( $batch as $batchItem ) {
2408 if ( $result[$batchItem[0]] ) {
2409 $newBatch[] = $batchItem;
2413 return Status
::newGood( $newBatch );
2417 # ------------------------------------------------------------------------------
2420 * Helper class for file undeletion
2421 * @ingroup FileAbstraction
2423 class LocalFileRestoreBatch
{
2424 /** @var LocalFile */
2427 /** @var array List of file IDs to restore */
2428 private $cleanupBatch;
2430 /** @var array List of file IDs to restore */
2433 /** @var bool Add all revisions of the file */
2436 /** @var bool Whether to remove all settings for suppressed fields */
2437 private $unsuppress = false;
2441 * @param bool $unsuppress
2443 function __construct( File
$file, $unsuppress = false ) {
2444 $this->file
= $file;
2445 $this->cleanupBatch
= $this->ids
= [];
2447 $this->unsuppress
= $unsuppress;
2454 public function addId( $fa_id ) {
2455 $this->ids
[] = $fa_id;
2459 * Add a whole lot of files by ID
2462 public function addIds( $ids ) {
2463 $this->ids
= array_merge( $this->ids
, $ids );
2467 * Add all revisions of the file
2469 public function addAll() {
2474 * Run the transaction, except the cleanup batch.
2475 * The cleanup batch should be run in a separate transaction, because it locks different
2476 * rows and there's no need to keep the image row locked while it's acquiring those locks
2477 * The caller may have its own transaction open.
2478 * So we save the batch and let the caller call cleanup()
2479 * @return FileRepoStatus
2481 public function execute() {
2484 $repo = $this->file
->getRepo();
2485 if ( !$this->all
&& !$this->ids
) {
2487 return $repo->newGood();
2490 $lockOwnsTrx = $this->file
->lock();
2492 $dbw = $this->file
->repo
->getMasterDB();
2493 $status = $this->file
->repo
->newGood();
2495 $exists = (bool)$dbw->selectField( 'image', '1',
2496 [ 'img_name' => $this->file
->getName() ],
2498 // The lock() should already prevents changes, but this still may need
2499 // to bypass any transaction snapshot. However, if lock() started the
2500 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2501 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2504 // Fetch all or selected archived revisions for the file,
2505 // sorted from the most recent to the oldest.
2506 $conditions = [ 'fa_name' => $this->file
->getName() ];
2508 if ( !$this->all
) {
2509 $conditions['fa_id'] = $this->ids
;
2512 $result = $dbw->select(
2514 ArchivedFile
::selectFields(),
2517 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2523 $insertCurrent = false;
2528 foreach ( $result as $row ) {
2529 $idsPresent[] = $row->fa_id
;
2531 if ( $row->fa_name
!= $this->file
->getName() ) {
2532 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2533 $status->failCount++
;
2537 if ( $row->fa_storage_key
== '' ) {
2538 // Revision was missing pre-deletion
2539 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2540 $status->failCount++
;
2544 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2545 $row->fa_storage_key
;
2546 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2548 if ( isset( $row->fa_sha1
) ) {
2549 $sha1 = $row->fa_sha1
;
2551 // old row, populate from key
2552 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2556 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2557 $sha1 = substr( $sha1, 1 );
2560 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2561 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2562 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2563 ||
is_null( $row->fa_metadata
)
2565 // Refresh our metadata
2566 // Required for a new current revision; nice for older ones too. :)
2567 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2570 'minor_mime' => $row->fa_minor_mime
,
2571 'major_mime' => $row->fa_major_mime
,
2572 'media_type' => $row->fa_media_type
,
2573 'metadata' => $row->fa_metadata
2577 if ( $first && !$exists ) {
2578 // This revision will be published as the new current version
2579 $destRel = $this->file
->getRel();
2581 'img_name' => $row->fa_name
,
2582 'img_size' => $row->fa_size
,
2583 'img_width' => $row->fa_width
,
2584 'img_height' => $row->fa_height
,
2585 'img_metadata' => $props['metadata'],
2586 'img_bits' => $row->fa_bits
,
2587 'img_media_type' => $props['media_type'],
2588 'img_major_mime' => $props['major_mime'],
2589 'img_minor_mime' => $props['minor_mime'],
2590 'img_description' => $row->fa_description
,
2591 'img_user' => $row->fa_user
,
2592 'img_user_text' => $row->fa_user_text
,
2593 'img_timestamp' => $row->fa_timestamp
,
2597 // The live (current) version cannot be hidden!
2598 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2599 $status->fatal( 'undeleterevdel' );
2600 $this->file
->unlock();
2604 $archiveName = $row->fa_archive_name
;
2606 if ( $archiveName == '' ) {
2607 // This was originally a current version; we
2608 // have to devise a new archive name for it.
2609 // Format is <timestamp of archiving>!<name>
2610 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2613 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2615 } while ( isset( $archiveNames[$archiveName] ) );
2618 $archiveNames[$archiveName] = true;
2619 $destRel = $this->file
->getArchiveRel( $archiveName );
2621 'oi_name' => $row->fa_name
,
2622 'oi_archive_name' => $archiveName,
2623 'oi_size' => $row->fa_size
,
2624 'oi_width' => $row->fa_width
,
2625 'oi_height' => $row->fa_height
,
2626 'oi_bits' => $row->fa_bits
,
2627 'oi_description' => $row->fa_description
,
2628 'oi_user' => $row->fa_user
,
2629 'oi_user_text' => $row->fa_user_text
,
2630 'oi_timestamp' => $row->fa_timestamp
,
2631 'oi_metadata' => $props['metadata'],
2632 'oi_media_type' => $props['media_type'],
2633 'oi_major_mime' => $props['major_mime'],
2634 'oi_minor_mime' => $props['minor_mime'],
2635 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2636 'oi_sha1' => $sha1 ];
2639 $deleteIds[] = $row->fa_id
;
2641 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2642 // private files can stay where they are
2643 $status->successCount++
;
2645 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2646 $this->cleanupBatch
[] = $row->fa_storage_key
;
2654 // Add a warning to the status object for missing IDs
2655 $missingIds = array_diff( $this->ids
, $idsPresent );
2657 foreach ( $missingIds as $id ) {
2658 $status->error( 'undelete-missing-filearchive', $id );
2661 if ( !$repo->hasSha1Storage() ) {
2662 // Remove missing files from batch, so we don't get errors when undeleting them
2663 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2664 if ( !$checkStatus->isGood() ) {
2665 $status->merge( $checkStatus );
2668 $storeBatch = $checkStatus->value
;
2670 // Run the store batch
2671 // Use the OVERWRITE_SAME flag to smooth over a common error
2672 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2673 $status->merge( $storeStatus );
2675 if ( !$status->isGood() ) {
2676 // Even if some files could be copied, fail entirely as that is the
2677 // easiest thing to do without data loss
2678 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2679 $status->ok
= false;
2680 $this->file
->unlock();
2686 // Run the DB updates
2687 // Because we have locked the image row, key conflicts should be rare.
2688 // If they do occur, we can roll back the transaction at this time with
2689 // no data loss, but leaving unregistered files scattered throughout the
2691 // This is not ideal, which is why it's important to lock the image row.
2692 if ( $insertCurrent ) {
2693 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2696 if ( $insertBatch ) {
2697 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2701 $dbw->delete( 'filearchive',
2702 [ 'fa_id' => $deleteIds ],
2706 // If store batch is empty (all files are missing), deletion is to be considered successful
2707 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2709 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2711 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2713 $this->file
->purgeEverything();
2715 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2716 $this->file
->purgeDescription();
2720 $this->file
->unlock();
2726 * Removes non-existent files from a store batch.
2727 * @param array $triplets
2730 protected function removeNonexistentFiles( $triplets ) {
2731 $files = $filteredTriplets = [];
2732 foreach ( $triplets as $file ) {
2733 $files[$file[0]] = $file[0];
2736 $result = $this->file
->repo
->fileExistsBatch( $files );
2737 if ( in_array( null, $result, true ) ) {
2738 return Status
::newFatal( 'backend-fail-internal',
2739 $this->file
->repo
->getBackend()->getName() );
2742 foreach ( $triplets as $file ) {
2743 if ( $result[$file[0]] ) {
2744 $filteredTriplets[] = $file;
2748 return Status
::newGood( $filteredTriplets );
2752 * Removes non-existent files from a cleanup batch.
2753 * @param array $batch
2756 protected function removeNonexistentFromCleanup( $batch ) {
2757 $files = $newBatch = [];
2758 $repo = $this->file
->repo
;
2760 foreach ( $batch as $file ) {
2761 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2762 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2765 $result = $repo->fileExistsBatch( $files );
2767 foreach ( $batch as $file ) {
2768 if ( $result[$file] ) {
2769 $newBatch[] = $file;
2777 * Delete unused files in the deleted zone.
2778 * This should be called from outside the transaction in which execute() was called.
2779 * @return FileRepoStatus
2781 public function cleanup() {
2782 if ( !$this->cleanupBatch
) {
2783 return $this->file
->repo
->newGood();
2786 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2788 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2794 * Cleanup a failed batch. The batch was only partially successful, so
2795 * rollback by removing all items that were succesfully copied.
2797 * @param Status $storeStatus
2798 * @param array $storeBatch
2800 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2803 foreach ( $storeStatus->success
as $i => $success ) {
2804 // Check if this item of the batch was successfully copied
2806 // Item was successfully copied and needs to be removed again
2807 // Extract ($dstZone, $dstRel) from the batch
2808 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2811 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2815 # ------------------------------------------------------------------------------
2818 * Helper class for file movement
2819 * @ingroup FileAbstraction
2821 class LocalFileMoveBatch
{
2822 /** @var LocalFile */
2832 protected $oldCount;
2836 /** @var DatabaseBase */
2841 * @param Title $target
2843 function __construct( File
$file, Title
$target ) {
2844 $this->file
= $file;
2845 $this->target
= $target;
2846 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2847 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2848 $this->oldName
= $this->file
->getName();
2849 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2850 $this->oldRel
= $this->oldHash
. $this->oldName
;
2851 $this->newRel
= $this->newHash
. $this->newName
;
2852 $this->db
= $file->getRepo()->getMasterDB();
2856 * Add the current image to the batch
2858 public function addCurrent() {
2859 $this->cur
= [ $this->oldRel
, $this->newRel
];
2863 * Add the old versions of the image to the batch
2864 * @return array List of archive names from old versions
2866 public function addOlds() {
2867 $archiveBase = 'archive';
2869 $this->oldCount
= 0;
2872 $result = $this->db
->select( 'oldimage',
2873 [ 'oi_archive_name', 'oi_deleted' ],
2874 [ 'oi_name' => $this->oldName
],
2876 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2879 foreach ( $result as $row ) {
2880 $archiveNames[] = $row->oi_archive_name
;
2881 $oldName = $row->oi_archive_name
;
2882 $bits = explode( '!', $oldName, 2 );
2884 if ( count( $bits ) != 2 ) {
2885 wfDebug( "Old file name missing !: '$oldName' \n" );
2889 list( $timestamp, $filename ) = $bits;
2891 if ( $this->oldName
!= $filename ) {
2892 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2898 // Do we want to add those to oldCount?
2899 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2904 "{$archiveBase}/{$this->oldHash}{$oldName}",
2905 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2909 return $archiveNames;
2914 * @return FileRepoStatus
2916 public function execute() {
2917 $repo = $this->file
->repo
;
2918 $status = $repo->newGood();
2919 $destFile = wfLocalFile( $this->target
);
2921 $this->file
->lock(); // begin
2922 $destFile->lock(); // quickly fail if destination is not available
2924 $triplets = $this->getMoveTriplets();
2925 $checkStatus = $this->removeNonexistentFiles( $triplets );
2926 if ( !$checkStatus->isGood() ) {
2927 $destFile->unlock();
2928 $this->file
->unlock();
2929 $status->merge( $checkStatus ); // couldn't talk to file backend
2932 $triplets = $checkStatus->value
;
2934 // Verify the file versions metadata in the DB.
2935 $statusDb = $this->verifyDBUpdates();
2936 if ( !$statusDb->isGood() ) {
2937 $destFile->unlock();
2938 $this->file
->unlock();
2939 $statusDb->ok
= false;
2944 if ( !$repo->hasSha1Storage() ) {
2945 // Copy the files into their new location.
2946 // If a prior process fataled copying or cleaning up files we tolerate any
2947 // of the existing files if they are identical to the ones being stored.
2948 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2949 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2950 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2951 if ( !$statusMove->isGood() ) {
2952 // Delete any files copied over (while the destination is still locked)
2953 $this->cleanupTarget( $triplets );
2954 $destFile->unlock();
2955 $this->file
->unlock();
2956 wfDebugLog( 'imagemove', "Error in moving files: "
2957 . $statusMove->getWikiText( false, false, 'en' ) );
2958 $statusMove->ok
= false;
2962 $status->merge( $statusMove );
2965 // Rename the file versions metadata in the DB.
2966 $this->doDBUpdates();
2968 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2969 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2971 $destFile->unlock();
2972 $this->file
->unlock(); // done
2974 // Everything went ok, remove the source files
2975 $this->cleanupSource( $triplets );
2977 $status->merge( $statusDb );
2983 * Verify the database updates and return a new FileRepoStatus indicating how
2984 * many rows would be updated.
2986 * @return FileRepoStatus
2988 protected function verifyDBUpdates() {
2989 $repo = $this->file
->repo
;
2990 $status = $repo->newGood();
2993 $hasCurrent = $dbw->selectField(
2996 [ 'img_name' => $this->oldName
],
3000 $oldRowCount = $dbw->selectField(
3003 [ 'oi_name' => $this->oldName
],
3008 if ( $hasCurrent ) {
3009 $status->successCount++
;
3011 $status->failCount++
;
3013 $status->successCount +
= $oldRowCount;
3014 // Bug 34934: oldCount is based on files that actually exist.
3015 // There may be more DB rows than such files, in which case $affected
3016 // can be greater than $total. We use max() to avoid negatives here.
3017 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3018 if ( $status->failCount
) {
3019 $status->error( 'imageinvalidfilename' );
3026 * Do the database updates and return a new FileRepoStatus indicating how
3027 * many rows where updated.
3029 protected function doDBUpdates() {
3032 // Update current image
3035 [ 'img_name' => $this->newName
],
3036 [ 'img_name' => $this->oldName
],
3039 // Update old images
3043 'oi_name' => $this->newName
,
3044 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3045 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3047 [ 'oi_name' => $this->oldName
],
3053 * Generate triplets for FileRepo::storeBatch().
3056 protected function getMoveTriplets() {
3057 $moves = array_merge( [ $this->cur
], $this->olds
);
3058 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3060 foreach ( $moves as $move ) {
3061 // $move: (oldRelativePath, newRelativePath)
3062 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3063 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3066 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3074 * Removes non-existent files from move batch.
3075 * @param array $triplets
3078 protected function removeNonexistentFiles( $triplets ) {
3081 foreach ( $triplets as $file ) {
3082 $files[$file[0]] = $file[0];
3085 $result = $this->file
->repo
->fileExistsBatch( $files );
3086 if ( in_array( null, $result, true ) ) {
3087 return Status
::newFatal( 'backend-fail-internal',
3088 $this->file
->repo
->getBackend()->getName() );
3091 $filteredTriplets = [];
3092 foreach ( $triplets as $file ) {
3093 if ( $result[$file[0]] ) {
3094 $filteredTriplets[] = $file;
3096 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3100 return Status
::newGood( $filteredTriplets );
3104 * Cleanup a partially moved array of triplets by deleting the target
3105 * files. Called if something went wrong half way.
3106 * @param array $triplets
3108 protected function cleanupTarget( $triplets ) {
3109 // Create dest pairs from the triplets
3111 foreach ( $triplets as $triplet ) {
3112 // $triplet: (old source virtual URL, dst zone, dest rel)
3113 $pairs[] = [ $triplet[1], $triplet[2] ];
3116 $this->file
->repo
->cleanupBatch( $pairs );
3120 * Cleanup a fully moved array of triplets by deleting the source files.
3121 * Called at the end of the move process if everything else went ok.
3122 * @param array $triplets
3124 protected function cleanupSource( $triplets ) {
3125 // Create source file names from the triplets
3127 foreach ( $triplets as $triplet ) {
3128 $files[] = $triplet[0];
3131 $this->file
->repo
->cleanupBatch( $files );
3135 class LocalFileLockError
extends ErrorPageError
{
3136 public function __construct( Status
$status ) {
3137 parent
::__construct(
3139 $status->getMessage()
3143 public function report() {
3145 $wgOut->setStatusCode( 429 );