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 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)
133 * Create a LocalFile from a title
134 * Do not call this except from inside a repo class.
136 * Note: $unused param is only here to avoid an E_STRICT
138 * @param Title $title
139 * @param FileRepo $repo
140 * @param null $unused
144 static function newFromTitle( $title, $repo, $unused = null ) {
145 return new self( $title, $repo );
149 * Create a LocalFile from a title
150 * Do not call this except from inside a repo class.
152 * @param stdClass $row
153 * @param FileRepo $repo
157 static function newFromRow( $row, $repo ) {
158 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
159 $file = new self( $title, $repo );
160 $file->loadFromRow( $row );
166 * Create a LocalFile from a SHA-1 key
167 * Do not call this except from inside a repo class.
169 * @param string $sha1 Base-36 SHA-1
170 * @param LocalRepo $repo
171 * @param string|bool $timestamp MW_timestamp (optional)
172 * @return bool|LocalFile
174 static function newFromKey( $sha1, $repo, $timestamp = false ) {
175 $dbr = $repo->getSlaveDB();
177 $conds = [ 'img_sha1' => $sha1 ];
179 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
182 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
184 return self
::newFromRow( $row, $repo );
191 * Fields in the image table
194 static function selectFields() {
215 * Do not call this except from inside a repo class.
216 * @param Title $title
217 * @param FileRepo $repo
219 function __construct( $title, $repo ) {
220 parent
::__construct( $title, $repo );
222 $this->metadata
= '';
223 $this->historyLine
= 0;
224 $this->historyRes
= null;
225 $this->dataLoaded
= false;
226 $this->extraDataLoaded
= false;
228 $this->assertRepoDefined();
229 $this->assertTitleDefined();
233 * Get the memcached key for the main data for this file, or false if
234 * there is no access to the shared cache.
235 * @return string|bool
237 function getCacheKey() {
238 $hashedName = md5( $this->getName() );
240 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
244 * Try to load file metadata from memcached. Returns true on success.
247 private function loadFromCache() {
248 $this->dataLoaded
= false;
249 $this->extraDataLoaded
= false;
250 $key = $this->getCacheKey();
256 $cache = ObjectCache
::getMainWANInstance();
257 $cachedValues = $cache->get( $key );
259 // Check if the key existed and belongs to this version of MediaWiki
260 if ( is_array( $cachedValues ) && $cachedValues['version'] == MW_FILE_VERSION
) {
261 $this->fileExists
= $cachedValues['fileExists'];
262 if ( $this->fileExists
) {
263 $this->setProps( $cachedValues );
265 $this->dataLoaded
= true;
266 $this->extraDataLoaded
= true;
267 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
268 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
272 return $this->dataLoaded
;
276 * Save the file metadata to memcached
278 private function saveToCache() {
281 $key = $this->getCacheKey();
286 $fields = $this->getCacheFields( '' );
287 $cacheVal = [ 'version' => MW_FILE_VERSION
];
288 $cacheVal['fileExists'] = $this->fileExists
;
290 if ( $this->fileExists
) {
291 foreach ( $fields as $field ) {
292 $cacheVal[$field] = $this->$field;
296 // Strip off excessive entries from the subset of fields that can become large.
297 // If the cache value gets to large it will not fit in memcached and nothing will
298 // get cached at all, causing master queries for any file access.
299 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
300 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
301 unset( $cacheVal[$field] ); // don't let the value get too big
305 // Cache presence for 1 week and negatives for 1 day
306 $ttl = $this->fileExists ?
86400 * 7 : 86400;
307 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
308 ObjectCache
::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
312 * Purge the file object/metadata cache
314 public function invalidateCache() {
315 $key = $this->getCacheKey();
320 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
321 ObjectCache
::getMainWANInstance()->delete( $key );
326 * Load metadata from the file itself
328 function loadFromFile() {
329 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
330 $this->setProps( $props );
334 * @param string $prefix
337 function getCacheFields( $prefix = 'img_' ) {
338 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
339 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
340 'user_text', 'description' ];
341 static $results = [];
343 if ( $prefix == '' ) {
347 if ( !isset( $results[$prefix] ) ) {
348 $prefixedFields = [];
349 foreach ( $fields as $field ) {
350 $prefixedFields[] = $prefix . $field;
352 $results[$prefix] = $prefixedFields;
355 return $results[$prefix];
359 * @param string $prefix
362 function getLazyCacheFields( $prefix = 'img_' ) {
363 static $fields = [ 'metadata' ];
364 static $results = [];
366 if ( $prefix == '' ) {
370 if ( !isset( $results[$prefix] ) ) {
371 $prefixedFields = [];
372 foreach ( $fields as $field ) {
373 $prefixedFields[] = $prefix . $field;
375 $results[$prefix] = $prefixedFields;
378 return $results[$prefix];
382 * Load file metadata from the DB
385 function loadFromDB( $flags = 0 ) {
386 $fname = get_class( $this ) . '::' . __FUNCTION__
;
388 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
389 $this->dataLoaded
= true;
390 $this->extraDataLoaded
= true;
392 $dbr = ( $flags & self
::READ_LATEST
)
393 ?
$this->repo
->getMasterDB()
394 : $this->repo
->getSlaveDB();
396 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
397 [ 'img_name' => $this->getName() ], $fname );
400 $this->loadFromRow( $row );
402 $this->fileExists
= false;
407 * Load lazy file metadata from the DB.
408 * This covers fields that are sometimes not cached.
410 protected function loadExtraFromDB() {
411 $fname = get_class( $this ) . '::' . __FUNCTION__
;
413 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
414 $this->extraDataLoaded
= true;
416 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
418 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
422 foreach ( $fieldMap as $name => $value ) {
423 $this->$name = $value;
426 throw new MWException( "Could not find data for image '{$this->getName()}'." );
431 * @param IDatabase $dbr
432 * @param string $fname
435 private function loadFieldsWithTimestamp( $dbr, $fname ) {
438 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
439 [ 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ],
442 $fieldMap = $this->unprefixRow( $row, 'img_' );
444 # File may have been uploaded over in the meantime; check the old versions
445 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
446 [ 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ],
449 $fieldMap = $this->unprefixRow( $row, 'oi_' );
457 * @param array|object $row
458 * @param string $prefix
459 * @throws MWException
462 protected function unprefixRow( $row, $prefix = 'img_' ) {
463 $array = (array)$row;
464 $prefixLength = strlen( $prefix );
466 // Sanity check prefix once
467 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
468 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
472 foreach ( $array as $name => $value ) {
473 $decoded[substr( $name, $prefixLength )] = $value;
480 * Decode a row from the database (either object or array) to an array
481 * with timestamps and MIME types decoded, and the field prefix removed.
483 * @param string $prefix
484 * @throws MWException
487 function decodeRow( $row, $prefix = 'img_' ) {
488 $decoded = $this->unprefixRow( $row, $prefix );
490 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
492 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
494 if ( empty( $decoded['major_mime'] ) ) {
495 $decoded['mime'] = 'unknown/unknown';
497 if ( !$decoded['minor_mime'] ) {
498 $decoded['minor_mime'] = 'unknown';
500 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
503 // Trim zero padding from char/binary field
504 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
506 // Normalize some fields to integer type, per their database definition.
507 // Use unary + so that overflows will be upgraded to double instead of
508 // being trucated as with intval(). This is important to allow >2GB
509 // files on 32-bit systems.
510 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
511 $decoded[$field] = +
$decoded[$field];
518 * Load file metadata from a DB result row
521 * @param string $prefix
523 function loadFromRow( $row, $prefix = 'img_' ) {
524 $this->dataLoaded
= true;
525 $this->extraDataLoaded
= true;
527 $array = $this->decodeRow( $row, $prefix );
529 foreach ( $array as $name => $value ) {
530 $this->$name = $value;
533 $this->fileExists
= true;
534 $this->maybeUpgradeRow();
538 * Load file metadata from cache or DB, unless already loaded
541 function load( $flags = 0 ) {
542 if ( !$this->dataLoaded
) {
543 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
544 $this->loadFromDB( $flags );
545 $this->saveToCache();
547 $this->dataLoaded
= true;
549 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
550 // @note: loads on name/timestamp to reduce race condition problems
551 $this->loadExtraFromDB();
556 * Upgrade a row if it needs it
558 function maybeUpgradeRow() {
559 global $wgUpdateCompatibleMetadata;
560 if ( wfReadOnly() ) {
565 if ( is_null( $this->media_type
) ||
566 $this->mime
== 'image/svg'
570 $handler = $this->getHandler();
572 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
573 if ( $validity === MediaHandler
::METADATA_BAD
574 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
584 } catch ( LocalFileLockError
$e ) {
585 // let the other process handle it (or do it next time)
587 $this->upgraded
= true; // avoid rework/retries
591 function getUpgraded() {
592 return $this->upgraded
;
596 * Fix assorted version-related problems with the image row by reloading it from the file
598 function upgradeRow() {
599 $this->lock(); // begin
601 $this->loadFromFile();
603 # Don't destroy file info of missing files
604 if ( !$this->fileExists
) {
606 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
611 $dbw = $this->repo
->getMasterDB();
612 list( $major, $minor ) = self
::splitMime( $this->mime
);
614 if ( wfReadOnly() ) {
619 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
621 $dbw->update( 'image',
623 'img_size' => $this->size
, // sanity
624 'img_width' => $this->width
,
625 'img_height' => $this->height
,
626 'img_bits' => $this->bits
,
627 'img_media_type' => $this->media_type
,
628 'img_major_mime' => $major,
629 'img_minor_mime' => $minor,
630 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
631 'img_sha1' => $this->sha1
,
633 [ 'img_name' => $this->getName() ],
637 $this->invalidateCache();
639 $this->unlock(); // done
644 * Set properties in this object to be equal to those given in the
645 * associative array $info. Only cacheable fields can be set.
646 * All fields *must* be set in $info except for getLazyCacheFields().
648 * If 'mime' is given, it will be split into major_mime/minor_mime.
649 * If major_mime/minor_mime are given, $this->mime will also be set.
653 function setProps( $info ) {
654 $this->dataLoaded
= true;
655 $fields = $this->getCacheFields( '' );
656 $fields[] = 'fileExists';
658 foreach ( $fields as $field ) {
659 if ( isset( $info[$field] ) ) {
660 $this->$field = $info[$field];
664 // Fix up mime fields
665 if ( isset( $info['major_mime'] ) ) {
666 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
667 } elseif ( isset( $info['mime'] ) ) {
668 $this->mime
= $info['mime'];
669 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
673 /** splitMime inherited */
674 /** getName inherited */
675 /** getTitle inherited */
676 /** getURL inherited */
677 /** getViewURL inherited */
678 /** getPath inherited */
679 /** isVisible inherited */
684 function isMissing() {
685 if ( $this->missing
=== null ) {
686 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
687 $this->missing
= !$fileExists;
690 return $this->missing
;
694 * Return the width of the image
699 public function getWidth( $page = 1 ) {
702 if ( $this->isMultipage() ) {
703 $handler = $this->getHandler();
707 $dim = $handler->getPageDimensions( $this, $page );
709 return $dim['width'];
711 // For non-paged media, the false goes through an
712 // intval, turning failure into 0, so do same here.
721 * Return the height of the image
726 public function getHeight( $page = 1 ) {
729 if ( $this->isMultipage() ) {
730 $handler = $this->getHandler();
734 $dim = $handler->getPageDimensions( $this, $page );
736 return $dim['height'];
738 // For non-paged media, the false goes through an
739 // intval, turning failure into 0, so do same here.
743 return $this->height
;
748 * Returns ID or name of user who uploaded the file
750 * @param string $type 'text' or 'id'
753 function getUser( $type = 'text' ) {
756 if ( $type == 'text' ) {
757 return $this->user_text
;
758 } elseif ( $type == 'id' ) {
759 return (int)$this->user
;
764 * Get short description URL for a file based on the page ID.
766 * @return string|null
767 * @throws MWException
770 public function getDescriptionShortUrl() {
771 $pageId = $this->title
->getArticleID();
773 if ( $pageId !== null ) {
774 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
775 if ( $url !== false ) {
783 * Get handler-specific metadata
786 function getMetadata() {
787 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
788 return $this->metadata
;
794 function getBitDepth() {
797 return (int)$this->bits
;
801 * Returns the size of the image file, in bytes
804 public function getSize() {
811 * Returns the MIME type of the file.
814 function getMimeType() {
821 * Returns the type of the media in the file.
822 * Use the value returned by this function with the MEDIATYPE_xxx constants.
825 function getMediaType() {
828 return $this->media_type
;
831 /** canRender inherited */
832 /** mustRender inherited */
833 /** allowInlineDisplay inherited */
834 /** isSafeFile inherited */
835 /** isTrustedFile inherited */
838 * Returns true if the file exists on disk.
839 * @return bool Whether file exist on disk.
841 public function exists() {
844 return $this->fileExists
;
847 /** getTransformScript inherited */
848 /** getUnscaledThumb inherited */
849 /** thumbName inherited */
850 /** createThumb inherited */
851 /** transform inherited */
853 /** getHandler inherited */
854 /** iconThumb inherited */
855 /** getLastError inherited */
858 * Get all thumbnail names previously generated for this file
859 * @param string|bool $archiveName Name of an archive file, default false
860 * @return array First element is the base dir, then files in that base dir.
862 function getThumbnails( $archiveName = false ) {
863 if ( $archiveName ) {
864 $dir = $this->getArchiveThumbPath( $archiveName );
866 $dir = $this->getThumbPath();
869 $backend = $this->repo
->getBackend();
872 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
873 foreach ( $iterator as $file ) {
876 } catch ( FileBackendError
$e ) {
877 } // suppress (bug 54674)
883 * Refresh metadata in memcached, but don't touch thumbnails or CDN
885 function purgeMetadataCache() {
886 $this->invalidateCache();
890 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
892 * @param array $options An array potentially with the key forThumbRefresh.
894 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
896 function purgeCache( $options = [] ) {
897 // Refresh metadata cache
898 $this->purgeMetadataCache();
901 $this->purgeThumbnails( $options );
903 // Purge CDN cache for this file
904 DeferredUpdates
::addUpdate(
905 new CdnCacheUpdate( [ $this->getUrl() ] ),
906 DeferredUpdates
::PRESEND
911 * Delete cached transformed files for an archived version only.
912 * @param string $archiveName Name of the archived file
914 function purgeOldThumbnails( $archiveName ) {
915 // Get a list of old thumbnails and URLs
916 $files = $this->getThumbnails( $archiveName );
918 // Purge any custom thumbnail caches
919 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
922 $dir = array_shift( $files );
923 $this->purgeThumbList( $dir, $files );
927 foreach ( $files as $file ) {
928 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
930 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
934 * Delete cached transformed files for the current version only.
935 * @param array $options
937 public function purgeThumbnails( $options = [] ) {
938 $files = $this->getThumbnails();
939 // Always purge all files from CDN regardless of handler filters
941 foreach ( $files as $file ) {
942 $urls[] = $this->getThumbUrl( $file );
944 array_shift( $urls ); // don't purge directory
946 // Give media handler a chance to filter the file purge list
947 if ( !empty( $options['forThumbRefresh'] ) ) {
948 $handler = $this->getHandler();
950 $handler->filterThumbnailPurgeList( $files, $options );
954 // Purge any custom thumbnail caches
955 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
958 $dir = array_shift( $files );
959 $this->purgeThumbList( $dir, $files );
962 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
966 * Delete a list of thumbnails visible at urls
967 * @param string $dir Base dir of the files.
968 * @param array $files Array of strings: relative filenames (to $dir)
970 protected function purgeThumbList( $dir, $files ) {
971 $fileListDebug = strtr(
972 var_export( $files, true ),
975 wfDebug( __METHOD__
. ": $fileListDebug\n" );
978 foreach ( $files as $file ) {
979 # Check that the base file name is part of the thumb name
980 # This is a basic sanity check to avoid erasing unrelated directories
981 if ( strpos( $file, $this->getName() ) !== false
982 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
984 $purgeList[] = "{$dir}/{$file}";
988 # Delete the thumbnails
989 $this->repo
->quickPurgeBatch( $purgeList );
990 # Clear out the thumbnail directory if empty
991 $this->repo
->quickCleanDir( $dir );
994 /** purgeDescription inherited */
995 /** purgeEverything inherited */
998 * @param int $limit Optional: Limit to number of results
999 * @param int $start Optional: Timestamp, start from
1000 * @param int $end Optional: Timestamp, end at
1002 * @return OldLocalFile[]
1004 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1005 $dbr = $this->repo
->getSlaveDB();
1006 $tables = [ 'oldimage' ];
1007 $fields = OldLocalFile
::selectFields();
1008 $conds = $opts = $join_conds = [];
1009 $eq = $inc ?
'=' : '';
1010 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1013 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1017 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1021 $opts['LIMIT'] = $limit;
1024 // Search backwards for time > x queries
1025 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1026 $opts['ORDER BY'] = "oi_timestamp $order";
1027 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1029 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1030 &$conds, &$opts, &$join_conds ] );
1032 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1035 foreach ( $res as $row ) {
1036 $r[] = $this->repo
->newFileFromRow( $row );
1039 if ( $order == 'ASC' ) {
1040 $r = array_reverse( $r ); // make sure it ends up descending
1047 * Returns the history of this file, line by line.
1048 * starts with current version, then old versions.
1049 * uses $this->historyLine to check which line to return:
1050 * 0 return line for current version
1051 * 1 query for old versions, return first one
1052 * 2, ... return next old version from above query
1055 public function nextHistoryLine() {
1056 # Polymorphic function name to distinguish foreign and local fetches
1057 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1059 $dbr = $this->repo
->getSlaveDB();
1061 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1062 $this->historyRes
= $dbr->select( 'image',
1065 "'' AS oi_archive_name",
1069 [ 'img_name' => $this->title
->getDBkey() ],
1073 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1074 $this->historyRes
= null;
1078 } elseif ( $this->historyLine
== 1 ) {
1079 $this->historyRes
= $dbr->select( 'oldimage', '*',
1080 [ 'oi_name' => $this->title
->getDBkey() ],
1082 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1085 $this->historyLine++
;
1087 return $dbr->fetchObject( $this->historyRes
);
1091 * Reset the history pointer to the first element of the history
1093 public function resetHistory() {
1094 $this->historyLine
= 0;
1096 if ( !is_null( $this->historyRes
) ) {
1097 $this->historyRes
= null;
1101 /** getHashPath inherited */
1102 /** getRel inherited */
1103 /** getUrlRel inherited */
1104 /** getArchiveRel inherited */
1105 /** getArchivePath inherited */
1106 /** getThumbPath inherited */
1107 /** getArchiveUrl inherited */
1108 /** getThumbUrl inherited */
1109 /** getArchiveVirtualUrl inherited */
1110 /** getThumbVirtualUrl inherited */
1111 /** isHashed inherited */
1114 * Upload a file and record it in the DB
1115 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1116 * @param string $comment Upload description
1117 * @param string $pageText Text to use for the new description page,
1118 * if a new description page is created
1119 * @param int|bool $flags Flags for publish()
1120 * @param array|bool $props File properties, if known. This can be used to
1121 * reduce the upload time when uploading virtual URLs for which the file
1122 * info is already known
1123 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1125 * @param User|null $user User object or null to use $wgUser
1126 * @param string[] $tags Change tags to add to the log entry and page revision.
1127 * (This doesn't check $user's permissions.)
1128 * @return FileRepoStatus On success, the value member contains the
1129 * archive name, or an empty string if it was a new file.
1131 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1132 $timestamp = false, $user = null, $tags = []
1136 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1137 return $this->readOnlyFatalStatus();
1140 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1142 if ( $this->repo
->isVirtualUrl( $srcPath )
1143 || FileBackend
::isStoragePath( $srcPath )
1145 $props = $this->repo
->getFileProps( $srcPath );
1147 $props = FSFile
::getPropsFromPath( $srcPath );
1152 $handler = MediaHandler
::getHandler( $props['mime'] );
1154 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1156 $options['headers'] = [];
1159 // Trim spaces on user supplied text
1160 $comment = trim( $comment );
1162 // Truncate nicely or the DB will do it for us
1163 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1164 $comment = $wgContLang->truncate( $comment, 255 );
1165 $this->lock(); // begin
1166 $status = $this->publish( $src, $flags, $options );
1168 if ( $status->successCount
>= 2 ) {
1169 // There will be a copy+(one of move,copy,store).
1170 // The first succeeding does not commit us to updating the DB
1171 // since it simply copied the current version to a timestamped file name.
1172 // It is only *preferable* to avoid leaving such files orphaned.
1173 // Once the second operation goes through, then the current version was
1174 // updated and we must therefore update the DB too.
1175 $oldver = $status->value
;
1176 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1177 $status->fatal( 'filenotfound', $srcPath );
1181 $this->unlock(); // done
1187 * Record a file upload in the upload log and the image table
1188 * @param string $oldver
1189 * @param string $desc
1190 * @param string $license
1191 * @param string $copyStatus
1192 * @param string $source
1193 * @param bool $watch
1194 * @param string|bool $timestamp
1195 * @param User|null $user User object or null to use $wgUser
1198 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1199 $watch = false, $timestamp = false, User
$user = null ) {
1205 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1207 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1212 $user->addWatch( $this->getTitle() );
1219 * Record a file upload in the upload log and the image table
1220 * @param string $oldver
1221 * @param string $comment
1222 * @param string $pageText
1223 * @param bool|array $props
1224 * @param string|bool $timestamp
1225 * @param null|User $user
1226 * @param string[] $tags
1229 function recordUpload2(
1230 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1232 if ( is_null( $user ) ) {
1237 $dbw = $this->repo
->getMasterDB();
1239 # Imports or such might force a certain timestamp; otherwise we generate
1240 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1241 if ( $timestamp === false ) {
1242 $timestamp = $dbw->timestamp();
1243 $allowTimeKludge = true;
1245 $allowTimeKludge = false;
1248 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1249 $props['description'] = $comment;
1250 $props['user'] = $user->getId();
1251 $props['user_text'] = $user->getName();
1252 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1253 $this->setProps( $props );
1255 # Fail now if the file isn't there
1256 if ( !$this->fileExists
) {
1257 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1262 $dbw->startAtomic( __METHOD__
);
1264 # Test to see if the row exists using INSERT IGNORE
1265 # This avoids race conditions by locking the row until the commit, and also
1266 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1267 $dbw->insert( 'image',
1269 'img_name' => $this->getName(),
1270 'img_size' => $this->size
,
1271 'img_width' => intval( $this->width
),
1272 'img_height' => intval( $this->height
),
1273 'img_bits' => $this->bits
,
1274 'img_media_type' => $this->media_type
,
1275 'img_major_mime' => $this->major_mime
,
1276 'img_minor_mime' => $this->minor_mime
,
1277 'img_timestamp' => $timestamp,
1278 'img_description' => $comment,
1279 'img_user' => $user->getId(),
1280 'img_user_text' => $user->getName(),
1281 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1282 'img_sha1' => $this->sha1
1288 $reupload = ( $dbw->affectedRows() == 0 );
1290 if ( $allowTimeKludge ) {
1291 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1292 $ltimestamp = $dbw->selectField(
1295 [ 'img_name' => $this->getName() ],
1297 [ 'LOCK IN SHARE MODE' ]
1299 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1300 # Avoid a timestamp that is not newer than the last version
1301 # TODO: the image/oldimage tables should be like page/revision with an ID field
1302 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1303 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1304 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1305 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1309 # (bug 34993) Note: $oldver can be empty here, if the previous
1310 # version of the file was broken. Allow registration of the new
1311 # version to continue anyway, because that's better than having
1312 # an image that's not fixable by user operations.
1313 # Collision, this is an update of a file
1314 # Insert previous contents into oldimage
1315 $dbw->insertSelect( 'oldimage', 'image',
1317 'oi_name' => 'img_name',
1318 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1319 'oi_size' => 'img_size',
1320 'oi_width' => 'img_width',
1321 'oi_height' => 'img_height',
1322 'oi_bits' => 'img_bits',
1323 'oi_timestamp' => 'img_timestamp',
1324 'oi_description' => 'img_description',
1325 'oi_user' => 'img_user',
1326 'oi_user_text' => 'img_user_text',
1327 'oi_metadata' => 'img_metadata',
1328 'oi_media_type' => 'img_media_type',
1329 'oi_major_mime' => 'img_major_mime',
1330 'oi_minor_mime' => 'img_minor_mime',
1331 'oi_sha1' => 'img_sha1'
1333 [ 'img_name' => $this->getName() ],
1337 # Update the current image row
1338 $dbw->update( 'image',
1340 'img_size' => $this->size
,
1341 'img_width' => intval( $this->width
),
1342 'img_height' => intval( $this->height
),
1343 'img_bits' => $this->bits
,
1344 'img_media_type' => $this->media_type
,
1345 'img_major_mime' => $this->major_mime
,
1346 'img_minor_mime' => $this->minor_mime
,
1347 'img_timestamp' => $timestamp,
1348 'img_description' => $comment,
1349 'img_user' => $user->getId(),
1350 'img_user_text' => $user->getName(),
1351 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1352 'img_sha1' => $this->sha1
1354 [ 'img_name' => $this->getName() ],
1359 $descTitle = $this->getTitle();
1360 $descId = $descTitle->getArticleID();
1361 $wikiPage = new WikiFilePage( $descTitle );
1362 $wikiPage->setFile( $this );
1364 // Add the log entry...
1365 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1366 $logEntry->setTimestamp( $this->timestamp
);
1367 $logEntry->setPerformer( $user );
1368 $logEntry->setComment( $comment );
1369 $logEntry->setTarget( $descTitle );
1370 // Allow people using the api to associate log entries with the upload.
1371 // Log has a timestamp, but sometimes different from upload timestamp.
1372 $logEntry->setParameters(
1374 'img_sha1' => $this->sha1
,
1375 'img_timestamp' => $timestamp,
1378 // Note we keep $logId around since during new image
1379 // creation, page doesn't exist yet, so log_page = 0
1380 // but we want it to point to the page we're making,
1381 // so we later modify the log entry.
1382 // For a similar reason, we avoid making an RC entry
1383 // now and wait until the page exists.
1384 $logId = $logEntry->insert();
1386 if ( $descTitle->exists() ) {
1387 // Use own context to get the action text in content language
1388 $formatter = LogFormatter
::newFromEntry( $logEntry );
1389 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1390 $editSummary = $formatter->getPlainActionText();
1392 $nullRevision = Revision
::newNullRevision(
1399 if ( $nullRevision ) {
1400 $nullRevision->insertOn( $dbw );
1402 'NewRevisionFromEditComplete',
1403 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1405 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1406 // Associate null revision id
1407 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1410 $newPageContent = null;
1412 // Make the description page and RC log entry post-commit
1413 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1416 # Defer purges, page creation, and link updates in case they error out.
1417 # The most important thing is that files and the DB registry stay synced.
1418 $dbw->endAtomic( __METHOD__
);
1420 # Do some cache purges after final commit so that:
1421 # a) Changes are more likely to be seen post-purge
1422 # b) They won't cause rollback of the log publish/update above
1424 $dbw->onTransactionIdle( function () use (
1425 $that, $reupload, $wikiPage, $newPageContent, $comment, $user, $logEntry, $logId, $descId, $tags
1427 # Update memcache after the commit
1428 $that->invalidateCache();
1430 $updateLogPage = false;
1431 if ( $newPageContent ) {
1432 # New file page; create the description page.
1433 # There's already a log entry, so don't make a second RC entry
1434 # CDN and file cache for the description page are purged by doEditContent.
1435 $status = $wikiPage->doEditContent(
1438 EDIT_NEW | EDIT_SUPPRESS_RC
,
1443 if ( isset( $status->value
['revision'] ) ) {
1444 // Associate new page revision id
1445 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1447 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1448 // which is triggered on $descTitle by doEditContent() above.
1449 if ( isset( $status->value
['revision'] ) ) {
1450 /** @var $rev Revision */
1451 $rev = $status->value
['revision'];
1452 $updateLogPage = $rev->getPage();
1455 # Existing file page: invalidate description page cache
1456 $wikiPage->getTitle()->invalidateCache();
1457 $wikiPage->getTitle()->purgeSquid();
1458 # Allow the new file version to be patrolled from the page footer
1459 Article
::purgePatrolFooterCache( $descId );
1462 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1463 # but setAssociatedRevId() wasn't called at that point yet...
1464 $logParams = $logEntry->getParameters();
1465 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1466 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1467 if ( $updateLogPage ) {
1468 # Also log page, in case where we just created it above
1469 $update['log_page'] = $updateLogPage;
1471 $that->getRepo()->getMasterDB()->update(
1474 [ 'log_id' => $logId ],
1477 $that->getRepo()->getMasterDB()->insert(
1480 'ls_field' => 'associated_rev_id',
1481 'ls_value' => $logEntry->getAssociatedRevId(),
1482 'ls_log_id' => $logId,
1487 # Add change tags, if any
1489 $logEntry->setTags( $tags );
1492 # Uploads can be patrolled
1493 $logEntry->setIsPatrollable( true );
1495 # Now that the log entry is up-to-date, make an RC entry.
1496 $logEntry->publish( $logId );
1498 # Run hook for other updates (typically more cache purging)
1499 Hooks
::run( 'FileUpload', [ $that, $reupload, !$newPageContent ] );
1502 # Delete old thumbnails
1503 $that->purgeThumbnails();
1504 # Remove the old file from the CDN cache
1505 DeferredUpdates
::addUpdate(
1506 new CdnCacheUpdate( [ $that->getUrl() ] ),
1507 DeferredUpdates
::PRESEND
1510 # Update backlink pages pointing to this title if created
1511 LinksUpdate
::queueRecursiveJobsForTable( $that->getTitle(), 'imagelinks' );
1516 # This is a new file, so update the image count
1517 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1520 # Invalidate cache for all pages using this file
1521 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1527 * Move or copy a file to its public location. If a file exists at the
1528 * destination, move it to an archive. Returns a FileRepoStatus object with
1529 * the archive name in the "value" member on success.
1531 * The archive name should be passed through to recordUpload for database
1534 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1535 * @param int $flags A bitwise combination of:
1536 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1537 * @param array $options Optional additional parameters
1538 * @return FileRepoStatus On success, the value member contains the
1539 * archive name, or an empty string if it was a new file.
1541 function publish( $src, $flags = 0, array $options = [] ) {
1542 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1546 * Move or copy a file to a specified location. Returns a FileRepoStatus
1547 * object with the archive name in the "value" member on success.
1549 * The archive name should be passed through to recordUpload for database
1552 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1553 * @param string $dstRel Target relative path
1554 * @param int $flags A bitwise combination of:
1555 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1556 * @param array $options Optional additional parameters
1557 * @return FileRepoStatus On success, the value member contains the
1558 * archive name, or an empty string if it was a new file.
1560 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1561 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1563 $repo = $this->getRepo();
1564 if ( $repo->getReadOnlyReason() !== false ) {
1565 return $this->readOnlyFatalStatus();
1568 $this->lock(); // begin
1570 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1571 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1573 if ( $repo->hasSha1Storage() ) {
1574 $sha1 = $repo->isVirtualUrl( $srcPath )
1575 ?
$repo->getFileSha1( $srcPath )
1576 : FSFile
::getSha1Base36FromPath( $srcPath );
1577 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1578 $status = $repo->quickImport( $src, $dst );
1579 if ( $flags & File
::DELETE_SOURCE
) {
1583 if ( $this->exists() ) {
1584 $status->value
= $archiveName;
1587 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1588 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1590 if ( $status->value
== 'new' ) {
1591 $status->value
= '';
1593 $status->value
= $archiveName;
1597 $this->unlock(); // done
1602 /** getLinksTo inherited */
1603 /** getExifData inherited */
1604 /** isLocal inherited */
1605 /** wasDeleted inherited */
1608 * Move file to the new title
1610 * Move current, old version and all thumbnails
1611 * to the new filename. Old file is deleted.
1613 * Cache purging is done; checks for validity
1614 * and logging are caller's responsibility
1616 * @param Title $target New file name
1617 * @return FileRepoStatus
1619 function move( $target ) {
1620 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1621 return $this->readOnlyFatalStatus();
1624 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1625 $batch = new LocalFileMoveBatch( $this, $target );
1627 $this->lock(); // begin
1628 $batch->addCurrent();
1629 $archiveNames = $batch->addOlds();
1630 $status = $batch->execute();
1631 $this->unlock(); // done
1633 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1635 // Purge the source and target files...
1636 $oldTitleFile = wfLocalFile( $this->title
);
1637 $newTitleFile = wfLocalFile( $target );
1638 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1639 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1640 $this->getRepo()->getMasterDB()->onTransactionIdle(
1641 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1642 $oldTitleFile->purgeEverything();
1643 foreach ( $archiveNames as $archiveName ) {
1644 $oldTitleFile->purgeOldThumbnails( $archiveName );
1646 $newTitleFile->purgeEverything();
1650 if ( $status->isOK() ) {
1651 // Now switch the object
1652 $this->title
= $target;
1653 // Force regeneration of the name and hashpath
1654 unset( $this->name
);
1655 unset( $this->hashPath
);
1662 * Delete all versions of the file.
1664 * Moves the files into an archive directory (or deletes them)
1665 * and removes the database rows.
1667 * Cache purging is done; logging is caller's responsibility.
1669 * @param string $reason
1670 * @param bool $suppress
1671 * @param User|null $user
1672 * @return FileRepoStatus
1674 function delete( $reason, $suppress = false, $user = null ) {
1675 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1676 return $this->readOnlyFatalStatus();
1679 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1681 $this->lock(); // begin
1682 $batch->addCurrent();
1683 # Get old version relative paths
1684 $archiveNames = $batch->addOlds();
1685 $status = $batch->execute();
1686 $this->unlock(); // done
1688 if ( $status->isOK() ) {
1689 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1692 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1693 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1695 $this->getRepo()->getMasterDB()->onTransactionIdle(
1696 function () use ( $that, $archiveNames ) {
1697 $that->purgeEverything();
1698 foreach ( $archiveNames as $archiveName ) {
1699 $that->purgeOldThumbnails( $archiveName );
1706 foreach ( $archiveNames as $archiveName ) {
1707 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1709 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1715 * Delete an old version of the file.
1717 * Moves the file into an archive directory (or deletes it)
1718 * and removes the database row.
1720 * Cache purging is done; logging is caller's responsibility.
1722 * @param string $archiveName
1723 * @param string $reason
1724 * @param bool $suppress
1725 * @param User|null $user
1726 * @throws MWException Exception on database or file store failure
1727 * @return FileRepoStatus
1729 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1730 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1731 return $this->readOnlyFatalStatus();
1734 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1736 $this->lock(); // begin
1737 $batch->addOld( $archiveName );
1738 $status = $batch->execute();
1739 $this->unlock(); // done
1741 $this->purgeOldThumbnails( $archiveName );
1742 if ( $status->isOK() ) {
1743 $this->purgeDescription();
1746 DeferredUpdates
::addUpdate(
1747 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1748 DeferredUpdates
::PRESEND
1755 * Restore all or specified deleted revisions to the given file.
1756 * Permissions and logging are left to the caller.
1758 * May throw database exceptions on error.
1760 * @param array $versions Set of record ids of deleted items to restore,
1761 * or empty to restore all revisions.
1762 * @param bool $unsuppress
1763 * @return FileRepoStatus
1765 function restore( $versions = [], $unsuppress = false ) {
1766 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1767 return $this->readOnlyFatalStatus();
1770 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1772 $this->lock(); // begin
1776 $batch->addIds( $versions );
1778 $status = $batch->execute();
1779 if ( $status->isGood() ) {
1780 $cleanupStatus = $batch->cleanup();
1781 $cleanupStatus->successCount
= 0;
1782 $cleanupStatus->failCount
= 0;
1783 $status->merge( $cleanupStatus );
1785 $this->unlock(); // done
1790 /** isMultipage inherited */
1791 /** pageCount inherited */
1792 /** scaleHeight inherited */
1793 /** getImageSize inherited */
1796 * Get the URL of the file description page.
1799 function getDescriptionUrl() {
1800 return $this->title
->getLocalURL();
1804 * Get the HTML text of the description page
1805 * This is not used by ImagePage for local files, since (among other things)
1806 * it skips the parser cache.
1808 * @param Language $lang What language to get description in (Optional)
1809 * @return bool|mixed
1811 function getDescriptionText( $lang = null ) {
1812 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1816 $content = $revision->getContent();
1820 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1822 return $pout->getText();
1826 * @param int $audience
1830 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1832 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1834 } elseif ( $audience == self
::FOR_THIS_USER
1835 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1839 return $this->description
;
1844 * @return bool|string
1846 function getTimestamp() {
1849 return $this->timestamp
;
1853 * @return bool|string
1855 public function getDescriptionTouched() {
1856 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1857 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1858 // need to differentiate between null (uninitialized) and false (failed to load).
1859 if ( $this->descriptionTouched
=== null ) {
1861 'page_namespace' => $this->title
->getNamespace(),
1862 'page_title' => $this->title
->getDBkey()
1864 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1865 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1868 return $this->descriptionTouched
;
1874 function getSha1() {
1876 // Initialise now if necessary
1877 if ( $this->sha1
== '' && $this->fileExists
) {
1878 $this->lock(); // begin
1880 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1881 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1882 $dbw = $this->repo
->getMasterDB();
1883 $dbw->update( 'image',
1884 [ 'img_sha1' => $this->sha1
],
1885 [ 'img_name' => $this->getName() ],
1887 $this->invalidateCache();
1890 $this->unlock(); // done
1897 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1899 function isCacheable() {
1902 // If extra data (metadata) was not loaded then it must have been large
1903 return $this->extraDataLoaded
1904 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1908 * Start a transaction and lock the image for update
1909 * Increments a reference counter if the lock is already held
1910 * @throws LocalFileLockError Throws an error if the lock was not acquired
1911 * @return bool Whether the file lock owns/spawned the DB transaction
1914 if ( !$this->locked
) {
1915 $logger = LoggerFactory
::getInstance( 'LocalFile' );
1916 $dbw = $this->repo
->getMasterDB();
1917 if ( !$dbw->trxLevel() ) {
1918 $dbw->begin( __METHOD__
);
1919 $this->lockedOwnTrx
= true;
1921 // Bug 54736: use simple lock to handle when the file does not exist.
1922 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1923 // Also, that would cause contention on INSERT of similarly named rows.
1924 $backend = $this->getRepo()->getBackend();
1925 $lockPaths = [ $this->getPath() ]; // represents all versions of the file
1926 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 10 );
1927 if ( !$status->isGood() ) {
1928 if ( $this->lockedOwnTrx
) {
1929 $dbw->rollback( __METHOD__
);
1931 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
1933 throw new LocalFileLockError( $status );
1935 // Release the lock *after* commit to avoid row-level contention.
1936 // Make sure it triggers on rollback() as well as commit() (T132921).
1937 $dbw->onTransactionResolution( function () use ( $backend, $lockPaths, $logger ) {
1938 $status = $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
);
1939 if ( !$status->isGood() ) {
1940 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
1947 return $this->lockedOwnTrx
;
1951 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1952 * the transaction and thereby releases the image lock.
1955 if ( $this->locked
) {
1957 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1958 $dbw = $this->repo
->getMasterDB();
1959 $dbw->commit( __METHOD__
);
1960 $this->lockedOwnTrx
= false;
1966 * Roll back the DB transaction and mark the image unlocked
1968 function unlockAndRollback() {
1969 $this->locked
= false;
1970 $dbw = $this->repo
->getMasterDB();
1971 $dbw->rollback( __METHOD__
);
1972 $this->lockedOwnTrx
= false;
1978 protected function readOnlyFatalStatus() {
1979 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1980 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1984 * Clean up any dangling locks
1986 function __destruct() {
1989 } // LocalFile class
1991 # ------------------------------------------------------------------------------
1994 * Helper class for file deletion
1995 * @ingroup FileAbstraction
1997 class LocalFileDeleteBatch
{
1998 /** @var LocalFile */
2005 private $srcRels = [];
2008 private $archiveUrls = [];
2010 /** @var array Items to be processed in the deletion batch */
2011 private $deletionBatch;
2013 /** @var bool Whether to suppress all suppressable fields when deleting */
2016 /** @var FileRepoStatus */
2024 * @param string $reason
2025 * @param bool $suppress
2026 * @param User|null $user
2028 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2029 $this->file
= $file;
2030 $this->reason
= $reason;
2031 $this->suppress
= $suppress;
2033 $this->user
= $user;
2036 $this->user
= $wgUser;
2038 $this->status
= $file->repo
->newGood();
2041 public function addCurrent() {
2042 $this->srcRels
['.'] = $this->file
->getRel();
2046 * @param string $oldName
2048 public function addOld( $oldName ) {
2049 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2050 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2054 * Add the old versions of the image to the batch
2055 * @return array List of archive names from old versions
2057 public function addOlds() {
2060 $dbw = $this->file
->repo
->getMasterDB();
2061 $result = $dbw->select( 'oldimage',
2062 [ 'oi_archive_name' ],
2063 [ 'oi_name' => $this->file
->getName() ],
2067 foreach ( $result as $row ) {
2068 $this->addOld( $row->oi_archive_name
);
2069 $archiveNames[] = $row->oi_archive_name
;
2072 return $archiveNames;
2078 protected function getOldRels() {
2079 if ( !isset( $this->srcRels
['.'] ) ) {
2080 $oldRels =& $this->srcRels
;
2081 $deleteCurrent = false;
2083 $oldRels = $this->srcRels
;
2084 unset( $oldRels['.'] );
2085 $deleteCurrent = true;
2088 return [ $oldRels, $deleteCurrent ];
2094 protected function getHashes() {
2096 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2098 if ( $deleteCurrent ) {
2099 $hashes['.'] = $this->file
->getSha1();
2102 if ( count( $oldRels ) ) {
2103 $dbw = $this->file
->repo
->getMasterDB();
2104 $res = $dbw->select(
2106 [ 'oi_archive_name', 'oi_sha1' ],
2107 [ 'oi_archive_name' => array_keys( $oldRels ),
2108 'oi_name' => $this->file
->getName() ], // performance
2112 foreach ( $res as $row ) {
2113 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2114 // Get the hash from the file
2115 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2116 $props = $this->file
->repo
->getFileProps( $oldUrl );
2118 if ( $props['fileExists'] ) {
2119 // Upgrade the oldimage row
2120 $dbw->update( 'oldimage',
2121 [ 'oi_sha1' => $props['sha1'] ],
2122 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2124 $hashes[$row->oi_archive_name
] = $props['sha1'];
2126 $hashes[$row->oi_archive_name
] = false;
2129 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2134 $missing = array_diff_key( $this->srcRels
, $hashes );
2136 foreach ( $missing as $name => $rel ) {
2137 $this->status
->error( 'filedelete-old-unregistered', $name );
2140 foreach ( $hashes as $name => $hash ) {
2142 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2143 unset( $hashes[$name] );
2150 protected function doDBInserts() {
2151 $dbw = $this->file
->repo
->getMasterDB();
2152 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2153 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2154 $encReason = $dbw->addQuotes( $this->reason
);
2155 $encGroup = $dbw->addQuotes( 'deleted' );
2156 $ext = $this->file
->getExtension();
2157 $dotExt = $ext === '' ?
'' : ".$ext";
2158 $encExt = $dbw->addQuotes( $dotExt );
2159 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2161 // Bitfields to further suppress the content
2162 if ( $this->suppress
) {
2164 // This should be 15...
2165 $bitfield |
= Revision
::DELETED_TEXT
;
2166 $bitfield |
= Revision
::DELETED_COMMENT
;
2167 $bitfield |
= Revision
::DELETED_USER
;
2168 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2170 $bitfield = 'oi_deleted';
2173 if ( $deleteCurrent ) {
2174 $concat = $dbw->buildConcat( [ "img_sha1", $encExt ] );
2175 $where = [ 'img_name' => $this->file
->getName() ];
2176 $dbw->insertSelect( 'filearchive', 'image',
2178 'fa_storage_group' => $encGroup,
2179 'fa_storage_key' => $dbw->conditional(
2180 [ 'img_sha1' => '' ],
2181 $dbw->addQuotes( '' ),
2184 'fa_deleted_user' => $encUserId,
2185 'fa_deleted_timestamp' => $encTimestamp,
2186 'fa_deleted_reason' => $encReason,
2187 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2189 'fa_name' => 'img_name',
2190 'fa_archive_name' => 'NULL',
2191 'fa_size' => 'img_size',
2192 'fa_width' => 'img_width',
2193 'fa_height' => 'img_height',
2194 'fa_metadata' => 'img_metadata',
2195 'fa_bits' => 'img_bits',
2196 'fa_media_type' => 'img_media_type',
2197 'fa_major_mime' => 'img_major_mime',
2198 'fa_minor_mime' => 'img_minor_mime',
2199 'fa_description' => 'img_description',
2200 'fa_user' => 'img_user',
2201 'fa_user_text' => 'img_user_text',
2202 'fa_timestamp' => 'img_timestamp',
2203 'fa_sha1' => 'img_sha1',
2204 ], $where, __METHOD__
);
2207 if ( count( $oldRels ) ) {
2208 $concat = $dbw->buildConcat( [ "oi_sha1", $encExt ] );
2210 'oi_name' => $this->file
->getName(),
2211 'oi_archive_name' => array_keys( $oldRels ) ];
2212 $dbw->insertSelect( 'filearchive', 'oldimage',
2214 'fa_storage_group' => $encGroup,
2215 'fa_storage_key' => $dbw->conditional(
2216 [ 'oi_sha1' => '' ],
2217 $dbw->addQuotes( '' ),
2220 'fa_deleted_user' => $encUserId,
2221 'fa_deleted_timestamp' => $encTimestamp,
2222 'fa_deleted_reason' => $encReason,
2223 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2225 'fa_name' => 'oi_name',
2226 'fa_archive_name' => 'oi_archive_name',
2227 'fa_size' => 'oi_size',
2228 'fa_width' => 'oi_width',
2229 'fa_height' => 'oi_height',
2230 'fa_metadata' => 'oi_metadata',
2231 'fa_bits' => 'oi_bits',
2232 'fa_media_type' => 'oi_media_type',
2233 'fa_major_mime' => 'oi_major_mime',
2234 'fa_minor_mime' => 'oi_minor_mime',
2235 'fa_description' => 'oi_description',
2236 'fa_user' => 'oi_user',
2237 'fa_user_text' => 'oi_user_text',
2238 'fa_timestamp' => 'oi_timestamp',
2239 'fa_sha1' => 'oi_sha1',
2240 ], $where, __METHOD__
);
2244 function doDBDeletes() {
2245 $dbw = $this->file
->repo
->getMasterDB();
2246 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2248 if ( count( $oldRels ) ) {
2249 $dbw->delete( 'oldimage',
2251 'oi_name' => $this->file
->getName(),
2252 'oi_archive_name' => array_keys( $oldRels )
2256 if ( $deleteCurrent ) {
2257 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2262 * Run the transaction
2263 * @return FileRepoStatus
2265 public function execute() {
2266 $repo = $this->file
->getRepo();
2267 $this->file
->lock();
2269 // Prepare deletion batch
2270 $hashes = $this->getHashes();
2271 $this->deletionBatch
= [];
2272 $ext = $this->file
->getExtension();
2273 $dotExt = $ext === '' ?
'' : ".$ext";
2275 foreach ( $this->srcRels
as $name => $srcRel ) {
2276 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2277 if ( isset( $hashes[$name] ) ) {
2278 $hash = $hashes[$name];
2279 $key = $hash . $dotExt;
2280 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2281 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2285 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2286 // We acquire this lock by running the inserts now, before the file operations.
2287 // This potentially has poor lock contention characteristics -- an alternative
2288 // scheme would be to insert stub filearchive entries with no fa_name and commit
2289 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2290 $this->doDBInserts();
2292 if ( !$repo->hasSha1Storage() ) {
2293 // Removes non-existent file from the batch, so we don't get errors.
2294 // This also handles files in the 'deleted' zone deleted via revision deletion.
2295 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2296 if ( !$checkStatus->isGood() ) {
2297 $this->status
->merge( $checkStatus );
2298 return $this->status
;
2300 $this->deletionBatch
= $checkStatus->value
;
2302 // Execute the file deletion batch
2303 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2305 if ( !$status->isGood() ) {
2306 $this->status
->merge( $status );
2310 if ( !$this->status
->isOK() ) {
2311 // Critical file deletion error
2312 // Roll back inserts, release lock and abort
2313 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2314 $this->file
->unlockAndRollback();
2316 return $this->status
;
2319 // Delete image/oldimage rows
2320 $this->doDBDeletes();
2322 // Commit and return
2323 $this->file
->unlock();
2325 return $this->status
;
2329 * Removes non-existent files from a deletion batch.
2330 * @param array $batch
2333 protected function removeNonexistentFiles( $batch ) {
2334 $files = $newBatch = [];
2336 foreach ( $batch as $batchItem ) {
2337 list( $src, ) = $batchItem;
2338 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2341 $result = $this->file
->repo
->fileExistsBatch( $files );
2342 if ( in_array( null, $result, true ) ) {
2343 return Status
::newFatal( 'backend-fail-internal',
2344 $this->file
->repo
->getBackend()->getName() );
2347 foreach ( $batch as $batchItem ) {
2348 if ( $result[$batchItem[0]] ) {
2349 $newBatch[] = $batchItem;
2353 return Status
::newGood( $newBatch );
2357 # ------------------------------------------------------------------------------
2360 * Helper class for file undeletion
2361 * @ingroup FileAbstraction
2363 class LocalFileRestoreBatch
{
2364 /** @var LocalFile */
2367 /** @var array List of file IDs to restore */
2368 private $cleanupBatch;
2370 /** @var array List of file IDs to restore */
2373 /** @var bool Add all revisions of the file */
2376 /** @var bool Whether to remove all settings for suppressed fields */
2377 private $unsuppress = false;
2381 * @param bool $unsuppress
2383 function __construct( File
$file, $unsuppress = false ) {
2384 $this->file
= $file;
2385 $this->cleanupBatch
= $this->ids
= [];
2387 $this->unsuppress
= $unsuppress;
2394 public function addId( $fa_id ) {
2395 $this->ids
[] = $fa_id;
2399 * Add a whole lot of files by ID
2402 public function addIds( $ids ) {
2403 $this->ids
= array_merge( $this->ids
, $ids );
2407 * Add all revisions of the file
2409 public function addAll() {
2414 * Run the transaction, except the cleanup batch.
2415 * The cleanup batch should be run in a separate transaction, because it locks different
2416 * rows and there's no need to keep the image row locked while it's acquiring those locks
2417 * The caller may have its own transaction open.
2418 * So we save the batch and let the caller call cleanup()
2419 * @return FileRepoStatus
2421 public function execute() {
2424 $repo = $this->file
->getRepo();
2425 if ( !$this->all
&& !$this->ids
) {
2427 return $repo->newGood();
2430 $lockOwnsTrx = $this->file
->lock();
2432 $dbw = $this->file
->repo
->getMasterDB();
2433 $status = $this->file
->repo
->newGood();
2435 $exists = (bool)$dbw->selectField( 'image', '1',
2436 [ 'img_name' => $this->file
->getName() ],
2438 // The lock() should already prevents changes, but this still may need
2439 // to bypass any transaction snapshot. However, if lock() started the
2440 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2441 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2444 // Fetch all or selected archived revisions for the file,
2445 // sorted from the most recent to the oldest.
2446 $conditions = [ 'fa_name' => $this->file
->getName() ];
2448 if ( !$this->all
) {
2449 $conditions['fa_id'] = $this->ids
;
2452 $result = $dbw->select(
2454 ArchivedFile
::selectFields(),
2457 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2463 $insertCurrent = false;
2468 foreach ( $result as $row ) {
2469 $idsPresent[] = $row->fa_id
;
2471 if ( $row->fa_name
!= $this->file
->getName() ) {
2472 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2473 $status->failCount++
;
2477 if ( $row->fa_storage_key
== '' ) {
2478 // Revision was missing pre-deletion
2479 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2480 $status->failCount++
;
2484 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2485 $row->fa_storage_key
;
2486 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2488 if ( isset( $row->fa_sha1
) ) {
2489 $sha1 = $row->fa_sha1
;
2491 // old row, populate from key
2492 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2496 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2497 $sha1 = substr( $sha1, 1 );
2500 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2501 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2502 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2503 ||
is_null( $row->fa_metadata
)
2505 // Refresh our metadata
2506 // Required for a new current revision; nice for older ones too. :)
2507 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2510 'minor_mime' => $row->fa_minor_mime
,
2511 'major_mime' => $row->fa_major_mime
,
2512 'media_type' => $row->fa_media_type
,
2513 'metadata' => $row->fa_metadata
2517 if ( $first && !$exists ) {
2518 // This revision will be published as the new current version
2519 $destRel = $this->file
->getRel();
2521 'img_name' => $row->fa_name
,
2522 'img_size' => $row->fa_size
,
2523 'img_width' => $row->fa_width
,
2524 'img_height' => $row->fa_height
,
2525 'img_metadata' => $props['metadata'],
2526 'img_bits' => $row->fa_bits
,
2527 'img_media_type' => $props['media_type'],
2528 'img_major_mime' => $props['major_mime'],
2529 'img_minor_mime' => $props['minor_mime'],
2530 'img_description' => $row->fa_description
,
2531 'img_user' => $row->fa_user
,
2532 'img_user_text' => $row->fa_user_text
,
2533 'img_timestamp' => $row->fa_timestamp
,
2537 // The live (current) version cannot be hidden!
2538 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2539 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2540 $this->cleanupBatch
[] = $row->fa_storage_key
;
2543 $archiveName = $row->fa_archive_name
;
2545 if ( $archiveName == '' ) {
2546 // This was originally a current version; we
2547 // have to devise a new archive name for it.
2548 // Format is <timestamp of archiving>!<name>
2549 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2552 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2554 } while ( isset( $archiveNames[$archiveName] ) );
2557 $archiveNames[$archiveName] = true;
2558 $destRel = $this->file
->getArchiveRel( $archiveName );
2560 'oi_name' => $row->fa_name
,
2561 'oi_archive_name' => $archiveName,
2562 'oi_size' => $row->fa_size
,
2563 'oi_width' => $row->fa_width
,
2564 'oi_height' => $row->fa_height
,
2565 'oi_bits' => $row->fa_bits
,
2566 'oi_description' => $row->fa_description
,
2567 'oi_user' => $row->fa_user
,
2568 'oi_user_text' => $row->fa_user_text
,
2569 'oi_timestamp' => $row->fa_timestamp
,
2570 'oi_metadata' => $props['metadata'],
2571 'oi_media_type' => $props['media_type'],
2572 'oi_major_mime' => $props['major_mime'],
2573 'oi_minor_mime' => $props['minor_mime'],
2574 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2575 'oi_sha1' => $sha1 ];
2578 $deleteIds[] = $row->fa_id
;
2580 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2581 // private files can stay where they are
2582 $status->successCount++
;
2584 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2585 $this->cleanupBatch
[] = $row->fa_storage_key
;
2593 // Add a warning to the status object for missing IDs
2594 $missingIds = array_diff( $this->ids
, $idsPresent );
2596 foreach ( $missingIds as $id ) {
2597 $status->error( 'undelete-missing-filearchive', $id );
2600 if ( !$repo->hasSha1Storage() ) {
2601 // Remove missing files from batch, so we don't get errors when undeleting them
2602 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2603 if ( !$checkStatus->isGood() ) {
2604 $status->merge( $checkStatus );
2607 $storeBatch = $checkStatus->value
;
2609 // Run the store batch
2610 // Use the OVERWRITE_SAME flag to smooth over a common error
2611 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2612 $status->merge( $storeStatus );
2614 if ( !$status->isGood() ) {
2615 // Even if some files could be copied, fail entirely as that is the
2616 // easiest thing to do without data loss
2617 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2618 $status->ok
= false;
2619 $this->file
->unlock();
2625 // Run the DB updates
2626 // Because we have locked the image row, key conflicts should be rare.
2627 // If they do occur, we can roll back the transaction at this time with
2628 // no data loss, but leaving unregistered files scattered throughout the
2630 // This is not ideal, which is why it's important to lock the image row.
2631 if ( $insertCurrent ) {
2632 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2635 if ( $insertBatch ) {
2636 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2640 $dbw->delete( 'filearchive',
2641 [ 'fa_id' => $deleteIds ],
2645 // If store batch is empty (all files are missing), deletion is to be considered successful
2646 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2648 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2650 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2652 $this->file
->purgeEverything();
2654 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2655 $this->file
->purgeDescription();
2659 $this->file
->unlock();
2665 * Removes non-existent files from a store batch.
2666 * @param array $triplets
2669 protected function removeNonexistentFiles( $triplets ) {
2670 $files = $filteredTriplets = [];
2671 foreach ( $triplets as $file ) {
2672 $files[$file[0]] = $file[0];
2675 $result = $this->file
->repo
->fileExistsBatch( $files );
2676 if ( in_array( null, $result, true ) ) {
2677 return Status
::newFatal( 'backend-fail-internal',
2678 $this->file
->repo
->getBackend()->getName() );
2681 foreach ( $triplets as $file ) {
2682 if ( $result[$file[0]] ) {
2683 $filteredTriplets[] = $file;
2687 return Status
::newGood( $filteredTriplets );
2691 * Removes non-existent files from a cleanup batch.
2692 * @param array $batch
2695 protected function removeNonexistentFromCleanup( $batch ) {
2696 $files = $newBatch = [];
2697 $repo = $this->file
->repo
;
2699 foreach ( $batch as $file ) {
2700 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2701 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2704 $result = $repo->fileExistsBatch( $files );
2706 foreach ( $batch as $file ) {
2707 if ( $result[$file] ) {
2708 $newBatch[] = $file;
2716 * Delete unused files in the deleted zone.
2717 * This should be called from outside the transaction in which execute() was called.
2718 * @return FileRepoStatus
2720 public function cleanup() {
2721 if ( !$this->cleanupBatch
) {
2722 return $this->file
->repo
->newGood();
2725 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2727 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2733 * Cleanup a failed batch. The batch was only partially successful, so
2734 * rollback by removing all items that were succesfully copied.
2736 * @param Status $storeStatus
2737 * @param array $storeBatch
2739 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2742 foreach ( $storeStatus->success
as $i => $success ) {
2743 // Check if this item of the batch was successfully copied
2745 // Item was successfully copied and needs to be removed again
2746 // Extract ($dstZone, $dstRel) from the batch
2747 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2750 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2754 # ------------------------------------------------------------------------------
2757 * Helper class for file movement
2758 * @ingroup FileAbstraction
2760 class LocalFileMoveBatch
{
2761 /** @var LocalFile */
2771 protected $oldCount;
2775 /** @var DatabaseBase */
2780 * @param Title $target
2782 function __construct( File
$file, Title
$target ) {
2783 $this->file
= $file;
2784 $this->target
= $target;
2785 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2786 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2787 $this->oldName
= $this->file
->getName();
2788 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2789 $this->oldRel
= $this->oldHash
. $this->oldName
;
2790 $this->newRel
= $this->newHash
. $this->newName
;
2791 $this->db
= $file->getRepo()->getMasterDB();
2795 * Add the current image to the batch
2797 public function addCurrent() {
2798 $this->cur
= [ $this->oldRel
, $this->newRel
];
2802 * Add the old versions of the image to the batch
2803 * @return array List of archive names from old versions
2805 public function addOlds() {
2806 $archiveBase = 'archive';
2808 $this->oldCount
= 0;
2811 $result = $this->db
->select( 'oldimage',
2812 [ 'oi_archive_name', 'oi_deleted' ],
2813 [ 'oi_name' => $this->oldName
],
2815 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2818 foreach ( $result as $row ) {
2819 $archiveNames[] = $row->oi_archive_name
;
2820 $oldName = $row->oi_archive_name
;
2821 $bits = explode( '!', $oldName, 2 );
2823 if ( count( $bits ) != 2 ) {
2824 wfDebug( "Old file name missing !: '$oldName' \n" );
2828 list( $timestamp, $filename ) = $bits;
2830 if ( $this->oldName
!= $filename ) {
2831 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2837 // Do we want to add those to oldCount?
2838 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2843 "{$archiveBase}/{$this->oldHash}{$oldName}",
2844 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2848 return $archiveNames;
2853 * @return FileRepoStatus
2855 public function execute() {
2856 $repo = $this->file
->repo
;
2857 $status = $repo->newGood();
2859 $triplets = $this->getMoveTriplets();
2860 $checkStatus = $this->removeNonexistentFiles( $triplets );
2861 if ( !$checkStatus->isGood() ) {
2862 $status->merge( $checkStatus );
2865 $triplets = $checkStatus->value
;
2866 $destFile = wfLocalFile( $this->target
);
2868 $this->file
->lock(); // begin
2869 $destFile->lock(); // quickly fail if destination is not available
2870 // Rename the file versions metadata in the DB.
2871 // This implicitly locks the destination file, which avoids race conditions.
2872 // If we moved the files from A -> C before DB updates, another process could
2873 // move files from B -> C at this point, causing storeBatch() to fail and thus
2874 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2875 $statusDb = $this->doDBUpdates();
2876 if ( !$statusDb->isGood() ) {
2877 $destFile->unlock();
2878 $this->file
->unlockAndRollback();
2879 $statusDb->ok
= false;
2883 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2884 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2886 if ( !$repo->hasSha1Storage() ) {
2887 // Copy the files into their new location.
2888 // If a prior process fataled copying or cleaning up files we tolerate any
2889 // of the existing files if they are identical to the ones being stored.
2890 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2891 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2892 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2893 if ( !$statusMove->isGood() ) {
2894 // Delete any files copied over (while the destination is still locked)
2895 $this->cleanupTarget( $triplets );
2896 $destFile->unlock();
2897 $this->file
->unlockAndRollback(); // unlocks the destination
2898 wfDebugLog( 'imagemove', "Error in moving files: "
2899 . $statusMove->getWikiText( false, false, 'en' ) );
2900 $statusMove->ok
= false;
2904 $status->merge( $statusMove );
2907 $destFile->unlock();
2908 $this->file
->unlock(); // done
2910 // Everything went ok, remove the source files
2911 $this->cleanupSource( $triplets );
2913 $status->merge( $statusDb );
2919 * Do the database updates and return a new FileRepoStatus indicating how
2920 * many rows where updated.
2922 * @return FileRepoStatus
2924 protected function doDBUpdates() {
2925 $repo = $this->file
->repo
;
2926 $status = $repo->newGood();
2929 // Update current image
2932 [ 'img_name' => $this->newName
],
2933 [ 'img_name' => $this->oldName
],
2937 if ( $dbw->affectedRows() ) {
2938 $status->successCount++
;
2940 $status->failCount++
;
2941 $status->fatal( 'imageinvalidfilename' );
2946 // Update old images
2950 'oi_name' => $this->newName
,
2951 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2952 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2954 [ 'oi_name' => $this->oldName
],
2958 $affected = $dbw->affectedRows();
2959 $total = $this->oldCount
;
2960 $status->successCount +
= $affected;
2961 // Bug 34934: $total is based on files that actually exist.
2962 // There may be more DB rows than such files, in which case $affected
2963 // can be greater than $total. We use max() to avoid negatives here.
2964 $status->failCount +
= max( 0, $total - $affected );
2965 if ( $status->failCount
) {
2966 $status->error( 'imageinvalidfilename' );
2973 * Generate triplets for FileRepo::storeBatch().
2976 protected function getMoveTriplets() {
2977 $moves = array_merge( [ $this->cur
], $this->olds
);
2978 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
2980 foreach ( $moves as $move ) {
2981 // $move: (oldRelativePath, newRelativePath)
2982 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2983 $triplets[] = [ $srcUrl, 'public', $move[1] ];
2986 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2994 * Removes non-existent files from move batch.
2995 * @param array $triplets
2998 protected function removeNonexistentFiles( $triplets ) {
3001 foreach ( $triplets as $file ) {
3002 $files[$file[0]] = $file[0];
3005 $result = $this->file
->repo
->fileExistsBatch( $files );
3006 if ( in_array( null, $result, true ) ) {
3007 return Status
::newFatal( 'backend-fail-internal',
3008 $this->file
->repo
->getBackend()->getName() );
3011 $filteredTriplets = [];
3012 foreach ( $triplets as $file ) {
3013 if ( $result[$file[0]] ) {
3014 $filteredTriplets[] = $file;
3016 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3020 return Status
::newGood( $filteredTriplets );
3024 * Cleanup a partially moved array of triplets by deleting the target
3025 * files. Called if something went wrong half way.
3026 * @param array $triplets
3028 protected function cleanupTarget( $triplets ) {
3029 // Create dest pairs from the triplets
3031 foreach ( $triplets as $triplet ) {
3032 // $triplet: (old source virtual URL, dst zone, dest rel)
3033 $pairs[] = [ $triplet[1], $triplet[2] ];
3036 $this->file
->repo
->cleanupBatch( $pairs );
3040 * Cleanup a fully moved array of triplets by deleting the source files.
3041 * Called at the end of the move process if everything else went ok.
3042 * @param array $triplets
3044 protected function cleanupSource( $triplets ) {
3045 // Create source file names from the triplets
3047 foreach ( $triplets as $triplet ) {
3048 $files[] = $triplet[0];
3051 $this->file
->repo
->cleanupBatch( $files );
3055 class LocalFileLockError
extends ErrorPageError
{
3056 public function __construct( Status
$status ) {
3057 parent
::__construct(
3059 $status->getMessage()
3063 public function report() {
3065 $wgOut->setStatusCode( 429 );