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
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
29 * Class to represent a local file in the wiki's own database
31 * Provides methods to retrieve paths (physical, logical, URL),
32 * to generate image thumbnails or for uploading.
34 * Note that only the repo object knows what its file class is called. You should
35 * never name a file class explictly outside of the repo class. Instead use the
36 * repo's factory functions to generate file objects, for example:
38 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
40 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
43 * @ingroup FileAbstraction
45 class LocalFile
extends File
{
46 const VERSION
= 11; // cache version
48 const CACHE_FIELD_MAX_LEN
= 1000;
50 /** @var bool Does the file exist on disk? (loadFromXxx) */
51 protected $fileExists;
53 /** @var int Image width */
56 /** @var int Image height */
59 /** @var int Returned by getimagesize (loadFromXxx) */
62 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
63 protected $media_type;
65 /** @var string MIME type, determined by MimeMagic::guessMimeType */
68 /** @var int Size in bytes (loadFromXxx) */
71 /** @var string Handler-specific metadata */
74 /** @var string SHA-1 base 36 content hash */
77 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
78 protected $dataLoaded;
80 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
81 protected $extraDataLoaded;
83 /** @var int Bitfield akin to rev_deleted */
87 protected $repoClass = 'LocalRepo';
89 /** @var int Number of line to return by nextHistoryLine() (constructor) */
92 /** @var int Result of the query for the file's history (nextHistoryLine) */
95 /** @var string Major MIME type */
98 /** @var string Minor MIME type */
101 /** @var string Upload timestamp */
104 /** @var int User ID of uploader */
107 /** @var string User name of uploader */
110 /** @var string Description of current revision of the file */
111 private $description;
113 /** @var string TS_MW timestamp of the last change of the file description */
114 private $descriptionTouched;
116 /** @var bool Whether the row was upgraded on load */
119 /** @var bool Whether the row was scheduled to upgrade on load */
122 /** @var bool True if the image row is locked */
125 /** @var bool True if the image row is locked with a lock initiated transaction */
126 private $lockedOwnTrx;
128 /** @var bool True if file is not present in file system. Not to be cached in memcached */
131 // @note: higher than IDBAccessObject constants
132 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
134 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
137 * Create a LocalFile from a title
138 * Do not call this except from inside a repo class.
140 * Note: $unused param is only here to avoid an E_STRICT
142 * @param Title $title
143 * @param FileRepo $repo
144 * @param null $unused
148 static function newFromTitle( $title, $repo, $unused = null ) {
149 return new self( $title, $repo );
153 * Create a LocalFile from a title
154 * Do not call this except from inside a repo class.
156 * @param stdClass $row
157 * @param FileRepo $repo
161 static function newFromRow( $row, $repo ) {
162 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
163 $file = new self( $title, $repo );
164 $file->loadFromRow( $row );
170 * Create a LocalFile from a SHA-1 key
171 * Do not call this except from inside a repo class.
173 * @param string $sha1 Base-36 SHA-1
174 * @param LocalRepo $repo
175 * @param string|bool $timestamp MW_timestamp (optional)
176 * @return bool|LocalFile
178 static function newFromKey( $sha1, $repo, $timestamp = false ) {
179 $dbr = $repo->getReplicaDB();
181 $conds = [ 'img_sha1' => $sha1 ];
183 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
186 $fileQuery = self
::getQueryInfo();
187 $row = $dbr->selectRow(
188 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__
, [], $fileQuery['joins']
191 return self
::newFromRow( $row, $repo );
198 * Fields in the image table
199 * @deprecated since 1.31, use self::getQueryInfo() instead.
202 static function selectFields() {
217 ] + CommentStore
::newKey( 'img_description' )->getFields();
221 * Return the tables, fields, and join conditions to be selected to create
222 * a new localfile object.
224 * @param string[] $options
225 * - omit-lazy: Omit fields that are lazily cached.
226 * @return array With three keys:
227 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
228 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
229 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
231 public static function getQueryInfo( array $options = [] ) {
232 $commentQuery = CommentStore
::newKey( 'img_description' )->getJoin();
234 'tables' => [ 'image' ] +
$commentQuery['tables'],
249 ] +
$commentQuery['fields'],
250 'joins' => $commentQuery['joins'],
253 if ( in_array( 'omit-nonlazy', $options, true ) ) {
254 // Internal use only for getting only the lazy fields
257 if ( !in_array( 'omit-lazy', $options, true ) ) {
258 // Note: Keep this in sync with self::getLazyCacheFields()
259 $ret['fields'][] = 'img_metadata';
266 * Do not call this except from inside a repo class.
267 * @param Title $title
268 * @param FileRepo $repo
270 function __construct( $title, $repo ) {
271 parent
::__construct( $title, $repo );
273 $this->metadata
= '';
274 $this->historyLine
= 0;
275 $this->historyRes
= null;
276 $this->dataLoaded
= false;
277 $this->extraDataLoaded
= false;
279 $this->assertRepoDefined();
280 $this->assertTitleDefined();
284 * Get the memcached key for the main data for this file, or false if
285 * there is no access to the shared cache.
286 * @return string|bool
288 function getCacheKey() {
289 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
293 * @param WANObjectCache $cache
297 public function getMutableCacheKeys( WANObjectCache
$cache ) {
298 return [ $this->getCacheKey() ];
302 * Try to load file metadata from memcached, falling back to the database
304 private function loadFromCache() {
305 $this->dataLoaded
= false;
306 $this->extraDataLoaded
= false;
308 $key = $this->getCacheKey();
310 $this->loadFromDB( self
::READ_NORMAL
);
315 $cache = ObjectCache
::getMainWANInstance();
316 $cachedValues = $cache->getWithSetCallback(
319 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
320 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
322 $this->loadFromDB( self
::READ_NORMAL
);
324 $fields = $this->getCacheFields( '' );
325 $cacheVal['fileExists'] = $this->fileExists
;
326 if ( $this->fileExists
) {
327 foreach ( $fields as $field ) {
328 $cacheVal[$field] = $this->$field;
331 // Strip off excessive entries from the subset of fields that can become large.
332 // If the cache value gets to large it will not fit in memcached and nothing will
333 // get cached at all, causing master queries for any file access.
334 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
335 if ( isset( $cacheVal[$field] )
336 && strlen( $cacheVal[$field] ) > 100 * 1024
338 unset( $cacheVal[$field] ); // don't let the value get too big
342 if ( $this->fileExists
) {
343 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
345 $ttl = $cache::TTL_DAY
;
350 [ 'version' => self
::VERSION
]
353 $this->fileExists
= $cachedValues['fileExists'];
354 if ( $this->fileExists
) {
355 $this->setProps( $cachedValues );
358 $this->dataLoaded
= true;
359 $this->extraDataLoaded
= true;
360 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
361 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
366 * Purge the file object/metadata cache
368 public function invalidateCache() {
369 $key = $this->getCacheKey();
374 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
375 function () use ( $key ) {
376 ObjectCache
::getMainWANInstance()->delete( $key );
383 * Load metadata from the file itself
385 function loadFromFile() {
386 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
387 $this->setProps( $props );
391 * Returns the list of object properties that are included as-is in the cache.
392 * @param string $prefix Must be the empty string
394 * @since 1.31 No longer accepts a non-empty $prefix
396 protected function getCacheFields( $prefix = 'img_' ) {
397 if ( $prefix !== '' ) {
398 throw new InvalidArgumentException(
399 __METHOD__
. ' with a non-empty prefix is no longer supported.'
403 // See self::getQueryInfo() for the fetching of the data from the DB,
404 // self::loadFromRow() for the loading of the object from the DB row,
405 // and self::loadFromCache() for the caching, and self::setProps() for
406 // populating the object from an array of data.
407 return [ 'size', 'width', 'height', 'bits', 'media_type',
408 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
409 'user_text', 'description' ];
413 * Returns the list of object properties that are included as-is in the
414 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
415 * @param string $prefix Must be the empty string
417 * @since 1.31 No longer accepts a non-empty $prefix
419 protected function getLazyCacheFields( $prefix = 'img_' ) {
420 if ( $prefix !== '' ) {
421 throw new InvalidArgumentException(
422 __METHOD__
. ' with a non-empty prefix is no longer supported.'
426 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
427 return [ 'metadata' ];
431 * Load file metadata from the DB
434 function loadFromDB( $flags = 0 ) {
435 $fname = static::class . '::' . __FUNCTION__
;
437 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
438 $this->dataLoaded
= true;
439 $this->extraDataLoaded
= true;
441 $dbr = ( $flags & self
::READ_LATEST
)
442 ?
$this->repo
->getMasterDB()
443 : $this->repo
->getReplicaDB();
445 $fileQuery = static::getQueryInfo();
446 $row = $dbr->selectRow(
447 $fileQuery['tables'],
448 $fileQuery['fields'],
449 [ 'img_name' => $this->getName() ],
456 $this->loadFromRow( $row );
458 $this->fileExists
= false;
463 * Load lazy file metadata from the DB.
464 * This covers fields that are sometimes not cached.
466 protected function loadExtraFromDB() {
467 $fname = static::class . '::' . __FUNCTION__
;
469 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
470 $this->extraDataLoaded
= true;
472 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
474 $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
478 foreach ( $fieldMap as $name => $value ) {
479 $this->$name = $value;
482 throw new MWException( "Could not find data for image '{$this->getName()}'." );
487 * @param IDatabase $dbr
488 * @param string $fname
491 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
494 $fileQuery = self
::getQueryInfo( [ 'omit-nonlazy' ] );
495 $row = $dbr->selectRow(
496 $fileQuery['tables'],
497 $fileQuery['fields'],
499 'img_name' => $this->getName(),
500 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
507 $fieldMap = $this->unprefixRow( $row, 'img_' );
509 # File may have been uploaded over in the meantime; check the old versions
510 $fileQuery = OldLocalFile
::getQueryInfo( [ 'omit-nonlazy' ] );
511 $row = $dbr->selectRow(
512 $fileQuery['tables'],
513 $fileQuery['fields'],
515 'oi_name' => $this->getName(),
516 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
523 $fieldMap = $this->unprefixRow( $row, 'oi_' );
527 if ( isset( $fieldMap['metadata'] ) ) {
528 $fieldMap['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
535 * @param array|object $row
536 * @param string $prefix
537 * @throws MWException
540 protected function unprefixRow( $row, $prefix = 'img_' ) {
541 $array = (array)$row;
542 $prefixLength = strlen( $prefix );
544 // Sanity check prefix once
545 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
546 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
550 foreach ( $array as $name => $value ) {
551 $decoded[substr( $name, $prefixLength )] = $value;
558 * Decode a row from the database (either object or array) to an array
559 * with timestamps and MIME types decoded, and the field prefix removed.
561 * @param string $prefix
562 * @throws MWException
565 function decodeRow( $row, $prefix = 'img_' ) {
566 $decoded = $this->unprefixRow( $row, $prefix );
568 $decoded['description'] = CommentStore
::newKey( 'description' )
569 ->getComment( (object)$decoded )->text
;
571 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
573 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
575 if ( empty( $decoded['major_mime'] ) ) {
576 $decoded['mime'] = 'unknown/unknown';
578 if ( !$decoded['minor_mime'] ) {
579 $decoded['minor_mime'] = 'unknown';
581 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
584 // Trim zero padding from char/binary field
585 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
587 // Normalize some fields to integer type, per their database definition.
588 // Use unary + so that overflows will be upgraded to double instead of
589 // being trucated as with intval(). This is important to allow >2GB
590 // files on 32-bit systems.
591 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
592 $decoded[$field] = +
$decoded[$field];
599 * Load file metadata from a DB result row
602 * @param string $prefix
604 function loadFromRow( $row, $prefix = 'img_' ) {
605 $this->dataLoaded
= true;
606 $this->extraDataLoaded
= true;
608 $array = $this->decodeRow( $row, $prefix );
610 foreach ( $array as $name => $value ) {
611 $this->$name = $value;
614 $this->fileExists
= true;
615 $this->maybeUpgradeRow();
619 * Load file metadata from cache or DB, unless already loaded
622 function load( $flags = 0 ) {
623 if ( !$this->dataLoaded
) {
624 if ( $flags & self
::READ_LATEST
) {
625 $this->loadFromDB( $flags );
627 $this->loadFromCache();
631 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
632 // @note: loads on name/timestamp to reduce race condition problems
633 $this->loadExtraFromDB();
638 * Upgrade a row if it needs it
640 function maybeUpgradeRow() {
641 global $wgUpdateCompatibleMetadata;
643 if ( wfReadOnly() ||
$this->upgrading
) {
648 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
651 $handler = $this->getHandler();
653 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
654 if ( $validity === MediaHandler
::METADATA_BAD
) {
656 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
657 $upgrade = $wgUpdateCompatibleMetadata;
663 $this->upgrading
= true;
664 // Defer updates unless in auto-commit CLI mode
665 DeferredUpdates
::addCallableUpdate( function () {
666 $this->upgrading
= false; // avoid duplicate updates
669 } catch ( LocalFileLockError
$e ) {
670 // let the other process handle it (or do it next time)
677 * @return bool Whether upgradeRow() ran for this object
679 function getUpgraded() {
680 return $this->upgraded
;
684 * Fix assorted version-related problems with the image row by reloading it from the file
686 function upgradeRow() {
687 $this->lock(); // begin
689 $this->loadFromFile();
691 # Don't destroy file info of missing files
692 if ( !$this->fileExists
) {
694 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
699 $dbw = $this->repo
->getMasterDB();
700 list( $major, $minor ) = self
::splitMime( $this->mime
);
702 if ( wfReadOnly() ) {
707 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
709 $dbw->update( 'image',
711 'img_size' => $this->size
, // sanity
712 'img_width' => $this->width
,
713 'img_height' => $this->height
,
714 'img_bits' => $this->bits
,
715 'img_media_type' => $this->media_type
,
716 'img_major_mime' => $major,
717 'img_minor_mime' => $minor,
718 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
719 'img_sha1' => $this->sha1
,
721 [ 'img_name' => $this->getName() ],
725 $this->invalidateCache();
727 $this->unlock(); // done
728 $this->upgraded
= true; // avoid rework/retries
732 * Set properties in this object to be equal to those given in the
733 * associative array $info. Only cacheable fields can be set.
734 * All fields *must* be set in $info except for getLazyCacheFields().
736 * If 'mime' is given, it will be split into major_mime/minor_mime.
737 * If major_mime/minor_mime are given, $this->mime will also be set.
741 function setProps( $info ) {
742 $this->dataLoaded
= true;
743 $fields = $this->getCacheFields( '' );
744 $fields[] = 'fileExists';
746 foreach ( $fields as $field ) {
747 if ( isset( $info[$field] ) ) {
748 $this->$field = $info[$field];
752 // Fix up mime fields
753 if ( isset( $info['major_mime'] ) ) {
754 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
755 } elseif ( isset( $info['mime'] ) ) {
756 $this->mime
= $info['mime'];
757 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
761 /** splitMime inherited */
762 /** getName inherited */
763 /** getTitle inherited */
764 /** getURL inherited */
765 /** getViewURL inherited */
766 /** getPath inherited */
767 /** isVisible inherited */
772 function isMissing() {
773 if ( $this->missing
=== null ) {
774 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
775 $this->missing
= !$fileExists;
778 return $this->missing
;
782 * Return the width of the image
787 public function getWidth( $page = 1 ) {
795 if ( $this->isMultipage() ) {
796 $handler = $this->getHandler();
800 $dim = $handler->getPageDimensions( $this, $page );
802 return $dim['width'];
804 // For non-paged media, the false goes through an
805 // intval, turning failure into 0, so do same here.
814 * Return the height of the image
819 public function getHeight( $page = 1 ) {
827 if ( $this->isMultipage() ) {
828 $handler = $this->getHandler();
832 $dim = $handler->getPageDimensions( $this, $page );
834 return $dim['height'];
836 // For non-paged media, the false goes through an
837 // intval, turning failure into 0, so do same here.
841 return $this->height
;
846 * Returns ID or name of user who uploaded the file
848 * @param string $type 'text' or 'id'
851 function getUser( $type = 'text' ) {
854 if ( $type == 'text' ) {
855 return $this->user_text
;
857 return (int)$this->user
;
862 * Get short description URL for a file based on the page ID.
864 * @return string|null
865 * @throws MWException
868 public function getDescriptionShortUrl() {
869 $pageId = $this->title
->getArticleID();
871 if ( $pageId !== null ) {
872 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
873 if ( $url !== false ) {
881 * Get handler-specific metadata
884 function getMetadata() {
885 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
886 return $this->metadata
;
892 function getBitDepth() {
895 return (int)$this->bits
;
899 * Returns the size of the image file, in bytes
902 public function getSize() {
909 * Returns the MIME type of the file.
912 function getMimeType() {
919 * Returns the type of the media in the file.
920 * Use the value returned by this function with the MEDIATYPE_xxx constants.
923 function getMediaType() {
926 return $this->media_type
;
929 /** canRender inherited */
930 /** mustRender inherited */
931 /** allowInlineDisplay inherited */
932 /** isSafeFile inherited */
933 /** isTrustedFile inherited */
936 * Returns true if the file exists on disk.
937 * @return bool Whether file exist on disk.
939 public function exists() {
942 return $this->fileExists
;
945 /** getTransformScript inherited */
946 /** getUnscaledThumb inherited */
947 /** thumbName inherited */
948 /** createThumb inherited */
949 /** transform inherited */
951 /** getHandler inherited */
952 /** iconThumb inherited */
953 /** getLastError inherited */
956 * Get all thumbnail names previously generated for this file
957 * @param string|bool $archiveName Name of an archive file, default false
958 * @return array First element is the base dir, then files in that base dir.
960 function getThumbnails( $archiveName = false ) {
961 if ( $archiveName ) {
962 $dir = $this->getArchiveThumbPath( $archiveName );
964 $dir = $this->getThumbPath();
967 $backend = $this->repo
->getBackend();
970 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
971 foreach ( $iterator as $file ) {
974 } catch ( FileBackendError
$e ) {
975 } // suppress (T56674)
981 * Refresh metadata in memcached, but don't touch thumbnails or CDN
983 function purgeMetadataCache() {
984 $this->invalidateCache();
988 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
990 * @param array $options An array potentially with the key forThumbRefresh.
992 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
994 function purgeCache( $options = [] ) {
995 // Refresh metadata cache
996 $this->purgeMetadataCache();
999 $this->purgeThumbnails( $options );
1001 // Purge CDN cache for this file
1002 DeferredUpdates
::addUpdate(
1003 new CdnCacheUpdate( [ $this->getUrl() ] ),
1004 DeferredUpdates
::PRESEND
1009 * Delete cached transformed files for an archived version only.
1010 * @param string $archiveName Name of the archived file
1012 function purgeOldThumbnails( $archiveName ) {
1013 // Get a list of old thumbnails and URLs
1014 $files = $this->getThumbnails( $archiveName );
1016 // Purge any custom thumbnail caches
1017 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1019 // Delete thumbnails
1020 $dir = array_shift( $files );
1021 $this->purgeThumbList( $dir, $files );
1025 foreach ( $files as $file ) {
1026 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1028 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1032 * Delete cached transformed files for the current version only.
1033 * @param array $options
1035 public function purgeThumbnails( $options = [] ) {
1036 $files = $this->getThumbnails();
1037 // Always purge all files from CDN regardless of handler filters
1039 foreach ( $files as $file ) {
1040 $urls[] = $this->getThumbUrl( $file );
1042 array_shift( $urls ); // don't purge directory
1044 // Give media handler a chance to filter the file purge list
1045 if ( !empty( $options['forThumbRefresh'] ) ) {
1046 $handler = $this->getHandler();
1048 $handler->filterThumbnailPurgeList( $files, $options );
1052 // Purge any custom thumbnail caches
1053 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1055 // Delete thumbnails
1056 $dir = array_shift( $files );
1057 $this->purgeThumbList( $dir, $files );
1060 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
1064 * Prerenders a configurable set of thumbnails
1068 public function prerenderThumbnails() {
1069 global $wgUploadThumbnailRenderMap;
1073 $sizes = $wgUploadThumbnailRenderMap;
1076 foreach ( $sizes as $size ) {
1077 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
1078 $jobs[] = new ThumbnailRenderJob(
1080 [ 'transformParams' => [ 'width' => $size ] ]
1086 JobQueueGroup
::singleton()->lazyPush( $jobs );
1091 * Delete a list of thumbnails visible at urls
1092 * @param string $dir Base dir of the files.
1093 * @param array $files Array of strings: relative filenames (to $dir)
1095 protected function purgeThumbList( $dir, $files ) {
1096 $fileListDebug = strtr(
1097 var_export( $files, true ),
1100 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1103 foreach ( $files as $file ) {
1104 if ( $this->repo
->supportsSha1URLs() ) {
1105 $reference = $this->getSha1();
1107 $reference = $this->getName();
1110 # Check that the reference (filename or sha1) is part of the thumb name
1111 # This is a basic sanity check to avoid erasing unrelated directories
1112 if ( strpos( $file, $reference ) !== false
1113 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1115 $purgeList[] = "{$dir}/{$file}";
1119 # Delete the thumbnails
1120 $this->repo
->quickPurgeBatch( $purgeList );
1121 # Clear out the thumbnail directory if empty
1122 $this->repo
->quickCleanDir( $dir );
1125 /** purgeDescription inherited */
1126 /** purgeEverything inherited */
1129 * @param int $limit Optional: Limit to number of results
1130 * @param int $start Optional: Timestamp, start from
1131 * @param int $end Optional: Timestamp, end at
1133 * @return OldLocalFile[]
1135 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1136 $dbr = $this->repo
->getReplicaDB();
1137 $oldFileQuery = OldLocalFile
::getQueryInfo();
1139 $tables = $oldFileQuery['tables'];
1140 $fields = $oldFileQuery['fields'];
1141 $join_conds = $oldFileQuery['joins'];
1142 $conds = $opts = [];
1143 $eq = $inc ?
'=' : '';
1144 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1147 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1151 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1155 $opts['LIMIT'] = $limit;
1158 // Search backwards for time > x queries
1159 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1160 $opts['ORDER BY'] = "oi_timestamp $order";
1161 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1163 // Avoid PHP 7.1 warning from passing $this by reference
1165 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1166 &$conds, &$opts, &$join_conds ] );
1168 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1171 foreach ( $res as $row ) {
1172 $r[] = $this->repo
->newFileFromRow( $row );
1175 if ( $order == 'ASC' ) {
1176 $r = array_reverse( $r ); // make sure it ends up descending
1183 * Returns the history of this file, line by line.
1184 * starts with current version, then old versions.
1185 * uses $this->historyLine to check which line to return:
1186 * 0 return line for current version
1187 * 1 query for old versions, return first one
1188 * 2, ... return next old version from above query
1191 public function nextHistoryLine() {
1192 # Polymorphic function name to distinguish foreign and local fetches
1193 $fname = static::class . '::' . __FUNCTION__
;
1195 $dbr = $this->repo
->getReplicaDB();
1197 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1198 $fileQuery = self
::getQueryInfo();
1199 $this->historyRes
= $dbr->select( $fileQuery['tables'],
1200 $fileQuery['fields'] +
[
1201 'oi_archive_name' => $dbr->addQuotes( '' ),
1204 [ 'img_name' => $this->title
->getDBkey() ],
1210 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1211 $this->historyRes
= null;
1215 } elseif ( $this->historyLine
== 1 ) {
1216 $fileQuery = OldLocalFile
::getQueryInfo();
1217 $this->historyRes
= $dbr->select(
1218 $fileQuery['tables'],
1219 $fileQuery['fields'],
1220 [ 'oi_name' => $this->title
->getDBkey() ],
1222 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1226 $this->historyLine++
;
1228 return $dbr->fetchObject( $this->historyRes
);
1232 * Reset the history pointer to the first element of the history
1234 public function resetHistory() {
1235 $this->historyLine
= 0;
1237 if ( !is_null( $this->historyRes
) ) {
1238 $this->historyRes
= null;
1242 /** getHashPath inherited */
1243 /** getRel inherited */
1244 /** getUrlRel inherited */
1245 /** getArchiveRel inherited */
1246 /** getArchivePath inherited */
1247 /** getThumbPath inherited */
1248 /** getArchiveUrl inherited */
1249 /** getThumbUrl inherited */
1250 /** getArchiveVirtualUrl inherited */
1251 /** getThumbVirtualUrl inherited */
1252 /** isHashed inherited */
1255 * Upload a file and record it in the DB
1256 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1257 * @param string $comment Upload description
1258 * @param string $pageText Text to use for the new description page,
1259 * if a new description page is created
1260 * @param int|bool $flags Flags for publish()
1261 * @param array|bool $props File properties, if known. This can be used to
1262 * reduce the upload time when uploading virtual URLs for which the file
1263 * info is already known
1264 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1266 * @param User|null $user User object or null to use $wgUser
1267 * @param string[] $tags Change tags to add to the log entry and page revision.
1268 * (This doesn't check $user's permissions.)
1269 * @return Status On success, the value member contains the
1270 * archive name, or an empty string if it was a new file.
1272 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1273 $timestamp = false, $user = null, $tags = []
1275 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1276 return $this->readOnlyFatalStatus();
1279 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1281 if ( $this->repo
->isVirtualUrl( $srcPath )
1282 || FileBackend
::isStoragePath( $srcPath )
1284 $props = $this->repo
->getFileProps( $srcPath );
1286 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1287 $props = $mwProps->getPropsFromPath( $srcPath, true );
1292 $handler = MediaHandler
::getHandler( $props['mime'] );
1294 $metadata = MediaWiki\
quietCall( 'unserialize', $props['metadata'] );
1296 if ( !is_array( $metadata ) ) {
1300 $options['headers'] = $handler->getContentHeaders( $metadata );
1302 $options['headers'] = [];
1305 // Trim spaces on user supplied text
1306 $comment = trim( $comment );
1308 $this->lock(); // begin
1309 $status = $this->publish( $src, $flags, $options );
1311 if ( $status->successCount
>= 2 ) {
1312 // There will be a copy+(one of move,copy,store).
1313 // The first succeeding does not commit us to updating the DB
1314 // since it simply copied the current version to a timestamped file name.
1315 // It is only *preferable* to avoid leaving such files orphaned.
1316 // Once the second operation goes through, then the current version was
1317 // updated and we must therefore update the DB too.
1318 $oldver = $status->value
;
1319 $uploadStatus = $this->recordUpload2(
1328 if ( !$uploadStatus->isOK() ) {
1329 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1330 // update filenotfound error with more specific path
1331 $status->fatal( 'filenotfound', $srcPath );
1333 $status->merge( $uploadStatus );
1338 $this->unlock(); // done
1344 * Record a file upload in the upload log and the image table
1345 * @param string $oldver
1346 * @param string $desc
1347 * @param string $license
1348 * @param string $copyStatus
1349 * @param string $source
1350 * @param bool $watch
1351 * @param string|bool $timestamp
1352 * @param User|null $user User object or null to use $wgUser
1355 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1356 $watch = false, $timestamp = false, User
$user = null ) {
1362 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1364 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1369 $user->addWatch( $this->getTitle() );
1376 * Record a file upload in the upload log and the image table
1377 * @param string $oldver
1378 * @param string $comment
1379 * @param string $pageText
1380 * @param bool|array $props
1381 * @param string|bool $timestamp
1382 * @param null|User $user
1383 * @param string[] $tags
1386 function recordUpload2(
1387 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1389 global $wgCommentTableSchemaMigrationStage;
1391 if ( is_null( $user ) ) {
1396 $dbw = $this->repo
->getMasterDB();
1398 # Imports or such might force a certain timestamp; otherwise we generate
1399 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1400 if ( $timestamp === false ) {
1401 $timestamp = $dbw->timestamp();
1402 $allowTimeKludge = true;
1404 $allowTimeKludge = false;
1407 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1408 $props['description'] = $comment;
1409 $props['user'] = $user->getId();
1410 $props['user_text'] = $user->getName();
1411 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1412 $this->setProps( $props );
1414 # Fail now if the file isn't there
1415 if ( !$this->fileExists
) {
1416 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1418 return Status
::newFatal( 'filenotfound', $this->getRel() );
1421 $dbw->startAtomic( __METHOD__
);
1423 # Test to see if the row exists using INSERT IGNORE
1424 # This avoids race conditions by locking the row until the commit, and also
1425 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1426 $commentStore = new CommentStore( 'img_description' );
1427 list( $commentFields, $commentCallback ) =
1428 $commentStore->insertWithTempTable( $dbw, $comment );
1429 $dbw->insert( 'image',
1431 'img_name' => $this->getName(),
1432 'img_size' => $this->size
,
1433 'img_width' => intval( $this->width
),
1434 'img_height' => intval( $this->height
),
1435 'img_bits' => $this->bits
,
1436 'img_media_type' => $this->media_type
,
1437 'img_major_mime' => $this->major_mime
,
1438 'img_minor_mime' => $this->minor_mime
,
1439 'img_timestamp' => $timestamp,
1440 'img_user' => $user->getId(),
1441 'img_user_text' => $user->getName(),
1442 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1443 'img_sha1' => $this->sha1
1448 $reupload = ( $dbw->affectedRows() == 0 );
1451 $row = $dbw->selectRow(
1453 [ 'img_timestamp', 'img_sha1' ],
1454 [ 'img_name' => $this->getName() ],
1456 [ 'LOCK IN SHARE MODE' ]
1459 if ( $row && $row->img_sha1
=== $this->sha1
) {
1460 $dbw->endAtomic( __METHOD__
);
1461 wfDebug( __METHOD__
. ": File " . $this->getRel() . " already exists!\n" );
1462 $title = Title
::newFromText( $this->getName(), NS_FILE
);
1463 return Status
::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1466 if ( $allowTimeKludge ) {
1467 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1468 $lUnixtime = $row ?
wfTimestamp( TS_UNIX
, $row->img_timestamp
) : false;
1469 # Avoid a timestamp that is not newer than the last version
1470 # TODO: the image/oldimage tables should be like page/revision with an ID field
1471 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1472 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1473 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1474 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1478 $tables = [ 'image' ];
1480 'oi_name' => 'img_name',
1481 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1482 'oi_size' => 'img_size',
1483 'oi_width' => 'img_width',
1484 'oi_height' => 'img_height',
1485 'oi_bits' => 'img_bits',
1486 'oi_timestamp' => 'img_timestamp',
1487 'oi_user' => 'img_user',
1488 'oi_user_text' => 'img_user_text',
1489 'oi_metadata' => 'img_metadata',
1490 'oi_media_type' => 'img_media_type',
1491 'oi_major_mime' => 'img_major_mime',
1492 'oi_minor_mime' => 'img_minor_mime',
1493 'oi_sha1' => 'img_sha1',
1497 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
1498 $fields['oi_description'] = 'img_description';
1500 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1501 $tables[] = 'image_comment_temp';
1502 $fields['oi_description_id'] = 'imgcomment_description_id';
1503 $joins['image_comment_temp'] = [
1504 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
1505 [ 'imgcomment_name = img_name' ]
1509 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
1510 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1512 // Upgrade any rows that are still old-style. Otherwise an upgrade
1513 // might be missed if a deletion happens while the migration script
1515 $res = $dbw->select(
1516 [ 'image', 'image_comment_temp' ],
1517 [ 'img_name', 'img_description' ],
1518 [ 'img_name' => $this->getName(), 'imgcomment_name' => null ],
1521 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1523 foreach ( $res as $row ) {
1524 list( , $callback ) = $commentStore->insertWithTempTable( $dbw, $row->img_description
);
1525 $callback( $row->img_name
);
1529 # (T36993) Note: $oldver can be empty here, if the previous
1530 # version of the file was broken. Allow registration of the new
1531 # version to continue anyway, because that's better than having
1532 # an image that's not fixable by user operations.
1533 # Collision, this is an update of a file
1534 # Insert previous contents into oldimage
1535 $dbw->insertSelect( 'oldimage', $tables, $fields,
1536 [ 'img_name' => $this->getName() ], __METHOD__
, [], [], $joins );
1538 # Update the current image row
1539 $dbw->update( 'image',
1541 'img_size' => $this->size
,
1542 'img_width' => intval( $this->width
),
1543 'img_height' => intval( $this->height
),
1544 'img_bits' => $this->bits
,
1545 'img_media_type' => $this->media_type
,
1546 'img_major_mime' => $this->major_mime
,
1547 'img_minor_mime' => $this->minor_mime
,
1548 'img_timestamp' => $timestamp,
1549 'img_user' => $user->getId(),
1550 'img_user_text' => $user->getName(),
1551 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1552 'img_sha1' => $this->sha1
1554 [ 'img_name' => $this->getName() ],
1557 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
1558 // So $commentCallback can insert the new row
1559 $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__
);
1562 $commentCallback( $this->getName() );
1564 $descTitle = $this->getTitle();
1565 $descId = $descTitle->getArticleID();
1566 $wikiPage = new WikiFilePage( $descTitle );
1567 $wikiPage->setFile( $this );
1569 // Add the log entry...
1570 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1571 $logEntry->setTimestamp( $this->timestamp
);
1572 $logEntry->setPerformer( $user );
1573 $logEntry->setComment( $comment );
1574 $logEntry->setTarget( $descTitle );
1575 // Allow people using the api to associate log entries with the upload.
1576 // Log has a timestamp, but sometimes different from upload timestamp.
1577 $logEntry->setParameters(
1579 'img_sha1' => $this->sha1
,
1580 'img_timestamp' => $timestamp,
1583 // Note we keep $logId around since during new image
1584 // creation, page doesn't exist yet, so log_page = 0
1585 // but we want it to point to the page we're making,
1586 // so we later modify the log entry.
1587 // For a similar reason, we avoid making an RC entry
1588 // now and wait until the page exists.
1589 $logId = $logEntry->insert();
1591 if ( $descTitle->exists() ) {
1592 // Use own context to get the action text in content language
1593 $formatter = LogFormatter
::newFromEntry( $logEntry );
1594 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1595 $editSummary = $formatter->getPlainActionText();
1597 $nullRevision = Revision
::newNullRevision(
1604 if ( $nullRevision ) {
1605 $nullRevision->insertOn( $dbw );
1607 'NewRevisionFromEditComplete',
1608 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1610 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1611 // Associate null revision id
1612 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1615 $newPageContent = null;
1617 // Make the description page and RC log entry post-commit
1618 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1621 # Defer purges, page creation, and link updates in case they error out.
1622 # The most important thing is that files and the DB registry stay synced.
1623 $dbw->endAtomic( __METHOD__
);
1625 # Do some cache purges after final commit so that:
1626 # a) Changes are more likely to be seen post-purge
1627 # b) They won't cause rollback of the log publish/update above
1628 DeferredUpdates
::addUpdate(
1629 new AutoCommitUpdate(
1633 $reupload, $wikiPage, $newPageContent, $comment, $user,
1634 $logEntry, $logId, $descId, $tags
1636 # Update memcache after the commit
1637 $this->invalidateCache();
1639 $updateLogPage = false;
1640 if ( $newPageContent ) {
1641 # New file page; create the description page.
1642 # There's already a log entry, so don't make a second RC entry
1643 # CDN and file cache for the description page are purged by doEditContent.
1644 $status = $wikiPage->doEditContent(
1647 EDIT_NEW | EDIT_SUPPRESS_RC
,
1652 if ( isset( $status->value
['revision'] ) ) {
1653 /** @var Revision $rev */
1654 $rev = $status->value
['revision'];
1655 // Associate new page revision id
1656 $logEntry->setAssociatedRevId( $rev->getId() );
1658 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1659 // which is triggered on $descTitle by doEditContent() above.
1660 if ( isset( $status->value
['revision'] ) ) {
1661 /** @var Revision $rev */
1662 $rev = $status->value
['revision'];
1663 $updateLogPage = $rev->getPage();
1666 # Existing file page: invalidate description page cache
1667 $wikiPage->getTitle()->invalidateCache();
1668 $wikiPage->getTitle()->purgeSquid();
1669 # Allow the new file version to be patrolled from the page footer
1670 Article
::purgePatrolFooterCache( $descId );
1673 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1674 # but setAssociatedRevId() wasn't called at that point yet...
1675 $logParams = $logEntry->getParameters();
1676 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1677 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1678 if ( $updateLogPage ) {
1679 # Also log page, in case where we just created it above
1680 $update['log_page'] = $updateLogPage;
1682 $this->getRepo()->getMasterDB()->update(
1685 [ 'log_id' => $logId ],
1688 $this->getRepo()->getMasterDB()->insert(
1691 'ls_field' => 'associated_rev_id',
1692 'ls_value' => $logEntry->getAssociatedRevId(),
1693 'ls_log_id' => $logId,
1698 # Add change tags, if any
1700 $logEntry->setTags( $tags );
1703 # Uploads can be patrolled
1704 $logEntry->setIsPatrollable( true );
1706 # Now that the log entry is up-to-date, make an RC entry.
1707 $logEntry->publish( $logId );
1709 # Run hook for other updates (typically more cache purging)
1710 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1713 # Delete old thumbnails
1714 $this->purgeThumbnails();
1715 # Remove the old file from the CDN cache
1716 DeferredUpdates
::addUpdate(
1717 new CdnCacheUpdate( [ $this->getUrl() ] ),
1718 DeferredUpdates
::PRESEND
1721 # Update backlink pages pointing to this title if created
1722 LinksUpdate
::queueRecursiveJobsForTable(
1730 $this->prerenderThumbnails();
1733 DeferredUpdates
::PRESEND
1737 # This is a new file, so update the image count
1738 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1741 # Invalidate cache for all pages using this file
1742 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1744 return Status
::newGood();
1748 * Move or copy a file to its public location. If a file exists at the
1749 * destination, move it to an archive. Returns a Status object with
1750 * the archive name in the "value" member on success.
1752 * The archive name should be passed through to recordUpload for database
1755 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1756 * @param int $flags A bitwise combination of:
1757 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1758 * @param array $options Optional additional parameters
1759 * @return Status On success, the value member contains the
1760 * archive name, or an empty string if it was a new file.
1762 function publish( $src, $flags = 0, array $options = [] ) {
1763 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1767 * Move or copy a file to a specified location. Returns a Status
1768 * object with the archive name in the "value" member on success.
1770 * The archive name should be passed through to recordUpload for database
1773 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1774 * @param string $dstRel Target relative path
1775 * @param int $flags A bitwise combination of:
1776 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1777 * @param array $options Optional additional parameters
1778 * @return Status On success, the value member contains the
1779 * archive name, or an empty string if it was a new file.
1781 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1782 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1784 $repo = $this->getRepo();
1785 if ( $repo->getReadOnlyReason() !== false ) {
1786 return $this->readOnlyFatalStatus();
1789 $this->lock(); // begin
1791 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1792 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1794 if ( $repo->hasSha1Storage() ) {
1795 $sha1 = $repo->isVirtualUrl( $srcPath )
1796 ?
$repo->getFileSha1( $srcPath )
1797 : FSFile
::getSha1Base36FromPath( $srcPath );
1798 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1799 $wrapperBackend = $repo->getBackend();
1800 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1801 $status = $repo->quickImport( $src, $dst );
1802 if ( $flags & File
::DELETE_SOURCE
) {
1806 if ( $this->exists() ) {
1807 $status->value
= $archiveName;
1810 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1811 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1813 if ( $status->value
== 'new' ) {
1814 $status->value
= '';
1816 $status->value
= $archiveName;
1820 $this->unlock(); // done
1825 /** getLinksTo inherited */
1826 /** getExifData inherited */
1827 /** isLocal inherited */
1828 /** wasDeleted inherited */
1831 * Move file to the new title
1833 * Move current, old version and all thumbnails
1834 * to the new filename. Old file is deleted.
1836 * Cache purging is done; checks for validity
1837 * and logging are caller's responsibility
1839 * @param Title $target New file name
1842 function move( $target ) {
1843 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1844 return $this->readOnlyFatalStatus();
1847 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1848 $batch = new LocalFileMoveBatch( $this, $target );
1850 $this->lock(); // begin
1851 $batch->addCurrent();
1852 $archiveNames = $batch->addOlds();
1853 $status = $batch->execute();
1854 $this->unlock(); // done
1856 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1858 // Purge the source and target files...
1859 $oldTitleFile = wfLocalFile( $this->title
);
1860 $newTitleFile = wfLocalFile( $target );
1861 // To avoid slow purges in the transaction, move them outside...
1862 DeferredUpdates
::addUpdate(
1863 new AutoCommitUpdate(
1864 $this->getRepo()->getMasterDB(),
1866 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1867 $oldTitleFile->purgeEverything();
1868 foreach ( $archiveNames as $archiveName ) {
1869 $oldTitleFile->purgeOldThumbnails( $archiveName );
1871 $newTitleFile->purgeEverything();
1874 DeferredUpdates
::PRESEND
1877 if ( $status->isOK() ) {
1878 // Now switch the object
1879 $this->title
= $target;
1880 // Force regeneration of the name and hashpath
1881 unset( $this->name
);
1882 unset( $this->hashPath
);
1889 * Delete all versions of the file.
1891 * Moves the files into an archive directory (or deletes them)
1892 * and removes the database rows.
1894 * Cache purging is done; logging is caller's responsibility.
1896 * @param string $reason
1897 * @param bool $suppress
1898 * @param User|null $user
1901 function delete( $reason, $suppress = false, $user = null ) {
1902 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1903 return $this->readOnlyFatalStatus();
1906 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1908 $this->lock(); // begin
1909 $batch->addCurrent();
1910 // Get old version relative paths
1911 $archiveNames = $batch->addOlds();
1912 $status = $batch->execute();
1913 $this->unlock(); // done
1915 if ( $status->isOK() ) {
1916 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1919 // To avoid slow purges in the transaction, move them outside...
1920 DeferredUpdates
::addUpdate(
1921 new AutoCommitUpdate(
1922 $this->getRepo()->getMasterDB(),
1924 function () use ( $archiveNames ) {
1925 $this->purgeEverything();
1926 foreach ( $archiveNames as $archiveName ) {
1927 $this->purgeOldThumbnails( $archiveName );
1931 DeferredUpdates
::PRESEND
1936 foreach ( $archiveNames as $archiveName ) {
1937 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1939 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1945 * Delete an old version of the file.
1947 * Moves the file into an archive directory (or deletes it)
1948 * and removes the database row.
1950 * Cache purging is done; logging is caller's responsibility.
1952 * @param string $archiveName
1953 * @param string $reason
1954 * @param bool $suppress
1955 * @param User|null $user
1956 * @throws MWException Exception on database or file store failure
1959 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1960 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1961 return $this->readOnlyFatalStatus();
1964 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1966 $this->lock(); // begin
1967 $batch->addOld( $archiveName );
1968 $status = $batch->execute();
1969 $this->unlock(); // done
1971 $this->purgeOldThumbnails( $archiveName );
1972 if ( $status->isOK() ) {
1973 $this->purgeDescription();
1976 DeferredUpdates
::addUpdate(
1977 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1978 DeferredUpdates
::PRESEND
1985 * Restore all or specified deleted revisions to the given file.
1986 * Permissions and logging are left to the caller.
1988 * May throw database exceptions on error.
1990 * @param array $versions Set of record ids of deleted items to restore,
1991 * or empty to restore all revisions.
1992 * @param bool $unsuppress
1995 function restore( $versions = [], $unsuppress = false ) {
1996 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1997 return $this->readOnlyFatalStatus();
2000 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2002 $this->lock(); // begin
2006 $batch->addIds( $versions );
2008 $status = $batch->execute();
2009 if ( $status->isGood() ) {
2010 $cleanupStatus = $batch->cleanup();
2011 $cleanupStatus->successCount
= 0;
2012 $cleanupStatus->failCount
= 0;
2013 $status->merge( $cleanupStatus );
2015 $this->unlock(); // done
2020 /** isMultipage inherited */
2021 /** pageCount inherited */
2022 /** scaleHeight inherited */
2023 /** getImageSize inherited */
2026 * Get the URL of the file description page.
2029 function getDescriptionUrl() {
2030 return $this->title
->getLocalURL();
2034 * Get the HTML text of the description page
2035 * This is not used by ImagePage for local files, since (among other things)
2036 * it skips the parser cache.
2038 * @param Language $lang What language to get description in (Optional)
2039 * @return bool|mixed
2041 function getDescriptionText( $lang = null ) {
2042 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
2046 $content = $revision->getContent();
2050 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
2052 return $pout->getText();
2056 * @param int $audience
2060 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2062 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
2064 } elseif ( $audience == self
::FOR_THIS_USER
2065 && !$this->userCan( self
::DELETED_COMMENT
, $user )
2069 return $this->description
;
2074 * @return bool|string
2076 function getTimestamp() {
2079 return $this->timestamp
;
2083 * @return bool|string
2085 public function getDescriptionTouched() {
2086 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2087 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2088 // need to differentiate between null (uninitialized) and false (failed to load).
2089 if ( $this->descriptionTouched
=== null ) {
2091 'page_namespace' => $this->title
->getNamespace(),
2092 'page_title' => $this->title
->getDBkey()
2094 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
2095 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
2098 return $this->descriptionTouched
;
2104 function getSha1() {
2106 // Initialise now if necessary
2107 if ( $this->sha1
== '' && $this->fileExists
) {
2108 $this->lock(); // begin
2110 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
2111 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
2112 $dbw = $this->repo
->getMasterDB();
2113 $dbw->update( 'image',
2114 [ 'img_sha1' => $this->sha1
],
2115 [ 'img_name' => $this->getName() ],
2117 $this->invalidateCache();
2120 $this->unlock(); // done
2127 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2129 function isCacheable() {
2132 // If extra data (metadata) was not loaded then it must have been large
2133 return $this->extraDataLoaded
2134 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
2141 public function acquireFileLock() {
2142 return $this->getRepo()->getBackend()->lockFiles(
2143 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
2151 public function releaseFileLock() {
2152 return $this->getRepo()->getBackend()->unlockFiles(
2153 [ $this->getPath() ], LockManager
::LOCK_EX
2158 * Start an atomic DB section and lock the image for update
2159 * or increments a reference counter if the lock is already held
2161 * This method should not be used outside of LocalFile/LocalFile*Batch
2163 * @throws LocalFileLockError Throws an error if the lock was not acquired
2164 * @return bool Whether the file lock owns/spawned the DB transaction
2166 public function lock() {
2167 if ( !$this->locked
) {
2168 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2170 $dbw = $this->repo
->getMasterDB();
2171 $makesTransaction = !$dbw->trxLevel();
2172 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2173 // T56736: use simple lock to handle when the file does not exist.
2174 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2175 // Also, that would cause contention on INSERT of similarly named rows.
2176 $status = $this->acquireFileLock(); // represents all versions of the file
2177 if ( !$status->isGood() ) {
2178 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2179 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2181 throw new LocalFileLockError( $status );
2183 // Release the lock *after* commit to avoid row-level contention.
2184 // Make sure it triggers on rollback() as well as commit() (T132921).
2185 $dbw->onTransactionResolution(
2186 function () use ( $logger ) {
2187 $status = $this->releaseFileLock();
2188 if ( !$status->isGood() ) {
2189 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2194 // Callers might care if the SELECT snapshot is safely fresh
2195 $this->lockedOwnTrx
= $makesTransaction;
2200 return $this->lockedOwnTrx
;
2204 * Decrement the lock reference count and end the atomic section if it reaches zero
2206 * This method should not be used outside of LocalFile/LocalFile*Batch
2208 * The commit and loc release will happen when no atomic sections are active, which
2209 * may happen immediately or at some point after calling this
2211 public function unlock() {
2212 if ( $this->locked
) {
2214 if ( !$this->locked
) {
2215 $dbw = $this->repo
->getMasterDB();
2216 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2217 $this->lockedOwnTrx
= false;
2225 protected function readOnlyFatalStatus() {
2226 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2227 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2231 * Clean up any dangling locks
2233 function __destruct() {
2236 } // LocalFile class
2238 # ------------------------------------------------------------------------------
2241 * Helper class for file deletion
2242 * @ingroup FileAbstraction
2244 class LocalFileDeleteBatch
{
2245 /** @var LocalFile */
2252 private $srcRels = [];
2255 private $archiveUrls = [];
2257 /** @var array Items to be processed in the deletion batch */
2258 private $deletionBatch;
2260 /** @var bool Whether to suppress all suppressable fields when deleting */
2271 * @param string $reason
2272 * @param bool $suppress
2273 * @param User|null $user
2275 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2276 $this->file
= $file;
2277 $this->reason
= $reason;
2278 $this->suppress
= $suppress;
2280 $this->user
= $user;
2283 $this->user
= $wgUser;
2285 $this->status
= $file->repo
->newGood();
2288 public function addCurrent() {
2289 $this->srcRels
['.'] = $this->file
->getRel();
2293 * @param string $oldName
2295 public function addOld( $oldName ) {
2296 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2297 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2301 * Add the old versions of the image to the batch
2302 * @return array List of archive names from old versions
2304 public function addOlds() {
2307 $dbw = $this->file
->repo
->getMasterDB();
2308 $result = $dbw->select( 'oldimage',
2309 [ 'oi_archive_name' ],
2310 [ 'oi_name' => $this->file
->getName() ],
2314 foreach ( $result as $row ) {
2315 $this->addOld( $row->oi_archive_name
);
2316 $archiveNames[] = $row->oi_archive_name
;
2319 return $archiveNames;
2325 protected function getOldRels() {
2326 if ( !isset( $this->srcRels
['.'] ) ) {
2327 $oldRels =& $this->srcRels
;
2328 $deleteCurrent = false;
2330 $oldRels = $this->srcRels
;
2331 unset( $oldRels['.'] );
2332 $deleteCurrent = true;
2335 return [ $oldRels, $deleteCurrent ];
2341 protected function getHashes() {
2343 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2345 if ( $deleteCurrent ) {
2346 $hashes['.'] = $this->file
->getSha1();
2349 if ( count( $oldRels ) ) {
2350 $dbw = $this->file
->repo
->getMasterDB();
2351 $res = $dbw->select(
2353 [ 'oi_archive_name', 'oi_sha1' ],
2354 [ 'oi_archive_name' => array_keys( $oldRels ),
2355 'oi_name' => $this->file
->getName() ], // performance
2359 foreach ( $res as $row ) {
2360 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2361 // Get the hash from the file
2362 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2363 $props = $this->file
->repo
->getFileProps( $oldUrl );
2365 if ( $props['fileExists'] ) {
2366 // Upgrade the oldimage row
2367 $dbw->update( 'oldimage',
2368 [ 'oi_sha1' => $props['sha1'] ],
2369 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2371 $hashes[$row->oi_archive_name
] = $props['sha1'];
2373 $hashes[$row->oi_archive_name
] = false;
2376 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2381 $missing = array_diff_key( $this->srcRels
, $hashes );
2383 foreach ( $missing as $name => $rel ) {
2384 $this->status
->error( 'filedelete-old-unregistered', $name );
2387 foreach ( $hashes as $name => $hash ) {
2389 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2390 unset( $hashes[$name] );
2397 protected function doDBInserts() {
2398 global $wgCommentTableSchemaMigrationStage;
2401 $dbw = $this->file
->repo
->getMasterDB();
2403 $commentStoreImgDesc = new CommentStore( 'img_description' );
2404 $commentStoreOiDesc = new CommentStore( 'oi_description' );
2405 $commentStoreFaDesc = new CommentStore( 'fa_description' );
2406 $commentStoreFaReason = new CommentStore( 'fa_deleted_reason' );
2408 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2409 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2410 $encGroup = $dbw->addQuotes( 'deleted' );
2411 $ext = $this->file
->getExtension();
2412 $dotExt = $ext === '' ?
'' : ".$ext";
2413 $encExt = $dbw->addQuotes( $dotExt );
2414 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2416 // Bitfields to further suppress the content
2417 if ( $this->suppress
) {
2418 $bitfield = Revision
::SUPPRESSED_ALL
;
2420 $bitfield = 'oi_deleted';
2423 if ( $deleteCurrent ) {
2424 $tables = [ 'image' ];
2426 'fa_storage_group' => $encGroup,
2427 'fa_storage_key' => $dbw->conditional(
2428 [ 'img_sha1' => '' ],
2429 $dbw->addQuotes( '' ),
2430 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2432 'fa_deleted_user' => $encUserId,
2433 'fa_deleted_timestamp' => $encTimestamp,
2434 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2435 'fa_name' => 'img_name',
2436 'fa_archive_name' => 'NULL',
2437 'fa_size' => 'img_size',
2438 'fa_width' => 'img_width',
2439 'fa_height' => 'img_height',
2440 'fa_metadata' => 'img_metadata',
2441 'fa_bits' => 'img_bits',
2442 'fa_media_type' => 'img_media_type',
2443 'fa_major_mime' => 'img_major_mime',
2444 'fa_minor_mime' => 'img_minor_mime',
2445 'fa_user' => 'img_user',
2446 'fa_user_text' => 'img_user_text',
2447 'fa_timestamp' => 'img_timestamp',
2448 'fa_sha1' => 'img_sha1'
2452 $fields +
= array_map(
2453 [ $dbw, 'addQuotes' ],
2454 $commentStoreFaReason->insert( $dbw, $this->reason
)
2457 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH
) {
2458 $fields['fa_description'] = 'img_description';
2460 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
2461 $tables[] = 'image_comment_temp';
2462 $fields['fa_description_id'] = 'imgcomment_description_id';
2463 $joins['image_comment_temp'] = [
2464 $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
2465 [ 'imgcomment_name = img_name' ]
2469 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD
&&
2470 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2472 // Upgrade any rows that are still old-style. Otherwise an upgrade
2473 // might be missed if a deletion happens while the migration script
2475 $res = $dbw->select(
2476 [ 'image', 'image_comment_temp' ],
2477 [ 'img_name', 'img_description' ],
2478 [ 'img_name' => $this->file
->getName(), 'imgcomment_name' => null ],
2481 [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2483 foreach ( $res as $row ) {
2484 list( , $callback ) = $commentStoreImgDesc->insertWithTempTable( $dbw, $row->img_description
);
2485 $callback( $row->img_name
);
2489 $dbw->insertSelect( 'filearchive', $tables, $fields,
2490 [ 'img_name' => $this->file
->getName() ], __METHOD__
, [], [], $joins );
2493 if ( count( $oldRels ) ) {
2494 $fileQuery = OldLocalFile
::getQueryInfo();
2495 $res = $dbw->select(
2496 $fileQuery['tables'],
2497 $fileQuery['fields'],
2499 'oi_name' => $this->file
->getName(),
2500 'oi_archive_name' => array_keys( $oldRels )
2507 if ( $res->numRows() ) {
2508 $reason = $commentStoreFaReason->createComment( $dbw, $this->reason
);
2509 foreach ( $res as $row ) {
2510 $comment = $commentStoreOiDesc->getComment( $row );
2512 // Deletion-specific fields
2513 'fa_storage_group' => 'deleted',
2514 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2516 : "{$row->oi_sha1}{$dotExt}",
2517 'fa_deleted_user' => $this->user
->getId(),
2518 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2519 // Counterpart fields
2520 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2521 'fa_name' => $row->oi_name
,
2522 'fa_archive_name' => $row->oi_archive_name
,
2523 'fa_size' => $row->oi_size
,
2524 'fa_width' => $row->oi_width
,
2525 'fa_height' => $row->oi_height
,
2526 'fa_metadata' => $row->oi_metadata
,
2527 'fa_bits' => $row->oi_bits
,
2528 'fa_media_type' => $row->oi_media_type
,
2529 'fa_major_mime' => $row->oi_major_mime
,
2530 'fa_minor_mime' => $row->oi_minor_mime
,
2531 'fa_user' => $row->oi_user
,
2532 'fa_user_text' => $row->oi_user_text
,
2533 'fa_timestamp' => $row->oi_timestamp
,
2534 'fa_sha1' => $row->oi_sha1
2535 ] +
$commentStoreFaReason->insert( $dbw, $reason )
2536 +
$commentStoreFaDesc->insert( $dbw, $comment );
2540 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2544 function doDBDeletes() {
2545 global $wgCommentTableSchemaMigrationStage;
2547 $dbw = $this->file
->repo
->getMasterDB();
2548 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2550 if ( count( $oldRels ) ) {
2551 $dbw->delete( 'oldimage',
2553 'oi_name' => $this->file
->getName(),
2554 'oi_archive_name' => array_keys( $oldRels )
2558 if ( $deleteCurrent ) {
2559 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2560 if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD
) {
2562 'image_comment_temp', [ 'imgcomment_name' => $this->file
->getName() ], __METHOD__
2569 * Run the transaction
2572 public function execute() {
2573 $repo = $this->file
->getRepo();
2574 $this->file
->lock();
2576 // Prepare deletion batch
2577 $hashes = $this->getHashes();
2578 $this->deletionBatch
= [];
2579 $ext = $this->file
->getExtension();
2580 $dotExt = $ext === '' ?
'' : ".$ext";
2582 foreach ( $this->srcRels
as $name => $srcRel ) {
2583 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2584 if ( isset( $hashes[$name] ) ) {
2585 $hash = $hashes[$name];
2586 $key = $hash . $dotExt;
2587 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2588 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2592 if ( !$repo->hasSha1Storage() ) {
2593 // Removes non-existent file from the batch, so we don't get errors.
2594 // This also handles files in the 'deleted' zone deleted via revision deletion.
2595 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2596 if ( !$checkStatus->isGood() ) {
2597 $this->status
->merge( $checkStatus );
2598 return $this->status
;
2600 $this->deletionBatch
= $checkStatus->value
;
2602 // Execute the file deletion batch
2603 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2604 if ( !$status->isGood() ) {
2605 $this->status
->merge( $status );
2609 if ( !$this->status
->isOK() ) {
2610 // Critical file deletion error; abort
2611 $this->file
->unlock();
2613 return $this->status
;
2616 // Copy the image/oldimage rows to filearchive
2617 $this->doDBInserts();
2618 // Delete image/oldimage rows
2619 $this->doDBDeletes();
2621 // Commit and return
2622 $this->file
->unlock();
2624 return $this->status
;
2628 * Removes non-existent files from a deletion batch.
2629 * @param array $batch
2632 protected function removeNonexistentFiles( $batch ) {
2633 $files = $newBatch = [];
2635 foreach ( $batch as $batchItem ) {
2636 list( $src, ) = $batchItem;
2637 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2640 $result = $this->file
->repo
->fileExistsBatch( $files );
2641 if ( in_array( null, $result, true ) ) {
2642 return Status
::newFatal( 'backend-fail-internal',
2643 $this->file
->repo
->getBackend()->getName() );
2646 foreach ( $batch as $batchItem ) {
2647 if ( $result[$batchItem[0]] ) {
2648 $newBatch[] = $batchItem;
2652 return Status
::newGood( $newBatch );
2656 # ------------------------------------------------------------------------------
2659 * Helper class for file undeletion
2660 * @ingroup FileAbstraction
2662 class LocalFileRestoreBatch
{
2663 /** @var LocalFile */
2666 /** @var array List of file IDs to restore */
2667 private $cleanupBatch;
2669 /** @var array List of file IDs to restore */
2672 /** @var bool Add all revisions of the file */
2675 /** @var bool Whether to remove all settings for suppressed fields */
2676 private $unsuppress = false;
2680 * @param bool $unsuppress
2682 function __construct( File
$file, $unsuppress = false ) {
2683 $this->file
= $file;
2684 $this->cleanupBatch
= $this->ids
= [];
2686 $this->unsuppress
= $unsuppress;
2693 public function addId( $fa_id ) {
2694 $this->ids
[] = $fa_id;
2698 * Add a whole lot of files by ID
2701 public function addIds( $ids ) {
2702 $this->ids
= array_merge( $this->ids
, $ids );
2706 * Add all revisions of the file
2708 public function addAll() {
2713 * Run the transaction, except the cleanup batch.
2714 * The cleanup batch should be run in a separate transaction, because it locks different
2715 * rows and there's no need to keep the image row locked while it's acquiring those locks
2716 * The caller may have its own transaction open.
2717 * So we save the batch and let the caller call cleanup()
2720 public function execute() {
2721 /** @var Language */
2724 $repo = $this->file
->getRepo();
2725 if ( !$this->all
&& !$this->ids
) {
2727 return $repo->newGood();
2730 $lockOwnsTrx = $this->file
->lock();
2732 $dbw = $this->file
->repo
->getMasterDB();
2734 $commentStoreImgDesc = new CommentStore( 'img_description' );
2735 $commentStoreOiDesc = new CommentStore( 'oi_description' );
2736 $commentStoreFaDesc = new CommentStore( 'fa_description' );
2738 $status = $this->file
->repo
->newGood();
2740 $exists = (bool)$dbw->selectField( 'image', '1',
2741 [ 'img_name' => $this->file
->getName() ],
2743 // The lock() should already prevents changes, but this still may need
2744 // to bypass any transaction snapshot. However, if lock() started the
2745 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2746 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2749 // Fetch all or selected archived revisions for the file,
2750 // sorted from the most recent to the oldest.
2751 $conditions = [ 'fa_name' => $this->file
->getName() ];
2753 if ( !$this->all
) {
2754 $conditions['fa_id'] = $this->ids
;
2757 $arFileQuery = ArchivedFile
::getQueryInfo();
2758 $result = $dbw->select(
2759 $arFileQuery['tables'],
2760 $arFileQuery['fields'],
2763 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2764 $arFileQuery['joins']
2770 $insertCurrent = false;
2775 foreach ( $result as $row ) {
2776 $idsPresent[] = $row->fa_id
;
2778 if ( $row->fa_name
!= $this->file
->getName() ) {
2779 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2780 $status->failCount++
;
2784 if ( $row->fa_storage_key
== '' ) {
2785 // Revision was missing pre-deletion
2786 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2787 $status->failCount++
;
2791 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2792 $row->fa_storage_key
;
2793 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2795 if ( isset( $row->fa_sha1
) ) {
2796 $sha1 = $row->fa_sha1
;
2798 // old row, populate from key
2799 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2803 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2804 $sha1 = substr( $sha1, 1 );
2807 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2808 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2809 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2810 ||
is_null( $row->fa_metadata
)
2812 // Refresh our metadata
2813 // Required for a new current revision; nice for older ones too. :)
2814 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2817 'minor_mime' => $row->fa_minor_mime
,
2818 'major_mime' => $row->fa_major_mime
,
2819 'media_type' => $row->fa_media_type
,
2820 'metadata' => $row->fa_metadata
2824 $comment = $commentStoreFaDesc->getComment( $row );
2825 if ( $first && !$exists ) {
2826 // This revision will be published as the new current version
2827 $destRel = $this->file
->getRel();
2828 list( $commentFields, $commentCallback ) =
2829 $commentStoreImgDesc->insertWithTempTable( $dbw, $comment );
2831 'img_name' => $row->fa_name
,
2832 'img_size' => $row->fa_size
,
2833 'img_width' => $row->fa_width
,
2834 'img_height' => $row->fa_height
,
2835 'img_metadata' => $props['metadata'],
2836 'img_bits' => $row->fa_bits
,
2837 'img_media_type' => $props['media_type'],
2838 'img_major_mime' => $props['major_mime'],
2839 'img_minor_mime' => $props['minor_mime'],
2840 'img_user' => $row->fa_user
,
2841 'img_user_text' => $row->fa_user_text
,
2842 'img_timestamp' => $row->fa_timestamp
,
2846 // The live (current) version cannot be hidden!
2847 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2848 $status->fatal( 'undeleterevdel' );
2849 $this->file
->unlock();
2853 $archiveName = $row->fa_archive_name
;
2855 if ( $archiveName == '' ) {
2856 // This was originally a current version; we
2857 // have to devise a new archive name for it.
2858 // Format is <timestamp of archiving>!<name>
2859 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2862 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2864 } while ( isset( $archiveNames[$archiveName] ) );
2867 $archiveNames[$archiveName] = true;
2868 $destRel = $this->file
->getArchiveRel( $archiveName );
2870 'oi_name' => $row->fa_name
,
2871 'oi_archive_name' => $archiveName,
2872 'oi_size' => $row->fa_size
,
2873 'oi_width' => $row->fa_width
,
2874 'oi_height' => $row->fa_height
,
2875 'oi_bits' => $row->fa_bits
,
2876 'oi_user' => $row->fa_user
,
2877 'oi_user_text' => $row->fa_user_text
,
2878 'oi_timestamp' => $row->fa_timestamp
,
2879 'oi_metadata' => $props['metadata'],
2880 'oi_media_type' => $props['media_type'],
2881 'oi_major_mime' => $props['major_mime'],
2882 'oi_minor_mime' => $props['minor_mime'],
2883 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2885 ] +
$commentStoreOiDesc->insert( $dbw, $comment );
2888 $deleteIds[] = $row->fa_id
;
2890 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2891 // private files can stay where they are
2892 $status->successCount++
;
2894 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2895 $this->cleanupBatch
[] = $row->fa_storage_key
;
2903 // Add a warning to the status object for missing IDs
2904 $missingIds = array_diff( $this->ids
, $idsPresent );
2906 foreach ( $missingIds as $id ) {
2907 $status->error( 'undelete-missing-filearchive', $id );
2910 if ( !$repo->hasSha1Storage() ) {
2911 // Remove missing files from batch, so we don't get errors when undeleting them
2912 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2913 if ( !$checkStatus->isGood() ) {
2914 $status->merge( $checkStatus );
2917 $storeBatch = $checkStatus->value
;
2919 // Run the store batch
2920 // Use the OVERWRITE_SAME flag to smooth over a common error
2921 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2922 $status->merge( $storeStatus );
2924 if ( !$status->isGood() ) {
2925 // Even if some files could be copied, fail entirely as that is the
2926 // easiest thing to do without data loss
2927 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2928 $status->setOK( false );
2929 $this->file
->unlock();
2935 // Run the DB updates
2936 // Because we have locked the image row, key conflicts should be rare.
2937 // If they do occur, we can roll back the transaction at this time with
2938 // no data loss, but leaving unregistered files scattered throughout the
2940 // This is not ideal, which is why it's important to lock the image row.
2941 if ( $insertCurrent ) {
2942 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2943 $commentCallback( $insertCurrent['img_name'] );
2946 if ( $insertBatch ) {
2947 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2951 $dbw->delete( 'filearchive',
2952 [ 'fa_id' => $deleteIds ],
2956 // If store batch is empty (all files are missing), deletion is to be considered successful
2957 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2959 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2961 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2963 $this->file
->purgeEverything();
2965 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2966 $this->file
->purgeDescription();
2970 $this->file
->unlock();
2976 * Removes non-existent files from a store batch.
2977 * @param array $triplets
2980 protected function removeNonexistentFiles( $triplets ) {
2981 $files = $filteredTriplets = [];
2982 foreach ( $triplets as $file ) {
2983 $files[$file[0]] = $file[0];
2986 $result = $this->file
->repo
->fileExistsBatch( $files );
2987 if ( in_array( null, $result, true ) ) {
2988 return Status
::newFatal( 'backend-fail-internal',
2989 $this->file
->repo
->getBackend()->getName() );
2992 foreach ( $triplets as $file ) {
2993 if ( $result[$file[0]] ) {
2994 $filteredTriplets[] = $file;
2998 return Status
::newGood( $filteredTriplets );
3002 * Removes non-existent files from a cleanup batch.
3003 * @param array $batch
3006 protected function removeNonexistentFromCleanup( $batch ) {
3007 $files = $newBatch = [];
3008 $repo = $this->file
->repo
;
3010 foreach ( $batch as $file ) {
3011 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3012 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3015 $result = $repo->fileExistsBatch( $files );
3017 foreach ( $batch as $file ) {
3018 if ( $result[$file] ) {
3019 $newBatch[] = $file;
3027 * Delete unused files in the deleted zone.
3028 * This should be called from outside the transaction in which execute() was called.
3031 public function cleanup() {
3032 if ( !$this->cleanupBatch
) {
3033 return $this->file
->repo
->newGood();
3036 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
3038 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
3044 * Cleanup a failed batch. The batch was only partially successful, so
3045 * rollback by removing all items that were succesfully copied.
3047 * @param Status $storeStatus
3048 * @param array $storeBatch
3050 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3053 foreach ( $storeStatus->success
as $i => $success ) {
3054 // Check if this item of the batch was successfully copied
3056 // Item was successfully copied and needs to be removed again
3057 // Extract ($dstZone, $dstRel) from the batch
3058 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3061 $this->file
->repo
->cleanupBatch( $cleanupBatch );
3065 # ------------------------------------------------------------------------------
3068 * Helper class for file movement
3069 * @ingroup FileAbstraction
3071 class LocalFileMoveBatch
{
3072 /** @var LocalFile */
3082 protected $oldCount;
3086 /** @var IDatabase */
3091 * @param Title $target
3093 function __construct( File
$file, Title
$target ) {
3094 $this->file
= $file;
3095 $this->target
= $target;
3096 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
3097 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
3098 $this->oldName
= $this->file
->getName();
3099 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
3100 $this->oldRel
= $this->oldHash
. $this->oldName
;
3101 $this->newRel
= $this->newHash
. $this->newName
;
3102 $this->db
= $file->getRepo()->getMasterDB();
3106 * Add the current image to the batch
3108 public function addCurrent() {
3109 $this->cur
= [ $this->oldRel
, $this->newRel
];
3113 * Add the old versions of the image to the batch
3114 * @return array List of archive names from old versions
3116 public function addOlds() {
3117 $archiveBase = 'archive';
3119 $this->oldCount
= 0;
3122 $result = $this->db
->select( 'oldimage',
3123 [ 'oi_archive_name', 'oi_deleted' ],
3124 [ 'oi_name' => $this->oldName
],
3126 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3129 foreach ( $result as $row ) {
3130 $archiveNames[] = $row->oi_archive_name
;
3131 $oldName = $row->oi_archive_name
;
3132 $bits = explode( '!', $oldName, 2 );
3134 if ( count( $bits ) != 2 ) {
3135 wfDebug( "Old file name missing !: '$oldName' \n" );
3139 list( $timestamp, $filename ) = $bits;
3141 if ( $this->oldName
!= $filename ) {
3142 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3148 // Do we want to add those to oldCount?
3149 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
3154 "{$archiveBase}/{$this->oldHash}{$oldName}",
3155 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3159 return $archiveNames;
3166 public function execute() {
3167 $repo = $this->file
->repo
;
3168 $status = $repo->newGood();
3169 $destFile = wfLocalFile( $this->target
);
3171 $this->file
->lock(); // begin
3172 $destFile->lock(); // quickly fail if destination is not available
3174 $triplets = $this->getMoveTriplets();
3175 $checkStatus = $this->removeNonexistentFiles( $triplets );
3176 if ( !$checkStatus->isGood() ) {
3177 $destFile->unlock();
3178 $this->file
->unlock();
3179 $status->merge( $checkStatus ); // couldn't talk to file backend
3182 $triplets = $checkStatus->value
;
3184 // Verify the file versions metadata in the DB.
3185 $statusDb = $this->verifyDBUpdates();
3186 if ( !$statusDb->isGood() ) {
3187 $destFile->unlock();
3188 $this->file
->unlock();
3189 $statusDb->setOK( false );
3194 if ( !$repo->hasSha1Storage() ) {
3195 // Copy the files into their new location.
3196 // If a prior process fataled copying or cleaning up files we tolerate any
3197 // of the existing files if they are identical to the ones being stored.
3198 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
3199 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3200 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3201 if ( !$statusMove->isGood() ) {
3202 // Delete any files copied over (while the destination is still locked)
3203 $this->cleanupTarget( $triplets );
3204 $destFile->unlock();
3205 $this->file
->unlock();
3206 wfDebugLog( 'imagemove', "Error in moving files: "
3207 . $statusMove->getWikiText( false, false, 'en' ) );
3208 $statusMove->setOK( false );
3212 $status->merge( $statusMove );
3215 // Rename the file versions metadata in the DB.
3216 $this->doDBUpdates();
3218 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3219 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3221 $destFile->unlock();
3222 $this->file
->unlock(); // done
3224 // Everything went ok, remove the source files
3225 $this->cleanupSource( $triplets );
3227 $status->merge( $statusDb );
3233 * Verify the database updates and return a new Status indicating how
3234 * many rows would be updated.
3238 protected function verifyDBUpdates() {
3239 $repo = $this->file
->repo
;
3240 $status = $repo->newGood();
3243 $hasCurrent = $dbw->selectField(
3246 [ 'img_name' => $this->oldName
],
3250 $oldRowCount = $dbw->selectField(
3253 [ 'oi_name' => $this->oldName
],
3258 if ( $hasCurrent ) {
3259 $status->successCount++
;
3261 $status->failCount++
;
3263 $status->successCount +
= $oldRowCount;
3264 // T36934: oldCount is based on files that actually exist.
3265 // There may be more DB rows than such files, in which case $affected
3266 // can be greater than $total. We use max() to avoid negatives here.
3267 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3268 if ( $status->failCount
) {
3269 $status->error( 'imageinvalidfilename' );
3276 * Do the database updates and return a new Status indicating how
3277 * many rows where updated.
3279 protected function doDBUpdates() {
3282 // Update current image
3285 [ 'img_name' => $this->newName
],
3286 [ 'img_name' => $this->oldName
],
3289 // Update old images
3293 'oi_name' => $this->newName
,
3294 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3295 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3297 [ 'oi_name' => $this->oldName
],
3303 * Generate triplets for FileRepo::storeBatch().
3306 protected function getMoveTriplets() {
3307 $moves = array_merge( [ $this->cur
], $this->olds
);
3308 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3310 foreach ( $moves as $move ) {
3311 // $move: (oldRelativePath, newRelativePath)
3312 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3313 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3316 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3324 * Removes non-existent files from move batch.
3325 * @param array $triplets
3328 protected function removeNonexistentFiles( $triplets ) {
3331 foreach ( $triplets as $file ) {
3332 $files[$file[0]] = $file[0];
3335 $result = $this->file
->repo
->fileExistsBatch( $files );
3336 if ( in_array( null, $result, true ) ) {
3337 return Status
::newFatal( 'backend-fail-internal',
3338 $this->file
->repo
->getBackend()->getName() );
3341 $filteredTriplets = [];
3342 foreach ( $triplets as $file ) {
3343 if ( $result[$file[0]] ) {
3344 $filteredTriplets[] = $file;
3346 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3350 return Status
::newGood( $filteredTriplets );
3354 * Cleanup a partially moved array of triplets by deleting the target
3355 * files. Called if something went wrong half way.
3356 * @param array $triplets
3358 protected function cleanupTarget( $triplets ) {
3359 // Create dest pairs from the triplets
3361 foreach ( $triplets as $triplet ) {
3362 // $triplet: (old source virtual URL, dst zone, dest rel)
3363 $pairs[] = [ $triplet[1], $triplet[2] ];
3366 $this->file
->repo
->cleanupBatch( $pairs );
3370 * Cleanup a fully moved array of triplets by deleting the source files.
3371 * Called at the end of the move process if everything else went ok.
3372 * @param array $triplets
3374 protected function cleanupSource( $triplets ) {
3375 // Create source file names from the triplets
3377 foreach ( $triplets as $triplet ) {
3378 $files[] = $triplet[0];
3381 $this->file
->repo
->cleanupBatch( $files );
3385 class LocalFileLockError
extends ErrorPageError
{
3386 public function __construct( Status
$status ) {
3387 parent
::__construct(
3389 $status->getMessage()
3393 public function report() {
3395 $wgOut->setStatusCode( 429 );