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
282 * @param array $cacheSetOpts Result of Database::getCacheSetOptions()
284 private function saveToCache( array $cacheSetOpts ) {
287 $key = $this->getCacheKey();
292 $fields = $this->getCacheFields( '' );
293 $cacheVal = [ 'version' => MW_FILE_VERSION
];
294 $cacheVal['fileExists'] = $this->fileExists
;
296 if ( $this->fileExists
) {
297 foreach ( $fields as $field ) {
298 $cacheVal[$field] = $this->$field;
302 // Strip off excessive entries from the subset of fields that can become large.
303 // If the cache value gets to large it will not fit in memcached and nothing will
304 // get cached at all, causing master queries for any file access.
305 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
306 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
307 unset( $cacheVal[$field] ); // don't let the value get too big
311 // Cache presence for 1 week and negatives for 1 day
312 $wanCache = ObjectCache
::getMainWANInstance();
313 if ( $this->fileExists
) {
314 $ttl = $wanCache::TTL_WEEK
;
315 $ttl = $wanCache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
317 $ttl = $wanCache::TTL_DAY
;
319 $wanCache->set( $key, $cacheVal, $ttl, $cacheSetOpts );
323 * Purge the file object/metadata cache
325 public function invalidateCache() {
326 $key = $this->getCacheKey();
331 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
332 ObjectCache
::getMainWANInstance()->delete( $key );
337 * Load metadata from the file itself
339 function loadFromFile() {
340 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
341 $this->setProps( $props );
345 * @param string $prefix
348 function getCacheFields( $prefix = 'img_' ) {
349 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
350 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
351 'user_text', 'description' ];
352 static $results = [];
354 if ( $prefix == '' ) {
358 if ( !isset( $results[$prefix] ) ) {
359 $prefixedFields = [];
360 foreach ( $fields as $field ) {
361 $prefixedFields[] = $prefix . $field;
363 $results[$prefix] = $prefixedFields;
366 return $results[$prefix];
370 * @param string $prefix
373 function getLazyCacheFields( $prefix = 'img_' ) {
374 static $fields = [ 'metadata' ];
375 static $results = [];
377 if ( $prefix == '' ) {
381 if ( !isset( $results[$prefix] ) ) {
382 $prefixedFields = [];
383 foreach ( $fields as $field ) {
384 $prefixedFields[] = $prefix . $field;
386 $results[$prefix] = $prefixedFields;
389 return $results[$prefix];
393 * Load file metadata from the DB
396 function loadFromDB( $flags = 0 ) {
397 $fname = get_class( $this ) . '::' . __FUNCTION__
;
399 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
400 $this->dataLoaded
= true;
401 $this->extraDataLoaded
= true;
403 $dbr = ( $flags & self
::READ_LATEST
)
404 ?
$this->repo
->getMasterDB()
405 : $this->repo
->getSlaveDB();
407 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
408 [ 'img_name' => $this->getName() ], $fname );
411 $this->loadFromRow( $row );
413 $this->fileExists
= false;
418 * Load lazy file metadata from the DB.
419 * This covers fields that are sometimes not cached.
421 protected function loadExtraFromDB() {
422 $fname = get_class( $this ) . '::' . __FUNCTION__
;
424 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
425 $this->extraDataLoaded
= true;
427 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
429 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
433 foreach ( $fieldMap as $name => $value ) {
434 $this->$name = $value;
437 throw new MWException( "Could not find data for image '{$this->getName()}'." );
442 * @param IDatabase $dbr
443 * @param string $fname
446 private function loadFieldsWithTimestamp( $dbr, $fname ) {
449 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
450 [ 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ],
453 $fieldMap = $this->unprefixRow( $row, 'img_' );
455 # File may have been uploaded over in the meantime; check the old versions
456 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
457 [ 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ],
460 $fieldMap = $this->unprefixRow( $row, 'oi_' );
468 * @param array|object $row
469 * @param string $prefix
470 * @throws MWException
473 protected function unprefixRow( $row, $prefix = 'img_' ) {
474 $array = (array)$row;
475 $prefixLength = strlen( $prefix );
477 // Sanity check prefix once
478 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
479 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
483 foreach ( $array as $name => $value ) {
484 $decoded[substr( $name, $prefixLength )] = $value;
491 * Decode a row from the database (either object or array) to an array
492 * with timestamps and MIME types decoded, and the field prefix removed.
494 * @param string $prefix
495 * @throws MWException
498 function decodeRow( $row, $prefix = 'img_' ) {
499 $decoded = $this->unprefixRow( $row, $prefix );
501 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
503 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
505 if ( empty( $decoded['major_mime'] ) ) {
506 $decoded['mime'] = 'unknown/unknown';
508 if ( !$decoded['minor_mime'] ) {
509 $decoded['minor_mime'] = 'unknown';
511 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
514 // Trim zero padding from char/binary field
515 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
517 // Normalize some fields to integer type, per their database definition.
518 // Use unary + so that overflows will be upgraded to double instead of
519 // being trucated as with intval(). This is important to allow >2GB
520 // files on 32-bit systems.
521 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
522 $decoded[$field] = +
$decoded[$field];
529 * Load file metadata from a DB result row
532 * @param string $prefix
534 function loadFromRow( $row, $prefix = 'img_' ) {
535 $this->dataLoaded
= true;
536 $this->extraDataLoaded
= true;
538 $array = $this->decodeRow( $row, $prefix );
540 foreach ( $array as $name => $value ) {
541 $this->$name = $value;
544 $this->fileExists
= true;
545 $this->maybeUpgradeRow();
549 * Load file metadata from cache or DB, unless already loaded
552 function load( $flags = 0 ) {
553 if ( !$this->dataLoaded
) {
554 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
555 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
556 $this->loadFromDB( $flags );
557 $this->saveToCache( $opts );
559 $this->dataLoaded
= true;
561 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
562 // @note: loads on name/timestamp to reduce race condition problems
563 $this->loadExtraFromDB();
568 * Upgrade a row if it needs it
570 function maybeUpgradeRow() {
571 global $wgUpdateCompatibleMetadata;
573 if ( wfReadOnly() ||
$this->upgrading
) {
578 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
581 $handler = $this->getHandler();
583 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
584 if ( $validity === MediaHandler
::METADATA_BAD
) {
586 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
587 $upgrade = $wgUpdateCompatibleMetadata;
593 $this->upgrading
= true;
594 // Defer updates unless in auto-commit CLI mode
595 DeferredUpdates
::addCallableUpdate( function() {
596 $this->upgrading
= false; // avoid duplicate updates
599 } catch ( LocalFileLockError
$e ) {
600 // let the other process handle it (or do it next time)
607 * @return bool Whether upgradeRow() ran for this object
609 function getUpgraded() {
610 return $this->upgraded
;
614 * Fix assorted version-related problems with the image row by reloading it from the file
616 function upgradeRow() {
617 $this->lock(); // begin
619 $this->loadFromFile();
621 # Don't destroy file info of missing files
622 if ( !$this->fileExists
) {
624 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
629 $dbw = $this->repo
->getMasterDB();
630 list( $major, $minor ) = self
::splitMime( $this->mime
);
632 if ( wfReadOnly() ) {
637 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
639 $dbw->update( 'image',
641 'img_size' => $this->size
, // sanity
642 'img_width' => $this->width
,
643 'img_height' => $this->height
,
644 'img_bits' => $this->bits
,
645 'img_media_type' => $this->media_type
,
646 'img_major_mime' => $major,
647 'img_minor_mime' => $minor,
648 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
649 'img_sha1' => $this->sha1
,
651 [ 'img_name' => $this->getName() ],
655 $this->invalidateCache();
657 $this->unlock(); // done
658 $this->upgraded
= true; // avoid rework/retries
662 * Set properties in this object to be equal to those given in the
663 * associative array $info. Only cacheable fields can be set.
664 * All fields *must* be set in $info except for getLazyCacheFields().
666 * If 'mime' is given, it will be split into major_mime/minor_mime.
667 * If major_mime/minor_mime are given, $this->mime will also be set.
671 function setProps( $info ) {
672 $this->dataLoaded
= true;
673 $fields = $this->getCacheFields( '' );
674 $fields[] = 'fileExists';
676 foreach ( $fields as $field ) {
677 if ( isset( $info[$field] ) ) {
678 $this->$field = $info[$field];
682 // Fix up mime fields
683 if ( isset( $info['major_mime'] ) ) {
684 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
685 } elseif ( isset( $info['mime'] ) ) {
686 $this->mime
= $info['mime'];
687 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
691 /** splitMime inherited */
692 /** getName inherited */
693 /** getTitle inherited */
694 /** getURL inherited */
695 /** getViewURL inherited */
696 /** getPath inherited */
697 /** isVisible inherited */
702 function isMissing() {
703 if ( $this->missing
=== null ) {
704 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
705 $this->missing
= !$fileExists;
708 return $this->missing
;
712 * Return the width of the image
717 public function getWidth( $page = 1 ) {
720 if ( $this->isMultipage() ) {
721 $handler = $this->getHandler();
725 $dim = $handler->getPageDimensions( $this, $page );
727 return $dim['width'];
729 // For non-paged media, the false goes through an
730 // intval, turning failure into 0, so do same here.
739 * Return the height of the image
744 public function getHeight( $page = 1 ) {
747 if ( $this->isMultipage() ) {
748 $handler = $this->getHandler();
752 $dim = $handler->getPageDimensions( $this, $page );
754 return $dim['height'];
756 // For non-paged media, the false goes through an
757 // intval, turning failure into 0, so do same here.
761 return $this->height
;
766 * Returns ID or name of user who uploaded the file
768 * @param string $type 'text' or 'id'
771 function getUser( $type = 'text' ) {
774 if ( $type == 'text' ) {
775 return $this->user_text
;
776 } elseif ( $type == 'id' ) {
777 return (int)$this->user
;
782 * Get short description URL for a file based on the page ID.
784 * @return string|null
785 * @throws MWException
788 public function getDescriptionShortUrl() {
789 $pageId = $this->title
->getArticleID();
791 if ( $pageId !== null ) {
792 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
793 if ( $url !== false ) {
801 * Get handler-specific metadata
804 function getMetadata() {
805 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
806 return $this->metadata
;
812 function getBitDepth() {
815 return (int)$this->bits
;
819 * Returns the size of the image file, in bytes
822 public function getSize() {
829 * Returns the MIME type of the file.
832 function getMimeType() {
839 * Returns the type of the media in the file.
840 * Use the value returned by this function with the MEDIATYPE_xxx constants.
843 function getMediaType() {
846 return $this->media_type
;
849 /** canRender inherited */
850 /** mustRender inherited */
851 /** allowInlineDisplay inherited */
852 /** isSafeFile inherited */
853 /** isTrustedFile inherited */
856 * Returns true if the file exists on disk.
857 * @return bool Whether file exist on disk.
859 public function exists() {
862 return $this->fileExists
;
865 /** getTransformScript inherited */
866 /** getUnscaledThumb inherited */
867 /** thumbName inherited */
868 /** createThumb inherited */
869 /** transform inherited */
871 /** getHandler inherited */
872 /** iconThumb inherited */
873 /** getLastError inherited */
876 * Get all thumbnail names previously generated for this file
877 * @param string|bool $archiveName Name of an archive file, default false
878 * @return array First element is the base dir, then files in that base dir.
880 function getThumbnails( $archiveName = false ) {
881 if ( $archiveName ) {
882 $dir = $this->getArchiveThumbPath( $archiveName );
884 $dir = $this->getThumbPath();
887 $backend = $this->repo
->getBackend();
890 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
891 foreach ( $iterator as $file ) {
894 } catch ( FileBackendError
$e ) {
895 } // suppress (bug 54674)
901 * Refresh metadata in memcached, but don't touch thumbnails or CDN
903 function purgeMetadataCache() {
904 $this->invalidateCache();
908 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
910 * @param array $options An array potentially with the key forThumbRefresh.
912 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
914 function purgeCache( $options = [] ) {
915 // Refresh metadata cache
916 $this->purgeMetadataCache();
919 $this->purgeThumbnails( $options );
921 // Purge CDN cache for this file
922 DeferredUpdates
::addUpdate(
923 new CdnCacheUpdate( [ $this->getUrl() ] ),
924 DeferredUpdates
::PRESEND
929 * Delete cached transformed files for an archived version only.
930 * @param string $archiveName Name of the archived file
932 function purgeOldThumbnails( $archiveName ) {
933 // Get a list of old thumbnails and URLs
934 $files = $this->getThumbnails( $archiveName );
936 // Purge any custom thumbnail caches
937 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
940 $dir = array_shift( $files );
941 $this->purgeThumbList( $dir, $files );
945 foreach ( $files as $file ) {
946 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
948 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
952 * Delete cached transformed files for the current version only.
953 * @param array $options
955 public function purgeThumbnails( $options = [] ) {
956 $files = $this->getThumbnails();
957 // Always purge all files from CDN regardless of handler filters
959 foreach ( $files as $file ) {
960 $urls[] = $this->getThumbUrl( $file );
962 array_shift( $urls ); // don't purge directory
964 // Give media handler a chance to filter the file purge list
965 if ( !empty( $options['forThumbRefresh'] ) ) {
966 $handler = $this->getHandler();
968 $handler->filterThumbnailPurgeList( $files, $options );
972 // Purge any custom thumbnail caches
973 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
976 $dir = array_shift( $files );
977 $this->purgeThumbList( $dir, $files );
980 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
984 * Prerenders a configurable set of thumbnails
988 public function prerenderThumbnails() {
989 global $wgUploadThumbnailRenderMap;
993 $sizes = $wgUploadThumbnailRenderMap;
996 foreach ( $sizes as $size ) {
997 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
998 $jobs[] = new ThumbnailRenderJob(
1000 [ 'transformParams' => [ 'width' => $size ] ]
1006 JobQueueGroup
::singleton()->lazyPush( $jobs );
1011 * Delete a list of thumbnails visible at urls
1012 * @param string $dir Base dir of the files.
1013 * @param array $files Array of strings: relative filenames (to $dir)
1015 protected function purgeThumbList( $dir, $files ) {
1016 $fileListDebug = strtr(
1017 var_export( $files, true ),
1020 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1023 foreach ( $files as $file ) {
1024 # Check that the base file name is part of the thumb name
1025 # This is a basic sanity check to avoid erasing unrelated directories
1026 if ( strpos( $file, $this->getName() ) !== false
1027 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1029 $purgeList[] = "{$dir}/{$file}";
1033 # Delete the thumbnails
1034 $this->repo
->quickPurgeBatch( $purgeList );
1035 # Clear out the thumbnail directory if empty
1036 $this->repo
->quickCleanDir( $dir );
1039 /** purgeDescription inherited */
1040 /** purgeEverything inherited */
1043 * @param int $limit Optional: Limit to number of results
1044 * @param int $start Optional: Timestamp, start from
1045 * @param int $end Optional: Timestamp, end at
1047 * @return OldLocalFile[]
1049 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1050 $dbr = $this->repo
->getSlaveDB();
1051 $tables = [ 'oldimage' ];
1052 $fields = OldLocalFile
::selectFields();
1053 $conds = $opts = $join_conds = [];
1054 $eq = $inc ?
'=' : '';
1055 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1058 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1062 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1066 $opts['LIMIT'] = $limit;
1069 // Search backwards for time > x queries
1070 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1071 $opts['ORDER BY'] = "oi_timestamp $order";
1072 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1074 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1075 &$conds, &$opts, &$join_conds ] );
1077 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1080 foreach ( $res as $row ) {
1081 $r[] = $this->repo
->newFileFromRow( $row );
1084 if ( $order == 'ASC' ) {
1085 $r = array_reverse( $r ); // make sure it ends up descending
1092 * Returns the history of this file, line by line.
1093 * starts with current version, then old versions.
1094 * uses $this->historyLine to check which line to return:
1095 * 0 return line for current version
1096 * 1 query for old versions, return first one
1097 * 2, ... return next old version from above query
1100 public function nextHistoryLine() {
1101 # Polymorphic function name to distinguish foreign and local fetches
1102 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1104 $dbr = $this->repo
->getSlaveDB();
1106 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1107 $this->historyRes
= $dbr->select( 'image',
1110 "'' AS oi_archive_name",
1114 [ 'img_name' => $this->title
->getDBkey() ],
1118 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1119 $this->historyRes
= null;
1123 } elseif ( $this->historyLine
== 1 ) {
1124 $this->historyRes
= $dbr->select( 'oldimage', '*',
1125 [ 'oi_name' => $this->title
->getDBkey() ],
1127 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1130 $this->historyLine++
;
1132 return $dbr->fetchObject( $this->historyRes
);
1136 * Reset the history pointer to the first element of the history
1138 public function resetHistory() {
1139 $this->historyLine
= 0;
1141 if ( !is_null( $this->historyRes
) ) {
1142 $this->historyRes
= null;
1146 /** getHashPath inherited */
1147 /** getRel inherited */
1148 /** getUrlRel inherited */
1149 /** getArchiveRel inherited */
1150 /** getArchivePath inherited */
1151 /** getThumbPath inherited */
1152 /** getArchiveUrl inherited */
1153 /** getThumbUrl inherited */
1154 /** getArchiveVirtualUrl inherited */
1155 /** getThumbVirtualUrl inherited */
1156 /** isHashed inherited */
1159 * Upload a file and record it in the DB
1160 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1161 * @param string $comment Upload description
1162 * @param string $pageText Text to use for the new description page,
1163 * if a new description page is created
1164 * @param int|bool $flags Flags for publish()
1165 * @param array|bool $props File properties, if known. This can be used to
1166 * reduce the upload time when uploading virtual URLs for which the file
1167 * info is already known
1168 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1170 * @param User|null $user User object or null to use $wgUser
1171 * @param string[] $tags Change tags to add to the log entry and page revision.
1172 * (This doesn't check $user's permissions.)
1173 * @return FileRepoStatus On success, the value member contains the
1174 * archive name, or an empty string if it was a new file.
1176 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1177 $timestamp = false, $user = null, $tags = []
1181 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1182 return $this->readOnlyFatalStatus();
1185 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1187 if ( $this->repo
->isVirtualUrl( $srcPath )
1188 || FileBackend
::isStoragePath( $srcPath )
1190 $props = $this->repo
->getFileProps( $srcPath );
1192 $props = FSFile
::getPropsFromPath( $srcPath );
1197 $handler = MediaHandler
::getHandler( $props['mime'] );
1199 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1201 $options['headers'] = [];
1204 // Trim spaces on user supplied text
1205 $comment = trim( $comment );
1207 // Truncate nicely or the DB will do it for us
1208 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1209 $comment = $wgContLang->truncate( $comment, 255 );
1210 $this->lock(); // begin
1211 $status = $this->publish( $src, $flags, $options );
1213 if ( $status->successCount
>= 2 ) {
1214 // There will be a copy+(one of move,copy,store).
1215 // The first succeeding does not commit us to updating the DB
1216 // since it simply copied the current version to a timestamped file name.
1217 // It is only *preferable* to avoid leaving such files orphaned.
1218 // Once the second operation goes through, then the current version was
1219 // updated and we must therefore update the DB too.
1220 $oldver = $status->value
;
1221 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1222 $status->fatal( 'filenotfound', $srcPath );
1226 $this->unlock(); // done
1232 * Record a file upload in the upload log and the image table
1233 * @param string $oldver
1234 * @param string $desc
1235 * @param string $license
1236 * @param string $copyStatus
1237 * @param string $source
1238 * @param bool $watch
1239 * @param string|bool $timestamp
1240 * @param User|null $user User object or null to use $wgUser
1243 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1244 $watch = false, $timestamp = false, User
$user = null ) {
1250 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1252 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1257 $user->addWatch( $this->getTitle() );
1264 * Record a file upload in the upload log and the image table
1265 * @param string $oldver
1266 * @param string $comment
1267 * @param string $pageText
1268 * @param bool|array $props
1269 * @param string|bool $timestamp
1270 * @param null|User $user
1271 * @param string[] $tags
1274 function recordUpload2(
1275 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1277 if ( is_null( $user ) ) {
1282 $dbw = $this->repo
->getMasterDB();
1284 # Imports or such might force a certain timestamp; otherwise we generate
1285 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1286 if ( $timestamp === false ) {
1287 $timestamp = $dbw->timestamp();
1288 $allowTimeKludge = true;
1290 $allowTimeKludge = false;
1293 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1294 $props['description'] = $comment;
1295 $props['user'] = $user->getId();
1296 $props['user_text'] = $user->getName();
1297 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1298 $this->setProps( $props );
1300 # Fail now if the file isn't there
1301 if ( !$this->fileExists
) {
1302 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1307 $dbw->startAtomic( __METHOD__
);
1309 # Test to see if the row exists using INSERT IGNORE
1310 # This avoids race conditions by locking the row until the commit, and also
1311 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1312 $dbw->insert( 'image',
1314 'img_name' => $this->getName(),
1315 'img_size' => $this->size
,
1316 'img_width' => intval( $this->width
),
1317 'img_height' => intval( $this->height
),
1318 'img_bits' => $this->bits
,
1319 'img_media_type' => $this->media_type
,
1320 'img_major_mime' => $this->major_mime
,
1321 'img_minor_mime' => $this->minor_mime
,
1322 'img_timestamp' => $timestamp,
1323 'img_description' => $comment,
1324 'img_user' => $user->getId(),
1325 'img_user_text' => $user->getName(),
1326 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1327 'img_sha1' => $this->sha1
1333 $reupload = ( $dbw->affectedRows() == 0 );
1335 if ( $allowTimeKludge ) {
1336 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1337 $ltimestamp = $dbw->selectField(
1340 [ 'img_name' => $this->getName() ],
1342 [ 'LOCK IN SHARE MODE' ]
1344 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1345 # Avoid a timestamp that is not newer than the last version
1346 # TODO: the image/oldimage tables should be like page/revision with an ID field
1347 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1348 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1349 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1350 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1354 # (bug 34993) Note: $oldver can be empty here, if the previous
1355 # version of the file was broken. Allow registration of the new
1356 # version to continue anyway, because that's better than having
1357 # an image that's not fixable by user operations.
1358 # Collision, this is an update of a file
1359 # Insert previous contents into oldimage
1360 $dbw->insertSelect( 'oldimage', 'image',
1362 'oi_name' => 'img_name',
1363 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1364 'oi_size' => 'img_size',
1365 'oi_width' => 'img_width',
1366 'oi_height' => 'img_height',
1367 'oi_bits' => 'img_bits',
1368 'oi_timestamp' => 'img_timestamp',
1369 'oi_description' => 'img_description',
1370 'oi_user' => 'img_user',
1371 'oi_user_text' => 'img_user_text',
1372 'oi_metadata' => 'img_metadata',
1373 'oi_media_type' => 'img_media_type',
1374 'oi_major_mime' => 'img_major_mime',
1375 'oi_minor_mime' => 'img_minor_mime',
1376 'oi_sha1' => 'img_sha1'
1378 [ 'img_name' => $this->getName() ],
1382 # Update the current image row
1383 $dbw->update( 'image',
1385 'img_size' => $this->size
,
1386 'img_width' => intval( $this->width
),
1387 'img_height' => intval( $this->height
),
1388 'img_bits' => $this->bits
,
1389 'img_media_type' => $this->media_type
,
1390 'img_major_mime' => $this->major_mime
,
1391 'img_minor_mime' => $this->minor_mime
,
1392 'img_timestamp' => $timestamp,
1393 'img_description' => $comment,
1394 'img_user' => $user->getId(),
1395 'img_user_text' => $user->getName(),
1396 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1397 'img_sha1' => $this->sha1
1399 [ 'img_name' => $this->getName() ],
1404 $descTitle = $this->getTitle();
1405 $descId = $descTitle->getArticleID();
1406 $wikiPage = new WikiFilePage( $descTitle );
1407 $wikiPage->setFile( $this );
1409 // Add the log entry...
1410 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1411 $logEntry->setTimestamp( $this->timestamp
);
1412 $logEntry->setPerformer( $user );
1413 $logEntry->setComment( $comment );
1414 $logEntry->setTarget( $descTitle );
1415 // Allow people using the api to associate log entries with the upload.
1416 // Log has a timestamp, but sometimes different from upload timestamp.
1417 $logEntry->setParameters(
1419 'img_sha1' => $this->sha1
,
1420 'img_timestamp' => $timestamp,
1423 // Note we keep $logId around since during new image
1424 // creation, page doesn't exist yet, so log_page = 0
1425 // but we want it to point to the page we're making,
1426 // so we later modify the log entry.
1427 // For a similar reason, we avoid making an RC entry
1428 // now and wait until the page exists.
1429 $logId = $logEntry->insert();
1431 if ( $descTitle->exists() ) {
1432 // Use own context to get the action text in content language
1433 $formatter = LogFormatter
::newFromEntry( $logEntry );
1434 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1435 $editSummary = $formatter->getPlainActionText();
1437 $nullRevision = Revision
::newNullRevision(
1444 if ( $nullRevision ) {
1445 $nullRevision->insertOn( $dbw );
1447 'NewRevisionFromEditComplete',
1448 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1450 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1451 // Associate null revision id
1452 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1455 $newPageContent = null;
1457 // Make the description page and RC log entry post-commit
1458 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1461 # Defer purges, page creation, and link updates in case they error out.
1462 # The most important thing is that files and the DB registry stay synced.
1463 $dbw->endAtomic( __METHOD__
);
1465 # Do some cache purges after final commit so that:
1466 # a) Changes are more likely to be seen post-purge
1467 # b) They won't cause rollback of the log publish/update above
1468 DeferredUpdates
::addUpdate(
1469 new AutoCommitUpdate(
1473 $reupload, $wikiPage, $newPageContent, $comment, $user,
1474 $logEntry, $logId, $descId, $tags
1476 # Update memcache after the commit
1477 $this->invalidateCache();
1479 $updateLogPage = false;
1480 if ( $newPageContent ) {
1481 # New file page; create the description page.
1482 # There's already a log entry, so don't make a second RC entry
1483 # CDN and file cache for the description page are purged by doEditContent.
1484 $status = $wikiPage->doEditContent(
1487 EDIT_NEW | EDIT_SUPPRESS_RC
,
1492 if ( isset( $status->value
['revision'] ) ) {
1493 // Associate new page revision id
1494 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1496 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1497 // which is triggered on $descTitle by doEditContent() above.
1498 if ( isset( $status->value
['revision'] ) ) {
1499 /** @var $rev Revision */
1500 $rev = $status->value
['revision'];
1501 $updateLogPage = $rev->getPage();
1504 # Existing file page: invalidate description page cache
1505 $wikiPage->getTitle()->invalidateCache();
1506 $wikiPage->getTitle()->purgeSquid();
1507 # Allow the new file version to be patrolled from the page footer
1508 Article
::purgePatrolFooterCache( $descId );
1511 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1512 # but setAssociatedRevId() wasn't called at that point yet...
1513 $logParams = $logEntry->getParameters();
1514 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1515 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1516 if ( $updateLogPage ) {
1517 # Also log page, in case where we just created it above
1518 $update['log_page'] = $updateLogPage;
1520 $this->getRepo()->getMasterDB()->update(
1523 [ 'log_id' => $logId ],
1526 $this->getRepo()->getMasterDB()->insert(
1529 'ls_field' => 'associated_rev_id',
1530 'ls_value' => $logEntry->getAssociatedRevId(),
1531 'ls_log_id' => $logId,
1536 # Add change tags, if any
1538 $logEntry->setTags( $tags );
1541 # Uploads can be patrolled
1542 $logEntry->setIsPatrollable( true );
1544 # Now that the log entry is up-to-date, make an RC entry.
1545 $logEntry->publish( $logId );
1547 # Run hook for other updates (typically more cache purging)
1548 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1551 # Delete old thumbnails
1552 $this->purgeThumbnails();
1553 # Remove the old file from the CDN cache
1554 DeferredUpdates
::addUpdate(
1555 new CdnCacheUpdate( [ $this->getUrl() ] ),
1556 DeferredUpdates
::PRESEND
1559 # Update backlink pages pointing to this title if created
1560 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1563 $this->prerenderThumbnails();
1566 DeferredUpdates
::PRESEND
1570 # This is a new file, so update the image count
1571 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1574 # Invalidate cache for all pages using this file
1575 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1581 * Move or copy a file to its public location. If a file exists at the
1582 * destination, move it to an archive. Returns a FileRepoStatus object with
1583 * the archive name in the "value" member on success.
1585 * The archive name should be passed through to recordUpload for database
1588 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1589 * @param int $flags A bitwise combination of:
1590 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1591 * @param array $options Optional additional parameters
1592 * @return FileRepoStatus On success, the value member contains the
1593 * archive name, or an empty string if it was a new file.
1595 function publish( $src, $flags = 0, array $options = [] ) {
1596 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1600 * Move or copy a file to a specified location. Returns a FileRepoStatus
1601 * object with the archive name in the "value" member on success.
1603 * The archive name should be passed through to recordUpload for database
1606 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1607 * @param string $dstRel Target relative path
1608 * @param int $flags A bitwise combination of:
1609 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1610 * @param array $options Optional additional parameters
1611 * @return FileRepoStatus On success, the value member contains the
1612 * archive name, or an empty string if it was a new file.
1614 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1615 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1617 $repo = $this->getRepo();
1618 if ( $repo->getReadOnlyReason() !== false ) {
1619 return $this->readOnlyFatalStatus();
1622 $this->lock(); // begin
1624 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1625 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1627 if ( $repo->hasSha1Storage() ) {
1628 $sha1 = $repo->isVirtualUrl( $srcPath )
1629 ?
$repo->getFileSha1( $srcPath )
1630 : FSFile
::getSha1Base36FromPath( $srcPath );
1631 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1632 $status = $repo->quickImport( $src, $dst );
1633 if ( $flags & File
::DELETE_SOURCE
) {
1637 if ( $this->exists() ) {
1638 $status->value
= $archiveName;
1641 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1642 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1644 if ( $status->value
== 'new' ) {
1645 $status->value
= '';
1647 $status->value
= $archiveName;
1651 $this->unlock(); // done
1656 /** getLinksTo inherited */
1657 /** getExifData inherited */
1658 /** isLocal inherited */
1659 /** wasDeleted inherited */
1662 * Move file to the new title
1664 * Move current, old version and all thumbnails
1665 * to the new filename. Old file is deleted.
1667 * Cache purging is done; checks for validity
1668 * and logging are caller's responsibility
1670 * @param Title $target New file name
1671 * @return FileRepoStatus
1673 function move( $target ) {
1674 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1675 return $this->readOnlyFatalStatus();
1678 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1679 $batch = new LocalFileMoveBatch( $this, $target );
1681 $this->lock(); // begin
1682 $batch->addCurrent();
1683 $archiveNames = $batch->addOlds();
1684 $status = $batch->execute();
1685 $this->unlock(); // done
1687 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1689 // Purge the source and target files...
1690 $oldTitleFile = wfLocalFile( $this->title
);
1691 $newTitleFile = wfLocalFile( $target );
1692 // To avoid slow purges in the transaction, move them outside...
1693 DeferredUpdates
::addUpdate(
1694 new AutoCommitUpdate(
1695 $this->getRepo()->getMasterDB(),
1697 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1698 $oldTitleFile->purgeEverything();
1699 foreach ( $archiveNames as $archiveName ) {
1700 $oldTitleFile->purgeOldThumbnails( $archiveName );
1702 $newTitleFile->purgeEverything();
1705 DeferredUpdates
::PRESEND
1708 if ( $status->isOK() ) {
1709 // Now switch the object
1710 $this->title
= $target;
1711 // Force regeneration of the name and hashpath
1712 unset( $this->name
);
1713 unset( $this->hashPath
);
1720 * Delete all versions of the file.
1722 * Moves the files into an archive directory (or deletes them)
1723 * and removes the database rows.
1725 * Cache purging is done; logging is caller's responsibility.
1727 * @param string $reason
1728 * @param bool $suppress
1729 * @param User|null $user
1730 * @return FileRepoStatus
1732 function delete( $reason, $suppress = false, $user = null ) {
1733 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1734 return $this->readOnlyFatalStatus();
1737 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1739 $this->lock(); // begin
1740 $batch->addCurrent();
1741 // Get old version relative paths
1742 $archiveNames = $batch->addOlds();
1743 $status = $batch->execute();
1744 $this->unlock(); // done
1746 if ( $status->isOK() ) {
1747 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1750 // To avoid slow purges in the transaction, move them outside...
1751 DeferredUpdates
::addUpdate(
1752 new AutoCommitUpdate(
1753 $this->getRepo()->getMasterDB(),
1755 function () use ( $archiveNames ) {
1756 $this->purgeEverything();
1757 foreach ( $archiveNames as $archiveName ) {
1758 $this->purgeOldThumbnails( $archiveName );
1762 DeferredUpdates
::PRESEND
1767 foreach ( $archiveNames as $archiveName ) {
1768 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1770 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1776 * Delete an old version of the file.
1778 * Moves the file into an archive directory (or deletes it)
1779 * and removes the database row.
1781 * Cache purging is done; logging is caller's responsibility.
1783 * @param string $archiveName
1784 * @param string $reason
1785 * @param bool $suppress
1786 * @param User|null $user
1787 * @throws MWException Exception on database or file store failure
1788 * @return FileRepoStatus
1790 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1791 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1792 return $this->readOnlyFatalStatus();
1795 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1797 $this->lock(); // begin
1798 $batch->addOld( $archiveName );
1799 $status = $batch->execute();
1800 $this->unlock(); // done
1802 $this->purgeOldThumbnails( $archiveName );
1803 if ( $status->isOK() ) {
1804 $this->purgeDescription();
1807 DeferredUpdates
::addUpdate(
1808 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1809 DeferredUpdates
::PRESEND
1816 * Restore all or specified deleted revisions to the given file.
1817 * Permissions and logging are left to the caller.
1819 * May throw database exceptions on error.
1821 * @param array $versions Set of record ids of deleted items to restore,
1822 * or empty to restore all revisions.
1823 * @param bool $unsuppress
1824 * @return FileRepoStatus
1826 function restore( $versions = [], $unsuppress = false ) {
1827 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1828 return $this->readOnlyFatalStatus();
1831 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1833 $this->lock(); // begin
1837 $batch->addIds( $versions );
1839 $status = $batch->execute();
1840 if ( $status->isGood() ) {
1841 $cleanupStatus = $batch->cleanup();
1842 $cleanupStatus->successCount
= 0;
1843 $cleanupStatus->failCount
= 0;
1844 $status->merge( $cleanupStatus );
1846 $this->unlock(); // done
1851 /** isMultipage inherited */
1852 /** pageCount inherited */
1853 /** scaleHeight inherited */
1854 /** getImageSize inherited */
1857 * Get the URL of the file description page.
1860 function getDescriptionUrl() {
1861 return $this->title
->getLocalURL();
1865 * Get the HTML text of the description page
1866 * This is not used by ImagePage for local files, since (among other things)
1867 * it skips the parser cache.
1869 * @param Language $lang What language to get description in (Optional)
1870 * @return bool|mixed
1872 function getDescriptionText( $lang = null ) {
1873 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1877 $content = $revision->getContent();
1881 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1883 return $pout->getText();
1887 * @param int $audience
1891 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1893 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1895 } elseif ( $audience == self
::FOR_THIS_USER
1896 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1900 return $this->description
;
1905 * @return bool|string
1907 function getTimestamp() {
1910 return $this->timestamp
;
1914 * @return bool|string
1916 public function getDescriptionTouched() {
1917 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1918 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1919 // need to differentiate between null (uninitialized) and false (failed to load).
1920 if ( $this->descriptionTouched
=== null ) {
1922 'page_namespace' => $this->title
->getNamespace(),
1923 'page_title' => $this->title
->getDBkey()
1925 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1926 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1929 return $this->descriptionTouched
;
1935 function getSha1() {
1937 // Initialise now if necessary
1938 if ( $this->sha1
== '' && $this->fileExists
) {
1939 $this->lock(); // begin
1941 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1942 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1943 $dbw = $this->repo
->getMasterDB();
1944 $dbw->update( 'image',
1945 [ 'img_sha1' => $this->sha1
],
1946 [ 'img_name' => $this->getName() ],
1948 $this->invalidateCache();
1951 $this->unlock(); // done
1958 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1960 function isCacheable() {
1963 // If extra data (metadata) was not loaded then it must have been large
1964 return $this->extraDataLoaded
1965 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1972 public function acquireFileLock() {
1973 return $this->getRepo()->getBackend()->lockFiles(
1974 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1982 public function releaseFileLock() {
1983 return $this->getRepo()->getBackend()->unlockFiles(
1984 [ $this->getPath() ], LockManager
::LOCK_EX
1989 * Start an atomic DB section and lock the image for update
1990 * or increments a reference counter if the lock is already held
1992 * This method should not be used outside of LocalFile/LocalFile*Batch
1994 * @throws LocalFileLockError Throws an error if the lock was not acquired
1995 * @return bool Whether the file lock owns/spawned the DB transaction
1997 public function lock() {
1998 if ( !$this->locked
) {
1999 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2001 $dbw = $this->repo
->getMasterDB();
2002 $makesTransaction = !$dbw->trxLevel();
2003 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2004 // Bug 54736: use simple lock to handle when the file does not exist.
2005 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2006 // Also, that would cause contention on INSERT of similarly named rows.
2007 $status = $this->acquireFileLock(); // represents all versions of the file
2008 if ( !$status->isGood() ) {
2009 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2010 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2012 throw new LocalFileLockError( $status );
2014 // Release the lock *after* commit to avoid row-level contention.
2015 // Make sure it triggers on rollback() as well as commit() (T132921).
2016 $dbw->onTransactionResolution( function () use ( $logger ) {
2017 $status = $this->releaseFileLock();
2018 if ( !$status->isGood() ) {
2019 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2022 // Callers might care if the SELECT snapshot is safely fresh
2023 $this->lockedOwnTrx
= $makesTransaction;
2028 return $this->lockedOwnTrx
;
2032 * Decrement the lock reference count and end the atomic section if it reaches zero
2034 * This method should not be used outside of LocalFile/LocalFile*Batch
2036 * The commit and loc release will happen when no atomic sections are active, which
2037 * may happen immediately or at some point after calling this
2039 public function unlock() {
2040 if ( $this->locked
) {
2042 if ( !$this->locked
) {
2043 $dbw = $this->repo
->getMasterDB();
2044 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2045 $this->lockedOwnTrx
= false;
2053 protected function readOnlyFatalStatus() {
2054 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2055 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2059 * Clean up any dangling locks
2061 function __destruct() {
2064 } // LocalFile class
2066 # ------------------------------------------------------------------------------
2069 * Helper class for file deletion
2070 * @ingroup FileAbstraction
2072 class LocalFileDeleteBatch
{
2073 /** @var LocalFile */
2080 private $srcRels = [];
2083 private $archiveUrls = [];
2085 /** @var array Items to be processed in the deletion batch */
2086 private $deletionBatch;
2088 /** @var bool Whether to suppress all suppressable fields when deleting */
2091 /** @var FileRepoStatus */
2099 * @param string $reason
2100 * @param bool $suppress
2101 * @param User|null $user
2103 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2104 $this->file
= $file;
2105 $this->reason
= $reason;
2106 $this->suppress
= $suppress;
2108 $this->user
= $user;
2111 $this->user
= $wgUser;
2113 $this->status
= $file->repo
->newGood();
2116 public function addCurrent() {
2117 $this->srcRels
['.'] = $this->file
->getRel();
2121 * @param string $oldName
2123 public function addOld( $oldName ) {
2124 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2125 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2129 * Add the old versions of the image to the batch
2130 * @return array List of archive names from old versions
2132 public function addOlds() {
2135 $dbw = $this->file
->repo
->getMasterDB();
2136 $result = $dbw->select( 'oldimage',
2137 [ 'oi_archive_name' ],
2138 [ 'oi_name' => $this->file
->getName() ],
2142 foreach ( $result as $row ) {
2143 $this->addOld( $row->oi_archive_name
);
2144 $archiveNames[] = $row->oi_archive_name
;
2147 return $archiveNames;
2153 protected function getOldRels() {
2154 if ( !isset( $this->srcRels
['.'] ) ) {
2155 $oldRels =& $this->srcRels
;
2156 $deleteCurrent = false;
2158 $oldRels = $this->srcRels
;
2159 unset( $oldRels['.'] );
2160 $deleteCurrent = true;
2163 return [ $oldRels, $deleteCurrent ];
2169 protected function getHashes() {
2171 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2173 if ( $deleteCurrent ) {
2174 $hashes['.'] = $this->file
->getSha1();
2177 if ( count( $oldRels ) ) {
2178 $dbw = $this->file
->repo
->getMasterDB();
2179 $res = $dbw->select(
2181 [ 'oi_archive_name', 'oi_sha1' ],
2182 [ 'oi_archive_name' => array_keys( $oldRels ),
2183 'oi_name' => $this->file
->getName() ], // performance
2187 foreach ( $res as $row ) {
2188 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2189 // Get the hash from the file
2190 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2191 $props = $this->file
->repo
->getFileProps( $oldUrl );
2193 if ( $props['fileExists'] ) {
2194 // Upgrade the oldimage row
2195 $dbw->update( 'oldimage',
2196 [ 'oi_sha1' => $props['sha1'] ],
2197 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2199 $hashes[$row->oi_archive_name
] = $props['sha1'];
2201 $hashes[$row->oi_archive_name
] = false;
2204 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2209 $missing = array_diff_key( $this->srcRels
, $hashes );
2211 foreach ( $missing as $name => $rel ) {
2212 $this->status
->error( 'filedelete-old-unregistered', $name );
2215 foreach ( $hashes as $name => $hash ) {
2217 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2218 unset( $hashes[$name] );
2225 protected function doDBInserts() {
2227 $dbw = $this->file
->repo
->getMasterDB();
2228 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2229 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2230 $encReason = $dbw->addQuotes( $this->reason
);
2231 $encGroup = $dbw->addQuotes( 'deleted' );
2232 $ext = $this->file
->getExtension();
2233 $dotExt = $ext === '' ?
'' : ".$ext";
2234 $encExt = $dbw->addQuotes( $dotExt );
2235 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2237 // Bitfields to further suppress the content
2238 if ( $this->suppress
) {
2240 // This should be 15...
2241 $bitfield |
= Revision
::DELETED_TEXT
;
2242 $bitfield |
= Revision
::DELETED_COMMENT
;
2243 $bitfield |
= Revision
::DELETED_USER
;
2244 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2246 $bitfield = 'oi_deleted';
2249 if ( $deleteCurrent ) {
2254 'fa_storage_group' => $encGroup,
2255 'fa_storage_key' => $dbw->conditional(
2256 [ 'img_sha1' => '' ],
2257 $dbw->addQuotes( '' ),
2258 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2260 'fa_deleted_user' => $encUserId,
2261 'fa_deleted_timestamp' => $encTimestamp,
2262 'fa_deleted_reason' => $encReason,
2263 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2265 'fa_name' => 'img_name',
2266 'fa_archive_name' => 'NULL',
2267 'fa_size' => 'img_size',
2268 'fa_width' => 'img_width',
2269 'fa_height' => 'img_height',
2270 'fa_metadata' => 'img_metadata',
2271 'fa_bits' => 'img_bits',
2272 'fa_media_type' => 'img_media_type',
2273 'fa_major_mime' => 'img_major_mime',
2274 'fa_minor_mime' => 'img_minor_mime',
2275 'fa_description' => 'img_description',
2276 'fa_user' => 'img_user',
2277 'fa_user_text' => 'img_user_text',
2278 'fa_timestamp' => 'img_timestamp',
2279 'fa_sha1' => 'img_sha1'
2281 [ 'img_name' => $this->file
->getName() ],
2286 if ( count( $oldRels ) ) {
2287 $res = $dbw->select(
2289 OldLocalFile
::selectFields(),
2291 'oi_name' => $this->file
->getName(),
2292 'oi_archive_name' => array_keys( $oldRels )
2298 foreach ( $res as $row ) {
2300 // Deletion-specific fields
2301 'fa_storage_group' => 'deleted',
2302 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2304 : "{$row->oi_sha1}{$dotExt}",
2305 'fa_deleted_user' => $this->user
->getId(),
2306 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2307 'fa_deleted_reason' => $this->reason
,
2308 // Counterpart fields
2309 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2310 'fa_name' => $row->oi_name
,
2311 'fa_archive_name' => $row->oi_archive_name
,
2312 'fa_size' => $row->oi_size
,
2313 'fa_width' => $row->oi_width
,
2314 'fa_height' => $row->oi_height
,
2315 'fa_metadata' => $row->oi_metadata
,
2316 'fa_bits' => $row->oi_bits
,
2317 'fa_media_type' => $row->oi_media_type
,
2318 'fa_major_mime' => $row->oi_major_mime
,
2319 'fa_minor_mime' => $row->oi_minor_mime
,
2320 'fa_description' => $row->oi_description
,
2321 'fa_user' => $row->oi_user
,
2322 'fa_user_text' => $row->oi_user_text
,
2323 'fa_timestamp' => $row->oi_timestamp
,
2324 'fa_sha1' => $row->oi_sha1
2328 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2332 function doDBDeletes() {
2333 $dbw = $this->file
->repo
->getMasterDB();
2334 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2336 if ( count( $oldRels ) ) {
2337 $dbw->delete( 'oldimage',
2339 'oi_name' => $this->file
->getName(),
2340 'oi_archive_name' => array_keys( $oldRels )
2344 if ( $deleteCurrent ) {
2345 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2350 * Run the transaction
2351 * @return FileRepoStatus
2353 public function execute() {
2354 $repo = $this->file
->getRepo();
2355 $this->file
->lock();
2357 // Prepare deletion batch
2358 $hashes = $this->getHashes();
2359 $this->deletionBatch
= [];
2360 $ext = $this->file
->getExtension();
2361 $dotExt = $ext === '' ?
'' : ".$ext";
2363 foreach ( $this->srcRels
as $name => $srcRel ) {
2364 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2365 if ( isset( $hashes[$name] ) ) {
2366 $hash = $hashes[$name];
2367 $key = $hash . $dotExt;
2368 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2369 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2373 if ( !$repo->hasSha1Storage() ) {
2374 // Removes non-existent file from the batch, so we don't get errors.
2375 // This also handles files in the 'deleted' zone deleted via revision deletion.
2376 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2377 if ( !$checkStatus->isGood() ) {
2378 $this->status
->merge( $checkStatus );
2379 return $this->status
;
2381 $this->deletionBatch
= $checkStatus->value
;
2383 // Execute the file deletion batch
2384 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2385 if ( !$status->isGood() ) {
2386 $this->status
->merge( $status );
2390 if ( !$this->status
->isOK() ) {
2391 // Critical file deletion error; abort
2392 $this->file
->unlock();
2394 return $this->status
;
2397 // Copy the image/oldimage rows to filearchive
2398 $this->doDBInserts();
2399 // Delete image/oldimage rows
2400 $this->doDBDeletes();
2402 // Commit and return
2403 $this->file
->unlock();
2405 return $this->status
;
2409 * Removes non-existent files from a deletion batch.
2410 * @param array $batch
2413 protected function removeNonexistentFiles( $batch ) {
2414 $files = $newBatch = [];
2416 foreach ( $batch as $batchItem ) {
2417 list( $src, ) = $batchItem;
2418 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2421 $result = $this->file
->repo
->fileExistsBatch( $files );
2422 if ( in_array( null, $result, true ) ) {
2423 return Status
::newFatal( 'backend-fail-internal',
2424 $this->file
->repo
->getBackend()->getName() );
2427 foreach ( $batch as $batchItem ) {
2428 if ( $result[$batchItem[0]] ) {
2429 $newBatch[] = $batchItem;
2433 return Status
::newGood( $newBatch );
2437 # ------------------------------------------------------------------------------
2440 * Helper class for file undeletion
2441 * @ingroup FileAbstraction
2443 class LocalFileRestoreBatch
{
2444 /** @var LocalFile */
2447 /** @var array List of file IDs to restore */
2448 private $cleanupBatch;
2450 /** @var array List of file IDs to restore */
2453 /** @var bool Add all revisions of the file */
2456 /** @var bool Whether to remove all settings for suppressed fields */
2457 private $unsuppress = false;
2461 * @param bool $unsuppress
2463 function __construct( File
$file, $unsuppress = false ) {
2464 $this->file
= $file;
2465 $this->cleanupBatch
= $this->ids
= [];
2467 $this->unsuppress
= $unsuppress;
2474 public function addId( $fa_id ) {
2475 $this->ids
[] = $fa_id;
2479 * Add a whole lot of files by ID
2482 public function addIds( $ids ) {
2483 $this->ids
= array_merge( $this->ids
, $ids );
2487 * Add all revisions of the file
2489 public function addAll() {
2494 * Run the transaction, except the cleanup batch.
2495 * The cleanup batch should be run in a separate transaction, because it locks different
2496 * rows and there's no need to keep the image row locked while it's acquiring those locks
2497 * The caller may have its own transaction open.
2498 * So we save the batch and let the caller call cleanup()
2499 * @return FileRepoStatus
2501 public function execute() {
2504 $repo = $this->file
->getRepo();
2505 if ( !$this->all
&& !$this->ids
) {
2507 return $repo->newGood();
2510 $lockOwnsTrx = $this->file
->lock();
2512 $dbw = $this->file
->repo
->getMasterDB();
2513 $status = $this->file
->repo
->newGood();
2515 $exists = (bool)$dbw->selectField( 'image', '1',
2516 [ 'img_name' => $this->file
->getName() ],
2518 // The lock() should already prevents changes, but this still may need
2519 // to bypass any transaction snapshot. However, if lock() started the
2520 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2521 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2524 // Fetch all or selected archived revisions for the file,
2525 // sorted from the most recent to the oldest.
2526 $conditions = [ 'fa_name' => $this->file
->getName() ];
2528 if ( !$this->all
) {
2529 $conditions['fa_id'] = $this->ids
;
2532 $result = $dbw->select(
2534 ArchivedFile
::selectFields(),
2537 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2543 $insertCurrent = false;
2548 foreach ( $result as $row ) {
2549 $idsPresent[] = $row->fa_id
;
2551 if ( $row->fa_name
!= $this->file
->getName() ) {
2552 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2553 $status->failCount++
;
2557 if ( $row->fa_storage_key
== '' ) {
2558 // Revision was missing pre-deletion
2559 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2560 $status->failCount++
;
2564 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2565 $row->fa_storage_key
;
2566 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2568 if ( isset( $row->fa_sha1
) ) {
2569 $sha1 = $row->fa_sha1
;
2571 // old row, populate from key
2572 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2576 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2577 $sha1 = substr( $sha1, 1 );
2580 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2581 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2582 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2583 ||
is_null( $row->fa_metadata
)
2585 // Refresh our metadata
2586 // Required for a new current revision; nice for older ones too. :)
2587 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2590 'minor_mime' => $row->fa_minor_mime
,
2591 'major_mime' => $row->fa_major_mime
,
2592 'media_type' => $row->fa_media_type
,
2593 'metadata' => $row->fa_metadata
2597 if ( $first && !$exists ) {
2598 // This revision will be published as the new current version
2599 $destRel = $this->file
->getRel();
2601 'img_name' => $row->fa_name
,
2602 'img_size' => $row->fa_size
,
2603 'img_width' => $row->fa_width
,
2604 'img_height' => $row->fa_height
,
2605 'img_metadata' => $props['metadata'],
2606 'img_bits' => $row->fa_bits
,
2607 'img_media_type' => $props['media_type'],
2608 'img_major_mime' => $props['major_mime'],
2609 'img_minor_mime' => $props['minor_mime'],
2610 'img_description' => $row->fa_description
,
2611 'img_user' => $row->fa_user
,
2612 'img_user_text' => $row->fa_user_text
,
2613 'img_timestamp' => $row->fa_timestamp
,
2617 // The live (current) version cannot be hidden!
2618 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2619 $status->fatal( 'undeleterevdel' );
2620 $this->file
->unlock();
2624 $archiveName = $row->fa_archive_name
;
2626 if ( $archiveName == '' ) {
2627 // This was originally a current version; we
2628 // have to devise a new archive name for it.
2629 // Format is <timestamp of archiving>!<name>
2630 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2633 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2635 } while ( isset( $archiveNames[$archiveName] ) );
2638 $archiveNames[$archiveName] = true;
2639 $destRel = $this->file
->getArchiveRel( $archiveName );
2641 'oi_name' => $row->fa_name
,
2642 'oi_archive_name' => $archiveName,
2643 'oi_size' => $row->fa_size
,
2644 'oi_width' => $row->fa_width
,
2645 'oi_height' => $row->fa_height
,
2646 'oi_bits' => $row->fa_bits
,
2647 'oi_description' => $row->fa_description
,
2648 'oi_user' => $row->fa_user
,
2649 'oi_user_text' => $row->fa_user_text
,
2650 'oi_timestamp' => $row->fa_timestamp
,
2651 'oi_metadata' => $props['metadata'],
2652 'oi_media_type' => $props['media_type'],
2653 'oi_major_mime' => $props['major_mime'],
2654 'oi_minor_mime' => $props['minor_mime'],
2655 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2656 'oi_sha1' => $sha1 ];
2659 $deleteIds[] = $row->fa_id
;
2661 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2662 // private files can stay where they are
2663 $status->successCount++
;
2665 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2666 $this->cleanupBatch
[] = $row->fa_storage_key
;
2674 // Add a warning to the status object for missing IDs
2675 $missingIds = array_diff( $this->ids
, $idsPresent );
2677 foreach ( $missingIds as $id ) {
2678 $status->error( 'undelete-missing-filearchive', $id );
2681 if ( !$repo->hasSha1Storage() ) {
2682 // Remove missing files from batch, so we don't get errors when undeleting them
2683 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2684 if ( !$checkStatus->isGood() ) {
2685 $status->merge( $checkStatus );
2688 $storeBatch = $checkStatus->value
;
2690 // Run the store batch
2691 // Use the OVERWRITE_SAME flag to smooth over a common error
2692 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2693 $status->merge( $storeStatus );
2695 if ( !$status->isGood() ) {
2696 // Even if some files could be copied, fail entirely as that is the
2697 // easiest thing to do without data loss
2698 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2699 $status->ok
= false;
2700 $this->file
->unlock();
2706 // Run the DB updates
2707 // Because we have locked the image row, key conflicts should be rare.
2708 // If they do occur, we can roll back the transaction at this time with
2709 // no data loss, but leaving unregistered files scattered throughout the
2711 // This is not ideal, which is why it's important to lock the image row.
2712 if ( $insertCurrent ) {
2713 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2716 if ( $insertBatch ) {
2717 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2721 $dbw->delete( 'filearchive',
2722 [ 'fa_id' => $deleteIds ],
2726 // If store batch is empty (all files are missing), deletion is to be considered successful
2727 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2729 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2731 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2733 $this->file
->purgeEverything();
2735 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2736 $this->file
->purgeDescription();
2740 $this->file
->unlock();
2746 * Removes non-existent files from a store batch.
2747 * @param array $triplets
2750 protected function removeNonexistentFiles( $triplets ) {
2751 $files = $filteredTriplets = [];
2752 foreach ( $triplets as $file ) {
2753 $files[$file[0]] = $file[0];
2756 $result = $this->file
->repo
->fileExistsBatch( $files );
2757 if ( in_array( null, $result, true ) ) {
2758 return Status
::newFatal( 'backend-fail-internal',
2759 $this->file
->repo
->getBackend()->getName() );
2762 foreach ( $triplets as $file ) {
2763 if ( $result[$file[0]] ) {
2764 $filteredTriplets[] = $file;
2768 return Status
::newGood( $filteredTriplets );
2772 * Removes non-existent files from a cleanup batch.
2773 * @param array $batch
2776 protected function removeNonexistentFromCleanup( $batch ) {
2777 $files = $newBatch = [];
2778 $repo = $this->file
->repo
;
2780 foreach ( $batch as $file ) {
2781 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2782 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2785 $result = $repo->fileExistsBatch( $files );
2787 foreach ( $batch as $file ) {
2788 if ( $result[$file] ) {
2789 $newBatch[] = $file;
2797 * Delete unused files in the deleted zone.
2798 * This should be called from outside the transaction in which execute() was called.
2799 * @return FileRepoStatus
2801 public function cleanup() {
2802 if ( !$this->cleanupBatch
) {
2803 return $this->file
->repo
->newGood();
2806 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2808 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2814 * Cleanup a failed batch. The batch was only partially successful, so
2815 * rollback by removing all items that were succesfully copied.
2817 * @param Status $storeStatus
2818 * @param array $storeBatch
2820 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2823 foreach ( $storeStatus->success
as $i => $success ) {
2824 // Check if this item of the batch was successfully copied
2826 // Item was successfully copied and needs to be removed again
2827 // Extract ($dstZone, $dstRel) from the batch
2828 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2831 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2835 # ------------------------------------------------------------------------------
2838 * Helper class for file movement
2839 * @ingroup FileAbstraction
2841 class LocalFileMoveBatch
{
2842 /** @var LocalFile */
2852 protected $oldCount;
2856 /** @var DatabaseBase */
2861 * @param Title $target
2863 function __construct( File
$file, Title
$target ) {
2864 $this->file
= $file;
2865 $this->target
= $target;
2866 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2867 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2868 $this->oldName
= $this->file
->getName();
2869 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2870 $this->oldRel
= $this->oldHash
. $this->oldName
;
2871 $this->newRel
= $this->newHash
. $this->newName
;
2872 $this->db
= $file->getRepo()->getMasterDB();
2876 * Add the current image to the batch
2878 public function addCurrent() {
2879 $this->cur
= [ $this->oldRel
, $this->newRel
];
2883 * Add the old versions of the image to the batch
2884 * @return array List of archive names from old versions
2886 public function addOlds() {
2887 $archiveBase = 'archive';
2889 $this->oldCount
= 0;
2892 $result = $this->db
->select( 'oldimage',
2893 [ 'oi_archive_name', 'oi_deleted' ],
2894 [ 'oi_name' => $this->oldName
],
2896 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2899 foreach ( $result as $row ) {
2900 $archiveNames[] = $row->oi_archive_name
;
2901 $oldName = $row->oi_archive_name
;
2902 $bits = explode( '!', $oldName, 2 );
2904 if ( count( $bits ) != 2 ) {
2905 wfDebug( "Old file name missing !: '$oldName' \n" );
2909 list( $timestamp, $filename ) = $bits;
2911 if ( $this->oldName
!= $filename ) {
2912 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2918 // Do we want to add those to oldCount?
2919 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2924 "{$archiveBase}/{$this->oldHash}{$oldName}",
2925 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2929 return $archiveNames;
2934 * @return FileRepoStatus
2936 public function execute() {
2937 $repo = $this->file
->repo
;
2938 $status = $repo->newGood();
2939 $destFile = wfLocalFile( $this->target
);
2941 $this->file
->lock(); // begin
2942 $destFile->lock(); // quickly fail if destination is not available
2944 $triplets = $this->getMoveTriplets();
2945 $checkStatus = $this->removeNonexistentFiles( $triplets );
2946 if ( !$checkStatus->isGood() ) {
2947 $destFile->unlock();
2948 $this->file
->unlock();
2949 $status->merge( $checkStatus ); // couldn't talk to file backend
2952 $triplets = $checkStatus->value
;
2954 // Verify the file versions metadata in the DB.
2955 $statusDb = $this->verifyDBUpdates();
2956 if ( !$statusDb->isGood() ) {
2957 $destFile->unlock();
2958 $this->file
->unlock();
2959 $statusDb->ok
= false;
2964 if ( !$repo->hasSha1Storage() ) {
2965 // Copy the files into their new location.
2966 // If a prior process fataled copying or cleaning up files we tolerate any
2967 // of the existing files if they are identical to the ones being stored.
2968 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2969 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2970 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2971 if ( !$statusMove->isGood() ) {
2972 // Delete any files copied over (while the destination is still locked)
2973 $this->cleanupTarget( $triplets );
2974 $destFile->unlock();
2975 $this->file
->unlock();
2976 wfDebugLog( 'imagemove', "Error in moving files: "
2977 . $statusMove->getWikiText( false, false, 'en' ) );
2978 $statusMove->ok
= false;
2982 $status->merge( $statusMove );
2985 // Rename the file versions metadata in the DB.
2986 $this->doDBUpdates();
2988 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2989 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2991 $destFile->unlock();
2992 $this->file
->unlock(); // done
2994 // Everything went ok, remove the source files
2995 $this->cleanupSource( $triplets );
2997 $status->merge( $statusDb );
3003 * Verify the database updates and return a new FileRepoStatus indicating how
3004 * many rows would be updated.
3006 * @return FileRepoStatus
3008 protected function verifyDBUpdates() {
3009 $repo = $this->file
->repo
;
3010 $status = $repo->newGood();
3013 $hasCurrent = $dbw->selectField(
3016 [ 'img_name' => $this->oldName
],
3020 $oldRowCount = $dbw->selectField(
3023 [ 'oi_name' => $this->oldName
],
3028 if ( $hasCurrent ) {
3029 $status->successCount++
;
3031 $status->failCount++
;
3033 $status->successCount +
= $oldRowCount;
3034 // Bug 34934: oldCount is based on files that actually exist.
3035 // There may be more DB rows than such files, in which case $affected
3036 // can be greater than $total. We use max() to avoid negatives here.
3037 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3038 if ( $status->failCount
) {
3039 $status->error( 'imageinvalidfilename' );
3046 * Do the database updates and return a new FileRepoStatus indicating how
3047 * many rows where updated.
3049 protected function doDBUpdates() {
3052 // Update current image
3055 [ 'img_name' => $this->newName
],
3056 [ 'img_name' => $this->oldName
],
3059 // Update old images
3063 'oi_name' => $this->newName
,
3064 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3065 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3067 [ 'oi_name' => $this->oldName
],
3073 * Generate triplets for FileRepo::storeBatch().
3076 protected function getMoveTriplets() {
3077 $moves = array_merge( [ $this->cur
], $this->olds
);
3078 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3080 foreach ( $moves as $move ) {
3081 // $move: (oldRelativePath, newRelativePath)
3082 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3083 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3086 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3094 * Removes non-existent files from move batch.
3095 * @param array $triplets
3098 protected function removeNonexistentFiles( $triplets ) {
3101 foreach ( $triplets as $file ) {
3102 $files[$file[0]] = $file[0];
3105 $result = $this->file
->repo
->fileExistsBatch( $files );
3106 if ( in_array( null, $result, true ) ) {
3107 return Status
::newFatal( 'backend-fail-internal',
3108 $this->file
->repo
->getBackend()->getName() );
3111 $filteredTriplets = [];
3112 foreach ( $triplets as $file ) {
3113 if ( $result[$file[0]] ) {
3114 $filteredTriplets[] = $file;
3116 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3120 return Status
::newGood( $filteredTriplets );
3124 * Cleanup a partially moved array of triplets by deleting the target
3125 * files. Called if something went wrong half way.
3126 * @param array $triplets
3128 protected function cleanupTarget( $triplets ) {
3129 // Create dest pairs from the triplets
3131 foreach ( $triplets as $triplet ) {
3132 // $triplet: (old source virtual URL, dst zone, dest rel)
3133 $pairs[] = [ $triplet[1], $triplet[2] ];
3136 $this->file
->repo
->cleanupBatch( $pairs );
3140 * Cleanup a fully moved array of triplets by deleting the source files.
3141 * Called at the end of the move process if everything else went ok.
3142 * @param array $triplets
3144 protected function cleanupSource( $triplets ) {
3145 // Create source file names from the triplets
3147 foreach ( $triplets as $triplet ) {
3148 $files[] = $triplet[0];
3151 $this->file
->repo
->cleanupBatch( $files );
3155 class LocalFileLockError
extends ErrorPageError
{
3156 public function __construct( Status
$status ) {
3157 parent
::__construct(
3159 $status->getMessage()
3163 public function report() {
3165 $wgOut->setStatusCode( 429 );