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( function() use ( $key ) {
317 ObjectCache
::getMainWANInstance()->delete( $key );
322 * Load metadata from the file itself
324 function loadFromFile() {
325 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
326 $this->setProps( $props );
330 * @param string $prefix
333 function getCacheFields( $prefix = 'img_' ) {
334 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
335 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
336 'user_text', 'description' ];
337 static $results = [];
339 if ( $prefix == '' ) {
343 if ( !isset( $results[$prefix] ) ) {
344 $prefixedFields = [];
345 foreach ( $fields as $field ) {
346 $prefixedFields[] = $prefix . $field;
348 $results[$prefix] = $prefixedFields;
351 return $results[$prefix];
355 * @param string $prefix
358 function getLazyCacheFields( $prefix = 'img_' ) {
359 static $fields = [ 'metadata' ];
360 static $results = [];
362 if ( $prefix == '' ) {
366 if ( !isset( $results[$prefix] ) ) {
367 $prefixedFields = [];
368 foreach ( $fields as $field ) {
369 $prefixedFields[] = $prefix . $field;
371 $results[$prefix] = $prefixedFields;
374 return $results[$prefix];
378 * Load file metadata from the DB
381 function loadFromDB( $flags = 0 ) {
382 $fname = get_class( $this ) . '::' . __FUNCTION__
;
384 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
385 $this->dataLoaded
= true;
386 $this->extraDataLoaded
= true;
388 $dbr = ( $flags & self
::READ_LATEST
)
389 ?
$this->repo
->getMasterDB()
390 : $this->repo
->getSlaveDB();
392 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
393 [ 'img_name' => $this->getName() ], $fname );
396 $this->loadFromRow( $row );
398 $this->fileExists
= false;
403 * Load lazy file metadata from the DB.
404 * This covers fields that are sometimes not cached.
406 protected function loadExtraFromDB() {
407 $fname = get_class( $this ) . '::' . __FUNCTION__
;
409 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
410 $this->extraDataLoaded
= true;
412 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
414 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
418 foreach ( $fieldMap as $name => $value ) {
419 $this->$name = $value;
422 throw new MWException( "Could not find data for image '{$this->getName()}'." );
427 * @param IDatabase $dbr
428 * @param string $fname
431 private function loadFieldsWithTimestamp( $dbr, $fname ) {
434 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
435 'img_name' => $this->getName(),
436 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
439 $fieldMap = $this->unprefixRow( $row, 'img_' );
441 # File may have been uploaded over in the meantime; check the old versions
442 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
443 'oi_name' => $this->getName(),
444 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
447 $fieldMap = $this->unprefixRow( $row, 'oi_' );
455 * @param array|object $row
456 * @param string $prefix
457 * @throws MWException
460 protected function unprefixRow( $row, $prefix = 'img_' ) {
461 $array = (array)$row;
462 $prefixLength = strlen( $prefix );
464 // Sanity check prefix once
465 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
466 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
470 foreach ( $array as $name => $value ) {
471 $decoded[substr( $name, $prefixLength )] = $value;
478 * Decode a row from the database (either object or array) to an array
479 * with timestamps and MIME types decoded, and the field prefix removed.
481 * @param string $prefix
482 * @throws MWException
485 function decodeRow( $row, $prefix = 'img_' ) {
486 $decoded = $this->unprefixRow( $row, $prefix );
488 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
490 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
492 if ( empty( $decoded['major_mime'] ) ) {
493 $decoded['mime'] = 'unknown/unknown';
495 if ( !$decoded['minor_mime'] ) {
496 $decoded['minor_mime'] = 'unknown';
498 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
501 // Trim zero padding from char/binary field
502 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
504 // Normalize some fields to integer type, per their database definition.
505 // Use unary + so that overflows will be upgraded to double instead of
506 // being trucated as with intval(). This is important to allow >2GB
507 // files on 32-bit systems.
508 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
509 $decoded[$field] = +
$decoded[$field];
516 * Load file metadata from a DB result row
519 * @param string $prefix
521 function loadFromRow( $row, $prefix = 'img_' ) {
522 $this->dataLoaded
= true;
523 $this->extraDataLoaded
= true;
525 $array = $this->decodeRow( $row, $prefix );
527 foreach ( $array as $name => $value ) {
528 $this->$name = $value;
531 $this->fileExists
= true;
532 $this->maybeUpgradeRow();
536 * Load file metadata from cache or DB, unless already loaded
539 function load( $flags = 0 ) {
540 if ( !$this->dataLoaded
) {
541 if ( $flags & self
::READ_LATEST
) {
542 $this->loadFromDB( $flags );
544 $this->loadFromCache();
548 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
549 // @note: loads on name/timestamp to reduce race condition problems
550 $this->loadExtraFromDB();
555 * Upgrade a row if it needs it
557 function maybeUpgradeRow() {
558 global $wgUpdateCompatibleMetadata;
560 if ( wfReadOnly() ||
$this->upgrading
) {
565 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
568 $handler = $this->getHandler();
570 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
571 if ( $validity === MediaHandler
::METADATA_BAD
) {
573 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
574 $upgrade = $wgUpdateCompatibleMetadata;
580 $this->upgrading
= true;
581 // Defer updates unless in auto-commit CLI mode
582 DeferredUpdates
::addCallableUpdate( function() {
583 $this->upgrading
= false; // avoid duplicate updates
586 } catch ( LocalFileLockError
$e ) {
587 // let the other process handle it (or do it next time)
594 * @return bool Whether upgradeRow() ran for this object
596 function getUpgraded() {
597 return $this->upgraded
;
601 * Fix assorted version-related problems with the image row by reloading it from the file
603 function upgradeRow() {
604 $this->lock(); // begin
606 $this->loadFromFile();
608 # Don't destroy file info of missing files
609 if ( !$this->fileExists
) {
611 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
616 $dbw = $this->repo
->getMasterDB();
617 list( $major, $minor ) = self
::splitMime( $this->mime
);
619 if ( wfReadOnly() ) {
624 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
626 $dbw->update( 'image',
628 'img_size' => $this->size
, // sanity
629 'img_width' => $this->width
,
630 'img_height' => $this->height
,
631 'img_bits' => $this->bits
,
632 'img_media_type' => $this->media_type
,
633 'img_major_mime' => $major,
634 'img_minor_mime' => $minor,
635 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
636 'img_sha1' => $this->sha1
,
638 [ 'img_name' => $this->getName() ],
642 $this->invalidateCache();
644 $this->unlock(); // done
645 $this->upgraded
= true; // avoid rework/retries
649 * Set properties in this object to be equal to those given in the
650 * associative array $info. Only cacheable fields can be set.
651 * All fields *must* be set in $info except for getLazyCacheFields().
653 * If 'mime' is given, it will be split into major_mime/minor_mime.
654 * If major_mime/minor_mime are given, $this->mime will also be set.
658 function setProps( $info ) {
659 $this->dataLoaded
= true;
660 $fields = $this->getCacheFields( '' );
661 $fields[] = 'fileExists';
663 foreach ( $fields as $field ) {
664 if ( isset( $info[$field] ) ) {
665 $this->$field = $info[$field];
669 // Fix up mime fields
670 if ( isset( $info['major_mime'] ) ) {
671 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
672 } elseif ( isset( $info['mime'] ) ) {
673 $this->mime
= $info['mime'];
674 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
678 /** splitMime inherited */
679 /** getName inherited */
680 /** getTitle inherited */
681 /** getURL inherited */
682 /** getViewURL inherited */
683 /** getPath inherited */
684 /** isVisible inherited */
689 function isMissing() {
690 if ( $this->missing
=== null ) {
691 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
692 $this->missing
= !$fileExists;
695 return $this->missing
;
699 * Return the width of the image
704 public function getWidth( $page = 1 ) {
707 if ( $this->isMultipage() ) {
708 $handler = $this->getHandler();
712 $dim = $handler->getPageDimensions( $this, $page );
714 return $dim['width'];
716 // For non-paged media, the false goes through an
717 // intval, turning failure into 0, so do same here.
726 * Return the height of the image
731 public function getHeight( $page = 1 ) {
734 if ( $this->isMultipage() ) {
735 $handler = $this->getHandler();
739 $dim = $handler->getPageDimensions( $this, $page );
741 return $dim['height'];
743 // For non-paged media, the false goes through an
744 // intval, turning failure into 0, so do same here.
748 return $this->height
;
753 * Returns ID or name of user who uploaded the file
755 * @param string $type 'text' or 'id'
758 function getUser( $type = 'text' ) {
761 if ( $type == 'text' ) {
762 return $this->user_text
;
764 return (int)$this->user
;
769 * Get short description URL for a file based on the page ID.
771 * @return string|null
772 * @throws MWException
775 public function getDescriptionShortUrl() {
776 $pageId = $this->title
->getArticleID();
778 if ( $pageId !== null ) {
779 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
780 if ( $url !== false ) {
788 * Get handler-specific metadata
791 function getMetadata() {
792 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
793 return $this->metadata
;
799 function getBitDepth() {
802 return (int)$this->bits
;
806 * Returns the size of the image file, in bytes
809 public function getSize() {
816 * Returns the MIME type of the file.
819 function getMimeType() {
826 * Returns the type of the media in the file.
827 * Use the value returned by this function with the MEDIATYPE_xxx constants.
830 function getMediaType() {
833 return $this->media_type
;
836 /** canRender inherited */
837 /** mustRender inherited */
838 /** allowInlineDisplay inherited */
839 /** isSafeFile inherited */
840 /** isTrustedFile inherited */
843 * Returns true if the file exists on disk.
844 * @return bool Whether file exist on disk.
846 public function exists() {
849 return $this->fileExists
;
852 /** getTransformScript inherited */
853 /** getUnscaledThumb inherited */
854 /** thumbName inherited */
855 /** createThumb inherited */
856 /** transform inherited */
858 /** getHandler inherited */
859 /** iconThumb inherited */
860 /** getLastError inherited */
863 * Get all thumbnail names previously generated for this file
864 * @param string|bool $archiveName Name of an archive file, default false
865 * @return array First element is the base dir, then files in that base dir.
867 function getThumbnails( $archiveName = false ) {
868 if ( $archiveName ) {
869 $dir = $this->getArchiveThumbPath( $archiveName );
871 $dir = $this->getThumbPath();
874 $backend = $this->repo
->getBackend();
877 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
878 foreach ( $iterator as $file ) {
881 } catch ( FileBackendError
$e ) {
882 } // suppress (bug 54674)
888 * Refresh metadata in memcached, but don't touch thumbnails or CDN
890 function purgeMetadataCache() {
891 $this->invalidateCache();
895 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
897 * @param array $options An array potentially with the key forThumbRefresh.
899 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
901 function purgeCache( $options = [] ) {
902 // Refresh metadata cache
903 $this->purgeMetadataCache();
906 $this->purgeThumbnails( $options );
908 // Purge CDN cache for this file
909 DeferredUpdates
::addUpdate(
910 new CdnCacheUpdate( [ $this->getUrl() ] ),
911 DeferredUpdates
::PRESEND
916 * Delete cached transformed files for an archived version only.
917 * @param string $archiveName Name of the archived file
919 function purgeOldThumbnails( $archiveName ) {
920 // Get a list of old thumbnails and URLs
921 $files = $this->getThumbnails( $archiveName );
923 // Purge any custom thumbnail caches
924 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
927 $dir = array_shift( $files );
928 $this->purgeThumbList( $dir, $files );
932 foreach ( $files as $file ) {
933 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
935 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
939 * Delete cached transformed files for the current version only.
940 * @param array $options
942 public function purgeThumbnails( $options = [] ) {
943 $files = $this->getThumbnails();
944 // Always purge all files from CDN regardless of handler filters
946 foreach ( $files as $file ) {
947 $urls[] = $this->getThumbUrl( $file );
949 array_shift( $urls ); // don't purge directory
951 // Give media handler a chance to filter the file purge list
952 if ( !empty( $options['forThumbRefresh'] ) ) {
953 $handler = $this->getHandler();
955 $handler->filterThumbnailPurgeList( $files, $options );
959 // Purge any custom thumbnail caches
960 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
963 $dir = array_shift( $files );
964 $this->purgeThumbList( $dir, $files );
967 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
971 * Prerenders a configurable set of thumbnails
975 public function prerenderThumbnails() {
976 global $wgUploadThumbnailRenderMap;
980 $sizes = $wgUploadThumbnailRenderMap;
983 foreach ( $sizes as $size ) {
984 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
985 $jobs[] = new ThumbnailRenderJob(
987 [ 'transformParams' => [ 'width' => $size ] ]
993 JobQueueGroup
::singleton()->lazyPush( $jobs );
998 * Delete a list of thumbnails visible at urls
999 * @param string $dir Base dir of the files.
1000 * @param array $files Array of strings: relative filenames (to $dir)
1002 protected function purgeThumbList( $dir, $files ) {
1003 $fileListDebug = strtr(
1004 var_export( $files, true ),
1007 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1010 foreach ( $files as $file ) {
1011 # Check that the base file name is part of the thumb name
1012 # This is a basic sanity check to avoid erasing unrelated directories
1013 if ( strpos( $file, $this->getName() ) !== false
1014 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1016 $purgeList[] = "{$dir}/{$file}";
1020 # Delete the thumbnails
1021 $this->repo
->quickPurgeBatch( $purgeList );
1022 # Clear out the thumbnail directory if empty
1023 $this->repo
->quickCleanDir( $dir );
1026 /** purgeDescription inherited */
1027 /** purgeEverything inherited */
1030 * @param int $limit Optional: Limit to number of results
1031 * @param int $start Optional: Timestamp, start from
1032 * @param int $end Optional: Timestamp, end at
1034 * @return OldLocalFile[]
1036 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1037 $dbr = $this->repo
->getSlaveDB();
1038 $tables = [ 'oldimage' ];
1039 $fields = OldLocalFile
::selectFields();
1040 $conds = $opts = $join_conds = [];
1041 $eq = $inc ?
'=' : '';
1042 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1045 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1049 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1053 $opts['LIMIT'] = $limit;
1056 // Search backwards for time > x queries
1057 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1058 $opts['ORDER BY'] = "oi_timestamp $order";
1059 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1061 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1062 &$conds, &$opts, &$join_conds ] );
1064 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1067 foreach ( $res as $row ) {
1068 $r[] = $this->repo
->newFileFromRow( $row );
1071 if ( $order == 'ASC' ) {
1072 $r = array_reverse( $r ); // make sure it ends up descending
1079 * Returns the history of this file, line by line.
1080 * starts with current version, then old versions.
1081 * uses $this->historyLine to check which line to return:
1082 * 0 return line for current version
1083 * 1 query for old versions, return first one
1084 * 2, ... return next old version from above query
1087 public function nextHistoryLine() {
1088 # Polymorphic function name to distinguish foreign and local fetches
1089 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1091 $dbr = $this->repo
->getSlaveDB();
1093 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1094 $this->historyRes
= $dbr->select( 'image',
1097 "'' AS oi_archive_name",
1101 [ 'img_name' => $this->title
->getDBkey() ],
1105 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1106 $this->historyRes
= null;
1110 } elseif ( $this->historyLine
== 1 ) {
1111 $this->historyRes
= $dbr->select( 'oldimage', '*',
1112 [ 'oi_name' => $this->title
->getDBkey() ],
1114 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1117 $this->historyLine++
;
1119 return $dbr->fetchObject( $this->historyRes
);
1123 * Reset the history pointer to the first element of the history
1125 public function resetHistory() {
1126 $this->historyLine
= 0;
1128 if ( !is_null( $this->historyRes
) ) {
1129 $this->historyRes
= null;
1133 /** getHashPath inherited */
1134 /** getRel inherited */
1135 /** getUrlRel inherited */
1136 /** getArchiveRel inherited */
1137 /** getArchivePath inherited */
1138 /** getThumbPath inherited */
1139 /** getArchiveUrl inherited */
1140 /** getThumbUrl inherited */
1141 /** getArchiveVirtualUrl inherited */
1142 /** getThumbVirtualUrl inherited */
1143 /** isHashed inherited */
1146 * Upload a file and record it in the DB
1147 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1148 * @param string $comment Upload description
1149 * @param string $pageText Text to use for the new description page,
1150 * if a new description page is created
1151 * @param int|bool $flags Flags for publish()
1152 * @param array|bool $props File properties, if known. This can be used to
1153 * reduce the upload time when uploading virtual URLs for which the file
1154 * info is already known
1155 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1157 * @param User|null $user User object or null to use $wgUser
1158 * @param string[] $tags Change tags to add to the log entry and page revision.
1159 * (This doesn't check $user's permissions.)
1160 * @return FileRepoStatus On success, the value member contains the
1161 * archive name, or an empty string if it was a new file.
1163 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1164 $timestamp = false, $user = null, $tags = []
1168 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1169 return $this->readOnlyFatalStatus();
1172 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1174 if ( $this->repo
->isVirtualUrl( $srcPath )
1175 || FileBackend
::isStoragePath( $srcPath )
1177 $props = $this->repo
->getFileProps( $srcPath );
1179 $props = FSFile
::getPropsFromPath( $srcPath );
1184 $handler = MediaHandler
::getHandler( $props['mime'] );
1186 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1188 $options['headers'] = [];
1191 // Trim spaces on user supplied text
1192 $comment = trim( $comment );
1194 // Truncate nicely or the DB will do it for us
1195 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1196 $comment = $wgContLang->truncate( $comment, 255 );
1197 $this->lock(); // begin
1198 $status = $this->publish( $src, $flags, $options );
1200 if ( $status->successCount
>= 2 ) {
1201 // There will be a copy+(one of move,copy,store).
1202 // The first succeeding does not commit us to updating the DB
1203 // since it simply copied the current version to a timestamped file name.
1204 // It is only *preferable* to avoid leaving such files orphaned.
1205 // Once the second operation goes through, then the current version was
1206 // updated and we must therefore update the DB too.
1207 $oldver = $status->value
;
1208 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1209 $status->fatal( 'filenotfound', $srcPath );
1213 $this->unlock(); // done
1219 * Record a file upload in the upload log and the image table
1220 * @param string $oldver
1221 * @param string $desc
1222 * @param string $license
1223 * @param string $copyStatus
1224 * @param string $source
1225 * @param bool $watch
1226 * @param string|bool $timestamp
1227 * @param User|null $user User object or null to use $wgUser
1230 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1231 $watch = false, $timestamp = false, User
$user = null ) {
1237 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1239 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1244 $user->addWatch( $this->getTitle() );
1251 * Record a file upload in the upload log and the image table
1252 * @param string $oldver
1253 * @param string $comment
1254 * @param string $pageText
1255 * @param bool|array $props
1256 * @param string|bool $timestamp
1257 * @param null|User $user
1258 * @param string[] $tags
1261 function recordUpload2(
1262 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1264 if ( is_null( $user ) ) {
1269 $dbw = $this->repo
->getMasterDB();
1271 # Imports or such might force a certain timestamp; otherwise we generate
1272 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1273 if ( $timestamp === false ) {
1274 $timestamp = $dbw->timestamp();
1275 $allowTimeKludge = true;
1277 $allowTimeKludge = false;
1280 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1281 $props['description'] = $comment;
1282 $props['user'] = $user->getId();
1283 $props['user_text'] = $user->getName();
1284 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1285 $this->setProps( $props );
1287 # Fail now if the file isn't there
1288 if ( !$this->fileExists
) {
1289 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1294 $dbw->startAtomic( __METHOD__
);
1296 # Test to see if the row exists using INSERT IGNORE
1297 # This avoids race conditions by locking the row until the commit, and also
1298 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1299 $dbw->insert( 'image',
1301 'img_name' => $this->getName(),
1302 'img_size' => $this->size
,
1303 'img_width' => intval( $this->width
),
1304 'img_height' => intval( $this->height
),
1305 'img_bits' => $this->bits
,
1306 'img_media_type' => $this->media_type
,
1307 'img_major_mime' => $this->major_mime
,
1308 'img_minor_mime' => $this->minor_mime
,
1309 'img_timestamp' => $timestamp,
1310 'img_description' => $comment,
1311 'img_user' => $user->getId(),
1312 'img_user_text' => $user->getName(),
1313 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1314 'img_sha1' => $this->sha1
1320 $reupload = ( $dbw->affectedRows() == 0 );
1322 if ( $allowTimeKludge ) {
1323 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1324 $ltimestamp = $dbw->selectField(
1327 [ 'img_name' => $this->getName() ],
1329 [ 'LOCK IN SHARE MODE' ]
1331 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1332 # Avoid a timestamp that is not newer than the last version
1333 # TODO: the image/oldimage tables should be like page/revision with an ID field
1334 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1335 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1336 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1337 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1341 # (bug 34993) Note: $oldver can be empty here, if the previous
1342 # version of the file was broken. Allow registration of the new
1343 # version to continue anyway, because that's better than having
1344 # an image that's not fixable by user operations.
1345 # Collision, this is an update of a file
1346 # Insert previous contents into oldimage
1347 $dbw->insertSelect( 'oldimage', 'image',
1349 'oi_name' => 'img_name',
1350 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1351 'oi_size' => 'img_size',
1352 'oi_width' => 'img_width',
1353 'oi_height' => 'img_height',
1354 'oi_bits' => 'img_bits',
1355 'oi_timestamp' => 'img_timestamp',
1356 'oi_description' => 'img_description',
1357 'oi_user' => 'img_user',
1358 'oi_user_text' => 'img_user_text',
1359 'oi_metadata' => 'img_metadata',
1360 'oi_media_type' => 'img_media_type',
1361 'oi_major_mime' => 'img_major_mime',
1362 'oi_minor_mime' => 'img_minor_mime',
1363 'oi_sha1' => 'img_sha1'
1365 [ 'img_name' => $this->getName() ],
1369 # Update the current image row
1370 $dbw->update( 'image',
1372 'img_size' => $this->size
,
1373 'img_width' => intval( $this->width
),
1374 'img_height' => intval( $this->height
),
1375 'img_bits' => $this->bits
,
1376 'img_media_type' => $this->media_type
,
1377 'img_major_mime' => $this->major_mime
,
1378 'img_minor_mime' => $this->minor_mime
,
1379 'img_timestamp' => $timestamp,
1380 'img_description' => $comment,
1381 'img_user' => $user->getId(),
1382 'img_user_text' => $user->getName(),
1383 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1384 'img_sha1' => $this->sha1
1386 [ 'img_name' => $this->getName() ],
1391 $descTitle = $this->getTitle();
1392 $descId = $descTitle->getArticleID();
1393 $wikiPage = new WikiFilePage( $descTitle );
1394 $wikiPage->setFile( $this );
1396 // Add the log entry...
1397 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1398 $logEntry->setTimestamp( $this->timestamp
);
1399 $logEntry->setPerformer( $user );
1400 $logEntry->setComment( $comment );
1401 $logEntry->setTarget( $descTitle );
1402 // Allow people using the api to associate log entries with the upload.
1403 // Log has a timestamp, but sometimes different from upload timestamp.
1404 $logEntry->setParameters(
1406 'img_sha1' => $this->sha1
,
1407 'img_timestamp' => $timestamp,
1410 // Note we keep $logId around since during new image
1411 // creation, page doesn't exist yet, so log_page = 0
1412 // but we want it to point to the page we're making,
1413 // so we later modify the log entry.
1414 // For a similar reason, we avoid making an RC entry
1415 // now and wait until the page exists.
1416 $logId = $logEntry->insert();
1418 if ( $descTitle->exists() ) {
1419 // Use own context to get the action text in content language
1420 $formatter = LogFormatter
::newFromEntry( $logEntry );
1421 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1422 $editSummary = $formatter->getPlainActionText();
1424 $nullRevision = Revision
::newNullRevision(
1431 if ( $nullRevision ) {
1432 $nullRevision->insertOn( $dbw );
1434 'NewRevisionFromEditComplete',
1435 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1437 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1438 // Associate null revision id
1439 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1442 $newPageContent = null;
1444 // Make the description page and RC log entry post-commit
1445 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1448 # Defer purges, page creation, and link updates in case they error out.
1449 # The most important thing is that files and the DB registry stay synced.
1450 $dbw->endAtomic( __METHOD__
);
1452 # Do some cache purges after final commit so that:
1453 # a) Changes are more likely to be seen post-purge
1454 # b) They won't cause rollback of the log publish/update above
1455 DeferredUpdates
::addUpdate(
1456 new AutoCommitUpdate(
1460 $reupload, $wikiPage, $newPageContent, $comment, $user,
1461 $logEntry, $logId, $descId, $tags
1463 # Update memcache after the commit
1464 $this->invalidateCache();
1466 $updateLogPage = false;
1467 if ( $newPageContent ) {
1468 # New file page; create the description page.
1469 # There's already a log entry, so don't make a second RC entry
1470 # CDN and file cache for the description page are purged by doEditContent.
1471 $status = $wikiPage->doEditContent(
1474 EDIT_NEW | EDIT_SUPPRESS_RC
,
1479 if ( isset( $status->value
['revision'] ) ) {
1480 // Associate new page revision id
1481 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1483 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1484 // which is triggered on $descTitle by doEditContent() above.
1485 if ( isset( $status->value
['revision'] ) ) {
1486 /** @var $rev Revision */
1487 $rev = $status->value
['revision'];
1488 $updateLogPage = $rev->getPage();
1491 # Existing file page: invalidate description page cache
1492 $wikiPage->getTitle()->invalidateCache();
1493 $wikiPage->getTitle()->purgeSquid();
1494 # Allow the new file version to be patrolled from the page footer
1495 Article
::purgePatrolFooterCache( $descId );
1498 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1499 # but setAssociatedRevId() wasn't called at that point yet...
1500 $logParams = $logEntry->getParameters();
1501 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1502 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1503 if ( $updateLogPage ) {
1504 # Also log page, in case where we just created it above
1505 $update['log_page'] = $updateLogPage;
1507 $this->getRepo()->getMasterDB()->update(
1510 [ 'log_id' => $logId ],
1513 $this->getRepo()->getMasterDB()->insert(
1516 'ls_field' => 'associated_rev_id',
1517 'ls_value' => $logEntry->getAssociatedRevId(),
1518 'ls_log_id' => $logId,
1523 # Add change tags, if any
1525 $logEntry->setTags( $tags );
1528 # Uploads can be patrolled
1529 $logEntry->setIsPatrollable( true );
1531 # Now that the log entry is up-to-date, make an RC entry.
1532 $logEntry->publish( $logId );
1534 # Run hook for other updates (typically more cache purging)
1535 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1538 # Delete old thumbnails
1539 $this->purgeThumbnails();
1540 # Remove the old file from the CDN cache
1541 DeferredUpdates
::addUpdate(
1542 new CdnCacheUpdate( [ $this->getUrl() ] ),
1543 DeferredUpdates
::PRESEND
1546 # Update backlink pages pointing to this title if created
1547 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1550 $this->prerenderThumbnails();
1553 DeferredUpdates
::PRESEND
1557 # This is a new file, so update the image count
1558 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1561 # Invalidate cache for all pages using this file
1562 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1568 * Move or copy a file to its public location. If a file exists at the
1569 * destination, move it to an archive. Returns a FileRepoStatus object with
1570 * the archive name in the "value" member on success.
1572 * The archive name should be passed through to recordUpload for database
1575 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1576 * @param int $flags A bitwise combination of:
1577 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1578 * @param array $options Optional additional parameters
1579 * @return FileRepoStatus On success, the value member contains the
1580 * archive name, or an empty string if it was a new file.
1582 function publish( $src, $flags = 0, array $options = [] ) {
1583 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1587 * Move or copy a file to a specified location. Returns a FileRepoStatus
1588 * object with the archive name in the "value" member on success.
1590 * The archive name should be passed through to recordUpload for database
1593 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1594 * @param string $dstRel Target relative path
1595 * @param int $flags A bitwise combination of:
1596 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1597 * @param array $options Optional additional parameters
1598 * @return FileRepoStatus On success, the value member contains the
1599 * archive name, or an empty string if it was a new file.
1601 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1602 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1604 $repo = $this->getRepo();
1605 if ( $repo->getReadOnlyReason() !== false ) {
1606 return $this->readOnlyFatalStatus();
1609 $this->lock(); // begin
1611 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1612 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1614 if ( $repo->hasSha1Storage() ) {
1615 $sha1 = $repo->isVirtualUrl( $srcPath )
1616 ?
$repo->getFileSha1( $srcPath )
1617 : FSFile
::getSha1Base36FromPath( $srcPath );
1618 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1619 $wrapperBackend = $repo->getBackend();
1620 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1621 $status = $repo->quickImport( $src, $dst );
1622 if ( $flags & File
::DELETE_SOURCE
) {
1626 if ( $this->exists() ) {
1627 $status->value
= $archiveName;
1630 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1631 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1633 if ( $status->value
== 'new' ) {
1634 $status->value
= '';
1636 $status->value
= $archiveName;
1640 $this->unlock(); // done
1645 /** getLinksTo inherited */
1646 /** getExifData inherited */
1647 /** isLocal inherited */
1648 /** wasDeleted inherited */
1651 * Move file to the new title
1653 * Move current, old version and all thumbnails
1654 * to the new filename. Old file is deleted.
1656 * Cache purging is done; checks for validity
1657 * and logging are caller's responsibility
1659 * @param Title $target New file name
1660 * @return FileRepoStatus
1662 function move( $target ) {
1663 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1664 return $this->readOnlyFatalStatus();
1667 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1668 $batch = new LocalFileMoveBatch( $this, $target );
1670 $this->lock(); // begin
1671 $batch->addCurrent();
1672 $archiveNames = $batch->addOlds();
1673 $status = $batch->execute();
1674 $this->unlock(); // done
1676 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1678 // Purge the source and target files...
1679 $oldTitleFile = wfLocalFile( $this->title
);
1680 $newTitleFile = wfLocalFile( $target );
1681 // To avoid slow purges in the transaction, move them outside...
1682 DeferredUpdates
::addUpdate(
1683 new AutoCommitUpdate(
1684 $this->getRepo()->getMasterDB(),
1686 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1687 $oldTitleFile->purgeEverything();
1688 foreach ( $archiveNames as $archiveName ) {
1689 $oldTitleFile->purgeOldThumbnails( $archiveName );
1691 $newTitleFile->purgeEverything();
1694 DeferredUpdates
::PRESEND
1697 if ( $status->isOK() ) {
1698 // Now switch the object
1699 $this->title
= $target;
1700 // Force regeneration of the name and hashpath
1701 unset( $this->name
);
1702 unset( $this->hashPath
);
1709 * Delete all versions of the file.
1711 * Moves the files into an archive directory (or deletes them)
1712 * and removes the database rows.
1714 * Cache purging is done; logging is caller's responsibility.
1716 * @param string $reason
1717 * @param bool $suppress
1718 * @param User|null $user
1719 * @return FileRepoStatus
1721 function delete( $reason, $suppress = false, $user = null ) {
1722 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1723 return $this->readOnlyFatalStatus();
1726 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1728 $this->lock(); // begin
1729 $batch->addCurrent();
1730 // Get old version relative paths
1731 $archiveNames = $batch->addOlds();
1732 $status = $batch->execute();
1733 $this->unlock(); // done
1735 if ( $status->isOK() ) {
1736 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1739 // To avoid slow purges in the transaction, move them outside...
1740 DeferredUpdates
::addUpdate(
1741 new AutoCommitUpdate(
1742 $this->getRepo()->getMasterDB(),
1744 function () use ( $archiveNames ) {
1745 $this->purgeEverything();
1746 foreach ( $archiveNames as $archiveName ) {
1747 $this->purgeOldThumbnails( $archiveName );
1751 DeferredUpdates
::PRESEND
1756 foreach ( $archiveNames as $archiveName ) {
1757 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1759 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1765 * Delete an old version of the file.
1767 * Moves the file into an archive directory (or deletes it)
1768 * and removes the database row.
1770 * Cache purging is done; logging is caller's responsibility.
1772 * @param string $archiveName
1773 * @param string $reason
1774 * @param bool $suppress
1775 * @param User|null $user
1776 * @throws MWException Exception on database or file store failure
1777 * @return FileRepoStatus
1779 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1780 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1781 return $this->readOnlyFatalStatus();
1784 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1786 $this->lock(); // begin
1787 $batch->addOld( $archiveName );
1788 $status = $batch->execute();
1789 $this->unlock(); // done
1791 $this->purgeOldThumbnails( $archiveName );
1792 if ( $status->isOK() ) {
1793 $this->purgeDescription();
1796 DeferredUpdates
::addUpdate(
1797 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1798 DeferredUpdates
::PRESEND
1805 * Restore all or specified deleted revisions to the given file.
1806 * Permissions and logging are left to the caller.
1808 * May throw database exceptions on error.
1810 * @param array $versions Set of record ids of deleted items to restore,
1811 * or empty to restore all revisions.
1812 * @param bool $unsuppress
1813 * @return FileRepoStatus
1815 function restore( $versions = [], $unsuppress = false ) {
1816 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1817 return $this->readOnlyFatalStatus();
1820 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1822 $this->lock(); // begin
1826 $batch->addIds( $versions );
1828 $status = $batch->execute();
1829 if ( $status->isGood() ) {
1830 $cleanupStatus = $batch->cleanup();
1831 $cleanupStatus->successCount
= 0;
1832 $cleanupStatus->failCount
= 0;
1833 $status->merge( $cleanupStatus );
1835 $this->unlock(); // done
1840 /** isMultipage inherited */
1841 /** pageCount inherited */
1842 /** scaleHeight inherited */
1843 /** getImageSize inherited */
1846 * Get the URL of the file description page.
1849 function getDescriptionUrl() {
1850 return $this->title
->getLocalURL();
1854 * Get the HTML text of the description page
1855 * This is not used by ImagePage for local files, since (among other things)
1856 * it skips the parser cache.
1858 * @param Language $lang What language to get description in (Optional)
1859 * @return bool|mixed
1861 function getDescriptionText( $lang = null ) {
1862 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1866 $content = $revision->getContent();
1870 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1872 return $pout->getText();
1876 * @param int $audience
1880 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1882 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1884 } elseif ( $audience == self
::FOR_THIS_USER
1885 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1889 return $this->description
;
1894 * @return bool|string
1896 function getTimestamp() {
1899 return $this->timestamp
;
1903 * @return bool|string
1905 public function getDescriptionTouched() {
1906 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1907 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1908 // need to differentiate between null (uninitialized) and false (failed to load).
1909 if ( $this->descriptionTouched
=== null ) {
1911 'page_namespace' => $this->title
->getNamespace(),
1912 'page_title' => $this->title
->getDBkey()
1914 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1915 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1918 return $this->descriptionTouched
;
1924 function getSha1() {
1926 // Initialise now if necessary
1927 if ( $this->sha1
== '' && $this->fileExists
) {
1928 $this->lock(); // begin
1930 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1931 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1932 $dbw = $this->repo
->getMasterDB();
1933 $dbw->update( 'image',
1934 [ 'img_sha1' => $this->sha1
],
1935 [ 'img_name' => $this->getName() ],
1937 $this->invalidateCache();
1940 $this->unlock(); // done
1947 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1949 function isCacheable() {
1952 // If extra data (metadata) was not loaded then it must have been large
1953 return $this->extraDataLoaded
1954 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1961 public function acquireFileLock() {
1962 return $this->getRepo()->getBackend()->lockFiles(
1963 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1971 public function releaseFileLock() {
1972 return $this->getRepo()->getBackend()->unlockFiles(
1973 [ $this->getPath() ], LockManager
::LOCK_EX
1978 * Start an atomic DB section and lock the image for update
1979 * or increments a reference counter if the lock is already held
1981 * This method should not be used outside of LocalFile/LocalFile*Batch
1983 * @throws LocalFileLockError Throws an error if the lock was not acquired
1984 * @return bool Whether the file lock owns/spawned the DB transaction
1986 public function lock() {
1987 if ( !$this->locked
) {
1988 $logger = LoggerFactory
::getInstance( 'LocalFile' );
1990 $dbw = $this->repo
->getMasterDB();
1991 $makesTransaction = !$dbw->trxLevel();
1992 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
1993 // Bug 54736: use simple lock to handle when the file does not exist.
1994 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1995 // Also, that would cause contention on INSERT of similarly named rows.
1996 $status = $this->acquireFileLock(); // represents all versions of the file
1997 if ( !$status->isGood() ) {
1998 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
1999 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2001 throw new LocalFileLockError( $status );
2003 // Release the lock *after* commit to avoid row-level contention.
2004 // Make sure it triggers on rollback() as well as commit() (T132921).
2005 $dbw->onTransactionResolution( function () use ( $logger ) {
2006 $status = $this->releaseFileLock();
2007 if ( !$status->isGood() ) {
2008 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2011 // Callers might care if the SELECT snapshot is safely fresh
2012 $this->lockedOwnTrx
= $makesTransaction;
2017 return $this->lockedOwnTrx
;
2021 * Decrement the lock reference count and end the atomic section if it reaches zero
2023 * This method should not be used outside of LocalFile/LocalFile*Batch
2025 * The commit and loc release will happen when no atomic sections are active, which
2026 * may happen immediately or at some point after calling this
2028 public function unlock() {
2029 if ( $this->locked
) {
2031 if ( !$this->locked
) {
2032 $dbw = $this->repo
->getMasterDB();
2033 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2034 $this->lockedOwnTrx
= false;
2042 protected function readOnlyFatalStatus() {
2043 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2044 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2048 * Clean up any dangling locks
2050 function __destruct() {
2053 } // LocalFile class
2055 # ------------------------------------------------------------------------------
2058 * Helper class for file deletion
2059 * @ingroup FileAbstraction
2061 class LocalFileDeleteBatch
{
2062 /** @var LocalFile */
2069 private $srcRels = [];
2072 private $archiveUrls = [];
2074 /** @var array Items to be processed in the deletion batch */
2075 private $deletionBatch;
2077 /** @var bool Whether to suppress all suppressable fields when deleting */
2080 /** @var FileRepoStatus */
2088 * @param string $reason
2089 * @param bool $suppress
2090 * @param User|null $user
2092 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2093 $this->file
= $file;
2094 $this->reason
= $reason;
2095 $this->suppress
= $suppress;
2097 $this->user
= $user;
2100 $this->user
= $wgUser;
2102 $this->status
= $file->repo
->newGood();
2105 public function addCurrent() {
2106 $this->srcRels
['.'] = $this->file
->getRel();
2110 * @param string $oldName
2112 public function addOld( $oldName ) {
2113 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2114 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2118 * Add the old versions of the image to the batch
2119 * @return array List of archive names from old versions
2121 public function addOlds() {
2124 $dbw = $this->file
->repo
->getMasterDB();
2125 $result = $dbw->select( 'oldimage',
2126 [ 'oi_archive_name' ],
2127 [ 'oi_name' => $this->file
->getName() ],
2131 foreach ( $result as $row ) {
2132 $this->addOld( $row->oi_archive_name
);
2133 $archiveNames[] = $row->oi_archive_name
;
2136 return $archiveNames;
2142 protected function getOldRels() {
2143 if ( !isset( $this->srcRels
['.'] ) ) {
2144 $oldRels =& $this->srcRels
;
2145 $deleteCurrent = false;
2147 $oldRels = $this->srcRels
;
2148 unset( $oldRels['.'] );
2149 $deleteCurrent = true;
2152 return [ $oldRels, $deleteCurrent ];
2158 protected function getHashes() {
2160 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2162 if ( $deleteCurrent ) {
2163 $hashes['.'] = $this->file
->getSha1();
2166 if ( count( $oldRels ) ) {
2167 $dbw = $this->file
->repo
->getMasterDB();
2168 $res = $dbw->select(
2170 [ 'oi_archive_name', 'oi_sha1' ],
2171 [ 'oi_archive_name' => array_keys( $oldRels ),
2172 'oi_name' => $this->file
->getName() ], // performance
2176 foreach ( $res as $row ) {
2177 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2178 // Get the hash from the file
2179 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2180 $props = $this->file
->repo
->getFileProps( $oldUrl );
2182 if ( $props['fileExists'] ) {
2183 // Upgrade the oldimage row
2184 $dbw->update( 'oldimage',
2185 [ 'oi_sha1' => $props['sha1'] ],
2186 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2188 $hashes[$row->oi_archive_name
] = $props['sha1'];
2190 $hashes[$row->oi_archive_name
] = false;
2193 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2198 $missing = array_diff_key( $this->srcRels
, $hashes );
2200 foreach ( $missing as $name => $rel ) {
2201 $this->status
->error( 'filedelete-old-unregistered', $name );
2204 foreach ( $hashes as $name => $hash ) {
2206 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2207 unset( $hashes[$name] );
2214 protected function doDBInserts() {
2216 $dbw = $this->file
->repo
->getMasterDB();
2217 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2218 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2219 $encReason = $dbw->addQuotes( $this->reason
);
2220 $encGroup = $dbw->addQuotes( 'deleted' );
2221 $ext = $this->file
->getExtension();
2222 $dotExt = $ext === '' ?
'' : ".$ext";
2223 $encExt = $dbw->addQuotes( $dotExt );
2224 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2226 // Bitfields to further suppress the content
2227 if ( $this->suppress
) {
2229 // This should be 15...
2230 $bitfield |
= Revision
::DELETED_TEXT
;
2231 $bitfield |
= Revision
::DELETED_COMMENT
;
2232 $bitfield |
= Revision
::DELETED_USER
;
2233 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2235 $bitfield = 'oi_deleted';
2238 if ( $deleteCurrent ) {
2243 'fa_storage_group' => $encGroup,
2244 'fa_storage_key' => $dbw->conditional(
2245 [ 'img_sha1' => '' ],
2246 $dbw->addQuotes( '' ),
2247 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2249 'fa_deleted_user' => $encUserId,
2250 'fa_deleted_timestamp' => $encTimestamp,
2251 'fa_deleted_reason' => $encReason,
2252 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2254 'fa_name' => 'img_name',
2255 'fa_archive_name' => 'NULL',
2256 'fa_size' => 'img_size',
2257 'fa_width' => 'img_width',
2258 'fa_height' => 'img_height',
2259 'fa_metadata' => 'img_metadata',
2260 'fa_bits' => 'img_bits',
2261 'fa_media_type' => 'img_media_type',
2262 'fa_major_mime' => 'img_major_mime',
2263 'fa_minor_mime' => 'img_minor_mime',
2264 'fa_description' => 'img_description',
2265 'fa_user' => 'img_user',
2266 'fa_user_text' => 'img_user_text',
2267 'fa_timestamp' => 'img_timestamp',
2268 'fa_sha1' => 'img_sha1'
2270 [ 'img_name' => $this->file
->getName() ],
2275 if ( count( $oldRels ) ) {
2276 $res = $dbw->select(
2278 OldLocalFile
::selectFields(),
2280 'oi_name' => $this->file
->getName(),
2281 'oi_archive_name' => array_keys( $oldRels )
2287 foreach ( $res as $row ) {
2289 // Deletion-specific fields
2290 'fa_storage_group' => 'deleted',
2291 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2293 : "{$row->oi_sha1}{$dotExt}",
2294 'fa_deleted_user' => $this->user
->getId(),
2295 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2296 'fa_deleted_reason' => $this->reason
,
2297 // Counterpart fields
2298 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2299 'fa_name' => $row->oi_name
,
2300 'fa_archive_name' => $row->oi_archive_name
,
2301 'fa_size' => $row->oi_size
,
2302 'fa_width' => $row->oi_width
,
2303 'fa_height' => $row->oi_height
,
2304 'fa_metadata' => $row->oi_metadata
,
2305 'fa_bits' => $row->oi_bits
,
2306 'fa_media_type' => $row->oi_media_type
,
2307 'fa_major_mime' => $row->oi_major_mime
,
2308 'fa_minor_mime' => $row->oi_minor_mime
,
2309 'fa_description' => $row->oi_description
,
2310 'fa_user' => $row->oi_user
,
2311 'fa_user_text' => $row->oi_user_text
,
2312 'fa_timestamp' => $row->oi_timestamp
,
2313 'fa_sha1' => $row->oi_sha1
2317 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2321 function doDBDeletes() {
2322 $dbw = $this->file
->repo
->getMasterDB();
2323 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2325 if ( count( $oldRels ) ) {
2326 $dbw->delete( 'oldimage',
2328 'oi_name' => $this->file
->getName(),
2329 'oi_archive_name' => array_keys( $oldRels )
2333 if ( $deleteCurrent ) {
2334 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2339 * Run the transaction
2340 * @return FileRepoStatus
2342 public function execute() {
2343 $repo = $this->file
->getRepo();
2344 $this->file
->lock();
2346 // Prepare deletion batch
2347 $hashes = $this->getHashes();
2348 $this->deletionBatch
= [];
2349 $ext = $this->file
->getExtension();
2350 $dotExt = $ext === '' ?
'' : ".$ext";
2352 foreach ( $this->srcRels
as $name => $srcRel ) {
2353 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2354 if ( isset( $hashes[$name] ) ) {
2355 $hash = $hashes[$name];
2356 $key = $hash . $dotExt;
2357 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2358 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2362 if ( !$repo->hasSha1Storage() ) {
2363 // Removes non-existent file from the batch, so we don't get errors.
2364 // This also handles files in the 'deleted' zone deleted via revision deletion.
2365 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2366 if ( !$checkStatus->isGood() ) {
2367 $this->status
->merge( $checkStatus );
2368 return $this->status
;
2370 $this->deletionBatch
= $checkStatus->value
;
2372 // Execute the file deletion batch
2373 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2374 if ( !$status->isGood() ) {
2375 $this->status
->merge( $status );
2379 if ( !$this->status
->isOK() ) {
2380 // Critical file deletion error; abort
2381 $this->file
->unlock();
2383 return $this->status
;
2386 // Copy the image/oldimage rows to filearchive
2387 $this->doDBInserts();
2388 // Delete image/oldimage rows
2389 $this->doDBDeletes();
2391 // Commit and return
2392 $this->file
->unlock();
2394 return $this->status
;
2398 * Removes non-existent files from a deletion batch.
2399 * @param array $batch
2402 protected function removeNonexistentFiles( $batch ) {
2403 $files = $newBatch = [];
2405 foreach ( $batch as $batchItem ) {
2406 list( $src, ) = $batchItem;
2407 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2410 $result = $this->file
->repo
->fileExistsBatch( $files );
2411 if ( in_array( null, $result, true ) ) {
2412 return Status
::newFatal( 'backend-fail-internal',
2413 $this->file
->repo
->getBackend()->getName() );
2416 foreach ( $batch as $batchItem ) {
2417 if ( $result[$batchItem[0]] ) {
2418 $newBatch[] = $batchItem;
2422 return Status
::newGood( $newBatch );
2426 # ------------------------------------------------------------------------------
2429 * Helper class for file undeletion
2430 * @ingroup FileAbstraction
2432 class LocalFileRestoreBatch
{
2433 /** @var LocalFile */
2436 /** @var array List of file IDs to restore */
2437 private $cleanupBatch;
2439 /** @var array List of file IDs to restore */
2442 /** @var bool Add all revisions of the file */
2445 /** @var bool Whether to remove all settings for suppressed fields */
2446 private $unsuppress = false;
2450 * @param bool $unsuppress
2452 function __construct( File
$file, $unsuppress = false ) {
2453 $this->file
= $file;
2454 $this->cleanupBatch
= $this->ids
= [];
2456 $this->unsuppress
= $unsuppress;
2463 public function addId( $fa_id ) {
2464 $this->ids
[] = $fa_id;
2468 * Add a whole lot of files by ID
2471 public function addIds( $ids ) {
2472 $this->ids
= array_merge( $this->ids
, $ids );
2476 * Add all revisions of the file
2478 public function addAll() {
2483 * Run the transaction, except the cleanup batch.
2484 * The cleanup batch should be run in a separate transaction, because it locks different
2485 * rows and there's no need to keep the image row locked while it's acquiring those locks
2486 * The caller may have its own transaction open.
2487 * So we save the batch and let the caller call cleanup()
2488 * @return FileRepoStatus
2490 public function execute() {
2491 /** @var Language */
2494 $repo = $this->file
->getRepo();
2495 if ( !$this->all
&& !$this->ids
) {
2497 return $repo->newGood();
2500 $lockOwnsTrx = $this->file
->lock();
2502 $dbw = $this->file
->repo
->getMasterDB();
2503 $status = $this->file
->repo
->newGood();
2505 $exists = (bool)$dbw->selectField( 'image', '1',
2506 [ 'img_name' => $this->file
->getName() ],
2508 // The lock() should already prevents changes, but this still may need
2509 // to bypass any transaction snapshot. However, if lock() started the
2510 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2511 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2514 // Fetch all or selected archived revisions for the file,
2515 // sorted from the most recent to the oldest.
2516 $conditions = [ 'fa_name' => $this->file
->getName() ];
2518 if ( !$this->all
) {
2519 $conditions['fa_id'] = $this->ids
;
2522 $result = $dbw->select(
2524 ArchivedFile
::selectFields(),
2527 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2533 $insertCurrent = false;
2538 foreach ( $result as $row ) {
2539 $idsPresent[] = $row->fa_id
;
2541 if ( $row->fa_name
!= $this->file
->getName() ) {
2542 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2543 $status->failCount++
;
2547 if ( $row->fa_storage_key
== '' ) {
2548 // Revision was missing pre-deletion
2549 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2550 $status->failCount++
;
2554 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2555 $row->fa_storage_key
;
2556 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2558 if ( isset( $row->fa_sha1
) ) {
2559 $sha1 = $row->fa_sha1
;
2561 // old row, populate from key
2562 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2566 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2567 $sha1 = substr( $sha1, 1 );
2570 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2571 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2572 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2573 ||
is_null( $row->fa_metadata
)
2575 // Refresh our metadata
2576 // Required for a new current revision; nice for older ones too. :)
2577 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2580 'minor_mime' => $row->fa_minor_mime
,
2581 'major_mime' => $row->fa_major_mime
,
2582 'media_type' => $row->fa_media_type
,
2583 'metadata' => $row->fa_metadata
2587 if ( $first && !$exists ) {
2588 // This revision will be published as the new current version
2589 $destRel = $this->file
->getRel();
2591 'img_name' => $row->fa_name
,
2592 'img_size' => $row->fa_size
,
2593 'img_width' => $row->fa_width
,
2594 'img_height' => $row->fa_height
,
2595 'img_metadata' => $props['metadata'],
2596 'img_bits' => $row->fa_bits
,
2597 'img_media_type' => $props['media_type'],
2598 'img_major_mime' => $props['major_mime'],
2599 'img_minor_mime' => $props['minor_mime'],
2600 'img_description' => $row->fa_description
,
2601 'img_user' => $row->fa_user
,
2602 'img_user_text' => $row->fa_user_text
,
2603 'img_timestamp' => $row->fa_timestamp
,
2607 // The live (current) version cannot be hidden!
2608 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2609 $status->fatal( 'undeleterevdel' );
2610 $this->file
->unlock();
2614 $archiveName = $row->fa_archive_name
;
2616 if ( $archiveName == '' ) {
2617 // This was originally a current version; we
2618 // have to devise a new archive name for it.
2619 // Format is <timestamp of archiving>!<name>
2620 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2623 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2625 } while ( isset( $archiveNames[$archiveName] ) );
2628 $archiveNames[$archiveName] = true;
2629 $destRel = $this->file
->getArchiveRel( $archiveName );
2631 'oi_name' => $row->fa_name
,
2632 'oi_archive_name' => $archiveName,
2633 'oi_size' => $row->fa_size
,
2634 'oi_width' => $row->fa_width
,
2635 'oi_height' => $row->fa_height
,
2636 'oi_bits' => $row->fa_bits
,
2637 'oi_description' => $row->fa_description
,
2638 'oi_user' => $row->fa_user
,
2639 'oi_user_text' => $row->fa_user_text
,
2640 'oi_timestamp' => $row->fa_timestamp
,
2641 'oi_metadata' => $props['metadata'],
2642 'oi_media_type' => $props['media_type'],
2643 'oi_major_mime' => $props['major_mime'],
2644 'oi_minor_mime' => $props['minor_mime'],
2645 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2646 'oi_sha1' => $sha1 ];
2649 $deleteIds[] = $row->fa_id
;
2651 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2652 // private files can stay where they are
2653 $status->successCount++
;
2655 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2656 $this->cleanupBatch
[] = $row->fa_storage_key
;
2664 // Add a warning to the status object for missing IDs
2665 $missingIds = array_diff( $this->ids
, $idsPresent );
2667 foreach ( $missingIds as $id ) {
2668 $status->error( 'undelete-missing-filearchive', $id );
2671 if ( !$repo->hasSha1Storage() ) {
2672 // Remove missing files from batch, so we don't get errors when undeleting them
2673 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2674 if ( !$checkStatus->isGood() ) {
2675 $status->merge( $checkStatus );
2678 $storeBatch = $checkStatus->value
;
2680 // Run the store batch
2681 // Use the OVERWRITE_SAME flag to smooth over a common error
2682 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2683 $status->merge( $storeStatus );
2685 if ( !$status->isGood() ) {
2686 // Even if some files could be copied, fail entirely as that is the
2687 // easiest thing to do without data loss
2688 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2689 $status->ok
= false;
2690 $this->file
->unlock();
2696 // Run the DB updates
2697 // Because we have locked the image row, key conflicts should be rare.
2698 // If they do occur, we can roll back the transaction at this time with
2699 // no data loss, but leaving unregistered files scattered throughout the
2701 // This is not ideal, which is why it's important to lock the image row.
2702 if ( $insertCurrent ) {
2703 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2706 if ( $insertBatch ) {
2707 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2711 $dbw->delete( 'filearchive',
2712 [ 'fa_id' => $deleteIds ],
2716 // If store batch is empty (all files are missing), deletion is to be considered successful
2717 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2719 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2721 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2723 $this->file
->purgeEverything();
2725 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2726 $this->file
->purgeDescription();
2730 $this->file
->unlock();
2736 * Removes non-existent files from a store batch.
2737 * @param array $triplets
2740 protected function removeNonexistentFiles( $triplets ) {
2741 $files = $filteredTriplets = [];
2742 foreach ( $triplets as $file ) {
2743 $files[$file[0]] = $file[0];
2746 $result = $this->file
->repo
->fileExistsBatch( $files );
2747 if ( in_array( null, $result, true ) ) {
2748 return Status
::newFatal( 'backend-fail-internal',
2749 $this->file
->repo
->getBackend()->getName() );
2752 foreach ( $triplets as $file ) {
2753 if ( $result[$file[0]] ) {
2754 $filteredTriplets[] = $file;
2758 return Status
::newGood( $filteredTriplets );
2762 * Removes non-existent files from a cleanup batch.
2763 * @param array $batch
2766 protected function removeNonexistentFromCleanup( $batch ) {
2767 $files = $newBatch = [];
2768 $repo = $this->file
->repo
;
2770 foreach ( $batch as $file ) {
2771 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2772 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2775 $result = $repo->fileExistsBatch( $files );
2777 foreach ( $batch as $file ) {
2778 if ( $result[$file] ) {
2779 $newBatch[] = $file;
2787 * Delete unused files in the deleted zone.
2788 * This should be called from outside the transaction in which execute() was called.
2789 * @return FileRepoStatus
2791 public function cleanup() {
2792 if ( !$this->cleanupBatch
) {
2793 return $this->file
->repo
->newGood();
2796 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2798 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2804 * Cleanup a failed batch. The batch was only partially successful, so
2805 * rollback by removing all items that were succesfully copied.
2807 * @param Status $storeStatus
2808 * @param array $storeBatch
2810 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2813 foreach ( $storeStatus->success
as $i => $success ) {
2814 // Check if this item of the batch was successfully copied
2816 // Item was successfully copied and needs to be removed again
2817 // Extract ($dstZone, $dstRel) from the batch
2818 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2821 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2825 # ------------------------------------------------------------------------------
2828 * Helper class for file movement
2829 * @ingroup FileAbstraction
2831 class LocalFileMoveBatch
{
2832 /** @var LocalFile */
2842 protected $oldCount;
2846 /** @var DatabaseBase */
2851 * @param Title $target
2853 function __construct( File
$file, Title
$target ) {
2854 $this->file
= $file;
2855 $this->target
= $target;
2856 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2857 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2858 $this->oldName
= $this->file
->getName();
2859 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2860 $this->oldRel
= $this->oldHash
. $this->oldName
;
2861 $this->newRel
= $this->newHash
. $this->newName
;
2862 $this->db
= $file->getRepo()->getMasterDB();
2866 * Add the current image to the batch
2868 public function addCurrent() {
2869 $this->cur
= [ $this->oldRel
, $this->newRel
];
2873 * Add the old versions of the image to the batch
2874 * @return array List of archive names from old versions
2876 public function addOlds() {
2877 $archiveBase = 'archive';
2879 $this->oldCount
= 0;
2882 $result = $this->db
->select( 'oldimage',
2883 [ 'oi_archive_name', 'oi_deleted' ],
2884 [ 'oi_name' => $this->oldName
],
2886 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2889 foreach ( $result as $row ) {
2890 $archiveNames[] = $row->oi_archive_name
;
2891 $oldName = $row->oi_archive_name
;
2892 $bits = explode( '!', $oldName, 2 );
2894 if ( count( $bits ) != 2 ) {
2895 wfDebug( "Old file name missing !: '$oldName' \n" );
2899 list( $timestamp, $filename ) = $bits;
2901 if ( $this->oldName
!= $filename ) {
2902 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2908 // Do we want to add those to oldCount?
2909 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2914 "{$archiveBase}/{$this->oldHash}{$oldName}",
2915 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2919 return $archiveNames;
2924 * @return FileRepoStatus
2926 public function execute() {
2927 $repo = $this->file
->repo
;
2928 $status = $repo->newGood();
2929 $destFile = wfLocalFile( $this->target
);
2931 $this->file
->lock(); // begin
2932 $destFile->lock(); // quickly fail if destination is not available
2934 $triplets = $this->getMoveTriplets();
2935 $checkStatus = $this->removeNonexistentFiles( $triplets );
2936 if ( !$checkStatus->isGood() ) {
2937 $destFile->unlock();
2938 $this->file
->unlock();
2939 $status->merge( $checkStatus ); // couldn't talk to file backend
2942 $triplets = $checkStatus->value
;
2944 // Verify the file versions metadata in the DB.
2945 $statusDb = $this->verifyDBUpdates();
2946 if ( !$statusDb->isGood() ) {
2947 $destFile->unlock();
2948 $this->file
->unlock();
2949 $statusDb->ok
= false;
2954 if ( !$repo->hasSha1Storage() ) {
2955 // Copy the files into their new location.
2956 // If a prior process fataled copying or cleaning up files we tolerate any
2957 // of the existing files if they are identical to the ones being stored.
2958 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2959 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2960 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2961 if ( !$statusMove->isGood() ) {
2962 // Delete any files copied over (while the destination is still locked)
2963 $this->cleanupTarget( $triplets );
2964 $destFile->unlock();
2965 $this->file
->unlock();
2966 wfDebugLog( 'imagemove', "Error in moving files: "
2967 . $statusMove->getWikiText( false, false, 'en' ) );
2968 $statusMove->ok
= false;
2972 $status->merge( $statusMove );
2975 // Rename the file versions metadata in the DB.
2976 $this->doDBUpdates();
2978 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2979 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2981 $destFile->unlock();
2982 $this->file
->unlock(); // done
2984 // Everything went ok, remove the source files
2985 $this->cleanupSource( $triplets );
2987 $status->merge( $statusDb );
2993 * Verify the database updates and return a new FileRepoStatus indicating how
2994 * many rows would be updated.
2996 * @return FileRepoStatus
2998 protected function verifyDBUpdates() {
2999 $repo = $this->file
->repo
;
3000 $status = $repo->newGood();
3003 $hasCurrent = $dbw->selectField(
3006 [ 'img_name' => $this->oldName
],
3010 $oldRowCount = $dbw->selectField(
3013 [ 'oi_name' => $this->oldName
],
3018 if ( $hasCurrent ) {
3019 $status->successCount++
;
3021 $status->failCount++
;
3023 $status->successCount +
= $oldRowCount;
3024 // Bug 34934: oldCount is based on files that actually exist.
3025 // There may be more DB rows than such files, in which case $affected
3026 // can be greater than $total. We use max() to avoid negatives here.
3027 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3028 if ( $status->failCount
) {
3029 $status->error( 'imageinvalidfilename' );
3036 * Do the database updates and return a new FileRepoStatus indicating how
3037 * many rows where updated.
3039 protected function doDBUpdates() {
3042 // Update current image
3045 [ 'img_name' => $this->newName
],
3046 [ 'img_name' => $this->oldName
],
3049 // Update old images
3053 'oi_name' => $this->newName
,
3054 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3055 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3057 [ 'oi_name' => $this->oldName
],
3063 * Generate triplets for FileRepo::storeBatch().
3066 protected function getMoveTriplets() {
3067 $moves = array_merge( [ $this->cur
], $this->olds
);
3068 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3070 foreach ( $moves as $move ) {
3071 // $move: (oldRelativePath, newRelativePath)
3072 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3073 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3076 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3084 * Removes non-existent files from move batch.
3085 * @param array $triplets
3088 protected function removeNonexistentFiles( $triplets ) {
3091 foreach ( $triplets as $file ) {
3092 $files[$file[0]] = $file[0];
3095 $result = $this->file
->repo
->fileExistsBatch( $files );
3096 if ( in_array( null, $result, true ) ) {
3097 return Status
::newFatal( 'backend-fail-internal',
3098 $this->file
->repo
->getBackend()->getName() );
3101 $filteredTriplets = [];
3102 foreach ( $triplets as $file ) {
3103 if ( $result[$file[0]] ) {
3104 $filteredTriplets[] = $file;
3106 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3110 return Status
::newGood( $filteredTriplets );
3114 * Cleanup a partially moved array of triplets by deleting the target
3115 * files. Called if something went wrong half way.
3116 * @param array $triplets
3118 protected function cleanupTarget( $triplets ) {
3119 // Create dest pairs from the triplets
3121 foreach ( $triplets as $triplet ) {
3122 // $triplet: (old source virtual URL, dst zone, dest rel)
3123 $pairs[] = [ $triplet[1], $triplet[2] ];
3126 $this->file
->repo
->cleanupBatch( $pairs );
3130 * Cleanup a fully moved array of triplets by deleting the source files.
3131 * Called at the end of the move process if everything else went ok.
3132 * @param array $triplets
3134 protected function cleanupSource( $triplets ) {
3135 // Create source file names from the triplets
3137 foreach ( $triplets as $triplet ) {
3138 $files[] = $triplet[0];
3141 $this->file
->repo
->cleanupBatch( $files );
3145 class LocalFileLockError
extends ErrorPageError
{
3146 public function __construct( Status
$status ) {
3147 parent
::__construct(
3149 $status->getMessage()
3153 public function report() {
3155 $wgOut->setStatusCode( 429 );