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
1937 $dbw->onTransactionIdle( 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
] );
1945 return $this->lockedOwnTrx
;
1949 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1950 * the transaction and thereby releases the image lock.
1953 if ( $this->locked
) {
1955 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1956 $dbw = $this->repo
->getMasterDB();
1957 $dbw->commit( __METHOD__
);
1958 $this->lockedOwnTrx
= false;
1964 * Roll back the DB transaction and mark the image unlocked
1966 function unlockAndRollback() {
1967 $this->locked
= false;
1968 $dbw = $this->repo
->getMasterDB();
1969 $dbw->rollback( __METHOD__
);
1970 $this->lockedOwnTrx
= false;
1976 protected function readOnlyFatalStatus() {
1977 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1978 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1982 * Clean up any dangling locks
1984 function __destruct() {
1987 } // LocalFile class
1989 # ------------------------------------------------------------------------------
1992 * Helper class for file deletion
1993 * @ingroup FileAbstraction
1995 class LocalFileDeleteBatch
{
1996 /** @var LocalFile */
2003 private $srcRels = [];
2006 private $archiveUrls = [];
2008 /** @var array Items to be processed in the deletion batch */
2009 private $deletionBatch;
2011 /** @var bool Whether to suppress all suppressable fields when deleting */
2014 /** @var FileRepoStatus */
2022 * @param string $reason
2023 * @param bool $suppress
2024 * @param User|null $user
2026 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2027 $this->file
= $file;
2028 $this->reason
= $reason;
2029 $this->suppress
= $suppress;
2031 $this->user
= $user;
2034 $this->user
= $wgUser;
2036 $this->status
= $file->repo
->newGood();
2039 public function addCurrent() {
2040 $this->srcRels
['.'] = $this->file
->getRel();
2044 * @param string $oldName
2046 public function addOld( $oldName ) {
2047 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2048 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2052 * Add the old versions of the image to the batch
2053 * @return array List of archive names from old versions
2055 public function addOlds() {
2058 $dbw = $this->file
->repo
->getMasterDB();
2059 $result = $dbw->select( 'oldimage',
2060 [ 'oi_archive_name' ],
2061 [ 'oi_name' => $this->file
->getName() ],
2065 foreach ( $result as $row ) {
2066 $this->addOld( $row->oi_archive_name
);
2067 $archiveNames[] = $row->oi_archive_name
;
2070 return $archiveNames;
2076 protected function getOldRels() {
2077 if ( !isset( $this->srcRels
['.'] ) ) {
2078 $oldRels =& $this->srcRels
;
2079 $deleteCurrent = false;
2081 $oldRels = $this->srcRels
;
2082 unset( $oldRels['.'] );
2083 $deleteCurrent = true;
2086 return [ $oldRels, $deleteCurrent ];
2092 protected function getHashes() {
2094 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2096 if ( $deleteCurrent ) {
2097 $hashes['.'] = $this->file
->getSha1();
2100 if ( count( $oldRels ) ) {
2101 $dbw = $this->file
->repo
->getMasterDB();
2102 $res = $dbw->select(
2104 [ 'oi_archive_name', 'oi_sha1' ],
2105 [ 'oi_archive_name' => array_keys( $oldRels ),
2106 'oi_name' => $this->file
->getName() ], // performance
2110 foreach ( $res as $row ) {
2111 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2112 // Get the hash from the file
2113 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2114 $props = $this->file
->repo
->getFileProps( $oldUrl );
2116 if ( $props['fileExists'] ) {
2117 // Upgrade the oldimage row
2118 $dbw->update( 'oldimage',
2119 [ 'oi_sha1' => $props['sha1'] ],
2120 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2122 $hashes[$row->oi_archive_name
] = $props['sha1'];
2124 $hashes[$row->oi_archive_name
] = false;
2127 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2132 $missing = array_diff_key( $this->srcRels
, $hashes );
2134 foreach ( $missing as $name => $rel ) {
2135 $this->status
->error( 'filedelete-old-unregistered', $name );
2138 foreach ( $hashes as $name => $hash ) {
2140 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2141 unset( $hashes[$name] );
2148 protected function doDBInserts() {
2149 $dbw = $this->file
->repo
->getMasterDB();
2150 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2151 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2152 $encReason = $dbw->addQuotes( $this->reason
);
2153 $encGroup = $dbw->addQuotes( 'deleted' );
2154 $ext = $this->file
->getExtension();
2155 $dotExt = $ext === '' ?
'' : ".$ext";
2156 $encExt = $dbw->addQuotes( $dotExt );
2157 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2159 // Bitfields to further suppress the content
2160 if ( $this->suppress
) {
2162 // This should be 15...
2163 $bitfield |
= Revision
::DELETED_TEXT
;
2164 $bitfield |
= Revision
::DELETED_COMMENT
;
2165 $bitfield |
= Revision
::DELETED_USER
;
2166 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2168 $bitfield = 'oi_deleted';
2171 if ( $deleteCurrent ) {
2172 $concat = $dbw->buildConcat( [ "img_sha1", $encExt ] );
2173 $where = [ 'img_name' => $this->file
->getName() ];
2174 $dbw->insertSelect( 'filearchive', 'image',
2176 'fa_storage_group' => $encGroup,
2177 'fa_storage_key' => $dbw->conditional(
2178 [ 'img_sha1' => '' ],
2179 $dbw->addQuotes( '' ),
2182 'fa_deleted_user' => $encUserId,
2183 'fa_deleted_timestamp' => $encTimestamp,
2184 'fa_deleted_reason' => $encReason,
2185 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2187 'fa_name' => 'img_name',
2188 'fa_archive_name' => 'NULL',
2189 'fa_size' => 'img_size',
2190 'fa_width' => 'img_width',
2191 'fa_height' => 'img_height',
2192 'fa_metadata' => 'img_metadata',
2193 'fa_bits' => 'img_bits',
2194 'fa_media_type' => 'img_media_type',
2195 'fa_major_mime' => 'img_major_mime',
2196 'fa_minor_mime' => 'img_minor_mime',
2197 'fa_description' => 'img_description',
2198 'fa_user' => 'img_user',
2199 'fa_user_text' => 'img_user_text',
2200 'fa_timestamp' => 'img_timestamp',
2201 'fa_sha1' => 'img_sha1',
2202 ], $where, __METHOD__
);
2205 if ( count( $oldRels ) ) {
2206 $concat = $dbw->buildConcat( [ "oi_sha1", $encExt ] );
2208 'oi_name' => $this->file
->getName(),
2209 'oi_archive_name' => array_keys( $oldRels ) ];
2210 $dbw->insertSelect( 'filearchive', 'oldimage',
2212 'fa_storage_group' => $encGroup,
2213 'fa_storage_key' => $dbw->conditional(
2214 [ 'oi_sha1' => '' ],
2215 $dbw->addQuotes( '' ),
2218 'fa_deleted_user' => $encUserId,
2219 'fa_deleted_timestamp' => $encTimestamp,
2220 'fa_deleted_reason' => $encReason,
2221 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2223 'fa_name' => 'oi_name',
2224 'fa_archive_name' => 'oi_archive_name',
2225 'fa_size' => 'oi_size',
2226 'fa_width' => 'oi_width',
2227 'fa_height' => 'oi_height',
2228 'fa_metadata' => 'oi_metadata',
2229 'fa_bits' => 'oi_bits',
2230 'fa_media_type' => 'oi_media_type',
2231 'fa_major_mime' => 'oi_major_mime',
2232 'fa_minor_mime' => 'oi_minor_mime',
2233 'fa_description' => 'oi_description',
2234 'fa_user' => 'oi_user',
2235 'fa_user_text' => 'oi_user_text',
2236 'fa_timestamp' => 'oi_timestamp',
2237 'fa_sha1' => 'oi_sha1',
2238 ], $where, __METHOD__
);
2242 function doDBDeletes() {
2243 $dbw = $this->file
->repo
->getMasterDB();
2244 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2246 if ( count( $oldRels ) ) {
2247 $dbw->delete( 'oldimage',
2249 'oi_name' => $this->file
->getName(),
2250 'oi_archive_name' => array_keys( $oldRels )
2254 if ( $deleteCurrent ) {
2255 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2260 * Run the transaction
2261 * @return FileRepoStatus
2263 public function execute() {
2264 $repo = $this->file
->getRepo();
2265 $this->file
->lock();
2267 // Prepare deletion batch
2268 $hashes = $this->getHashes();
2269 $this->deletionBatch
= [];
2270 $ext = $this->file
->getExtension();
2271 $dotExt = $ext === '' ?
'' : ".$ext";
2273 foreach ( $this->srcRels
as $name => $srcRel ) {
2274 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2275 if ( isset( $hashes[$name] ) ) {
2276 $hash = $hashes[$name];
2277 $key = $hash . $dotExt;
2278 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2279 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2283 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2284 // We acquire this lock by running the inserts now, before the file operations.
2285 // This potentially has poor lock contention characteristics -- an alternative
2286 // scheme would be to insert stub filearchive entries with no fa_name and commit
2287 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2288 $this->doDBInserts();
2290 if ( !$repo->hasSha1Storage() ) {
2291 // Removes non-existent file from the batch, so we don't get errors.
2292 // This also handles files in the 'deleted' zone deleted via revision deletion.
2293 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2294 if ( !$checkStatus->isGood() ) {
2295 $this->status
->merge( $checkStatus );
2296 return $this->status
;
2298 $this->deletionBatch
= $checkStatus->value
;
2300 // Execute the file deletion batch
2301 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2303 if ( !$status->isGood() ) {
2304 $this->status
->merge( $status );
2308 if ( !$this->status
->isOK() ) {
2309 // Critical file deletion error
2310 // Roll back inserts, release lock and abort
2311 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2312 $this->file
->unlockAndRollback();
2314 return $this->status
;
2317 // Delete image/oldimage rows
2318 $this->doDBDeletes();
2320 // Commit and return
2321 $this->file
->unlock();
2323 return $this->status
;
2327 * Removes non-existent files from a deletion batch.
2328 * @param array $batch
2331 protected function removeNonexistentFiles( $batch ) {
2332 $files = $newBatch = [];
2334 foreach ( $batch as $batchItem ) {
2335 list( $src, ) = $batchItem;
2336 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2339 $result = $this->file
->repo
->fileExistsBatch( $files );
2340 if ( in_array( null, $result, true ) ) {
2341 return Status
::newFatal( 'backend-fail-internal',
2342 $this->file
->repo
->getBackend()->getName() );
2345 foreach ( $batch as $batchItem ) {
2346 if ( $result[$batchItem[0]] ) {
2347 $newBatch[] = $batchItem;
2351 return Status
::newGood( $newBatch );
2355 # ------------------------------------------------------------------------------
2358 * Helper class for file undeletion
2359 * @ingroup FileAbstraction
2361 class LocalFileRestoreBatch
{
2362 /** @var LocalFile */
2365 /** @var array List of file IDs to restore */
2366 private $cleanupBatch;
2368 /** @var array List of file IDs to restore */
2371 /** @var bool Add all revisions of the file */
2374 /** @var bool Whether to remove all settings for suppressed fields */
2375 private $unsuppress = false;
2379 * @param bool $unsuppress
2381 function __construct( File
$file, $unsuppress = false ) {
2382 $this->file
= $file;
2383 $this->cleanupBatch
= $this->ids
= [];
2385 $this->unsuppress
= $unsuppress;
2392 public function addId( $fa_id ) {
2393 $this->ids
[] = $fa_id;
2397 * Add a whole lot of files by ID
2400 public function addIds( $ids ) {
2401 $this->ids
= array_merge( $this->ids
, $ids );
2405 * Add all revisions of the file
2407 public function addAll() {
2412 * Run the transaction, except the cleanup batch.
2413 * The cleanup batch should be run in a separate transaction, because it locks different
2414 * rows and there's no need to keep the image row locked while it's acquiring those locks
2415 * The caller may have its own transaction open.
2416 * So we save the batch and let the caller call cleanup()
2417 * @return FileRepoStatus
2419 public function execute() {
2422 $repo = $this->file
->getRepo();
2423 if ( !$this->all
&& !$this->ids
) {
2425 return $repo->newGood();
2428 $lockOwnsTrx = $this->file
->lock();
2430 $dbw = $this->file
->repo
->getMasterDB();
2431 $status = $this->file
->repo
->newGood();
2433 $exists = (bool)$dbw->selectField( 'image', '1',
2434 [ 'img_name' => $this->file
->getName() ],
2436 // The lock() should already prevents changes, but this still may need
2437 // to bypass any transaction snapshot. However, if lock() started the
2438 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2439 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2442 // Fetch all or selected archived revisions for the file,
2443 // sorted from the most recent to the oldest.
2444 $conditions = [ 'fa_name' => $this->file
->getName() ];
2446 if ( !$this->all
) {
2447 $conditions['fa_id'] = $this->ids
;
2450 $result = $dbw->select(
2452 ArchivedFile
::selectFields(),
2455 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2461 $insertCurrent = false;
2466 foreach ( $result as $row ) {
2467 $idsPresent[] = $row->fa_id
;
2469 if ( $row->fa_name
!= $this->file
->getName() ) {
2470 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2471 $status->failCount++
;
2475 if ( $row->fa_storage_key
== '' ) {
2476 // Revision was missing pre-deletion
2477 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2478 $status->failCount++
;
2482 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2483 $row->fa_storage_key
;
2484 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2486 if ( isset( $row->fa_sha1
) ) {
2487 $sha1 = $row->fa_sha1
;
2489 // old row, populate from key
2490 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2494 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2495 $sha1 = substr( $sha1, 1 );
2498 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2499 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2500 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2501 ||
is_null( $row->fa_metadata
)
2503 // Refresh our metadata
2504 // Required for a new current revision; nice for older ones too. :)
2505 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2508 'minor_mime' => $row->fa_minor_mime
,
2509 'major_mime' => $row->fa_major_mime
,
2510 'media_type' => $row->fa_media_type
,
2511 'metadata' => $row->fa_metadata
2515 if ( $first && !$exists ) {
2516 // This revision will be published as the new current version
2517 $destRel = $this->file
->getRel();
2519 'img_name' => $row->fa_name
,
2520 'img_size' => $row->fa_size
,
2521 'img_width' => $row->fa_width
,
2522 'img_height' => $row->fa_height
,
2523 'img_metadata' => $props['metadata'],
2524 'img_bits' => $row->fa_bits
,
2525 'img_media_type' => $props['media_type'],
2526 'img_major_mime' => $props['major_mime'],
2527 'img_minor_mime' => $props['minor_mime'],
2528 'img_description' => $row->fa_description
,
2529 'img_user' => $row->fa_user
,
2530 'img_user_text' => $row->fa_user_text
,
2531 'img_timestamp' => $row->fa_timestamp
,
2535 // The live (current) version cannot be hidden!
2536 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2537 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2538 $this->cleanupBatch
[] = $row->fa_storage_key
;
2541 $archiveName = $row->fa_archive_name
;
2543 if ( $archiveName == '' ) {
2544 // This was originally a current version; we
2545 // have to devise a new archive name for it.
2546 // Format is <timestamp of archiving>!<name>
2547 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2550 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2552 } while ( isset( $archiveNames[$archiveName] ) );
2555 $archiveNames[$archiveName] = true;
2556 $destRel = $this->file
->getArchiveRel( $archiveName );
2558 'oi_name' => $row->fa_name
,
2559 'oi_archive_name' => $archiveName,
2560 'oi_size' => $row->fa_size
,
2561 'oi_width' => $row->fa_width
,
2562 'oi_height' => $row->fa_height
,
2563 'oi_bits' => $row->fa_bits
,
2564 'oi_description' => $row->fa_description
,
2565 'oi_user' => $row->fa_user
,
2566 'oi_user_text' => $row->fa_user_text
,
2567 'oi_timestamp' => $row->fa_timestamp
,
2568 'oi_metadata' => $props['metadata'],
2569 'oi_media_type' => $props['media_type'],
2570 'oi_major_mime' => $props['major_mime'],
2571 'oi_minor_mime' => $props['minor_mime'],
2572 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2573 'oi_sha1' => $sha1 ];
2576 $deleteIds[] = $row->fa_id
;
2578 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2579 // private files can stay where they are
2580 $status->successCount++
;
2582 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2583 $this->cleanupBatch
[] = $row->fa_storage_key
;
2591 // Add a warning to the status object for missing IDs
2592 $missingIds = array_diff( $this->ids
, $idsPresent );
2594 foreach ( $missingIds as $id ) {
2595 $status->error( 'undelete-missing-filearchive', $id );
2598 if ( !$repo->hasSha1Storage() ) {
2599 // Remove missing files from batch, so we don't get errors when undeleting them
2600 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2601 if ( !$checkStatus->isGood() ) {
2602 $status->merge( $checkStatus );
2605 $storeBatch = $checkStatus->value
;
2607 // Run the store batch
2608 // Use the OVERWRITE_SAME flag to smooth over a common error
2609 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2610 $status->merge( $storeStatus );
2612 if ( !$status->isGood() ) {
2613 // Even if some files could be copied, fail entirely as that is the
2614 // easiest thing to do without data loss
2615 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2616 $status->ok
= false;
2617 $this->file
->unlock();
2623 // Run the DB updates
2624 // Because we have locked the image row, key conflicts should be rare.
2625 // If they do occur, we can roll back the transaction at this time with
2626 // no data loss, but leaving unregistered files scattered throughout the
2628 // This is not ideal, which is why it's important to lock the image row.
2629 if ( $insertCurrent ) {
2630 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2633 if ( $insertBatch ) {
2634 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2638 $dbw->delete( 'filearchive',
2639 [ 'fa_id' => $deleteIds ],
2643 // If store batch is empty (all files are missing), deletion is to be considered successful
2644 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2646 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2648 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2650 $this->file
->purgeEverything();
2652 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2653 $this->file
->purgeDescription();
2657 $this->file
->unlock();
2663 * Removes non-existent files from a store batch.
2664 * @param array $triplets
2667 protected function removeNonexistentFiles( $triplets ) {
2668 $files = $filteredTriplets = [];
2669 foreach ( $triplets as $file ) {
2670 $files[$file[0]] = $file[0];
2673 $result = $this->file
->repo
->fileExistsBatch( $files );
2674 if ( in_array( null, $result, true ) ) {
2675 return Status
::newFatal( 'backend-fail-internal',
2676 $this->file
->repo
->getBackend()->getName() );
2679 foreach ( $triplets as $file ) {
2680 if ( $result[$file[0]] ) {
2681 $filteredTriplets[] = $file;
2685 return Status
::newGood( $filteredTriplets );
2689 * Removes non-existent files from a cleanup batch.
2690 * @param array $batch
2693 protected function removeNonexistentFromCleanup( $batch ) {
2694 $files = $newBatch = [];
2695 $repo = $this->file
->repo
;
2697 foreach ( $batch as $file ) {
2698 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2699 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2702 $result = $repo->fileExistsBatch( $files );
2704 foreach ( $batch as $file ) {
2705 if ( $result[$file] ) {
2706 $newBatch[] = $file;
2714 * Delete unused files in the deleted zone.
2715 * This should be called from outside the transaction in which execute() was called.
2716 * @return FileRepoStatus
2718 public function cleanup() {
2719 if ( !$this->cleanupBatch
) {
2720 return $this->file
->repo
->newGood();
2723 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2725 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2731 * Cleanup a failed batch. The batch was only partially successful, so
2732 * rollback by removing all items that were succesfully copied.
2734 * @param Status $storeStatus
2735 * @param array $storeBatch
2737 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2740 foreach ( $storeStatus->success
as $i => $success ) {
2741 // Check if this item of the batch was successfully copied
2743 // Item was successfully copied and needs to be removed again
2744 // Extract ($dstZone, $dstRel) from the batch
2745 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2748 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2752 # ------------------------------------------------------------------------------
2755 * Helper class for file movement
2756 * @ingroup FileAbstraction
2758 class LocalFileMoveBatch
{
2759 /** @var LocalFile */
2769 protected $oldCount;
2773 /** @var DatabaseBase */
2778 * @param Title $target
2780 function __construct( File
$file, Title
$target ) {
2781 $this->file
= $file;
2782 $this->target
= $target;
2783 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2784 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2785 $this->oldName
= $this->file
->getName();
2786 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2787 $this->oldRel
= $this->oldHash
. $this->oldName
;
2788 $this->newRel
= $this->newHash
. $this->newName
;
2789 $this->db
= $file->getRepo()->getMasterDB();
2793 * Add the current image to the batch
2795 public function addCurrent() {
2796 $this->cur
= [ $this->oldRel
, $this->newRel
];
2800 * Add the old versions of the image to the batch
2801 * @return array List of archive names from old versions
2803 public function addOlds() {
2804 $archiveBase = 'archive';
2806 $this->oldCount
= 0;
2809 $result = $this->db
->select( 'oldimage',
2810 [ 'oi_archive_name', 'oi_deleted' ],
2811 [ 'oi_name' => $this->oldName
],
2813 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2816 foreach ( $result as $row ) {
2817 $archiveNames[] = $row->oi_archive_name
;
2818 $oldName = $row->oi_archive_name
;
2819 $bits = explode( '!', $oldName, 2 );
2821 if ( count( $bits ) != 2 ) {
2822 wfDebug( "Old file name missing !: '$oldName' \n" );
2826 list( $timestamp, $filename ) = $bits;
2828 if ( $this->oldName
!= $filename ) {
2829 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2835 // Do we want to add those to oldCount?
2836 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2841 "{$archiveBase}/{$this->oldHash}{$oldName}",
2842 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2846 return $archiveNames;
2851 * @return FileRepoStatus
2853 public function execute() {
2854 $repo = $this->file
->repo
;
2855 $status = $repo->newGood();
2857 $triplets = $this->getMoveTriplets();
2858 $checkStatus = $this->removeNonexistentFiles( $triplets );
2859 if ( !$checkStatus->isGood() ) {
2860 $status->merge( $checkStatus );
2863 $triplets = $checkStatus->value
;
2864 $destFile = wfLocalFile( $this->target
);
2866 $this->file
->lock(); // begin
2867 $destFile->lock(); // quickly fail if destination is not available
2868 // Rename the file versions metadata in the DB.
2869 // This implicitly locks the destination file, which avoids race conditions.
2870 // If we moved the files from A -> C before DB updates, another process could
2871 // move files from B -> C at this point, causing storeBatch() to fail and thus
2872 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2873 $statusDb = $this->doDBUpdates();
2874 if ( !$statusDb->isGood() ) {
2875 $destFile->unlock();
2876 $this->file
->unlockAndRollback();
2877 $statusDb->ok
= false;
2881 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2882 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2884 if ( !$repo->hasSha1Storage() ) {
2885 // Copy the files into their new location.
2886 // If a prior process fataled copying or cleaning up files we tolerate any
2887 // of the existing files if they are identical to the ones being stored.
2888 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2889 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2890 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2891 if ( !$statusMove->isGood() ) {
2892 // Delete any files copied over (while the destination is still locked)
2893 $this->cleanupTarget( $triplets );
2894 $destFile->unlock();
2895 $this->file
->unlockAndRollback(); // unlocks the destination
2896 wfDebugLog( 'imagemove', "Error in moving files: "
2897 . $statusMove->getWikiText( false, false, 'en' ) );
2898 $statusMove->ok
= false;
2902 $status->merge( $statusMove );
2905 $destFile->unlock();
2906 $this->file
->unlock(); // done
2908 // Everything went ok, remove the source files
2909 $this->cleanupSource( $triplets );
2911 $status->merge( $statusDb );
2917 * Do the database updates and return a new FileRepoStatus indicating how
2918 * many rows where updated.
2920 * @return FileRepoStatus
2922 protected function doDBUpdates() {
2923 $repo = $this->file
->repo
;
2924 $status = $repo->newGood();
2927 // Update current image
2930 [ 'img_name' => $this->newName
],
2931 [ 'img_name' => $this->oldName
],
2935 if ( $dbw->affectedRows() ) {
2936 $status->successCount++
;
2938 $status->failCount++
;
2939 $status->fatal( 'imageinvalidfilename' );
2944 // Update old images
2948 'oi_name' => $this->newName
,
2949 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2950 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2952 [ 'oi_name' => $this->oldName
],
2956 $affected = $dbw->affectedRows();
2957 $total = $this->oldCount
;
2958 $status->successCount +
= $affected;
2959 // Bug 34934: $total is based on files that actually exist.
2960 // There may be more DB rows than such files, in which case $affected
2961 // can be greater than $total. We use max() to avoid negatives here.
2962 $status->failCount +
= max( 0, $total - $affected );
2963 if ( $status->failCount
) {
2964 $status->error( 'imageinvalidfilename' );
2971 * Generate triplets for FileRepo::storeBatch().
2974 protected function getMoveTriplets() {
2975 $moves = array_merge( [ $this->cur
], $this->olds
);
2976 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
2978 foreach ( $moves as $move ) {
2979 // $move: (oldRelativePath, newRelativePath)
2980 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2981 $triplets[] = [ $srcUrl, 'public', $move[1] ];
2984 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2992 * Removes non-existent files from move batch.
2993 * @param array $triplets
2996 protected function removeNonexistentFiles( $triplets ) {
2999 foreach ( $triplets as $file ) {
3000 $files[$file[0]] = $file[0];
3003 $result = $this->file
->repo
->fileExistsBatch( $files );
3004 if ( in_array( null, $result, true ) ) {
3005 return Status
::newFatal( 'backend-fail-internal',
3006 $this->file
->repo
->getBackend()->getName() );
3009 $filteredTriplets = [];
3010 foreach ( $triplets as $file ) {
3011 if ( $result[$file[0]] ) {
3012 $filteredTriplets[] = $file;
3014 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3018 return Status
::newGood( $filteredTriplets );
3022 * Cleanup a partially moved array of triplets by deleting the target
3023 * files. Called if something went wrong half way.
3024 * @param array $triplets
3026 protected function cleanupTarget( $triplets ) {
3027 // Create dest pairs from the triplets
3029 foreach ( $triplets as $triplet ) {
3030 // $triplet: (old source virtual URL, dst zone, dest rel)
3031 $pairs[] = [ $triplet[1], $triplet[2] ];
3034 $this->file
->repo
->cleanupBatch( $pairs );
3038 * Cleanup a fully moved array of triplets by deleting the source files.
3039 * Called at the end of the move process if everything else went ok.
3040 * @param array $triplets
3042 protected function cleanupSource( $triplets ) {
3043 // Create source file names from the triplets
3045 foreach ( $triplets as $triplet ) {
3046 $files[] = $triplet[0];
3049 $this->file
->repo
->cleanupBatch( $files );
3053 class LocalFileLockError
extends ErrorPageError
{
3054 public function __construct( Status
$status ) {
3055 parent
::__construct(
3057 $status->getMessage()
3061 public function report() {
3063 $wgOut->setStatusCode( 429 );