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)
132 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
135 * Create a LocalFile from a title
136 * Do not call this except from inside a repo class.
138 * Note: $unused param is only here to avoid an E_STRICT
140 * @param Title $title
141 * @param FileRepo $repo
142 * @param null $unused
146 static function newFromTitle( $title, $repo, $unused = null ) {
147 return new self( $title, $repo );
151 * Create a LocalFile from a title
152 * Do not call this except from inside a repo class.
154 * @param stdClass $row
155 * @param FileRepo $repo
159 static function newFromRow( $row, $repo ) {
160 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
161 $file = new self( $title, $repo );
162 $file->loadFromRow( $row );
168 * Create a LocalFile from a SHA-1 key
169 * Do not call this except from inside a repo class.
171 * @param string $sha1 Base-36 SHA-1
172 * @param LocalRepo $repo
173 * @param string|bool $timestamp MW_timestamp (optional)
174 * @return bool|LocalFile
176 static function newFromKey( $sha1, $repo, $timestamp = false ) {
177 $dbr = $repo->getSlaveDB();
179 $conds = [ 'img_sha1' => $sha1 ];
181 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
184 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
186 return self
::newFromRow( $row, $repo );
193 * Fields in the image table
196 static function selectFields() {
217 * Do not call this except from inside a repo class.
218 * @param Title $title
219 * @param FileRepo $repo
221 function __construct( $title, $repo ) {
222 parent
::__construct( $title, $repo );
224 $this->metadata
= '';
225 $this->historyLine
= 0;
226 $this->historyRes
= null;
227 $this->dataLoaded
= false;
228 $this->extraDataLoaded
= false;
230 $this->assertRepoDefined();
231 $this->assertTitleDefined();
235 * Get the memcached key for the main data for this file, or false if
236 * there is no access to the shared cache.
237 * @return string|bool
239 function getCacheKey() {
240 $hashedName = md5( $this->getName() );
242 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
246 * Try to load file metadata from memcached. Returns true on success.
249 private function loadFromCache() {
250 $this->dataLoaded
= false;
251 $this->extraDataLoaded
= false;
252 $key = $this->getCacheKey();
258 $cache = ObjectCache
::getMainWANInstance();
259 $cachedValues = $cache->get( $key );
261 // Check if the key existed and belongs to this version of MediaWiki
262 if ( is_array( $cachedValues ) && $cachedValues['version'] == MW_FILE_VERSION
) {
263 $this->fileExists
= $cachedValues['fileExists'];
264 if ( $this->fileExists
) {
265 $this->setProps( $cachedValues );
267 $this->dataLoaded
= true;
268 $this->extraDataLoaded
= true;
269 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
270 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
274 return $this->dataLoaded
;
278 * Save the file metadata to memcached
280 private function saveToCache() {
283 $key = $this->getCacheKey();
288 $fields = $this->getCacheFields( '' );
289 $cacheVal = [ 'version' => MW_FILE_VERSION
];
290 $cacheVal['fileExists'] = $this->fileExists
;
292 if ( $this->fileExists
) {
293 foreach ( $fields as $field ) {
294 $cacheVal[$field] = $this->$field;
298 // Strip off excessive entries from the subset of fields that can become large.
299 // If the cache value gets to large it will not fit in memcached and nothing will
300 // get cached at all, causing master queries for any file access.
301 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
302 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
303 unset( $cacheVal[$field] ); // don't let the value get too big
307 // Cache presence for 1 week and negatives for 1 day
308 $ttl = $this->fileExists ?
86400 * 7 : 86400;
309 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
310 ObjectCache
::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
314 * Purge the file object/metadata cache
316 public function invalidateCache() {
317 $key = $this->getCacheKey();
322 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
323 ObjectCache
::getMainWANInstance()->delete( $key );
328 * Load metadata from the file itself
330 function loadFromFile() {
331 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
332 $this->setProps( $props );
336 * @param string $prefix
339 function getCacheFields( $prefix = 'img_' ) {
340 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
341 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
342 'user_text', 'description' ];
343 static $results = [];
345 if ( $prefix == '' ) {
349 if ( !isset( $results[$prefix] ) ) {
350 $prefixedFields = [];
351 foreach ( $fields as $field ) {
352 $prefixedFields[] = $prefix . $field;
354 $results[$prefix] = $prefixedFields;
357 return $results[$prefix];
361 * @param string $prefix
364 function getLazyCacheFields( $prefix = 'img_' ) {
365 static $fields = [ 'metadata' ];
366 static $results = [];
368 if ( $prefix == '' ) {
372 if ( !isset( $results[$prefix] ) ) {
373 $prefixedFields = [];
374 foreach ( $fields as $field ) {
375 $prefixedFields[] = $prefix . $field;
377 $results[$prefix] = $prefixedFields;
380 return $results[$prefix];
384 * Load file metadata from the DB
387 function loadFromDB( $flags = 0 ) {
388 $fname = get_class( $this ) . '::' . __FUNCTION__
;
390 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
391 $this->dataLoaded
= true;
392 $this->extraDataLoaded
= true;
394 $dbr = ( $flags & self
::READ_LATEST
)
395 ?
$this->repo
->getMasterDB()
396 : $this->repo
->getSlaveDB();
398 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
399 [ 'img_name' => $this->getName() ], $fname );
402 $this->loadFromRow( $row );
404 $this->fileExists
= false;
409 * Load lazy file metadata from the DB.
410 * This covers fields that are sometimes not cached.
412 protected function loadExtraFromDB() {
413 $fname = get_class( $this ) . '::' . __FUNCTION__
;
415 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
416 $this->extraDataLoaded
= true;
418 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
420 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
424 foreach ( $fieldMap as $name => $value ) {
425 $this->$name = $value;
428 throw new MWException( "Could not find data for image '{$this->getName()}'." );
433 * @param IDatabase $dbr
434 * @param string $fname
437 private function loadFieldsWithTimestamp( $dbr, $fname ) {
440 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
441 [ 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ],
444 $fieldMap = $this->unprefixRow( $row, 'img_' );
446 # File may have been uploaded over in the meantime; check the old versions
447 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
448 [ 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ],
451 $fieldMap = $this->unprefixRow( $row, 'oi_' );
459 * @param array|object $row
460 * @param string $prefix
461 * @throws MWException
464 protected function unprefixRow( $row, $prefix = 'img_' ) {
465 $array = (array)$row;
466 $prefixLength = strlen( $prefix );
468 // Sanity check prefix once
469 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
470 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
474 foreach ( $array as $name => $value ) {
475 $decoded[substr( $name, $prefixLength )] = $value;
482 * Decode a row from the database (either object or array) to an array
483 * with timestamps and MIME types decoded, and the field prefix removed.
485 * @param string $prefix
486 * @throws MWException
489 function decodeRow( $row, $prefix = 'img_' ) {
490 $decoded = $this->unprefixRow( $row, $prefix );
492 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
494 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
496 if ( empty( $decoded['major_mime'] ) ) {
497 $decoded['mime'] = 'unknown/unknown';
499 if ( !$decoded['minor_mime'] ) {
500 $decoded['minor_mime'] = 'unknown';
502 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
505 // Trim zero padding from char/binary field
506 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
508 // Normalize some fields to integer type, per their database definition.
509 // Use unary + so that overflows will be upgraded to double instead of
510 // being trucated as with intval(). This is important to allow >2GB
511 // files on 32-bit systems.
512 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
513 $decoded[$field] = +
$decoded[$field];
520 * Load file metadata from a DB result row
523 * @param string $prefix
525 function loadFromRow( $row, $prefix = 'img_' ) {
526 $this->dataLoaded
= true;
527 $this->extraDataLoaded
= true;
529 $array = $this->decodeRow( $row, $prefix );
531 foreach ( $array as $name => $value ) {
532 $this->$name = $value;
535 $this->fileExists
= true;
536 $this->maybeUpgradeRow();
540 * Load file metadata from cache or DB, unless already loaded
543 function load( $flags = 0 ) {
544 if ( !$this->dataLoaded
) {
545 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
546 $this->loadFromDB( $flags );
547 $this->saveToCache();
549 $this->dataLoaded
= true;
551 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
552 // @note: loads on name/timestamp to reduce race condition problems
553 $this->loadExtraFromDB();
558 * Upgrade a row if it needs it
560 function maybeUpgradeRow() {
561 global $wgUpdateCompatibleMetadata;
562 if ( wfReadOnly() ) {
567 if ( is_null( $this->media_type
) ||
568 $this->mime
== 'image/svg'
572 $handler = $this->getHandler();
574 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
575 if ( $validity === MediaHandler
::METADATA_BAD
576 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
586 } catch ( LocalFileLockError
$e ) {
587 // let the other process handle it (or do it next time)
589 $this->upgraded
= true; // avoid rework/retries
593 function getUpgraded() {
594 return $this->upgraded
;
598 * Fix assorted version-related problems with the image row by reloading it from the file
600 function upgradeRow() {
601 $this->lock(); // begin
603 $this->loadFromFile();
605 # Don't destroy file info of missing files
606 if ( !$this->fileExists
) {
608 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
613 $dbw = $this->repo
->getMasterDB();
614 list( $major, $minor ) = self
::splitMime( $this->mime
);
616 if ( wfReadOnly() ) {
621 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
623 $dbw->update( 'image',
625 'img_size' => $this->size
, // sanity
626 'img_width' => $this->width
,
627 'img_height' => $this->height
,
628 'img_bits' => $this->bits
,
629 'img_media_type' => $this->media_type
,
630 'img_major_mime' => $major,
631 'img_minor_mime' => $minor,
632 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
633 'img_sha1' => $this->sha1
,
635 [ 'img_name' => $this->getName() ],
639 $this->invalidateCache();
641 $this->unlock(); // done
646 * Set properties in this object to be equal to those given in the
647 * associative array $info. Only cacheable fields can be set.
648 * All fields *must* be set in $info except for getLazyCacheFields().
650 * If 'mime' is given, it will be split into major_mime/minor_mime.
651 * If major_mime/minor_mime are given, $this->mime will also be set.
655 function setProps( $info ) {
656 $this->dataLoaded
= true;
657 $fields = $this->getCacheFields( '' );
658 $fields[] = 'fileExists';
660 foreach ( $fields as $field ) {
661 if ( isset( $info[$field] ) ) {
662 $this->$field = $info[$field];
666 // Fix up mime fields
667 if ( isset( $info['major_mime'] ) ) {
668 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
669 } elseif ( isset( $info['mime'] ) ) {
670 $this->mime
= $info['mime'];
671 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
675 /** splitMime inherited */
676 /** getName inherited */
677 /** getTitle inherited */
678 /** getURL inherited */
679 /** getViewURL inherited */
680 /** getPath inherited */
681 /** isVisible inherited */
686 function isMissing() {
687 if ( $this->missing
=== null ) {
688 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
689 $this->missing
= !$fileExists;
692 return $this->missing
;
696 * Return the width of the image
701 public function getWidth( $page = 1 ) {
704 if ( $this->isMultipage() ) {
705 $handler = $this->getHandler();
709 $dim = $handler->getPageDimensions( $this, $page );
711 return $dim['width'];
713 // For non-paged media, the false goes through an
714 // intval, turning failure into 0, so do same here.
723 * Return the height of the image
728 public function getHeight( $page = 1 ) {
731 if ( $this->isMultipage() ) {
732 $handler = $this->getHandler();
736 $dim = $handler->getPageDimensions( $this, $page );
738 return $dim['height'];
740 // For non-paged media, the false goes through an
741 // intval, turning failure into 0, so do same here.
745 return $this->height
;
750 * Returns ID or name of user who uploaded the file
752 * @param string $type 'text' or 'id'
755 function getUser( $type = 'text' ) {
758 if ( $type == 'text' ) {
759 return $this->user_text
;
760 } elseif ( $type == 'id' ) {
761 return (int)$this->user
;
766 * Get short description URL for a file based on the page ID.
768 * @return string|null
769 * @throws MWException
772 public function getDescriptionShortUrl() {
773 $pageId = $this->title
->getArticleID();
775 if ( $pageId !== null ) {
776 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
777 if ( $url !== false ) {
785 * Get handler-specific metadata
788 function getMetadata() {
789 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
790 return $this->metadata
;
796 function getBitDepth() {
799 return (int)$this->bits
;
803 * Returns the size of the image file, in bytes
806 public function getSize() {
813 * Returns the MIME type of the file.
816 function getMimeType() {
823 * Returns the type of the media in the file.
824 * Use the value returned by this function with the MEDIATYPE_xxx constants.
827 function getMediaType() {
830 return $this->media_type
;
833 /** canRender inherited */
834 /** mustRender inherited */
835 /** allowInlineDisplay inherited */
836 /** isSafeFile inherited */
837 /** isTrustedFile inherited */
840 * Returns true if the file exists on disk.
841 * @return bool Whether file exist on disk.
843 public function exists() {
846 return $this->fileExists
;
849 /** getTransformScript inherited */
850 /** getUnscaledThumb inherited */
851 /** thumbName inherited */
852 /** createThumb inherited */
853 /** transform inherited */
855 /** getHandler inherited */
856 /** iconThumb inherited */
857 /** getLastError inherited */
860 * Get all thumbnail names previously generated for this file
861 * @param string|bool $archiveName Name of an archive file, default false
862 * @return array First element is the base dir, then files in that base dir.
864 function getThumbnails( $archiveName = false ) {
865 if ( $archiveName ) {
866 $dir = $this->getArchiveThumbPath( $archiveName );
868 $dir = $this->getThumbPath();
871 $backend = $this->repo
->getBackend();
874 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
875 foreach ( $iterator as $file ) {
878 } catch ( FileBackendError
$e ) {
879 } // suppress (bug 54674)
885 * Refresh metadata in memcached, but don't touch thumbnails or CDN
887 function purgeMetadataCache() {
888 $this->invalidateCache();
892 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
894 * @param array $options An array potentially with the key forThumbRefresh.
896 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
898 function purgeCache( $options = [] ) {
899 // Refresh metadata cache
900 $this->purgeMetadataCache();
903 $this->purgeThumbnails( $options );
905 // Purge CDN cache for this file
906 DeferredUpdates
::addUpdate(
907 new CdnCacheUpdate( [ $this->getUrl() ] ),
908 DeferredUpdates
::PRESEND
913 * Delete cached transformed files for an archived version only.
914 * @param string $archiveName Name of the archived file
916 function purgeOldThumbnails( $archiveName ) {
917 // Get a list of old thumbnails and URLs
918 $files = $this->getThumbnails( $archiveName );
920 // Purge any custom thumbnail caches
921 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
924 $dir = array_shift( $files );
925 $this->purgeThumbList( $dir, $files );
929 foreach ( $files as $file ) {
930 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
932 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
936 * Delete cached transformed files for the current version only.
937 * @param array $options
939 public function purgeThumbnails( $options = [] ) {
940 $files = $this->getThumbnails();
941 // Always purge all files from CDN regardless of handler filters
943 foreach ( $files as $file ) {
944 $urls[] = $this->getThumbUrl( $file );
946 array_shift( $urls ); // don't purge directory
948 // Give media handler a chance to filter the file purge list
949 if ( !empty( $options['forThumbRefresh'] ) ) {
950 $handler = $this->getHandler();
952 $handler->filterThumbnailPurgeList( $files, $options );
956 // Purge any custom thumbnail caches
957 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
960 $dir = array_shift( $files );
961 $this->purgeThumbList( $dir, $files );
964 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
968 * Delete a list of thumbnails visible at urls
969 * @param string $dir Base dir of the files.
970 * @param array $files Array of strings: relative filenames (to $dir)
972 protected function purgeThumbList( $dir, $files ) {
973 $fileListDebug = strtr(
974 var_export( $files, true ),
977 wfDebug( __METHOD__
. ": $fileListDebug\n" );
980 foreach ( $files as $file ) {
981 # Check that the base file name is part of the thumb name
982 # This is a basic sanity check to avoid erasing unrelated directories
983 if ( strpos( $file, $this->getName() ) !== false
984 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
986 $purgeList[] = "{$dir}/{$file}";
990 # Delete the thumbnails
991 $this->repo
->quickPurgeBatch( $purgeList );
992 # Clear out the thumbnail directory if empty
993 $this->repo
->quickCleanDir( $dir );
996 /** purgeDescription inherited */
997 /** purgeEverything inherited */
1000 * @param int $limit Optional: Limit to number of results
1001 * @param int $start Optional: Timestamp, start from
1002 * @param int $end Optional: Timestamp, end at
1004 * @return OldLocalFile[]
1006 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1007 $dbr = $this->repo
->getSlaveDB();
1008 $tables = [ 'oldimage' ];
1009 $fields = OldLocalFile
::selectFields();
1010 $conds = $opts = $join_conds = [];
1011 $eq = $inc ?
'=' : '';
1012 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1015 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1019 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1023 $opts['LIMIT'] = $limit;
1026 // Search backwards for time > x queries
1027 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1028 $opts['ORDER BY'] = "oi_timestamp $order";
1029 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1031 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1032 &$conds, &$opts, &$join_conds ] );
1034 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1037 foreach ( $res as $row ) {
1038 $r[] = $this->repo
->newFileFromRow( $row );
1041 if ( $order == 'ASC' ) {
1042 $r = array_reverse( $r ); // make sure it ends up descending
1049 * Returns the history of this file, line by line.
1050 * starts with current version, then old versions.
1051 * uses $this->historyLine to check which line to return:
1052 * 0 return line for current version
1053 * 1 query for old versions, return first one
1054 * 2, ... return next old version from above query
1057 public function nextHistoryLine() {
1058 # Polymorphic function name to distinguish foreign and local fetches
1059 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1061 $dbr = $this->repo
->getSlaveDB();
1063 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1064 $this->historyRes
= $dbr->select( 'image',
1067 "'' AS oi_archive_name",
1071 [ 'img_name' => $this->title
->getDBkey() ],
1075 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1076 $this->historyRes
= null;
1080 } elseif ( $this->historyLine
== 1 ) {
1081 $this->historyRes
= $dbr->select( 'oldimage', '*',
1082 [ 'oi_name' => $this->title
->getDBkey() ],
1084 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1087 $this->historyLine++
;
1089 return $dbr->fetchObject( $this->historyRes
);
1093 * Reset the history pointer to the first element of the history
1095 public function resetHistory() {
1096 $this->historyLine
= 0;
1098 if ( !is_null( $this->historyRes
) ) {
1099 $this->historyRes
= null;
1103 /** getHashPath inherited */
1104 /** getRel inherited */
1105 /** getUrlRel inherited */
1106 /** getArchiveRel inherited */
1107 /** getArchivePath inherited */
1108 /** getThumbPath inherited */
1109 /** getArchiveUrl inherited */
1110 /** getThumbUrl inherited */
1111 /** getArchiveVirtualUrl inherited */
1112 /** getThumbVirtualUrl inherited */
1113 /** isHashed inherited */
1116 * Upload a file and record it in the DB
1117 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1118 * @param string $comment Upload description
1119 * @param string $pageText Text to use for the new description page,
1120 * if a new description page is created
1121 * @param int|bool $flags Flags for publish()
1122 * @param array|bool $props File properties, if known. This can be used to
1123 * reduce the upload time when uploading virtual URLs for which the file
1124 * info is already known
1125 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1127 * @param User|null $user User object or null to use $wgUser
1128 * @param string[] $tags Change tags to add to the log entry and page revision.
1129 * (This doesn't check $user's permissions.)
1130 * @return FileRepoStatus On success, the value member contains the
1131 * archive name, or an empty string if it was a new file.
1133 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1134 $timestamp = false, $user = null, $tags = []
1138 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1139 return $this->readOnlyFatalStatus();
1142 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1144 if ( $this->repo
->isVirtualUrl( $srcPath )
1145 || FileBackend
::isStoragePath( $srcPath )
1147 $props = $this->repo
->getFileProps( $srcPath );
1149 $props = FSFile
::getPropsFromPath( $srcPath );
1154 $handler = MediaHandler
::getHandler( $props['mime'] );
1156 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1158 $options['headers'] = [];
1161 // Trim spaces on user supplied text
1162 $comment = trim( $comment );
1164 // Truncate nicely or the DB will do it for us
1165 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1166 $comment = $wgContLang->truncate( $comment, 255 );
1167 $this->lock(); // begin
1168 $status = $this->publish( $src, $flags, $options );
1170 if ( $status->successCount
>= 2 ) {
1171 // There will be a copy+(one of move,copy,store).
1172 // The first succeeding does not commit us to updating the DB
1173 // since it simply copied the current version to a timestamped file name.
1174 // It is only *preferable* to avoid leaving such files orphaned.
1175 // Once the second operation goes through, then the current version was
1176 // updated and we must therefore update the DB too.
1177 $oldver = $status->value
;
1178 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1179 $status->fatal( 'filenotfound', $srcPath );
1183 $this->unlock(); // done
1189 * Record a file upload in the upload log and the image table
1190 * @param string $oldver
1191 * @param string $desc
1192 * @param string $license
1193 * @param string $copyStatus
1194 * @param string $source
1195 * @param bool $watch
1196 * @param string|bool $timestamp
1197 * @param User|null $user User object or null to use $wgUser
1200 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1201 $watch = false, $timestamp = false, User
$user = null ) {
1207 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1209 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1214 $user->addWatch( $this->getTitle() );
1221 * Record a file upload in the upload log and the image table
1222 * @param string $oldver
1223 * @param string $comment
1224 * @param string $pageText
1225 * @param bool|array $props
1226 * @param string|bool $timestamp
1227 * @param null|User $user
1228 * @param string[] $tags
1231 function recordUpload2(
1232 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1234 if ( is_null( $user ) ) {
1239 $dbw = $this->repo
->getMasterDB();
1241 # Imports or such might force a certain timestamp; otherwise we generate
1242 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1243 if ( $timestamp === false ) {
1244 $timestamp = $dbw->timestamp();
1245 $allowTimeKludge = true;
1247 $allowTimeKludge = false;
1250 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1251 $props['description'] = $comment;
1252 $props['user'] = $user->getId();
1253 $props['user_text'] = $user->getName();
1254 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1255 $this->setProps( $props );
1257 # Fail now if the file isn't there
1258 if ( !$this->fileExists
) {
1259 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1264 $dbw->startAtomic( __METHOD__
);
1266 # Test to see if the row exists using INSERT IGNORE
1267 # This avoids race conditions by locking the row until the commit, and also
1268 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1269 $dbw->insert( 'image',
1271 'img_name' => $this->getName(),
1272 'img_size' => $this->size
,
1273 'img_width' => intval( $this->width
),
1274 'img_height' => intval( $this->height
),
1275 'img_bits' => $this->bits
,
1276 'img_media_type' => $this->media_type
,
1277 'img_major_mime' => $this->major_mime
,
1278 'img_minor_mime' => $this->minor_mime
,
1279 'img_timestamp' => $timestamp,
1280 'img_description' => $comment,
1281 'img_user' => $user->getId(),
1282 'img_user_text' => $user->getName(),
1283 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1284 'img_sha1' => $this->sha1
1290 $reupload = ( $dbw->affectedRows() == 0 );
1292 if ( $allowTimeKludge ) {
1293 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1294 $ltimestamp = $dbw->selectField(
1297 [ 'img_name' => $this->getName() ],
1299 [ 'LOCK IN SHARE MODE' ]
1301 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1302 # Avoid a timestamp that is not newer than the last version
1303 # TODO: the image/oldimage tables should be like page/revision with an ID field
1304 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1305 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1306 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1307 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1311 # (bug 34993) Note: $oldver can be empty here, if the previous
1312 # version of the file was broken. Allow registration of the new
1313 # version to continue anyway, because that's better than having
1314 # an image that's not fixable by user operations.
1315 # Collision, this is an update of a file
1316 # Insert previous contents into oldimage
1317 $dbw->insertSelect( 'oldimage', 'image',
1319 'oi_name' => 'img_name',
1320 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1321 'oi_size' => 'img_size',
1322 'oi_width' => 'img_width',
1323 'oi_height' => 'img_height',
1324 'oi_bits' => 'img_bits',
1325 'oi_timestamp' => 'img_timestamp',
1326 'oi_description' => 'img_description',
1327 'oi_user' => 'img_user',
1328 'oi_user_text' => 'img_user_text',
1329 'oi_metadata' => 'img_metadata',
1330 'oi_media_type' => 'img_media_type',
1331 'oi_major_mime' => 'img_major_mime',
1332 'oi_minor_mime' => 'img_minor_mime',
1333 'oi_sha1' => 'img_sha1'
1335 [ 'img_name' => $this->getName() ],
1339 # Update the current image row
1340 $dbw->update( 'image',
1342 'img_size' => $this->size
,
1343 'img_width' => intval( $this->width
),
1344 'img_height' => intval( $this->height
),
1345 'img_bits' => $this->bits
,
1346 'img_media_type' => $this->media_type
,
1347 'img_major_mime' => $this->major_mime
,
1348 'img_minor_mime' => $this->minor_mime
,
1349 'img_timestamp' => $timestamp,
1350 'img_description' => $comment,
1351 'img_user' => $user->getId(),
1352 'img_user_text' => $user->getName(),
1353 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1354 'img_sha1' => $this->sha1
1356 [ 'img_name' => $this->getName() ],
1361 $descTitle = $this->getTitle();
1362 $descId = $descTitle->getArticleID();
1363 $wikiPage = new WikiFilePage( $descTitle );
1364 $wikiPage->setFile( $this );
1366 // Add the log entry...
1367 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1368 $logEntry->setTimestamp( $this->timestamp
);
1369 $logEntry->setPerformer( $user );
1370 $logEntry->setComment( $comment );
1371 $logEntry->setTarget( $descTitle );
1372 // Allow people using the api to associate log entries with the upload.
1373 // Log has a timestamp, but sometimes different from upload timestamp.
1374 $logEntry->setParameters(
1376 'img_sha1' => $this->sha1
,
1377 'img_timestamp' => $timestamp,
1380 // Note we keep $logId around since during new image
1381 // creation, page doesn't exist yet, so log_page = 0
1382 // but we want it to point to the page we're making,
1383 // so we later modify the log entry.
1384 // For a similar reason, we avoid making an RC entry
1385 // now and wait until the page exists.
1386 $logId = $logEntry->insert();
1388 if ( $descTitle->exists() ) {
1389 // Use own context to get the action text in content language
1390 $formatter = LogFormatter
::newFromEntry( $logEntry );
1391 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1392 $editSummary = $formatter->getPlainActionText();
1394 $nullRevision = Revision
::newNullRevision(
1401 if ( $nullRevision ) {
1402 $nullRevision->insertOn( $dbw );
1404 'NewRevisionFromEditComplete',
1405 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1407 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1408 // Associate null revision id
1409 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1412 $newPageContent = null;
1414 // Make the description page and RC log entry post-commit
1415 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1418 # Defer purges, page creation, and link updates in case they error out.
1419 # The most important thing is that files and the DB registry stay synced.
1420 $dbw->endAtomic( __METHOD__
);
1422 # Do some cache purges after final commit so that:
1423 # a) Changes are more likely to be seen post-purge
1424 # b) They won't cause rollback of the log publish/update above
1426 $dbw->onTransactionIdle( function () use (
1427 $that, $reupload, $wikiPage, $newPageContent, $comment, $user, $logEntry, $logId, $descId, $tags
1429 # Update memcache after the commit
1430 $that->invalidateCache();
1432 $updateLogPage = false;
1433 if ( $newPageContent ) {
1434 # New file page; create the description page.
1435 # There's already a log entry, so don't make a second RC entry
1436 # CDN and file cache for the description page are purged by doEditContent.
1437 $status = $wikiPage->doEditContent(
1440 EDIT_NEW | EDIT_SUPPRESS_RC
,
1445 if ( isset( $status->value
['revision'] ) ) {
1446 // Associate new page revision id
1447 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1449 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1450 // which is triggered on $descTitle by doEditContent() above.
1451 if ( isset( $status->value
['revision'] ) ) {
1452 /** @var $rev Revision */
1453 $rev = $status->value
['revision'];
1454 $updateLogPage = $rev->getPage();
1457 # Existing file page: invalidate description page cache
1458 $wikiPage->getTitle()->invalidateCache();
1459 $wikiPage->getTitle()->purgeSquid();
1460 # Allow the new file version to be patrolled from the page footer
1461 Article
::purgePatrolFooterCache( $descId );
1464 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1465 # but setAssociatedRevId() wasn't called at that point yet...
1466 $logParams = $logEntry->getParameters();
1467 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1468 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1469 if ( $updateLogPage ) {
1470 # Also log page, in case where we just created it above
1471 $update['log_page'] = $updateLogPage;
1473 $that->getRepo()->getMasterDB()->update(
1476 [ 'log_id' => $logId ],
1479 $that->getRepo()->getMasterDB()->insert(
1482 'ls_field' => 'associated_rev_id',
1483 'ls_value' => $logEntry->getAssociatedRevId(),
1484 'ls_log_id' => $logId,
1489 # Add change tags, if any
1491 $logEntry->setTags( $tags );
1494 # Uploads can be patrolled
1495 $logEntry->setIsPatrollable( true );
1497 # Now that the log entry is up-to-date, make an RC entry.
1498 $logEntry->publish( $logId );
1500 # Run hook for other updates (typically more cache purging)
1501 Hooks
::run( 'FileUpload', [ $that, $reupload, !$newPageContent ] );
1504 # Delete old thumbnails
1505 $that->purgeThumbnails();
1506 # Remove the old file from the CDN cache
1507 DeferredUpdates
::addUpdate(
1508 new CdnCacheUpdate( [ $that->getUrl() ] ),
1509 DeferredUpdates
::PRESEND
1512 # Update backlink pages pointing to this title if created
1513 LinksUpdate
::queueRecursiveJobsForTable( $that->getTitle(), 'imagelinks' );
1518 # This is a new file, so update the image count
1519 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1522 # Invalidate cache for all pages using this file
1523 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1529 * Move or copy a file to its public location. If a file exists at the
1530 * destination, move it to an archive. Returns a FileRepoStatus object with
1531 * the archive name in the "value" member on success.
1533 * The archive name should be passed through to recordUpload for database
1536 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1537 * @param int $flags A bitwise combination of:
1538 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1539 * @param array $options Optional additional parameters
1540 * @return FileRepoStatus On success, the value member contains the
1541 * archive name, or an empty string if it was a new file.
1543 function publish( $src, $flags = 0, array $options = [] ) {
1544 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1548 * Move or copy a file to a specified location. Returns a FileRepoStatus
1549 * object with the archive name in the "value" member on success.
1551 * The archive name should be passed through to recordUpload for database
1554 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1555 * @param string $dstRel Target relative path
1556 * @param int $flags A bitwise combination of:
1557 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1558 * @param array $options Optional additional parameters
1559 * @return FileRepoStatus On success, the value member contains the
1560 * archive name, or an empty string if it was a new file.
1562 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1563 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1565 $repo = $this->getRepo();
1566 if ( $repo->getReadOnlyReason() !== false ) {
1567 return $this->readOnlyFatalStatus();
1570 $this->lock(); // begin
1572 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1573 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1575 if ( $repo->hasSha1Storage() ) {
1576 $sha1 = $repo->isVirtualUrl( $srcPath )
1577 ?
$repo->getFileSha1( $srcPath )
1578 : FSFile
::getSha1Base36FromPath( $srcPath );
1579 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1580 $status = $repo->quickImport( $src, $dst );
1581 if ( $flags & File
::DELETE_SOURCE
) {
1585 if ( $this->exists() ) {
1586 $status->value
= $archiveName;
1589 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1590 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1592 if ( $status->value
== 'new' ) {
1593 $status->value
= '';
1595 $status->value
= $archiveName;
1599 $this->unlock(); // done
1604 /** getLinksTo inherited */
1605 /** getExifData inherited */
1606 /** isLocal inherited */
1607 /** wasDeleted inherited */
1610 * Move file to the new title
1612 * Move current, old version and all thumbnails
1613 * to the new filename. Old file is deleted.
1615 * Cache purging is done; checks for validity
1616 * and logging are caller's responsibility
1618 * @param Title $target New file name
1619 * @return FileRepoStatus
1621 function move( $target ) {
1622 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1623 return $this->readOnlyFatalStatus();
1626 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1627 $batch = new LocalFileMoveBatch( $this, $target );
1629 $this->lock(); // begin
1630 $batch->addCurrent();
1631 $archiveNames = $batch->addOlds();
1632 $status = $batch->execute();
1633 $this->unlock(); // done
1635 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1637 // Purge the source and target files...
1638 $oldTitleFile = wfLocalFile( $this->title
);
1639 $newTitleFile = wfLocalFile( $target );
1640 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1641 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1642 $this->getRepo()->getMasterDB()->onTransactionIdle(
1643 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1644 $oldTitleFile->purgeEverything();
1645 foreach ( $archiveNames as $archiveName ) {
1646 $oldTitleFile->purgeOldThumbnails( $archiveName );
1648 $newTitleFile->purgeEverything();
1652 if ( $status->isOK() ) {
1653 // Now switch the object
1654 $this->title
= $target;
1655 // Force regeneration of the name and hashpath
1656 unset( $this->name
);
1657 unset( $this->hashPath
);
1664 * Delete all versions of the file.
1666 * Moves the files into an archive directory (or deletes them)
1667 * and removes the database rows.
1669 * Cache purging is done; logging is caller's responsibility.
1671 * @param string $reason
1672 * @param bool $suppress
1673 * @param User|null $user
1674 * @return FileRepoStatus
1676 function delete( $reason, $suppress = false, $user = null ) {
1677 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1678 return $this->readOnlyFatalStatus();
1681 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1683 $this->lock(); // begin
1684 $batch->addCurrent();
1685 # Get old version relative paths
1686 $archiveNames = $batch->addOlds();
1687 $status = $batch->execute();
1688 $this->unlock(); // done
1690 if ( $status->isOK() ) {
1691 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1694 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1695 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1697 $this->getRepo()->getMasterDB()->onTransactionIdle(
1698 function () use ( $that, $archiveNames ) {
1699 $that->purgeEverything();
1700 foreach ( $archiveNames as $archiveName ) {
1701 $that->purgeOldThumbnails( $archiveName );
1708 foreach ( $archiveNames as $archiveName ) {
1709 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1711 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1717 * Delete an old version of the file.
1719 * Moves the file into an archive directory (or deletes it)
1720 * and removes the database row.
1722 * Cache purging is done; logging is caller's responsibility.
1724 * @param string $archiveName
1725 * @param string $reason
1726 * @param bool $suppress
1727 * @param User|null $user
1728 * @throws MWException Exception on database or file store failure
1729 * @return FileRepoStatus
1731 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1732 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1733 return $this->readOnlyFatalStatus();
1736 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1738 $this->lock(); // begin
1739 $batch->addOld( $archiveName );
1740 $status = $batch->execute();
1741 $this->unlock(); // done
1743 $this->purgeOldThumbnails( $archiveName );
1744 if ( $status->isOK() ) {
1745 $this->purgeDescription();
1748 DeferredUpdates
::addUpdate(
1749 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1750 DeferredUpdates
::PRESEND
1757 * Restore all or specified deleted revisions to the given file.
1758 * Permissions and logging are left to the caller.
1760 * May throw database exceptions on error.
1762 * @param array $versions Set of record ids of deleted items to restore,
1763 * or empty to restore all revisions.
1764 * @param bool $unsuppress
1765 * @return FileRepoStatus
1767 function restore( $versions = [], $unsuppress = false ) {
1768 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1769 return $this->readOnlyFatalStatus();
1772 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1774 $this->lock(); // begin
1778 $batch->addIds( $versions );
1780 $status = $batch->execute();
1781 if ( $status->isGood() ) {
1782 $cleanupStatus = $batch->cleanup();
1783 $cleanupStatus->successCount
= 0;
1784 $cleanupStatus->failCount
= 0;
1785 $status->merge( $cleanupStatus );
1787 $this->unlock(); // done
1792 /** isMultipage inherited */
1793 /** pageCount inherited */
1794 /** scaleHeight inherited */
1795 /** getImageSize inherited */
1798 * Get the URL of the file description page.
1801 function getDescriptionUrl() {
1802 return $this->title
->getLocalURL();
1806 * Get the HTML text of the description page
1807 * This is not used by ImagePage for local files, since (among other things)
1808 * it skips the parser cache.
1810 * @param Language $lang What language to get description in (Optional)
1811 * @return bool|mixed
1813 function getDescriptionText( $lang = null ) {
1814 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1818 $content = $revision->getContent();
1822 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1824 return $pout->getText();
1828 * @param int $audience
1832 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1834 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1836 } elseif ( $audience == self
::FOR_THIS_USER
1837 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1841 return $this->description
;
1846 * @return bool|string
1848 function getTimestamp() {
1851 return $this->timestamp
;
1855 * @return bool|string
1857 public function getDescriptionTouched() {
1858 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1859 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1860 // need to differentiate between null (uninitialized) and false (failed to load).
1861 if ( $this->descriptionTouched
=== null ) {
1863 'page_namespace' => $this->title
->getNamespace(),
1864 'page_title' => $this->title
->getDBkey()
1866 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1867 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1870 return $this->descriptionTouched
;
1876 function getSha1() {
1878 // Initialise now if necessary
1879 if ( $this->sha1
== '' && $this->fileExists
) {
1880 $this->lock(); // begin
1882 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1883 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1884 $dbw = $this->repo
->getMasterDB();
1885 $dbw->update( 'image',
1886 [ 'img_sha1' => $this->sha1
],
1887 [ 'img_name' => $this->getName() ],
1889 $this->invalidateCache();
1892 $this->unlock(); // done
1899 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1901 function isCacheable() {
1904 // If extra data (metadata) was not loaded then it must have been large
1905 return $this->extraDataLoaded
1906 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1913 public function acquireFileLock() {
1914 return $this->getRepo()->getBackend()->lockFiles(
1915 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1923 public function releaseFileLock() {
1924 return $this->getRepo()->getBackend()->unlockFiles(
1925 [ $this->getPath() ], LockManager
::LOCK_EX
1930 * Start an atomic DB section and lock the image for update
1931 * or increments a reference counter if the lock is already held
1933 * This method should not be used outside of LocalFile/LocalFile*Batch
1935 * @throws LocalFileLockError Throws an error if the lock was not acquired
1936 * @return bool Whether the file lock owns/spawned the DB transaction
1938 public function lock() {
1939 if ( !$this->locked
) {
1940 $logger = LoggerFactory
::getInstance( 'LocalFile' );
1942 $dbw = $this->repo
->getMasterDB();
1943 $makesTransaction = !$dbw->trxLevel();
1944 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
1945 // Bug 54736: use simple lock to handle when the file does not exist.
1946 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1947 // Also, that would cause contention on INSERT of similarly named rows.
1948 $status = $this->acquireFileLock(); // represents all versions of the file
1949 if ( !$status->isGood() ) {
1950 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
1951 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
1953 throw new LocalFileLockError( $status );
1955 // Release the lock *after* commit to avoid row-level contention.
1956 // Make sure it triggers on rollback() as well as commit() (T132921).
1957 $dbw->onTransactionResolution( function () use ( $logger ) {
1958 $status = $this->releaseFileLock();
1959 if ( !$status->isGood() ) {
1960 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
1963 // Callers might care if the SELECT snapshot is safely fresh
1964 $this->lockedOwnTrx
= $makesTransaction;
1969 return $this->lockedOwnTrx
;
1973 * Decrement the lock reference count and end the atomic section if it reaches zero
1975 * This method should not be used outside of LocalFile/LocalFile*Batch
1977 * The commit and loc release will happen when no atomic sections are active, which
1978 * may happen immediately or at some point after calling this
1980 public function unlock() {
1981 if ( $this->locked
) {
1983 if ( !$this->locked
) {
1984 $dbw = $this->repo
->getMasterDB();
1985 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
1986 $this->lockedOwnTrx
= false;
1992 * Roll back the DB transaction and mark the image unlocked
1994 function unlockAndRollback() {
1995 $this->locked
= false;
1996 $dbw = $this->repo
->getMasterDB();
1997 $dbw->rollback( __METHOD__
);
1998 $this->lockedOwnTrx
= false;
2004 protected function readOnlyFatalStatus() {
2005 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2006 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2010 * Clean up any dangling locks
2012 function __destruct() {
2015 } // LocalFile class
2017 # ------------------------------------------------------------------------------
2020 * Helper class for file deletion
2021 * @ingroup FileAbstraction
2023 class LocalFileDeleteBatch
{
2024 /** @var LocalFile */
2031 private $srcRels = [];
2034 private $archiveUrls = [];
2036 /** @var array Items to be processed in the deletion batch */
2037 private $deletionBatch;
2039 /** @var bool Whether to suppress all suppressable fields when deleting */
2042 /** @var FileRepoStatus */
2050 * @param string $reason
2051 * @param bool $suppress
2052 * @param User|null $user
2054 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2055 $this->file
= $file;
2056 $this->reason
= $reason;
2057 $this->suppress
= $suppress;
2059 $this->user
= $user;
2062 $this->user
= $wgUser;
2064 $this->status
= $file->repo
->newGood();
2067 public function addCurrent() {
2068 $this->srcRels
['.'] = $this->file
->getRel();
2072 * @param string $oldName
2074 public function addOld( $oldName ) {
2075 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2076 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2080 * Add the old versions of the image to the batch
2081 * @return array List of archive names from old versions
2083 public function addOlds() {
2086 $dbw = $this->file
->repo
->getMasterDB();
2087 $result = $dbw->select( 'oldimage',
2088 [ 'oi_archive_name' ],
2089 [ 'oi_name' => $this->file
->getName() ],
2093 foreach ( $result as $row ) {
2094 $this->addOld( $row->oi_archive_name
);
2095 $archiveNames[] = $row->oi_archive_name
;
2098 return $archiveNames;
2104 protected function getOldRels() {
2105 if ( !isset( $this->srcRels
['.'] ) ) {
2106 $oldRels =& $this->srcRels
;
2107 $deleteCurrent = false;
2109 $oldRels = $this->srcRels
;
2110 unset( $oldRels['.'] );
2111 $deleteCurrent = true;
2114 return [ $oldRels, $deleteCurrent ];
2120 protected function getHashes() {
2122 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2124 if ( $deleteCurrent ) {
2125 $hashes['.'] = $this->file
->getSha1();
2128 if ( count( $oldRels ) ) {
2129 $dbw = $this->file
->repo
->getMasterDB();
2130 $res = $dbw->select(
2132 [ 'oi_archive_name', 'oi_sha1' ],
2133 [ 'oi_archive_name' => array_keys( $oldRels ),
2134 'oi_name' => $this->file
->getName() ], // performance
2138 foreach ( $res as $row ) {
2139 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2140 // Get the hash from the file
2141 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2142 $props = $this->file
->repo
->getFileProps( $oldUrl );
2144 if ( $props['fileExists'] ) {
2145 // Upgrade the oldimage row
2146 $dbw->update( 'oldimage',
2147 [ 'oi_sha1' => $props['sha1'] ],
2148 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2150 $hashes[$row->oi_archive_name
] = $props['sha1'];
2152 $hashes[$row->oi_archive_name
] = false;
2155 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2160 $missing = array_diff_key( $this->srcRels
, $hashes );
2162 foreach ( $missing as $name => $rel ) {
2163 $this->status
->error( 'filedelete-old-unregistered', $name );
2166 foreach ( $hashes as $name => $hash ) {
2168 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2169 unset( $hashes[$name] );
2176 protected function doDBInserts() {
2177 $dbw = $this->file
->repo
->getMasterDB();
2178 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2179 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2180 $encReason = $dbw->addQuotes( $this->reason
);
2181 $encGroup = $dbw->addQuotes( 'deleted' );
2182 $ext = $this->file
->getExtension();
2183 $dotExt = $ext === '' ?
'' : ".$ext";
2184 $encExt = $dbw->addQuotes( $dotExt );
2185 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2187 // Bitfields to further suppress the content
2188 if ( $this->suppress
) {
2190 // This should be 15...
2191 $bitfield |
= Revision
::DELETED_TEXT
;
2192 $bitfield |
= Revision
::DELETED_COMMENT
;
2193 $bitfield |
= Revision
::DELETED_USER
;
2194 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2196 $bitfield = 'oi_deleted';
2199 if ( $deleteCurrent ) {
2200 $concat = $dbw->buildConcat( [ "img_sha1", $encExt ] );
2201 $where = [ 'img_name' => $this->file
->getName() ];
2202 $dbw->insertSelect( 'filearchive', 'image',
2204 'fa_storage_group' => $encGroup,
2205 'fa_storage_key' => $dbw->conditional(
2206 [ 'img_sha1' => '' ],
2207 $dbw->addQuotes( '' ),
2210 'fa_deleted_user' => $encUserId,
2211 'fa_deleted_timestamp' => $encTimestamp,
2212 'fa_deleted_reason' => $encReason,
2213 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2215 'fa_name' => 'img_name',
2216 'fa_archive_name' => 'NULL',
2217 'fa_size' => 'img_size',
2218 'fa_width' => 'img_width',
2219 'fa_height' => 'img_height',
2220 'fa_metadata' => 'img_metadata',
2221 'fa_bits' => 'img_bits',
2222 'fa_media_type' => 'img_media_type',
2223 'fa_major_mime' => 'img_major_mime',
2224 'fa_minor_mime' => 'img_minor_mime',
2225 'fa_description' => 'img_description',
2226 'fa_user' => 'img_user',
2227 'fa_user_text' => 'img_user_text',
2228 'fa_timestamp' => 'img_timestamp',
2229 'fa_sha1' => 'img_sha1',
2230 ], $where, __METHOD__
);
2233 if ( count( $oldRels ) ) {
2234 $concat = $dbw->buildConcat( [ "oi_sha1", $encExt ] );
2236 'oi_name' => $this->file
->getName(),
2237 'oi_archive_name' => array_keys( $oldRels ) ];
2238 $dbw->insertSelect( 'filearchive', 'oldimage',
2240 'fa_storage_group' => $encGroup,
2241 'fa_storage_key' => $dbw->conditional(
2242 [ 'oi_sha1' => '' ],
2243 $dbw->addQuotes( '' ),
2246 'fa_deleted_user' => $encUserId,
2247 'fa_deleted_timestamp' => $encTimestamp,
2248 'fa_deleted_reason' => $encReason,
2249 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2251 'fa_name' => 'oi_name',
2252 'fa_archive_name' => 'oi_archive_name',
2253 'fa_size' => 'oi_size',
2254 'fa_width' => 'oi_width',
2255 'fa_height' => 'oi_height',
2256 'fa_metadata' => 'oi_metadata',
2257 'fa_bits' => 'oi_bits',
2258 'fa_media_type' => 'oi_media_type',
2259 'fa_major_mime' => 'oi_major_mime',
2260 'fa_minor_mime' => 'oi_minor_mime',
2261 'fa_description' => 'oi_description',
2262 'fa_user' => 'oi_user',
2263 'fa_user_text' => 'oi_user_text',
2264 'fa_timestamp' => 'oi_timestamp',
2265 'fa_sha1' => 'oi_sha1',
2266 ], $where, __METHOD__
);
2270 function doDBDeletes() {
2271 $dbw = $this->file
->repo
->getMasterDB();
2272 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2274 if ( count( $oldRels ) ) {
2275 $dbw->delete( 'oldimage',
2277 'oi_name' => $this->file
->getName(),
2278 'oi_archive_name' => array_keys( $oldRels )
2282 if ( $deleteCurrent ) {
2283 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2288 * Run the transaction
2289 * @return FileRepoStatus
2291 public function execute() {
2292 $repo = $this->file
->getRepo();
2293 $this->file
->lock();
2295 // Prepare deletion batch
2296 $hashes = $this->getHashes();
2297 $this->deletionBatch
= [];
2298 $ext = $this->file
->getExtension();
2299 $dotExt = $ext === '' ?
'' : ".$ext";
2301 foreach ( $this->srcRels
as $name => $srcRel ) {
2302 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2303 if ( isset( $hashes[$name] ) ) {
2304 $hash = $hashes[$name];
2305 $key = $hash . $dotExt;
2306 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2307 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2311 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2312 // We acquire this lock by running the inserts now, before the file operations.
2313 // This potentially has poor lock contention characteristics -- an alternative
2314 // scheme would be to insert stub filearchive entries with no fa_name and commit
2315 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2316 $this->doDBInserts();
2318 if ( !$repo->hasSha1Storage() ) {
2319 // Removes non-existent file from the batch, so we don't get errors.
2320 // This also handles files in the 'deleted' zone deleted via revision deletion.
2321 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2322 if ( !$checkStatus->isGood() ) {
2323 $this->status
->merge( $checkStatus );
2324 return $this->status
;
2326 $this->deletionBatch
= $checkStatus->value
;
2328 // Execute the file deletion batch
2329 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2331 if ( !$status->isGood() ) {
2332 $this->status
->merge( $status );
2336 if ( !$this->status
->isOK() ) {
2337 // Critical file deletion error
2338 // Roll back inserts, release lock and abort
2339 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2340 $this->file
->unlockAndRollback();
2342 return $this->status
;
2345 // Delete image/oldimage rows
2346 $this->doDBDeletes();
2348 // Commit and return
2349 $this->file
->unlock();
2351 return $this->status
;
2355 * Removes non-existent files from a deletion batch.
2356 * @param array $batch
2359 protected function removeNonexistentFiles( $batch ) {
2360 $files = $newBatch = [];
2362 foreach ( $batch as $batchItem ) {
2363 list( $src, ) = $batchItem;
2364 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2367 $result = $this->file
->repo
->fileExistsBatch( $files );
2368 if ( in_array( null, $result, true ) ) {
2369 return Status
::newFatal( 'backend-fail-internal',
2370 $this->file
->repo
->getBackend()->getName() );
2373 foreach ( $batch as $batchItem ) {
2374 if ( $result[$batchItem[0]] ) {
2375 $newBatch[] = $batchItem;
2379 return Status
::newGood( $newBatch );
2383 # ------------------------------------------------------------------------------
2386 * Helper class for file undeletion
2387 * @ingroup FileAbstraction
2389 class LocalFileRestoreBatch
{
2390 /** @var LocalFile */
2393 /** @var array List of file IDs to restore */
2394 private $cleanupBatch;
2396 /** @var array List of file IDs to restore */
2399 /** @var bool Add all revisions of the file */
2402 /** @var bool Whether to remove all settings for suppressed fields */
2403 private $unsuppress = false;
2407 * @param bool $unsuppress
2409 function __construct( File
$file, $unsuppress = false ) {
2410 $this->file
= $file;
2411 $this->cleanupBatch
= $this->ids
= [];
2413 $this->unsuppress
= $unsuppress;
2420 public function addId( $fa_id ) {
2421 $this->ids
[] = $fa_id;
2425 * Add a whole lot of files by ID
2428 public function addIds( $ids ) {
2429 $this->ids
= array_merge( $this->ids
, $ids );
2433 * Add all revisions of the file
2435 public function addAll() {
2440 * Run the transaction, except the cleanup batch.
2441 * The cleanup batch should be run in a separate transaction, because it locks different
2442 * rows and there's no need to keep the image row locked while it's acquiring those locks
2443 * The caller may have its own transaction open.
2444 * So we save the batch and let the caller call cleanup()
2445 * @return FileRepoStatus
2447 public function execute() {
2450 $repo = $this->file
->getRepo();
2451 if ( !$this->all
&& !$this->ids
) {
2453 return $repo->newGood();
2456 $lockOwnsTrx = $this->file
->lock();
2458 $dbw = $this->file
->repo
->getMasterDB();
2459 $status = $this->file
->repo
->newGood();
2461 $exists = (bool)$dbw->selectField( 'image', '1',
2462 [ 'img_name' => $this->file
->getName() ],
2464 // The lock() should already prevents changes, but this still may need
2465 // to bypass any transaction snapshot. However, if lock() started the
2466 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2467 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2470 // Fetch all or selected archived revisions for the file,
2471 // sorted from the most recent to the oldest.
2472 $conditions = [ 'fa_name' => $this->file
->getName() ];
2474 if ( !$this->all
) {
2475 $conditions['fa_id'] = $this->ids
;
2478 $result = $dbw->select(
2480 ArchivedFile
::selectFields(),
2483 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2489 $insertCurrent = false;
2494 foreach ( $result as $row ) {
2495 $idsPresent[] = $row->fa_id
;
2497 if ( $row->fa_name
!= $this->file
->getName() ) {
2498 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2499 $status->failCount++
;
2503 if ( $row->fa_storage_key
== '' ) {
2504 // Revision was missing pre-deletion
2505 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2506 $status->failCount++
;
2510 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2511 $row->fa_storage_key
;
2512 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2514 if ( isset( $row->fa_sha1
) ) {
2515 $sha1 = $row->fa_sha1
;
2517 // old row, populate from key
2518 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2522 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2523 $sha1 = substr( $sha1, 1 );
2526 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2527 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2528 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2529 ||
is_null( $row->fa_metadata
)
2531 // Refresh our metadata
2532 // Required for a new current revision; nice for older ones too. :)
2533 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2536 'minor_mime' => $row->fa_minor_mime
,
2537 'major_mime' => $row->fa_major_mime
,
2538 'media_type' => $row->fa_media_type
,
2539 'metadata' => $row->fa_metadata
2543 if ( $first && !$exists ) {
2544 // This revision will be published as the new current version
2545 $destRel = $this->file
->getRel();
2547 'img_name' => $row->fa_name
,
2548 'img_size' => $row->fa_size
,
2549 'img_width' => $row->fa_width
,
2550 'img_height' => $row->fa_height
,
2551 'img_metadata' => $props['metadata'],
2552 'img_bits' => $row->fa_bits
,
2553 'img_media_type' => $props['media_type'],
2554 'img_major_mime' => $props['major_mime'],
2555 'img_minor_mime' => $props['minor_mime'],
2556 'img_description' => $row->fa_description
,
2557 'img_user' => $row->fa_user
,
2558 'img_user_text' => $row->fa_user_text
,
2559 'img_timestamp' => $row->fa_timestamp
,
2563 // The live (current) version cannot be hidden!
2564 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2565 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2566 $this->cleanupBatch
[] = $row->fa_storage_key
;
2569 $archiveName = $row->fa_archive_name
;
2571 if ( $archiveName == '' ) {
2572 // This was originally a current version; we
2573 // have to devise a new archive name for it.
2574 // Format is <timestamp of archiving>!<name>
2575 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2578 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2580 } while ( isset( $archiveNames[$archiveName] ) );
2583 $archiveNames[$archiveName] = true;
2584 $destRel = $this->file
->getArchiveRel( $archiveName );
2586 'oi_name' => $row->fa_name
,
2587 'oi_archive_name' => $archiveName,
2588 'oi_size' => $row->fa_size
,
2589 'oi_width' => $row->fa_width
,
2590 'oi_height' => $row->fa_height
,
2591 'oi_bits' => $row->fa_bits
,
2592 'oi_description' => $row->fa_description
,
2593 'oi_user' => $row->fa_user
,
2594 'oi_user_text' => $row->fa_user_text
,
2595 'oi_timestamp' => $row->fa_timestamp
,
2596 'oi_metadata' => $props['metadata'],
2597 'oi_media_type' => $props['media_type'],
2598 'oi_major_mime' => $props['major_mime'],
2599 'oi_minor_mime' => $props['minor_mime'],
2600 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2601 'oi_sha1' => $sha1 ];
2604 $deleteIds[] = $row->fa_id
;
2606 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2607 // private files can stay where they are
2608 $status->successCount++
;
2610 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2611 $this->cleanupBatch
[] = $row->fa_storage_key
;
2619 // Add a warning to the status object for missing IDs
2620 $missingIds = array_diff( $this->ids
, $idsPresent );
2622 foreach ( $missingIds as $id ) {
2623 $status->error( 'undelete-missing-filearchive', $id );
2626 if ( !$repo->hasSha1Storage() ) {
2627 // Remove missing files from batch, so we don't get errors when undeleting them
2628 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2629 if ( !$checkStatus->isGood() ) {
2630 $status->merge( $checkStatus );
2633 $storeBatch = $checkStatus->value
;
2635 // Run the store batch
2636 // Use the OVERWRITE_SAME flag to smooth over a common error
2637 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2638 $status->merge( $storeStatus );
2640 if ( !$status->isGood() ) {
2641 // Even if some files could be copied, fail entirely as that is the
2642 // easiest thing to do without data loss
2643 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2644 $status->ok
= false;
2645 $this->file
->unlock();
2651 // Run the DB updates
2652 // Because we have locked the image row, key conflicts should be rare.
2653 // If they do occur, we can roll back the transaction at this time with
2654 // no data loss, but leaving unregistered files scattered throughout the
2656 // This is not ideal, which is why it's important to lock the image row.
2657 if ( $insertCurrent ) {
2658 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2661 if ( $insertBatch ) {
2662 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2666 $dbw->delete( 'filearchive',
2667 [ 'fa_id' => $deleteIds ],
2671 // If store batch is empty (all files are missing), deletion is to be considered successful
2672 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2674 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2676 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2678 $this->file
->purgeEverything();
2680 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2681 $this->file
->purgeDescription();
2685 $this->file
->unlock();
2691 * Removes non-existent files from a store batch.
2692 * @param array $triplets
2695 protected function removeNonexistentFiles( $triplets ) {
2696 $files = $filteredTriplets = [];
2697 foreach ( $triplets as $file ) {
2698 $files[$file[0]] = $file[0];
2701 $result = $this->file
->repo
->fileExistsBatch( $files );
2702 if ( in_array( null, $result, true ) ) {
2703 return Status
::newFatal( 'backend-fail-internal',
2704 $this->file
->repo
->getBackend()->getName() );
2707 foreach ( $triplets as $file ) {
2708 if ( $result[$file[0]] ) {
2709 $filteredTriplets[] = $file;
2713 return Status
::newGood( $filteredTriplets );
2717 * Removes non-existent files from a cleanup batch.
2718 * @param array $batch
2721 protected function removeNonexistentFromCleanup( $batch ) {
2722 $files = $newBatch = [];
2723 $repo = $this->file
->repo
;
2725 foreach ( $batch as $file ) {
2726 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2727 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2730 $result = $repo->fileExistsBatch( $files );
2732 foreach ( $batch as $file ) {
2733 if ( $result[$file] ) {
2734 $newBatch[] = $file;
2742 * Delete unused files in the deleted zone.
2743 * This should be called from outside the transaction in which execute() was called.
2744 * @return FileRepoStatus
2746 public function cleanup() {
2747 if ( !$this->cleanupBatch
) {
2748 return $this->file
->repo
->newGood();
2751 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2753 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2759 * Cleanup a failed batch. The batch was only partially successful, so
2760 * rollback by removing all items that were succesfully copied.
2762 * @param Status $storeStatus
2763 * @param array $storeBatch
2765 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2768 foreach ( $storeStatus->success
as $i => $success ) {
2769 // Check if this item of the batch was successfully copied
2771 // Item was successfully copied and needs to be removed again
2772 // Extract ($dstZone, $dstRel) from the batch
2773 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2776 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2780 # ------------------------------------------------------------------------------
2783 * Helper class for file movement
2784 * @ingroup FileAbstraction
2786 class LocalFileMoveBatch
{
2787 /** @var LocalFile */
2797 protected $oldCount;
2801 /** @var DatabaseBase */
2806 * @param Title $target
2808 function __construct( File
$file, Title
$target ) {
2809 $this->file
= $file;
2810 $this->target
= $target;
2811 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2812 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2813 $this->oldName
= $this->file
->getName();
2814 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2815 $this->oldRel
= $this->oldHash
. $this->oldName
;
2816 $this->newRel
= $this->newHash
. $this->newName
;
2817 $this->db
= $file->getRepo()->getMasterDB();
2821 * Add the current image to the batch
2823 public function addCurrent() {
2824 $this->cur
= [ $this->oldRel
, $this->newRel
];
2828 * Add the old versions of the image to the batch
2829 * @return array List of archive names from old versions
2831 public function addOlds() {
2832 $archiveBase = 'archive';
2834 $this->oldCount
= 0;
2837 $result = $this->db
->select( 'oldimage',
2838 [ 'oi_archive_name', 'oi_deleted' ],
2839 [ 'oi_name' => $this->oldName
],
2841 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2844 foreach ( $result as $row ) {
2845 $archiveNames[] = $row->oi_archive_name
;
2846 $oldName = $row->oi_archive_name
;
2847 $bits = explode( '!', $oldName, 2 );
2849 if ( count( $bits ) != 2 ) {
2850 wfDebug( "Old file name missing !: '$oldName' \n" );
2854 list( $timestamp, $filename ) = $bits;
2856 if ( $this->oldName
!= $filename ) {
2857 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2863 // Do we want to add those to oldCount?
2864 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2869 "{$archiveBase}/{$this->oldHash}{$oldName}",
2870 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2874 return $archiveNames;
2879 * @return FileRepoStatus
2881 public function execute() {
2882 $repo = $this->file
->repo
;
2883 $status = $repo->newGood();
2885 $triplets = $this->getMoveTriplets();
2886 $checkStatus = $this->removeNonexistentFiles( $triplets );
2887 if ( !$checkStatus->isGood() ) {
2888 $status->merge( $checkStatus );
2891 $triplets = $checkStatus->value
;
2892 $destFile = wfLocalFile( $this->target
);
2894 $this->file
->lock(); // begin
2895 $destFile->lock(); // quickly fail if destination is not available
2896 // Rename the file versions metadata in the DB.
2897 // This implicitly locks the destination file, which avoids race conditions.
2898 // If we moved the files from A -> C before DB updates, another process could
2899 // move files from B -> C at this point, causing storeBatch() to fail and thus
2900 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2901 $statusDb = $this->doDBUpdates();
2902 if ( !$statusDb->isGood() ) {
2903 $destFile->unlock();
2904 $this->file
->unlockAndRollback();
2905 $statusDb->ok
= false;
2909 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2910 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2912 if ( !$repo->hasSha1Storage() ) {
2913 // Copy the files into their new location.
2914 // If a prior process fataled copying or cleaning up files we tolerate any
2915 // of the existing files if they are identical to the ones being stored.
2916 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2917 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2918 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2919 if ( !$statusMove->isGood() ) {
2920 // Delete any files copied over (while the destination is still locked)
2921 $this->cleanupTarget( $triplets );
2922 $destFile->unlock();
2923 $this->file
->unlockAndRollback(); // unlocks the destination
2924 wfDebugLog( 'imagemove', "Error in moving files: "
2925 . $statusMove->getWikiText( false, false, 'en' ) );
2926 $statusMove->ok
= false;
2930 $status->merge( $statusMove );
2933 $destFile->unlock();
2934 $this->file
->unlock(); // done
2936 // Everything went ok, remove the source files
2937 $this->cleanupSource( $triplets );
2939 $status->merge( $statusDb );
2945 * Do the database updates and return a new FileRepoStatus indicating how
2946 * many rows where updated.
2948 * @return FileRepoStatus
2950 protected function doDBUpdates() {
2951 $repo = $this->file
->repo
;
2952 $status = $repo->newGood();
2955 // Update current image
2958 [ 'img_name' => $this->newName
],
2959 [ 'img_name' => $this->oldName
],
2963 if ( $dbw->affectedRows() ) {
2964 $status->successCount++
;
2966 $status->failCount++
;
2967 $status->fatal( 'imageinvalidfilename' );
2972 // Update old images
2976 'oi_name' => $this->newName
,
2977 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2978 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2980 [ 'oi_name' => $this->oldName
],
2984 $affected = $dbw->affectedRows();
2985 $total = $this->oldCount
;
2986 $status->successCount +
= $affected;
2987 // Bug 34934: $total is based on files that actually exist.
2988 // There may be more DB rows than such files, in which case $affected
2989 // can be greater than $total. We use max() to avoid negatives here.
2990 $status->failCount +
= max( 0, $total - $affected );
2991 if ( $status->failCount
) {
2992 $status->error( 'imageinvalidfilename' );
2999 * Generate triplets for FileRepo::storeBatch().
3002 protected function getMoveTriplets() {
3003 $moves = array_merge( [ $this->cur
], $this->olds
);
3004 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3006 foreach ( $moves as $move ) {
3007 // $move: (oldRelativePath, newRelativePath)
3008 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3009 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3012 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3020 * Removes non-existent files from move batch.
3021 * @param array $triplets
3024 protected function removeNonexistentFiles( $triplets ) {
3027 foreach ( $triplets as $file ) {
3028 $files[$file[0]] = $file[0];
3031 $result = $this->file
->repo
->fileExistsBatch( $files );
3032 if ( in_array( null, $result, true ) ) {
3033 return Status
::newFatal( 'backend-fail-internal',
3034 $this->file
->repo
->getBackend()->getName() );
3037 $filteredTriplets = [];
3038 foreach ( $triplets as $file ) {
3039 if ( $result[$file[0]] ) {
3040 $filteredTriplets[] = $file;
3042 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3046 return Status
::newGood( $filteredTriplets );
3050 * Cleanup a partially moved array of triplets by deleting the target
3051 * files. Called if something went wrong half way.
3052 * @param array $triplets
3054 protected function cleanupTarget( $triplets ) {
3055 // Create dest pairs from the triplets
3057 foreach ( $triplets as $triplet ) {
3058 // $triplet: (old source virtual URL, dst zone, dest rel)
3059 $pairs[] = [ $triplet[1], $triplet[2] ];
3062 $this->file
->repo
->cleanupBatch( $pairs );
3066 * Cleanup a fully moved array of triplets by deleting the source files.
3067 * Called at the end of the move process if everything else went ok.
3068 * @param array $triplets
3070 protected function cleanupSource( $triplets ) {
3071 // Create source file names from the triplets
3073 foreach ( $triplets as $triplet ) {
3074 $files[] = $triplet[0];
3077 $this->file
->repo
->cleanupBatch( $files );
3081 class LocalFileLockError
extends ErrorPageError
{
3082 public function __construct( Status
$status ) {
3083 parent
::__construct(
3085 $status->getMessage()
3089 public function report() {
3091 $wgOut->setStatusCode( 429 );