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->getSlaveDB();
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 * Try to load file metadata from memcached, falling back to the database
246 private function loadFromCache() {
247 $this->dataLoaded
= false;
248 $this->extraDataLoaded
= false;
250 $key = $this->getCacheKey();
252 $this->loadFromDB( self
::READ_NORMAL
);
257 $cache = ObjectCache
::getMainWANInstance();
258 $cachedValues = $cache->getWithSetCallback(
261 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
262 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
264 $this->loadFromDB( self
::READ_NORMAL
);
266 $fields = $this->getCacheFields( '' );
267 $cacheVal['fileExists'] = $this->fileExists
;
268 if ( $this->fileExists
) {
269 foreach ( $fields as $field ) {
270 $cacheVal[$field] = $this->$field;
273 // Strip off excessive entries from the subset of fields that can become large.
274 // If the cache value gets to large it will not fit in memcached and nothing will
275 // get cached at all, causing master queries for any file access.
276 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
277 if ( isset( $cacheVal[$field] )
278 && strlen( $cacheVal[$field] ) > 100 * 1024
280 unset( $cacheVal[$field] ); // don't let the value get too big
284 if ( $this->fileExists
) {
285 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
287 $ttl = $cache::TTL_DAY
;
292 [ 'version' => self
::VERSION
]
295 $this->fileExists
= $cachedValues['fileExists'];
296 if ( $this->fileExists
) {
297 $this->setProps( $cachedValues );
300 $this->dataLoaded
= true;
301 $this->extraDataLoaded
= true;
302 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
303 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
308 * Purge the file object/metadata cache
310 public function invalidateCache() {
311 $key = $this->getCacheKey();
316 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
317 function () use ( $key ) {
318 ObjectCache
::getMainWANInstance()->delete( $key );
325 * Load metadata from the file itself
327 function loadFromFile() {
328 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
329 $this->setProps( $props );
333 * @param string $prefix
336 function getCacheFields( $prefix = 'img_' ) {
337 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
338 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
339 'user_text', 'description' ];
340 static $results = [];
342 if ( $prefix == '' ) {
346 if ( !isset( $results[$prefix] ) ) {
347 $prefixedFields = [];
348 foreach ( $fields as $field ) {
349 $prefixedFields[] = $prefix . $field;
351 $results[$prefix] = $prefixedFields;
354 return $results[$prefix];
358 * @param string $prefix
361 function getLazyCacheFields( $prefix = 'img_' ) {
362 static $fields = [ 'metadata' ];
363 static $results = [];
365 if ( $prefix == '' ) {
369 if ( !isset( $results[$prefix] ) ) {
370 $prefixedFields = [];
371 foreach ( $fields as $field ) {
372 $prefixedFields[] = $prefix . $field;
374 $results[$prefix] = $prefixedFields;
377 return $results[$prefix];
381 * Load file metadata from the DB
384 function loadFromDB( $flags = 0 ) {
385 $fname = get_class( $this ) . '::' . __FUNCTION__
;
387 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
388 $this->dataLoaded
= true;
389 $this->extraDataLoaded
= true;
391 $dbr = ( $flags & self
::READ_LATEST
)
392 ?
$this->repo
->getMasterDB()
393 : $this->repo
->getSlaveDB();
395 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
396 [ 'img_name' => $this->getName() ], $fname );
399 $this->loadFromRow( $row );
401 $this->fileExists
= false;
406 * Load lazy file metadata from the DB.
407 * This covers fields that are sometimes not cached.
409 protected function loadExtraFromDB() {
410 $fname = get_class( $this ) . '::' . __FUNCTION__
;
412 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
413 $this->extraDataLoaded
= true;
415 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
417 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
421 foreach ( $fieldMap as $name => $value ) {
422 $this->$name = $value;
425 throw new MWException( "Could not find data for image '{$this->getName()}'." );
430 * @param IDatabase $dbr
431 * @param string $fname
434 private function loadFieldsWithTimestamp( $dbr, $fname ) {
437 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
438 'img_name' => $this->getName(),
439 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
442 $fieldMap = $this->unprefixRow( $row, 'img_' );
444 # File may have been uploaded over in the meantime; check the old versions
445 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
446 'oi_name' => $this->getName(),
447 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
450 $fieldMap = $this->unprefixRow( $row, 'oi_' );
458 * @param array|object $row
459 * @param string $prefix
460 * @throws MWException
463 protected function unprefixRow( $row, $prefix = 'img_' ) {
464 $array = (array)$row;
465 $prefixLength = strlen( $prefix );
467 // Sanity check prefix once
468 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
469 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
473 foreach ( $array as $name => $value ) {
474 $decoded[substr( $name, $prefixLength )] = $value;
481 * Decode a row from the database (either object or array) to an array
482 * with timestamps and MIME types decoded, and the field prefix removed.
484 * @param string $prefix
485 * @throws MWException
488 function decodeRow( $row, $prefix = 'img_' ) {
489 $decoded = $this->unprefixRow( $row, $prefix );
491 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
493 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
495 if ( empty( $decoded['major_mime'] ) ) {
496 $decoded['mime'] = 'unknown/unknown';
498 if ( !$decoded['minor_mime'] ) {
499 $decoded['minor_mime'] = 'unknown';
501 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
504 // Trim zero padding from char/binary field
505 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
507 // Normalize some fields to integer type, per their database definition.
508 // Use unary + so that overflows will be upgraded to double instead of
509 // being trucated as with intval(). This is important to allow >2GB
510 // files on 32-bit systems.
511 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
512 $decoded[$field] = +
$decoded[$field];
519 * Load file metadata from a DB result row
522 * @param string $prefix
524 function loadFromRow( $row, $prefix = 'img_' ) {
525 $this->dataLoaded
= true;
526 $this->extraDataLoaded
= true;
528 $array = $this->decodeRow( $row, $prefix );
530 foreach ( $array as $name => $value ) {
531 $this->$name = $value;
534 $this->fileExists
= true;
535 $this->maybeUpgradeRow();
539 * Load file metadata from cache or DB, unless already loaded
542 function load( $flags = 0 ) {
543 if ( !$this->dataLoaded
) {
544 if ( $flags & self
::READ_LATEST
) {
545 $this->loadFromDB( $flags );
547 $this->loadFromCache();
551 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
552 // @note: loads on name/timestamp to reduce race condition problems
553 $this->loadExtraFromDB();
558 * Upgrade a row if it needs it
560 function maybeUpgradeRow() {
561 global $wgUpdateCompatibleMetadata;
563 if ( wfReadOnly() ||
$this->upgrading
) {
568 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
571 $handler = $this->getHandler();
573 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
574 if ( $validity === MediaHandler
::METADATA_BAD
) {
576 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
577 $upgrade = $wgUpdateCompatibleMetadata;
583 $this->upgrading
= true;
584 // Defer updates unless in auto-commit CLI mode
585 DeferredUpdates
::addCallableUpdate( function() {
586 $this->upgrading
= false; // avoid duplicate updates
589 } catch ( LocalFileLockError
$e ) {
590 // let the other process handle it (or do it next time)
597 * @return bool Whether upgradeRow() ran for this object
599 function getUpgraded() {
600 return $this->upgraded
;
604 * Fix assorted version-related problems with the image row by reloading it from the file
606 function upgradeRow() {
607 $this->lock(); // begin
609 $this->loadFromFile();
611 # Don't destroy file info of missing files
612 if ( !$this->fileExists
) {
614 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
619 $dbw = $this->repo
->getMasterDB();
620 list( $major, $minor ) = self
::splitMime( $this->mime
);
622 if ( wfReadOnly() ) {
627 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
629 $dbw->update( 'image',
631 'img_size' => $this->size
, // sanity
632 'img_width' => $this->width
,
633 'img_height' => $this->height
,
634 'img_bits' => $this->bits
,
635 'img_media_type' => $this->media_type
,
636 'img_major_mime' => $major,
637 'img_minor_mime' => $minor,
638 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
639 'img_sha1' => $this->sha1
,
641 [ 'img_name' => $this->getName() ],
645 $this->invalidateCache();
647 $this->unlock(); // done
648 $this->upgraded
= true; // avoid rework/retries
652 * Set properties in this object to be equal to those given in the
653 * associative array $info. Only cacheable fields can be set.
654 * All fields *must* be set in $info except for getLazyCacheFields().
656 * If 'mime' is given, it will be split into major_mime/minor_mime.
657 * If major_mime/minor_mime are given, $this->mime will also be set.
661 function setProps( $info ) {
662 $this->dataLoaded
= true;
663 $fields = $this->getCacheFields( '' );
664 $fields[] = 'fileExists';
666 foreach ( $fields as $field ) {
667 if ( isset( $info[$field] ) ) {
668 $this->$field = $info[$field];
672 // Fix up mime fields
673 if ( isset( $info['major_mime'] ) ) {
674 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
675 } elseif ( isset( $info['mime'] ) ) {
676 $this->mime
= $info['mime'];
677 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
681 /** splitMime inherited */
682 /** getName inherited */
683 /** getTitle inherited */
684 /** getURL inherited */
685 /** getViewURL inherited */
686 /** getPath inherited */
687 /** isVisible inherited */
692 function isMissing() {
693 if ( $this->missing
=== null ) {
694 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
695 $this->missing
= !$fileExists;
698 return $this->missing
;
702 * Return the width of the image
707 public function getWidth( $page = 1 ) {
710 if ( $this->isMultipage() ) {
711 $handler = $this->getHandler();
715 $dim = $handler->getPageDimensions( $this, $page );
717 return $dim['width'];
719 // For non-paged media, the false goes through an
720 // intval, turning failure into 0, so do same here.
729 * Return the height of the image
734 public function getHeight( $page = 1 ) {
737 if ( $this->isMultipage() ) {
738 $handler = $this->getHandler();
742 $dim = $handler->getPageDimensions( $this, $page );
744 return $dim['height'];
746 // For non-paged media, the false goes through an
747 // intval, turning failure into 0, so do same here.
751 return $this->height
;
756 * Returns ID or name of user who uploaded the file
758 * @param string $type 'text' or 'id'
761 function getUser( $type = 'text' ) {
764 if ( $type == 'text' ) {
765 return $this->user_text
;
767 return (int)$this->user
;
772 * Get short description URL for a file based on the page ID.
774 * @return string|null
775 * @throws MWException
778 public function getDescriptionShortUrl() {
779 $pageId = $this->title
->getArticleID();
781 if ( $pageId !== null ) {
782 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
783 if ( $url !== false ) {
791 * Get handler-specific metadata
794 function getMetadata() {
795 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
796 return $this->metadata
;
802 function getBitDepth() {
805 return (int)$this->bits
;
809 * Returns the size of the image file, in bytes
812 public function getSize() {
819 * Returns the MIME type of the file.
822 function getMimeType() {
829 * Returns the type of the media in the file.
830 * Use the value returned by this function with the MEDIATYPE_xxx constants.
833 function getMediaType() {
836 return $this->media_type
;
839 /** canRender inherited */
840 /** mustRender inherited */
841 /** allowInlineDisplay inherited */
842 /** isSafeFile inherited */
843 /** isTrustedFile inherited */
846 * Returns true if the file exists on disk.
847 * @return bool Whether file exist on disk.
849 public function exists() {
852 return $this->fileExists
;
855 /** getTransformScript inherited */
856 /** getUnscaledThumb inherited */
857 /** thumbName inherited */
858 /** createThumb inherited */
859 /** transform inherited */
861 /** getHandler inherited */
862 /** iconThumb inherited */
863 /** getLastError inherited */
866 * Get all thumbnail names previously generated for this file
867 * @param string|bool $archiveName Name of an archive file, default false
868 * @return array First element is the base dir, then files in that base dir.
870 function getThumbnails( $archiveName = false ) {
871 if ( $archiveName ) {
872 $dir = $this->getArchiveThumbPath( $archiveName );
874 $dir = $this->getThumbPath();
877 $backend = $this->repo
->getBackend();
880 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
881 foreach ( $iterator as $file ) {
884 } catch ( FileBackendError
$e ) {
885 } // suppress (bug 54674)
891 * Refresh metadata in memcached, but don't touch thumbnails or CDN
893 function purgeMetadataCache() {
894 $this->invalidateCache();
898 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
900 * @param array $options An array potentially with the key forThumbRefresh.
902 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
904 function purgeCache( $options = [] ) {
905 // Refresh metadata cache
906 $this->purgeMetadataCache();
909 $this->purgeThumbnails( $options );
911 // Purge CDN cache for this file
912 DeferredUpdates
::addUpdate(
913 new CdnCacheUpdate( [ $this->getUrl() ] ),
914 DeferredUpdates
::PRESEND
919 * Delete cached transformed files for an archived version only.
920 * @param string $archiveName Name of the archived file
922 function purgeOldThumbnails( $archiveName ) {
923 // Get a list of old thumbnails and URLs
924 $files = $this->getThumbnails( $archiveName );
926 // Purge any custom thumbnail caches
927 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
930 $dir = array_shift( $files );
931 $this->purgeThumbList( $dir, $files );
935 foreach ( $files as $file ) {
936 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
938 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
942 * Delete cached transformed files for the current version only.
943 * @param array $options
945 public function purgeThumbnails( $options = [] ) {
946 $files = $this->getThumbnails();
947 // Always purge all files from CDN regardless of handler filters
949 foreach ( $files as $file ) {
950 $urls[] = $this->getThumbUrl( $file );
952 array_shift( $urls ); // don't purge directory
954 // Give media handler a chance to filter the file purge list
955 if ( !empty( $options['forThumbRefresh'] ) ) {
956 $handler = $this->getHandler();
958 $handler->filterThumbnailPurgeList( $files, $options );
962 // Purge any custom thumbnail caches
963 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
966 $dir = array_shift( $files );
967 $this->purgeThumbList( $dir, $files );
970 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
974 * Prerenders a configurable set of thumbnails
978 public function prerenderThumbnails() {
979 global $wgUploadThumbnailRenderMap;
983 $sizes = $wgUploadThumbnailRenderMap;
986 foreach ( $sizes as $size ) {
987 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
988 $jobs[] = new ThumbnailRenderJob(
990 [ 'transformParams' => [ 'width' => $size ] ]
996 JobQueueGroup
::singleton()->lazyPush( $jobs );
1001 * Delete a list of thumbnails visible at urls
1002 * @param string $dir Base dir of the files.
1003 * @param array $files Array of strings: relative filenames (to $dir)
1005 protected function purgeThumbList( $dir, $files ) {
1006 $fileListDebug = strtr(
1007 var_export( $files, true ),
1010 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1013 foreach ( $files as $file ) {
1014 # Check that the base file name is part of the thumb name
1015 # This is a basic sanity check to avoid erasing unrelated directories
1016 if ( strpos( $file, $this->getName() ) !== false
1017 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1019 $purgeList[] = "{$dir}/{$file}";
1023 # Delete the thumbnails
1024 $this->repo
->quickPurgeBatch( $purgeList );
1025 # Clear out the thumbnail directory if empty
1026 $this->repo
->quickCleanDir( $dir );
1029 /** purgeDescription inherited */
1030 /** purgeEverything inherited */
1033 * @param int $limit Optional: Limit to number of results
1034 * @param int $start Optional: Timestamp, start from
1035 * @param int $end Optional: Timestamp, end at
1037 * @return OldLocalFile[]
1039 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1040 $dbr = $this->repo
->getSlaveDB();
1041 $tables = [ 'oldimage' ];
1042 $fields = OldLocalFile
::selectFields();
1043 $conds = $opts = $join_conds = [];
1044 $eq = $inc ?
'=' : '';
1045 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1048 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1052 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1056 $opts['LIMIT'] = $limit;
1059 // Search backwards for time > x queries
1060 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1061 $opts['ORDER BY'] = "oi_timestamp $order";
1062 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1064 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1065 &$conds, &$opts, &$join_conds ] );
1067 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1070 foreach ( $res as $row ) {
1071 $r[] = $this->repo
->newFileFromRow( $row );
1074 if ( $order == 'ASC' ) {
1075 $r = array_reverse( $r ); // make sure it ends up descending
1082 * Returns the history of this file, line by line.
1083 * starts with current version, then old versions.
1084 * uses $this->historyLine to check which line to return:
1085 * 0 return line for current version
1086 * 1 query for old versions, return first one
1087 * 2, ... return next old version from above query
1090 public function nextHistoryLine() {
1091 # Polymorphic function name to distinguish foreign and local fetches
1092 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1094 $dbr = $this->repo
->getSlaveDB();
1096 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1097 $this->historyRes
= $dbr->select( 'image',
1100 "'' AS oi_archive_name",
1104 [ 'img_name' => $this->title
->getDBkey() ],
1108 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1109 $this->historyRes
= null;
1113 } elseif ( $this->historyLine
== 1 ) {
1114 $this->historyRes
= $dbr->select( 'oldimage', '*',
1115 [ 'oi_name' => $this->title
->getDBkey() ],
1117 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1120 $this->historyLine++
;
1122 return $dbr->fetchObject( $this->historyRes
);
1126 * Reset the history pointer to the first element of the history
1128 public function resetHistory() {
1129 $this->historyLine
= 0;
1131 if ( !is_null( $this->historyRes
) ) {
1132 $this->historyRes
= null;
1136 /** getHashPath inherited */
1137 /** getRel inherited */
1138 /** getUrlRel inherited */
1139 /** getArchiveRel inherited */
1140 /** getArchivePath inherited */
1141 /** getThumbPath inherited */
1142 /** getArchiveUrl inherited */
1143 /** getThumbUrl inherited */
1144 /** getArchiveVirtualUrl inherited */
1145 /** getThumbVirtualUrl inherited */
1146 /** isHashed inherited */
1149 * Upload a file and record it in the DB
1150 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1151 * @param string $comment Upload description
1152 * @param string $pageText Text to use for the new description page,
1153 * if a new description page is created
1154 * @param int|bool $flags Flags for publish()
1155 * @param array|bool $props File properties, if known. This can be used to
1156 * reduce the upload time when uploading virtual URLs for which the file
1157 * info is already known
1158 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1160 * @param User|null $user User object or null to use $wgUser
1161 * @param string[] $tags Change tags to add to the log entry and page revision.
1162 * (This doesn't check $user's permissions.)
1163 * @return FileRepoStatus On success, the value member contains the
1164 * archive name, or an empty string if it was a new file.
1166 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1167 $timestamp = false, $user = null, $tags = []
1171 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1172 return $this->readOnlyFatalStatus();
1175 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1177 if ( $this->repo
->isVirtualUrl( $srcPath )
1178 || FileBackend
::isStoragePath( $srcPath )
1180 $props = $this->repo
->getFileProps( $srcPath );
1182 $props = FSFile
::getPropsFromPath( $srcPath );
1187 $handler = MediaHandler
::getHandler( $props['mime'] );
1189 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1191 $options['headers'] = [];
1194 // Trim spaces on user supplied text
1195 $comment = trim( $comment );
1197 // Truncate nicely or the DB will do it for us
1198 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1199 $comment = $wgContLang->truncate( $comment, 255 );
1200 $this->lock(); // begin
1201 $status = $this->publish( $src, $flags, $options );
1203 if ( $status->successCount
>= 2 ) {
1204 // There will be a copy+(one of move,copy,store).
1205 // The first succeeding does not commit us to updating the DB
1206 // since it simply copied the current version to a timestamped file name.
1207 // It is only *preferable* to avoid leaving such files orphaned.
1208 // Once the second operation goes through, then the current version was
1209 // updated and we must therefore update the DB too.
1210 $oldver = $status->value
;
1211 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1212 $status->fatal( 'filenotfound', $srcPath );
1216 $this->unlock(); // done
1222 * Record a file upload in the upload log and the image table
1223 * @param string $oldver
1224 * @param string $desc
1225 * @param string $license
1226 * @param string $copyStatus
1227 * @param string $source
1228 * @param bool $watch
1229 * @param string|bool $timestamp
1230 * @param User|null $user User object or null to use $wgUser
1233 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1234 $watch = false, $timestamp = false, User
$user = null ) {
1240 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1242 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1247 $user->addWatch( $this->getTitle() );
1254 * Record a file upload in the upload log and the image table
1255 * @param string $oldver
1256 * @param string $comment
1257 * @param string $pageText
1258 * @param bool|array $props
1259 * @param string|bool $timestamp
1260 * @param null|User $user
1261 * @param string[] $tags
1264 function recordUpload2(
1265 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1267 if ( is_null( $user ) ) {
1272 $dbw = $this->repo
->getMasterDB();
1274 # Imports or such might force a certain timestamp; otherwise we generate
1275 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1276 if ( $timestamp === false ) {
1277 $timestamp = $dbw->timestamp();
1278 $allowTimeKludge = true;
1280 $allowTimeKludge = false;
1283 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1284 $props['description'] = $comment;
1285 $props['user'] = $user->getId();
1286 $props['user_text'] = $user->getName();
1287 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1288 $this->setProps( $props );
1290 # Fail now if the file isn't there
1291 if ( !$this->fileExists
) {
1292 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1297 $dbw->startAtomic( __METHOD__
);
1299 # Test to see if the row exists using INSERT IGNORE
1300 # This avoids race conditions by locking the row until the commit, and also
1301 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1302 $dbw->insert( 'image',
1304 'img_name' => $this->getName(),
1305 'img_size' => $this->size
,
1306 'img_width' => intval( $this->width
),
1307 'img_height' => intval( $this->height
),
1308 'img_bits' => $this->bits
,
1309 'img_media_type' => $this->media_type
,
1310 'img_major_mime' => $this->major_mime
,
1311 'img_minor_mime' => $this->minor_mime
,
1312 'img_timestamp' => $timestamp,
1313 'img_description' => $comment,
1314 'img_user' => $user->getId(),
1315 'img_user_text' => $user->getName(),
1316 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1317 'img_sha1' => $this->sha1
1323 $reupload = ( $dbw->affectedRows() == 0 );
1325 if ( $allowTimeKludge ) {
1326 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1327 $ltimestamp = $dbw->selectField(
1330 [ 'img_name' => $this->getName() ],
1332 [ 'LOCK IN SHARE MODE' ]
1334 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1335 # Avoid a timestamp that is not newer than the last version
1336 # TODO: the image/oldimage tables should be like page/revision with an ID field
1337 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1338 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1339 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1340 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1344 # (bug 34993) Note: $oldver can be empty here, if the previous
1345 # version of the file was broken. Allow registration of the new
1346 # version to continue anyway, because that's better than having
1347 # an image that's not fixable by user operations.
1348 # Collision, this is an update of a file
1349 # Insert previous contents into oldimage
1350 $dbw->insertSelect( 'oldimage', 'image',
1352 'oi_name' => 'img_name',
1353 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1354 'oi_size' => 'img_size',
1355 'oi_width' => 'img_width',
1356 'oi_height' => 'img_height',
1357 'oi_bits' => 'img_bits',
1358 'oi_timestamp' => 'img_timestamp',
1359 'oi_description' => 'img_description',
1360 'oi_user' => 'img_user',
1361 'oi_user_text' => 'img_user_text',
1362 'oi_metadata' => 'img_metadata',
1363 'oi_media_type' => 'img_media_type',
1364 'oi_major_mime' => 'img_major_mime',
1365 'oi_minor_mime' => 'img_minor_mime',
1366 'oi_sha1' => 'img_sha1'
1368 [ 'img_name' => $this->getName() ],
1372 # Update the current image row
1373 $dbw->update( 'image',
1375 'img_size' => $this->size
,
1376 'img_width' => intval( $this->width
),
1377 'img_height' => intval( $this->height
),
1378 'img_bits' => $this->bits
,
1379 'img_media_type' => $this->media_type
,
1380 'img_major_mime' => $this->major_mime
,
1381 'img_minor_mime' => $this->minor_mime
,
1382 'img_timestamp' => $timestamp,
1383 'img_description' => $comment,
1384 'img_user' => $user->getId(),
1385 'img_user_text' => $user->getName(),
1386 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1387 'img_sha1' => $this->sha1
1389 [ 'img_name' => $this->getName() ],
1394 $descTitle = $this->getTitle();
1395 $descId = $descTitle->getArticleID();
1396 $wikiPage = new WikiFilePage( $descTitle );
1397 $wikiPage->setFile( $this );
1399 // Add the log entry...
1400 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1401 $logEntry->setTimestamp( $this->timestamp
);
1402 $logEntry->setPerformer( $user );
1403 $logEntry->setComment( $comment );
1404 $logEntry->setTarget( $descTitle );
1405 // Allow people using the api to associate log entries with the upload.
1406 // Log has a timestamp, but sometimes different from upload timestamp.
1407 $logEntry->setParameters(
1409 'img_sha1' => $this->sha1
,
1410 'img_timestamp' => $timestamp,
1413 // Note we keep $logId around since during new image
1414 // creation, page doesn't exist yet, so log_page = 0
1415 // but we want it to point to the page we're making,
1416 // so we later modify the log entry.
1417 // For a similar reason, we avoid making an RC entry
1418 // now and wait until the page exists.
1419 $logId = $logEntry->insert();
1421 if ( $descTitle->exists() ) {
1422 // Use own context to get the action text in content language
1423 $formatter = LogFormatter
::newFromEntry( $logEntry );
1424 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1425 $editSummary = $formatter->getPlainActionText();
1427 $nullRevision = Revision
::newNullRevision(
1434 if ( $nullRevision ) {
1435 $nullRevision->insertOn( $dbw );
1437 'NewRevisionFromEditComplete',
1438 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1440 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1441 // Associate null revision id
1442 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1445 $newPageContent = null;
1447 // Make the description page and RC log entry post-commit
1448 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1451 # Defer purges, page creation, and link updates in case they error out.
1452 # The most important thing is that files and the DB registry stay synced.
1453 $dbw->endAtomic( __METHOD__
);
1455 # Do some cache purges after final commit so that:
1456 # a) Changes are more likely to be seen post-purge
1457 # b) They won't cause rollback of the log publish/update above
1458 DeferredUpdates
::addUpdate(
1459 new AutoCommitUpdate(
1463 $reupload, $wikiPage, $newPageContent, $comment, $user,
1464 $logEntry, $logId, $descId, $tags
1466 # Update memcache after the commit
1467 $this->invalidateCache();
1469 $updateLogPage = false;
1470 if ( $newPageContent ) {
1471 # New file page; create the description page.
1472 # There's already a log entry, so don't make a second RC entry
1473 # CDN and file cache for the description page are purged by doEditContent.
1474 $status = $wikiPage->doEditContent(
1477 EDIT_NEW | EDIT_SUPPRESS_RC
,
1482 if ( isset( $status->value
['revision'] ) ) {
1483 // Associate new page revision id
1484 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1486 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1487 // which is triggered on $descTitle by doEditContent() above.
1488 if ( isset( $status->value
['revision'] ) ) {
1489 /** @var $rev Revision */
1490 $rev = $status->value
['revision'];
1491 $updateLogPage = $rev->getPage();
1494 # Existing file page: invalidate description page cache
1495 $wikiPage->getTitle()->invalidateCache();
1496 $wikiPage->getTitle()->purgeSquid();
1497 # Allow the new file version to be patrolled from the page footer
1498 Article
::purgePatrolFooterCache( $descId );
1501 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1502 # but setAssociatedRevId() wasn't called at that point yet...
1503 $logParams = $logEntry->getParameters();
1504 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1505 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1506 if ( $updateLogPage ) {
1507 # Also log page, in case where we just created it above
1508 $update['log_page'] = $updateLogPage;
1510 $this->getRepo()->getMasterDB()->update(
1513 [ 'log_id' => $logId ],
1516 $this->getRepo()->getMasterDB()->insert(
1519 'ls_field' => 'associated_rev_id',
1520 'ls_value' => $logEntry->getAssociatedRevId(),
1521 'ls_log_id' => $logId,
1526 # Add change tags, if any
1528 $logEntry->setTags( $tags );
1531 # Uploads can be patrolled
1532 $logEntry->setIsPatrollable( true );
1534 # Now that the log entry is up-to-date, make an RC entry.
1535 $logEntry->publish( $logId );
1537 # Run hook for other updates (typically more cache purging)
1538 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1541 # Delete old thumbnails
1542 $this->purgeThumbnails();
1543 # Remove the old file from the CDN cache
1544 DeferredUpdates
::addUpdate(
1545 new CdnCacheUpdate( [ $this->getUrl() ] ),
1546 DeferredUpdates
::PRESEND
1549 # Update backlink pages pointing to this title if created
1550 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1553 $this->prerenderThumbnails();
1556 DeferredUpdates
::PRESEND
1560 # This is a new file, so update the image count
1561 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1564 # Invalidate cache for all pages using this file
1565 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1571 * Move or copy a file to its public location. If a file exists at the
1572 * destination, move it to an archive. Returns a FileRepoStatus object with
1573 * the archive name in the "value" member on success.
1575 * The archive name should be passed through to recordUpload for database
1578 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1579 * @param int $flags A bitwise combination of:
1580 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1581 * @param array $options Optional additional parameters
1582 * @return FileRepoStatus On success, the value member contains the
1583 * archive name, or an empty string if it was a new file.
1585 function publish( $src, $flags = 0, array $options = [] ) {
1586 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1590 * Move or copy a file to a specified location. Returns a FileRepoStatus
1591 * object with the archive name in the "value" member on success.
1593 * The archive name should be passed through to recordUpload for database
1596 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1597 * @param string $dstRel Target relative path
1598 * @param int $flags A bitwise combination of:
1599 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1600 * @param array $options Optional additional parameters
1601 * @return FileRepoStatus On success, the value member contains the
1602 * archive name, or an empty string if it was a new file.
1604 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1605 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1607 $repo = $this->getRepo();
1608 if ( $repo->getReadOnlyReason() !== false ) {
1609 return $this->readOnlyFatalStatus();
1612 $this->lock(); // begin
1614 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1615 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1617 if ( $repo->hasSha1Storage() ) {
1618 $sha1 = $repo->isVirtualUrl( $srcPath )
1619 ?
$repo->getFileSha1( $srcPath )
1620 : FSFile
::getSha1Base36FromPath( $srcPath );
1621 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1622 $wrapperBackend = $repo->getBackend();
1623 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1624 $status = $repo->quickImport( $src, $dst );
1625 if ( $flags & File
::DELETE_SOURCE
) {
1629 if ( $this->exists() ) {
1630 $status->value
= $archiveName;
1633 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1634 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1636 if ( $status->value
== 'new' ) {
1637 $status->value
= '';
1639 $status->value
= $archiveName;
1643 $this->unlock(); // done
1648 /** getLinksTo inherited */
1649 /** getExifData inherited */
1650 /** isLocal inherited */
1651 /** wasDeleted inherited */
1654 * Move file to the new title
1656 * Move current, old version and all thumbnails
1657 * to the new filename. Old file is deleted.
1659 * Cache purging is done; checks for validity
1660 * and logging are caller's responsibility
1662 * @param Title $target New file name
1663 * @return FileRepoStatus
1665 function move( $target ) {
1666 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1667 return $this->readOnlyFatalStatus();
1670 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1671 $batch = new LocalFileMoveBatch( $this, $target );
1673 $this->lock(); // begin
1674 $batch->addCurrent();
1675 $archiveNames = $batch->addOlds();
1676 $status = $batch->execute();
1677 $this->unlock(); // done
1679 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1681 // Purge the source and target files...
1682 $oldTitleFile = wfLocalFile( $this->title
);
1683 $newTitleFile = wfLocalFile( $target );
1684 // To avoid slow purges in the transaction, move them outside...
1685 DeferredUpdates
::addUpdate(
1686 new AutoCommitUpdate(
1687 $this->getRepo()->getMasterDB(),
1689 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1690 $oldTitleFile->purgeEverything();
1691 foreach ( $archiveNames as $archiveName ) {
1692 $oldTitleFile->purgeOldThumbnails( $archiveName );
1694 $newTitleFile->purgeEverything();
1697 DeferredUpdates
::PRESEND
1700 if ( $status->isOK() ) {
1701 // Now switch the object
1702 $this->title
= $target;
1703 // Force regeneration of the name and hashpath
1704 unset( $this->name
);
1705 unset( $this->hashPath
);
1712 * Delete all versions of the file.
1714 * Moves the files into an archive directory (or deletes them)
1715 * and removes the database rows.
1717 * Cache purging is done; logging is caller's responsibility.
1719 * @param string $reason
1720 * @param bool $suppress
1721 * @param User|null $user
1722 * @return FileRepoStatus
1724 function delete( $reason, $suppress = false, $user = null ) {
1725 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1726 return $this->readOnlyFatalStatus();
1729 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1731 $this->lock(); // begin
1732 $batch->addCurrent();
1733 // Get old version relative paths
1734 $archiveNames = $batch->addOlds();
1735 $status = $batch->execute();
1736 $this->unlock(); // done
1738 if ( $status->isOK() ) {
1739 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1742 // To avoid slow purges in the transaction, move them outside...
1743 DeferredUpdates
::addUpdate(
1744 new AutoCommitUpdate(
1745 $this->getRepo()->getMasterDB(),
1747 function () use ( $archiveNames ) {
1748 $this->purgeEverything();
1749 foreach ( $archiveNames as $archiveName ) {
1750 $this->purgeOldThumbnails( $archiveName );
1754 DeferredUpdates
::PRESEND
1759 foreach ( $archiveNames as $archiveName ) {
1760 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1762 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1768 * Delete an old version of the file.
1770 * Moves the file into an archive directory (or deletes it)
1771 * and removes the database row.
1773 * Cache purging is done; logging is caller's responsibility.
1775 * @param string $archiveName
1776 * @param string $reason
1777 * @param bool $suppress
1778 * @param User|null $user
1779 * @throws MWException Exception on database or file store failure
1780 * @return FileRepoStatus
1782 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1783 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1784 return $this->readOnlyFatalStatus();
1787 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1789 $this->lock(); // begin
1790 $batch->addOld( $archiveName );
1791 $status = $batch->execute();
1792 $this->unlock(); // done
1794 $this->purgeOldThumbnails( $archiveName );
1795 if ( $status->isOK() ) {
1796 $this->purgeDescription();
1799 DeferredUpdates
::addUpdate(
1800 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1801 DeferredUpdates
::PRESEND
1808 * Restore all or specified deleted revisions to the given file.
1809 * Permissions and logging are left to the caller.
1811 * May throw database exceptions on error.
1813 * @param array $versions Set of record ids of deleted items to restore,
1814 * or empty to restore all revisions.
1815 * @param bool $unsuppress
1816 * @return FileRepoStatus
1818 function restore( $versions = [], $unsuppress = false ) {
1819 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1820 return $this->readOnlyFatalStatus();
1823 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1825 $this->lock(); // begin
1829 $batch->addIds( $versions );
1831 $status = $batch->execute();
1832 if ( $status->isGood() ) {
1833 $cleanupStatus = $batch->cleanup();
1834 $cleanupStatus->successCount
= 0;
1835 $cleanupStatus->failCount
= 0;
1836 $status->merge( $cleanupStatus );
1838 $this->unlock(); // done
1843 /** isMultipage inherited */
1844 /** pageCount inherited */
1845 /** scaleHeight inherited */
1846 /** getImageSize inherited */
1849 * Get the URL of the file description page.
1852 function getDescriptionUrl() {
1853 return $this->title
->getLocalURL();
1857 * Get the HTML text of the description page
1858 * This is not used by ImagePage for local files, since (among other things)
1859 * it skips the parser cache.
1861 * @param Language $lang What language to get description in (Optional)
1862 * @return bool|mixed
1864 function getDescriptionText( $lang = null ) {
1865 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1869 $content = $revision->getContent();
1873 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1875 return $pout->getText();
1879 * @param int $audience
1883 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1885 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1887 } elseif ( $audience == self
::FOR_THIS_USER
1888 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1892 return $this->description
;
1897 * @return bool|string
1899 function getTimestamp() {
1902 return $this->timestamp
;
1906 * @return bool|string
1908 public function getDescriptionTouched() {
1909 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1910 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1911 // need to differentiate between null (uninitialized) and false (failed to load).
1912 if ( $this->descriptionTouched
=== null ) {
1914 'page_namespace' => $this->title
->getNamespace(),
1915 'page_title' => $this->title
->getDBkey()
1917 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1918 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1921 return $this->descriptionTouched
;
1927 function getSha1() {
1929 // Initialise now if necessary
1930 if ( $this->sha1
== '' && $this->fileExists
) {
1931 $this->lock(); // begin
1933 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1934 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1935 $dbw = $this->repo
->getMasterDB();
1936 $dbw->update( 'image',
1937 [ 'img_sha1' => $this->sha1
],
1938 [ 'img_name' => $this->getName() ],
1940 $this->invalidateCache();
1943 $this->unlock(); // done
1950 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1952 function isCacheable() {
1955 // If extra data (metadata) was not loaded then it must have been large
1956 return $this->extraDataLoaded
1957 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1964 public function acquireFileLock() {
1965 return $this->getRepo()->getBackend()->lockFiles(
1966 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1974 public function releaseFileLock() {
1975 return $this->getRepo()->getBackend()->unlockFiles(
1976 [ $this->getPath() ], LockManager
::LOCK_EX
1981 * Start an atomic DB section and lock the image for update
1982 * or increments a reference counter if the lock is already held
1984 * This method should not be used outside of LocalFile/LocalFile*Batch
1986 * @throws LocalFileLockError Throws an error if the lock was not acquired
1987 * @return bool Whether the file lock owns/spawned the DB transaction
1989 public function lock() {
1990 if ( !$this->locked
) {
1991 $logger = LoggerFactory
::getInstance( 'LocalFile' );
1993 $dbw = $this->repo
->getMasterDB();
1994 $makesTransaction = !$dbw->trxLevel();
1995 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
1996 // Bug 54736: use simple lock to handle when the file does not exist.
1997 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1998 // Also, that would cause contention on INSERT of similarly named rows.
1999 $status = $this->acquireFileLock(); // represents all versions of the file
2000 if ( !$status->isGood() ) {
2001 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2002 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2004 throw new LocalFileLockError( $status );
2006 // Release the lock *after* commit to avoid row-level contention.
2007 // Make sure it triggers on rollback() as well as commit() (T132921).
2008 $dbw->onTransactionResolution(
2009 function () use ( $logger ) {
2010 $status = $this->releaseFileLock();
2011 if ( !$status->isGood() ) {
2012 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2017 // Callers might care if the SELECT snapshot is safely fresh
2018 $this->lockedOwnTrx
= $makesTransaction;
2023 return $this->lockedOwnTrx
;
2027 * Decrement the lock reference count and end the atomic section if it reaches zero
2029 * This method should not be used outside of LocalFile/LocalFile*Batch
2031 * The commit and loc release will happen when no atomic sections are active, which
2032 * may happen immediately or at some point after calling this
2034 public function unlock() {
2035 if ( $this->locked
) {
2037 if ( !$this->locked
) {
2038 $dbw = $this->repo
->getMasterDB();
2039 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2040 $this->lockedOwnTrx
= false;
2048 protected function readOnlyFatalStatus() {
2049 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2050 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2054 * Clean up any dangling locks
2056 function __destruct() {
2059 } // LocalFile class
2061 # ------------------------------------------------------------------------------
2064 * Helper class for file deletion
2065 * @ingroup FileAbstraction
2067 class LocalFileDeleteBatch
{
2068 /** @var LocalFile */
2075 private $srcRels = [];
2078 private $archiveUrls = [];
2080 /** @var array Items to be processed in the deletion batch */
2081 private $deletionBatch;
2083 /** @var bool Whether to suppress all suppressable fields when deleting */
2086 /** @var FileRepoStatus */
2094 * @param string $reason
2095 * @param bool $suppress
2096 * @param User|null $user
2098 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2099 $this->file
= $file;
2100 $this->reason
= $reason;
2101 $this->suppress
= $suppress;
2103 $this->user
= $user;
2106 $this->user
= $wgUser;
2108 $this->status
= $file->repo
->newGood();
2111 public function addCurrent() {
2112 $this->srcRels
['.'] = $this->file
->getRel();
2116 * @param string $oldName
2118 public function addOld( $oldName ) {
2119 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2120 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2124 * Add the old versions of the image to the batch
2125 * @return array List of archive names from old versions
2127 public function addOlds() {
2130 $dbw = $this->file
->repo
->getMasterDB();
2131 $result = $dbw->select( 'oldimage',
2132 [ 'oi_archive_name' ],
2133 [ 'oi_name' => $this->file
->getName() ],
2137 foreach ( $result as $row ) {
2138 $this->addOld( $row->oi_archive_name
);
2139 $archiveNames[] = $row->oi_archive_name
;
2142 return $archiveNames;
2148 protected function getOldRels() {
2149 if ( !isset( $this->srcRels
['.'] ) ) {
2150 $oldRels =& $this->srcRels
;
2151 $deleteCurrent = false;
2153 $oldRels = $this->srcRels
;
2154 unset( $oldRels['.'] );
2155 $deleteCurrent = true;
2158 return [ $oldRels, $deleteCurrent ];
2164 protected function getHashes() {
2166 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2168 if ( $deleteCurrent ) {
2169 $hashes['.'] = $this->file
->getSha1();
2172 if ( count( $oldRels ) ) {
2173 $dbw = $this->file
->repo
->getMasterDB();
2174 $res = $dbw->select(
2176 [ 'oi_archive_name', 'oi_sha1' ],
2177 [ 'oi_archive_name' => array_keys( $oldRels ),
2178 'oi_name' => $this->file
->getName() ], // performance
2182 foreach ( $res as $row ) {
2183 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2184 // Get the hash from the file
2185 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2186 $props = $this->file
->repo
->getFileProps( $oldUrl );
2188 if ( $props['fileExists'] ) {
2189 // Upgrade the oldimage row
2190 $dbw->update( 'oldimage',
2191 [ 'oi_sha1' => $props['sha1'] ],
2192 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2194 $hashes[$row->oi_archive_name
] = $props['sha1'];
2196 $hashes[$row->oi_archive_name
] = false;
2199 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2204 $missing = array_diff_key( $this->srcRels
, $hashes );
2206 foreach ( $missing as $name => $rel ) {
2207 $this->status
->error( 'filedelete-old-unregistered', $name );
2210 foreach ( $hashes as $name => $hash ) {
2212 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2213 unset( $hashes[$name] );
2220 protected function doDBInserts() {
2222 $dbw = $this->file
->repo
->getMasterDB();
2223 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2224 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2225 $encReason = $dbw->addQuotes( $this->reason
);
2226 $encGroup = $dbw->addQuotes( 'deleted' );
2227 $ext = $this->file
->getExtension();
2228 $dotExt = $ext === '' ?
'' : ".$ext";
2229 $encExt = $dbw->addQuotes( $dotExt );
2230 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2232 // Bitfields to further suppress the content
2233 if ( $this->suppress
) {
2235 // This should be 15...
2236 $bitfield |
= Revision
::DELETED_TEXT
;
2237 $bitfield |
= Revision
::DELETED_COMMENT
;
2238 $bitfield |
= Revision
::DELETED_USER
;
2239 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2241 $bitfield = 'oi_deleted';
2244 if ( $deleteCurrent ) {
2249 'fa_storage_group' => $encGroup,
2250 'fa_storage_key' => $dbw->conditional(
2251 [ 'img_sha1' => '' ],
2252 $dbw->addQuotes( '' ),
2253 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2255 'fa_deleted_user' => $encUserId,
2256 'fa_deleted_timestamp' => $encTimestamp,
2257 'fa_deleted_reason' => $encReason,
2258 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2260 'fa_name' => 'img_name',
2261 'fa_archive_name' => 'NULL',
2262 'fa_size' => 'img_size',
2263 'fa_width' => 'img_width',
2264 'fa_height' => 'img_height',
2265 'fa_metadata' => 'img_metadata',
2266 'fa_bits' => 'img_bits',
2267 'fa_media_type' => 'img_media_type',
2268 'fa_major_mime' => 'img_major_mime',
2269 'fa_minor_mime' => 'img_minor_mime',
2270 'fa_description' => 'img_description',
2271 'fa_user' => 'img_user',
2272 'fa_user_text' => 'img_user_text',
2273 'fa_timestamp' => 'img_timestamp',
2274 'fa_sha1' => 'img_sha1'
2276 [ 'img_name' => $this->file
->getName() ],
2281 if ( count( $oldRels ) ) {
2282 $res = $dbw->select(
2284 OldLocalFile
::selectFields(),
2286 'oi_name' => $this->file
->getName(),
2287 'oi_archive_name' => array_keys( $oldRels )
2293 foreach ( $res as $row ) {
2295 // Deletion-specific fields
2296 'fa_storage_group' => 'deleted',
2297 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2299 : "{$row->oi_sha1}{$dotExt}",
2300 'fa_deleted_user' => $this->user
->getId(),
2301 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2302 'fa_deleted_reason' => $this->reason
,
2303 // Counterpart fields
2304 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2305 'fa_name' => $row->oi_name
,
2306 'fa_archive_name' => $row->oi_archive_name
,
2307 'fa_size' => $row->oi_size
,
2308 'fa_width' => $row->oi_width
,
2309 'fa_height' => $row->oi_height
,
2310 'fa_metadata' => $row->oi_metadata
,
2311 'fa_bits' => $row->oi_bits
,
2312 'fa_media_type' => $row->oi_media_type
,
2313 'fa_major_mime' => $row->oi_major_mime
,
2314 'fa_minor_mime' => $row->oi_minor_mime
,
2315 'fa_description' => $row->oi_description
,
2316 'fa_user' => $row->oi_user
,
2317 'fa_user_text' => $row->oi_user_text
,
2318 'fa_timestamp' => $row->oi_timestamp
,
2319 'fa_sha1' => $row->oi_sha1
2323 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2327 function doDBDeletes() {
2328 $dbw = $this->file
->repo
->getMasterDB();
2329 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2331 if ( count( $oldRels ) ) {
2332 $dbw->delete( 'oldimage',
2334 'oi_name' => $this->file
->getName(),
2335 'oi_archive_name' => array_keys( $oldRels )
2339 if ( $deleteCurrent ) {
2340 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2345 * Run the transaction
2346 * @return FileRepoStatus
2348 public function execute() {
2349 $repo = $this->file
->getRepo();
2350 $this->file
->lock();
2352 // Prepare deletion batch
2353 $hashes = $this->getHashes();
2354 $this->deletionBatch
= [];
2355 $ext = $this->file
->getExtension();
2356 $dotExt = $ext === '' ?
'' : ".$ext";
2358 foreach ( $this->srcRels
as $name => $srcRel ) {
2359 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2360 if ( isset( $hashes[$name] ) ) {
2361 $hash = $hashes[$name];
2362 $key = $hash . $dotExt;
2363 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2364 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2368 if ( !$repo->hasSha1Storage() ) {
2369 // Removes non-existent file from the batch, so we don't get errors.
2370 // This also handles files in the 'deleted' zone deleted via revision deletion.
2371 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2372 if ( !$checkStatus->isGood() ) {
2373 $this->status
->merge( $checkStatus );
2374 return $this->status
;
2376 $this->deletionBatch
= $checkStatus->value
;
2378 // Execute the file deletion batch
2379 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2380 if ( !$status->isGood() ) {
2381 $this->status
->merge( $status );
2385 if ( !$this->status
->isOK() ) {
2386 // Critical file deletion error; abort
2387 $this->file
->unlock();
2389 return $this->status
;
2392 // Copy the image/oldimage rows to filearchive
2393 $this->doDBInserts();
2394 // Delete image/oldimage rows
2395 $this->doDBDeletes();
2397 // Commit and return
2398 $this->file
->unlock();
2400 return $this->status
;
2404 * Removes non-existent files from a deletion batch.
2405 * @param array $batch
2408 protected function removeNonexistentFiles( $batch ) {
2409 $files = $newBatch = [];
2411 foreach ( $batch as $batchItem ) {
2412 list( $src, ) = $batchItem;
2413 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2416 $result = $this->file
->repo
->fileExistsBatch( $files );
2417 if ( in_array( null, $result, true ) ) {
2418 return Status
::newFatal( 'backend-fail-internal',
2419 $this->file
->repo
->getBackend()->getName() );
2422 foreach ( $batch as $batchItem ) {
2423 if ( $result[$batchItem[0]] ) {
2424 $newBatch[] = $batchItem;
2428 return Status
::newGood( $newBatch );
2432 # ------------------------------------------------------------------------------
2435 * Helper class for file undeletion
2436 * @ingroup FileAbstraction
2438 class LocalFileRestoreBatch
{
2439 /** @var LocalFile */
2442 /** @var array List of file IDs to restore */
2443 private $cleanupBatch;
2445 /** @var array List of file IDs to restore */
2448 /** @var bool Add all revisions of the file */
2451 /** @var bool Whether to remove all settings for suppressed fields */
2452 private $unsuppress = false;
2456 * @param bool $unsuppress
2458 function __construct( File
$file, $unsuppress = false ) {
2459 $this->file
= $file;
2460 $this->cleanupBatch
= $this->ids
= [];
2462 $this->unsuppress
= $unsuppress;
2469 public function addId( $fa_id ) {
2470 $this->ids
[] = $fa_id;
2474 * Add a whole lot of files by ID
2477 public function addIds( $ids ) {
2478 $this->ids
= array_merge( $this->ids
, $ids );
2482 * Add all revisions of the file
2484 public function addAll() {
2489 * Run the transaction, except the cleanup batch.
2490 * The cleanup batch should be run in a separate transaction, because it locks different
2491 * rows and there's no need to keep the image row locked while it's acquiring those locks
2492 * The caller may have its own transaction open.
2493 * So we save the batch and let the caller call cleanup()
2494 * @return FileRepoStatus
2496 public function execute() {
2497 /** @var Language */
2500 $repo = $this->file
->getRepo();
2501 if ( !$this->all
&& !$this->ids
) {
2503 return $repo->newGood();
2506 $lockOwnsTrx = $this->file
->lock();
2508 $dbw = $this->file
->repo
->getMasterDB();
2509 $status = $this->file
->repo
->newGood();
2511 $exists = (bool)$dbw->selectField( 'image', '1',
2512 [ 'img_name' => $this->file
->getName() ],
2514 // The lock() should already prevents changes, but this still may need
2515 // to bypass any transaction snapshot. However, if lock() started the
2516 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2517 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2520 // Fetch all or selected archived revisions for the file,
2521 // sorted from the most recent to the oldest.
2522 $conditions = [ 'fa_name' => $this->file
->getName() ];
2524 if ( !$this->all
) {
2525 $conditions['fa_id'] = $this->ids
;
2528 $result = $dbw->select(
2530 ArchivedFile
::selectFields(),
2533 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2539 $insertCurrent = false;
2544 foreach ( $result as $row ) {
2545 $idsPresent[] = $row->fa_id
;
2547 if ( $row->fa_name
!= $this->file
->getName() ) {
2548 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2549 $status->failCount++
;
2553 if ( $row->fa_storage_key
== '' ) {
2554 // Revision was missing pre-deletion
2555 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2556 $status->failCount++
;
2560 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2561 $row->fa_storage_key
;
2562 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2564 if ( isset( $row->fa_sha1
) ) {
2565 $sha1 = $row->fa_sha1
;
2567 // old row, populate from key
2568 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2572 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2573 $sha1 = substr( $sha1, 1 );
2576 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2577 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2578 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2579 ||
is_null( $row->fa_metadata
)
2581 // Refresh our metadata
2582 // Required for a new current revision; nice for older ones too. :)
2583 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2586 'minor_mime' => $row->fa_minor_mime
,
2587 'major_mime' => $row->fa_major_mime
,
2588 'media_type' => $row->fa_media_type
,
2589 'metadata' => $row->fa_metadata
2593 if ( $first && !$exists ) {
2594 // This revision will be published as the new current version
2595 $destRel = $this->file
->getRel();
2597 'img_name' => $row->fa_name
,
2598 'img_size' => $row->fa_size
,
2599 'img_width' => $row->fa_width
,
2600 'img_height' => $row->fa_height
,
2601 'img_metadata' => $props['metadata'],
2602 'img_bits' => $row->fa_bits
,
2603 'img_media_type' => $props['media_type'],
2604 'img_major_mime' => $props['major_mime'],
2605 'img_minor_mime' => $props['minor_mime'],
2606 'img_description' => $row->fa_description
,
2607 'img_user' => $row->fa_user
,
2608 'img_user_text' => $row->fa_user_text
,
2609 'img_timestamp' => $row->fa_timestamp
,
2613 // The live (current) version cannot be hidden!
2614 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2615 $status->fatal( 'undeleterevdel' );
2616 $this->file
->unlock();
2620 $archiveName = $row->fa_archive_name
;
2622 if ( $archiveName == '' ) {
2623 // This was originally a current version; we
2624 // have to devise a new archive name for it.
2625 // Format is <timestamp of archiving>!<name>
2626 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2629 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2631 } while ( isset( $archiveNames[$archiveName] ) );
2634 $archiveNames[$archiveName] = true;
2635 $destRel = $this->file
->getArchiveRel( $archiveName );
2637 'oi_name' => $row->fa_name
,
2638 'oi_archive_name' => $archiveName,
2639 'oi_size' => $row->fa_size
,
2640 'oi_width' => $row->fa_width
,
2641 'oi_height' => $row->fa_height
,
2642 'oi_bits' => $row->fa_bits
,
2643 'oi_description' => $row->fa_description
,
2644 'oi_user' => $row->fa_user
,
2645 'oi_user_text' => $row->fa_user_text
,
2646 'oi_timestamp' => $row->fa_timestamp
,
2647 'oi_metadata' => $props['metadata'],
2648 'oi_media_type' => $props['media_type'],
2649 'oi_major_mime' => $props['major_mime'],
2650 'oi_minor_mime' => $props['minor_mime'],
2651 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2652 'oi_sha1' => $sha1 ];
2655 $deleteIds[] = $row->fa_id
;
2657 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2658 // private files can stay where they are
2659 $status->successCount++
;
2661 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2662 $this->cleanupBatch
[] = $row->fa_storage_key
;
2670 // Add a warning to the status object for missing IDs
2671 $missingIds = array_diff( $this->ids
, $idsPresent );
2673 foreach ( $missingIds as $id ) {
2674 $status->error( 'undelete-missing-filearchive', $id );
2677 if ( !$repo->hasSha1Storage() ) {
2678 // Remove missing files from batch, so we don't get errors when undeleting them
2679 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2680 if ( !$checkStatus->isGood() ) {
2681 $status->merge( $checkStatus );
2684 $storeBatch = $checkStatus->value
;
2686 // Run the store batch
2687 // Use the OVERWRITE_SAME flag to smooth over a common error
2688 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2689 $status->merge( $storeStatus );
2691 if ( !$status->isGood() ) {
2692 // Even if some files could be copied, fail entirely as that is the
2693 // easiest thing to do without data loss
2694 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2695 $status->ok
= false;
2696 $this->file
->unlock();
2702 // Run the DB updates
2703 // Because we have locked the image row, key conflicts should be rare.
2704 // If they do occur, we can roll back the transaction at this time with
2705 // no data loss, but leaving unregistered files scattered throughout the
2707 // This is not ideal, which is why it's important to lock the image row.
2708 if ( $insertCurrent ) {
2709 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2712 if ( $insertBatch ) {
2713 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2717 $dbw->delete( 'filearchive',
2718 [ 'fa_id' => $deleteIds ],
2722 // If store batch is empty (all files are missing), deletion is to be considered successful
2723 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2725 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2727 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2729 $this->file
->purgeEverything();
2731 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2732 $this->file
->purgeDescription();
2736 $this->file
->unlock();
2742 * Removes non-existent files from a store batch.
2743 * @param array $triplets
2746 protected function removeNonexistentFiles( $triplets ) {
2747 $files = $filteredTriplets = [];
2748 foreach ( $triplets as $file ) {
2749 $files[$file[0]] = $file[0];
2752 $result = $this->file
->repo
->fileExistsBatch( $files );
2753 if ( in_array( null, $result, true ) ) {
2754 return Status
::newFatal( 'backend-fail-internal',
2755 $this->file
->repo
->getBackend()->getName() );
2758 foreach ( $triplets as $file ) {
2759 if ( $result[$file[0]] ) {
2760 $filteredTriplets[] = $file;
2764 return Status
::newGood( $filteredTriplets );
2768 * Removes non-existent files from a cleanup batch.
2769 * @param array $batch
2772 protected function removeNonexistentFromCleanup( $batch ) {
2773 $files = $newBatch = [];
2774 $repo = $this->file
->repo
;
2776 foreach ( $batch as $file ) {
2777 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2778 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2781 $result = $repo->fileExistsBatch( $files );
2783 foreach ( $batch as $file ) {
2784 if ( $result[$file] ) {
2785 $newBatch[] = $file;
2793 * Delete unused files in the deleted zone.
2794 * This should be called from outside the transaction in which execute() was called.
2795 * @return FileRepoStatus
2797 public function cleanup() {
2798 if ( !$this->cleanupBatch
) {
2799 return $this->file
->repo
->newGood();
2802 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2804 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2810 * Cleanup a failed batch. The batch was only partially successful, so
2811 * rollback by removing all items that were succesfully copied.
2813 * @param Status $storeStatus
2814 * @param array $storeBatch
2816 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2819 foreach ( $storeStatus->success
as $i => $success ) {
2820 // Check if this item of the batch was successfully copied
2822 // Item was successfully copied and needs to be removed again
2823 // Extract ($dstZone, $dstRel) from the batch
2824 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2827 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2831 # ------------------------------------------------------------------------------
2834 * Helper class for file movement
2835 * @ingroup FileAbstraction
2837 class LocalFileMoveBatch
{
2838 /** @var LocalFile */
2848 protected $oldCount;
2852 /** @var DatabaseBase */
2857 * @param Title $target
2859 function __construct( File
$file, Title
$target ) {
2860 $this->file
= $file;
2861 $this->target
= $target;
2862 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2863 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2864 $this->oldName
= $this->file
->getName();
2865 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2866 $this->oldRel
= $this->oldHash
. $this->oldName
;
2867 $this->newRel
= $this->newHash
. $this->newName
;
2868 $this->db
= $file->getRepo()->getMasterDB();
2872 * Add the current image to the batch
2874 public function addCurrent() {
2875 $this->cur
= [ $this->oldRel
, $this->newRel
];
2879 * Add the old versions of the image to the batch
2880 * @return array List of archive names from old versions
2882 public function addOlds() {
2883 $archiveBase = 'archive';
2885 $this->oldCount
= 0;
2888 $result = $this->db
->select( 'oldimage',
2889 [ 'oi_archive_name', 'oi_deleted' ],
2890 [ 'oi_name' => $this->oldName
],
2892 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2895 foreach ( $result as $row ) {
2896 $archiveNames[] = $row->oi_archive_name
;
2897 $oldName = $row->oi_archive_name
;
2898 $bits = explode( '!', $oldName, 2 );
2900 if ( count( $bits ) != 2 ) {
2901 wfDebug( "Old file name missing !: '$oldName' \n" );
2905 list( $timestamp, $filename ) = $bits;
2907 if ( $this->oldName
!= $filename ) {
2908 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2914 // Do we want to add those to oldCount?
2915 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2920 "{$archiveBase}/{$this->oldHash}{$oldName}",
2921 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2925 return $archiveNames;
2930 * @return FileRepoStatus
2932 public function execute() {
2933 $repo = $this->file
->repo
;
2934 $status = $repo->newGood();
2935 $destFile = wfLocalFile( $this->target
);
2937 $this->file
->lock(); // begin
2938 $destFile->lock(); // quickly fail if destination is not available
2940 $triplets = $this->getMoveTriplets();
2941 $checkStatus = $this->removeNonexistentFiles( $triplets );
2942 if ( !$checkStatus->isGood() ) {
2943 $destFile->unlock();
2944 $this->file
->unlock();
2945 $status->merge( $checkStatus ); // couldn't talk to file backend
2948 $triplets = $checkStatus->value
;
2950 // Verify the file versions metadata in the DB.
2951 $statusDb = $this->verifyDBUpdates();
2952 if ( !$statusDb->isGood() ) {
2953 $destFile->unlock();
2954 $this->file
->unlock();
2955 $statusDb->ok
= false;
2960 if ( !$repo->hasSha1Storage() ) {
2961 // Copy the files into their new location.
2962 // If a prior process fataled copying or cleaning up files we tolerate any
2963 // of the existing files if they are identical to the ones being stored.
2964 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2965 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2966 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2967 if ( !$statusMove->isGood() ) {
2968 // Delete any files copied over (while the destination is still locked)
2969 $this->cleanupTarget( $triplets );
2970 $destFile->unlock();
2971 $this->file
->unlock();
2972 wfDebugLog( 'imagemove', "Error in moving files: "
2973 . $statusMove->getWikiText( false, false, 'en' ) );
2974 $statusMove->ok
= false;
2978 $status->merge( $statusMove );
2981 // Rename the file versions metadata in the DB.
2982 $this->doDBUpdates();
2984 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2985 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2987 $destFile->unlock();
2988 $this->file
->unlock(); // done
2990 // Everything went ok, remove the source files
2991 $this->cleanupSource( $triplets );
2993 $status->merge( $statusDb );
2999 * Verify the database updates and return a new FileRepoStatus indicating how
3000 * many rows would be updated.
3002 * @return FileRepoStatus
3004 protected function verifyDBUpdates() {
3005 $repo = $this->file
->repo
;
3006 $status = $repo->newGood();
3009 $hasCurrent = $dbw->selectField(
3012 [ 'img_name' => $this->oldName
],
3016 $oldRowCount = $dbw->selectField(
3019 [ 'oi_name' => $this->oldName
],
3024 if ( $hasCurrent ) {
3025 $status->successCount++
;
3027 $status->failCount++
;
3029 $status->successCount +
= $oldRowCount;
3030 // Bug 34934: oldCount is based on files that actually exist.
3031 // There may be more DB rows than such files, in which case $affected
3032 // can be greater than $total. We use max() to avoid negatives here.
3033 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3034 if ( $status->failCount
) {
3035 $status->error( 'imageinvalidfilename' );
3042 * Do the database updates and return a new FileRepoStatus indicating how
3043 * many rows where updated.
3045 protected function doDBUpdates() {
3048 // Update current image
3051 [ 'img_name' => $this->newName
],
3052 [ 'img_name' => $this->oldName
],
3055 // Update old images
3059 'oi_name' => $this->newName
,
3060 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3061 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3063 [ 'oi_name' => $this->oldName
],
3069 * Generate triplets for FileRepo::storeBatch().
3072 protected function getMoveTriplets() {
3073 $moves = array_merge( [ $this->cur
], $this->olds
);
3074 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3076 foreach ( $moves as $move ) {
3077 // $move: (oldRelativePath, newRelativePath)
3078 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3079 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3082 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3090 * Removes non-existent files from move batch.
3091 * @param array $triplets
3094 protected function removeNonexistentFiles( $triplets ) {
3097 foreach ( $triplets as $file ) {
3098 $files[$file[0]] = $file[0];
3101 $result = $this->file
->repo
->fileExistsBatch( $files );
3102 if ( in_array( null, $result, true ) ) {
3103 return Status
::newFatal( 'backend-fail-internal',
3104 $this->file
->repo
->getBackend()->getName() );
3107 $filteredTriplets = [];
3108 foreach ( $triplets as $file ) {
3109 if ( $result[$file[0]] ) {
3110 $filteredTriplets[] = $file;
3112 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3116 return Status
::newGood( $filteredTriplets );
3120 * Cleanup a partially moved array of triplets by deleting the target
3121 * files. Called if something went wrong half way.
3122 * @param array $triplets
3124 protected function cleanupTarget( $triplets ) {
3125 // Create dest pairs from the triplets
3127 foreach ( $triplets as $triplet ) {
3128 // $triplet: (old source virtual URL, dst zone, dest rel)
3129 $pairs[] = [ $triplet[1], $triplet[2] ];
3132 $this->file
->repo
->cleanupBatch( $pairs );
3136 * Cleanup a fully moved array of triplets by deleting the source files.
3137 * Called at the end of the move process if everything else went ok.
3138 * @param array $triplets
3140 protected function cleanupSource( $triplets ) {
3141 // Create source file names from the triplets
3143 foreach ( $triplets as $triplet ) {
3144 $files[] = $triplet[0];
3147 $this->file
->repo
->cleanupBatch( $files );
3151 class LocalFileLockError
extends ErrorPageError
{
3152 public function __construct( Status
$status ) {
3153 parent
::__construct(
3155 $status->getMessage()
3159 public function report() {
3161 $wgOut->setStatusCode( 429 );