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
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 9 );
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const CACHE_FIELD_MAX_LEN
= 1000;
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
52 /** @var int Image width */
55 /** @var int Image height */
58 /** @var int Returned by getimagesize (loadFromXxx) */
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
67 /** @var int Size in bytes (loadFromXxx) */
70 /** @var string Handler-specific metadata */
73 /** @var string SHA-1 base 36 content hash */
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
82 /** @var int Bitfield akin to rev_deleted */
86 protected $repoClass = 'LocalRepo';
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
94 /** @var string Major MIME type */
97 /** @var string Minor MIME type */
100 /** @var string Upload timestamp */
103 /** @var int User ID of uploader */
106 /** @var string User name of uploader */
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var string TS_MW timestamp of the last change of the file description */
113 private $descriptionTouched;
115 /** @var bool Whether the row was upgraded on load */
118 /** @var bool True if the image row is locked */
121 /** @var bool True if the image row is locked with a lock initiated transaction */
122 private $lockedOwnTrx;
124 /** @var bool True if file is not present in file system. Not to be cached in memcached */
127 // @note: higher than IDBAccessObject constants
128 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
131 * Create a LocalFile from a title
132 * Do not call this except from inside a repo class.
134 * Note: $unused param is only here to avoid an E_STRICT
136 * @param Title $title
137 * @param FileRepo $repo
138 * @param null $unused
142 static function newFromTitle( $title, $repo, $unused = null ) {
143 return new self( $title, $repo );
147 * Create a LocalFile from a title
148 * Do not call this except from inside a repo class.
150 * @param stdClass $row
151 * @param FileRepo $repo
155 static function newFromRow( $row, $repo ) {
156 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
157 $file = new self( $title, $repo );
158 $file->loadFromRow( $row );
164 * Create a LocalFile from a SHA-1 key
165 * Do not call this except from inside a repo class.
167 * @param string $sha1 Base-36 SHA-1
168 * @param LocalRepo $repo
169 * @param string|bool $timestamp MW_timestamp (optional)
170 * @return bool|LocalFile
172 static function newFromKey( $sha1, $repo, $timestamp = false ) {
173 $dbr = $repo->getSlaveDB();
175 $conds = [ 'img_sha1' => $sha1 ];
177 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
180 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
182 return self
::newFromRow( $row, $repo );
189 * Fields in the image table
192 static function selectFields() {
213 * Do not call this except from inside a repo class.
214 * @param Title $title
215 * @param FileRepo $repo
217 function __construct( $title, $repo ) {
218 parent
::__construct( $title, $repo );
220 $this->metadata
= '';
221 $this->historyLine
= 0;
222 $this->historyRes
= null;
223 $this->dataLoaded
= false;
224 $this->extraDataLoaded
= false;
226 $this->assertRepoDefined();
227 $this->assertTitleDefined();
231 * Get the memcached key for the main data for this file, or false if
232 * there is no access to the shared cache.
233 * @return string|bool
235 function getCacheKey() {
236 $hashedName = md5( $this->getName() );
238 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
242 * Try to load file metadata from memcached. Returns true on success.
245 private function loadFromCache() {
246 $this->dataLoaded
= false;
247 $this->extraDataLoaded
= false;
248 $key = $this->getCacheKey();
254 $cache = ObjectCache
::getMainWANInstance();
255 $cachedValues = $cache->get( $key );
257 // Check if the key existed and belongs to this version of MediaWiki
258 if ( is_array( $cachedValues ) && $cachedValues['version'] == MW_FILE_VERSION
) {
259 $this->fileExists
= $cachedValues['fileExists'];
260 if ( $this->fileExists
) {
261 $this->setProps( $cachedValues );
263 $this->dataLoaded
= true;
264 $this->extraDataLoaded
= true;
265 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
266 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
270 return $this->dataLoaded
;
274 * Save the file metadata to memcached
276 private function saveToCache() {
279 $key = $this->getCacheKey();
284 $fields = $this->getCacheFields( '' );
285 $cacheVal = [ 'version' => MW_FILE_VERSION
];
286 $cacheVal['fileExists'] = $this->fileExists
;
288 if ( $this->fileExists
) {
289 foreach ( $fields as $field ) {
290 $cacheVal[$field] = $this->$field;
294 // Strip off excessive entries from the subset of fields that can become large.
295 // If the cache value gets to large it will not fit in memcached and nothing will
296 // get cached at all, causing master queries for any file access.
297 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
298 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
299 unset( $cacheVal[$field] ); // don't let the value get too big
303 // Cache presence for 1 week and negatives for 1 day
304 $ttl = $this->fileExists ?
86400 * 7 : 86400;
305 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
306 ObjectCache
::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
310 * Purge the file object/metadata cache
312 public function invalidateCache() {
313 $key = $this->getCacheKey();
318 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
319 ObjectCache
::getMainWANInstance()->delete( $key );
324 * Load metadata from the file itself
326 function loadFromFile() {
327 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
328 $this->setProps( $props );
332 * @param string $prefix
335 function getCacheFields( $prefix = 'img_' ) {
336 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
337 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
338 'user_text', 'description' ];
339 static $results = [];
341 if ( $prefix == '' ) {
345 if ( !isset( $results[$prefix] ) ) {
346 $prefixedFields = [];
347 foreach ( $fields as $field ) {
348 $prefixedFields[] = $prefix . $field;
350 $results[$prefix] = $prefixedFields;
353 return $results[$prefix];
357 * @param string $prefix
360 function getLazyCacheFields( $prefix = 'img_' ) {
361 static $fields = [ 'metadata' ];
362 static $results = [];
364 if ( $prefix == '' ) {
368 if ( !isset( $results[$prefix] ) ) {
369 $prefixedFields = [];
370 foreach ( $fields as $field ) {
371 $prefixedFields[] = $prefix . $field;
373 $results[$prefix] = $prefixedFields;
376 return $results[$prefix];
380 * Load file metadata from the DB
383 function loadFromDB( $flags = 0 ) {
384 $fname = get_class( $this ) . '::' . __FUNCTION__
;
386 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
387 $this->dataLoaded
= true;
388 $this->extraDataLoaded
= true;
390 $dbr = ( $flags & self
::READ_LATEST
)
391 ?
$this->repo
->getMasterDB()
392 : $this->repo
->getSlaveDB();
394 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
395 [ 'img_name' => $this->getName() ], $fname );
398 $this->loadFromRow( $row );
400 $this->fileExists
= false;
405 * Load lazy file metadata from the DB.
406 * This covers fields that are sometimes not cached.
408 protected function loadExtraFromDB() {
409 $fname = get_class( $this ) . '::' . __FUNCTION__
;
411 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
412 $this->extraDataLoaded
= true;
414 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
416 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
420 foreach ( $fieldMap as $name => $value ) {
421 $this->$name = $value;
424 throw new MWException( "Could not find data for image '{$this->getName()}'." );
429 * @param IDatabase $dbr
430 * @param string $fname
433 private function loadFieldsWithTimestamp( $dbr, $fname ) {
436 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
437 [ 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ],
440 $fieldMap = $this->unprefixRow( $row, 'img_' );
442 # File may have been uploaded over in the meantime; check the old versions
443 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
444 [ 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ],
447 $fieldMap = $this->unprefixRow( $row, 'oi_' );
455 * @param array|object $row
456 * @param string $prefix
457 * @throws MWException
460 protected function unprefixRow( $row, $prefix = 'img_' ) {
461 $array = (array)$row;
462 $prefixLength = strlen( $prefix );
464 // Sanity check prefix once
465 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
466 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
470 foreach ( $array as $name => $value ) {
471 $decoded[substr( $name, $prefixLength )] = $value;
478 * Decode a row from the database (either object or array) to an array
479 * with timestamps and MIME types decoded, and the field prefix removed.
481 * @param string $prefix
482 * @throws MWException
485 function decodeRow( $row, $prefix = 'img_' ) {
486 $decoded = $this->unprefixRow( $row, $prefix );
488 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
490 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
492 if ( empty( $decoded['major_mime'] ) ) {
493 $decoded['mime'] = 'unknown/unknown';
495 if ( !$decoded['minor_mime'] ) {
496 $decoded['minor_mime'] = 'unknown';
498 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
501 // Trim zero padding from char/binary field
502 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
504 // Normalize some fields to integer type, per their database definition.
505 // Use unary + so that overflows will be upgraded to double instead of
506 // being trucated as with intval(). This is important to allow >2GB
507 // files on 32-bit systems.
508 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
509 $decoded[$field] = +
$decoded[$field];
516 * Load file metadata from a DB result row
519 * @param string $prefix
521 function loadFromRow( $row, $prefix = 'img_' ) {
522 $this->dataLoaded
= true;
523 $this->extraDataLoaded
= true;
525 $array = $this->decodeRow( $row, $prefix );
527 foreach ( $array as $name => $value ) {
528 $this->$name = $value;
531 $this->fileExists
= true;
532 $this->maybeUpgradeRow();
536 * Load file metadata from cache or DB, unless already loaded
539 function load( $flags = 0 ) {
540 if ( !$this->dataLoaded
) {
541 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
542 $this->loadFromDB( $flags );
543 $this->saveToCache();
545 $this->dataLoaded
= true;
547 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
548 // @note: loads on name/timestamp to reduce race condition problems
549 $this->loadExtraFromDB();
554 * Upgrade a row if it needs it
556 function maybeUpgradeRow() {
557 global $wgUpdateCompatibleMetadata;
558 if ( wfReadOnly() ) {
562 if ( is_null( $this->media_type
) ||
563 $this->mime
== 'image/svg'
566 $this->upgraded
= true;
568 $handler = $this->getHandler();
570 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
571 if ( $validity === MediaHandler
::METADATA_BAD
572 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
575 $this->upgraded
= true;
581 function getUpgraded() {
582 return $this->upgraded
;
586 * Fix assorted version-related problems with the image row by reloading it from the file
588 function upgradeRow() {
590 $this->lock(); // begin
592 $this->loadFromFile();
594 # Don't destroy file info of missing files
595 if ( !$this->fileExists
) {
597 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
602 $dbw = $this->repo
->getMasterDB();
603 list( $major, $minor ) = self
::splitMime( $this->mime
);
605 if ( wfReadOnly() ) {
610 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
612 $dbw->update( 'image',
614 'img_size' => $this->size
, // sanity
615 'img_width' => $this->width
,
616 'img_height' => $this->height
,
617 'img_bits' => $this->bits
,
618 'img_media_type' => $this->media_type
,
619 'img_major_mime' => $major,
620 'img_minor_mime' => $minor,
621 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
622 'img_sha1' => $this->sha1
,
624 [ 'img_name' => $this->getName() ],
628 $this->invalidateCache();
630 $this->unlock(); // done
635 * Set properties in this object to be equal to those given in the
636 * associative array $info. Only cacheable fields can be set.
637 * All fields *must* be set in $info except for getLazyCacheFields().
639 * If 'mime' is given, it will be split into major_mime/minor_mime.
640 * If major_mime/minor_mime are given, $this->mime will also be set.
644 function setProps( $info ) {
645 $this->dataLoaded
= true;
646 $fields = $this->getCacheFields( '' );
647 $fields[] = 'fileExists';
649 foreach ( $fields as $field ) {
650 if ( isset( $info[$field] ) ) {
651 $this->$field = $info[$field];
655 // Fix up mime fields
656 if ( isset( $info['major_mime'] ) ) {
657 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
658 } elseif ( isset( $info['mime'] ) ) {
659 $this->mime
= $info['mime'];
660 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
664 /** splitMime inherited */
665 /** getName inherited */
666 /** getTitle inherited */
667 /** getURL inherited */
668 /** getViewURL inherited */
669 /** getPath inherited */
670 /** isVisible inherited */
675 function isMissing() {
676 if ( $this->missing
=== null ) {
677 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
678 $this->missing
= !$fileExists;
681 return $this->missing
;
685 * Return the width of the image
690 public function getWidth( $page = 1 ) {
693 if ( $this->isMultipage() ) {
694 $handler = $this->getHandler();
698 $dim = $handler->getPageDimensions( $this, $page );
700 return $dim['width'];
702 // For non-paged media, the false goes through an
703 // intval, turning failure into 0, so do same here.
712 * Return the height of the image
717 public function getHeight( $page = 1 ) {
720 if ( $this->isMultipage() ) {
721 $handler = $this->getHandler();
725 $dim = $handler->getPageDimensions( $this, $page );
727 return $dim['height'];
729 // For non-paged media, the false goes through an
730 // intval, turning failure into 0, so do same here.
734 return $this->height
;
739 * Returns ID or name of user who uploaded the file
741 * @param string $type 'text' or 'id'
744 function getUser( $type = 'text' ) {
747 if ( $type == 'text' ) {
748 return $this->user_text
;
749 } elseif ( $type == 'id' ) {
750 return (int)$this->user
;
755 * Get short description URL for a file based on the page ID.
757 * @return string|null
758 * @throws MWException
761 public function getDescriptionShortUrl() {
762 $pageId = $this->title
->getArticleID();
764 if ( $pageId !== null ) {
765 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
766 if ( $url !== false ) {
774 * Get handler-specific metadata
777 function getMetadata() {
778 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
779 return $this->metadata
;
785 function getBitDepth() {
788 return (int)$this->bits
;
792 * Returns the size of the image file, in bytes
795 public function getSize() {
802 * Returns the MIME type of the file.
805 function getMimeType() {
812 * Returns the type of the media in the file.
813 * Use the value returned by this function with the MEDIATYPE_xxx constants.
816 function getMediaType() {
819 return $this->media_type
;
822 /** canRender inherited */
823 /** mustRender inherited */
824 /** allowInlineDisplay inherited */
825 /** isSafeFile inherited */
826 /** isTrustedFile inherited */
829 * Returns true if the file exists on disk.
830 * @return bool Whether file exist on disk.
832 public function exists() {
835 return $this->fileExists
;
838 /** getTransformScript inherited */
839 /** getUnscaledThumb inherited */
840 /** thumbName inherited */
841 /** createThumb inherited */
842 /** transform inherited */
844 /** getHandler inherited */
845 /** iconThumb inherited */
846 /** getLastError inherited */
849 * Get all thumbnail names previously generated for this file
850 * @param string|bool $archiveName Name of an archive file, default false
851 * @return array First element is the base dir, then files in that base dir.
853 function getThumbnails( $archiveName = false ) {
854 if ( $archiveName ) {
855 $dir = $this->getArchiveThumbPath( $archiveName );
857 $dir = $this->getThumbPath();
860 $backend = $this->repo
->getBackend();
863 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
864 foreach ( $iterator as $file ) {
867 } catch ( FileBackendError
$e ) {
868 } // suppress (bug 54674)
874 * Refresh metadata in memcached, but don't touch thumbnails or CDN
876 function purgeMetadataCache() {
877 $this->invalidateCache();
881 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
883 * @param array $options An array potentially with the key forThumbRefresh.
885 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
887 function purgeCache( $options = [] ) {
888 // Refresh metadata cache
889 $this->purgeMetadataCache();
892 $this->purgeThumbnails( $options );
894 // Purge CDN cache for this file
895 DeferredUpdates
::addUpdate(
896 new CdnCacheUpdate( [ $this->getUrl() ] ),
897 DeferredUpdates
::PRESEND
902 * Delete cached transformed files for an archived version only.
903 * @param string $archiveName Name of the archived file
905 function purgeOldThumbnails( $archiveName ) {
906 // Get a list of old thumbnails and URLs
907 $files = $this->getThumbnails( $archiveName );
909 // Purge any custom thumbnail caches
910 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
913 $dir = array_shift( $files );
914 $this->purgeThumbList( $dir, $files );
918 foreach ( $files as $file ) {
919 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
921 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
925 * Delete cached transformed files for the current version only.
926 * @param array $options
928 public function purgeThumbnails( $options = [] ) {
929 $files = $this->getThumbnails();
930 // Always purge all files from CDN regardless of handler filters
932 foreach ( $files as $file ) {
933 $urls[] = $this->getThumbUrl( $file );
935 array_shift( $urls ); // don't purge directory
937 // Give media handler a chance to filter the file purge list
938 if ( !empty( $options['forThumbRefresh'] ) ) {
939 $handler = $this->getHandler();
941 $handler->filterThumbnailPurgeList( $files, $options );
945 // Purge any custom thumbnail caches
946 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
949 $dir = array_shift( $files );
950 $this->purgeThumbList( $dir, $files );
953 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
957 * Delete a list of thumbnails visible at urls
958 * @param string $dir Base dir of the files.
959 * @param array $files Array of strings: relative filenames (to $dir)
961 protected function purgeThumbList( $dir, $files ) {
962 $fileListDebug = strtr(
963 var_export( $files, true ),
966 wfDebug( __METHOD__
. ": $fileListDebug\n" );
969 foreach ( $files as $file ) {
970 # Check that the base file name is part of the thumb name
971 # This is a basic sanity check to avoid erasing unrelated directories
972 if ( strpos( $file, $this->getName() ) !== false
973 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
975 $purgeList[] = "{$dir}/{$file}";
979 # Delete the thumbnails
980 $this->repo
->quickPurgeBatch( $purgeList );
981 # Clear out the thumbnail directory if empty
982 $this->repo
->quickCleanDir( $dir );
985 /** purgeDescription inherited */
986 /** purgeEverything inherited */
989 * @param int $limit Optional: Limit to number of results
990 * @param int $start Optional: Timestamp, start from
991 * @param int $end Optional: Timestamp, end at
993 * @return OldLocalFile[]
995 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
996 $dbr = $this->repo
->getSlaveDB();
997 $tables = [ 'oldimage' ];
998 $fields = OldLocalFile
::selectFields();
999 $conds = $opts = $join_conds = [];
1000 $eq = $inc ?
'=' : '';
1001 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1004 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1008 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1012 $opts['LIMIT'] = $limit;
1015 // Search backwards for time > x queries
1016 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1017 $opts['ORDER BY'] = "oi_timestamp $order";
1018 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1020 Hooks
::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1021 &$conds, &$opts, &$join_conds ] );
1023 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1026 foreach ( $res as $row ) {
1027 $r[] = $this->repo
->newFileFromRow( $row );
1030 if ( $order == 'ASC' ) {
1031 $r = array_reverse( $r ); // make sure it ends up descending
1038 * Returns the history of this file, line by line.
1039 * starts with current version, then old versions.
1040 * uses $this->historyLine to check which line to return:
1041 * 0 return line for current version
1042 * 1 query for old versions, return first one
1043 * 2, ... return next old version from above query
1046 public function nextHistoryLine() {
1047 # Polymorphic function name to distinguish foreign and local fetches
1048 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1050 $dbr = $this->repo
->getSlaveDB();
1052 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1053 $this->historyRes
= $dbr->select( 'image',
1056 "'' AS oi_archive_name",
1060 [ 'img_name' => $this->title
->getDBkey() ],
1064 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1065 $this->historyRes
= null;
1069 } elseif ( $this->historyLine
== 1 ) {
1070 $this->historyRes
= $dbr->select( 'oldimage', '*',
1071 [ 'oi_name' => $this->title
->getDBkey() ],
1073 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1076 $this->historyLine++
;
1078 return $dbr->fetchObject( $this->historyRes
);
1082 * Reset the history pointer to the first element of the history
1084 public function resetHistory() {
1085 $this->historyLine
= 0;
1087 if ( !is_null( $this->historyRes
) ) {
1088 $this->historyRes
= null;
1092 /** getHashPath inherited */
1093 /** getRel inherited */
1094 /** getUrlRel inherited */
1095 /** getArchiveRel inherited */
1096 /** getArchivePath inherited */
1097 /** getThumbPath inherited */
1098 /** getArchiveUrl inherited */
1099 /** getThumbUrl inherited */
1100 /** getArchiveVirtualUrl inherited */
1101 /** getThumbVirtualUrl inherited */
1102 /** isHashed inherited */
1105 * Upload a file and record it in the DB
1106 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1107 * @param string $comment Upload description
1108 * @param string $pageText Text to use for the new description page,
1109 * if a new description page is created
1110 * @param int|bool $flags Flags for publish()
1111 * @param array|bool $props File properties, if known. This can be used to
1112 * reduce the upload time when uploading virtual URLs for which the file
1113 * info is already known
1114 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1116 * @param User|null $user User object or null to use $wgUser
1117 * @param string[] $tags Change tags to add to the log entry and page revision.
1118 * (This doesn't check $user's permissions.)
1119 * @return FileRepoStatus On success, the value member contains the
1120 * archive name, or an empty string if it was a new file.
1122 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1123 $timestamp = false, $user = null, $tags = []
1127 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1128 return $this->readOnlyFatalStatus();
1131 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1133 if ( $this->repo
->isVirtualUrl( $srcPath )
1134 || FileBackend
::isStoragePath( $srcPath )
1136 $props = $this->repo
->getFileProps( $srcPath );
1138 $props = FSFile
::getPropsFromPath( $srcPath );
1143 $handler = MediaHandler
::getHandler( $props['mime'] );
1145 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1147 $options['headers'] = [];
1150 // Trim spaces on user supplied text
1151 $comment = trim( $comment );
1153 // Truncate nicely or the DB will do it for us
1154 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1155 $comment = $wgContLang->truncate( $comment, 255 );
1156 $this->lock(); // begin
1157 $status = $this->publish( $src, $flags, $options );
1159 if ( $status->successCount
>= 2 ) {
1160 // There will be a copy+(one of move,copy,store).
1161 // The first succeeding does not commit us to updating the DB
1162 // since it simply copied the current version to a timestamped file name.
1163 // It is only *preferable* to avoid leaving such files orphaned.
1164 // Once the second operation goes through, then the current version was
1165 // updated and we must therefore update the DB too.
1166 $oldver = $status->value
;
1167 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1168 $status->fatal( 'filenotfound', $srcPath );
1172 $this->unlock(); // done
1178 * Record a file upload in the upload log and the image table
1179 * @param string $oldver
1180 * @param string $desc
1181 * @param string $license
1182 * @param string $copyStatus
1183 * @param string $source
1184 * @param bool $watch
1185 * @param string|bool $timestamp
1186 * @param User|null $user User object or null to use $wgUser
1189 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1190 $watch = false, $timestamp = false, User
$user = null ) {
1196 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1198 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1203 $user->addWatch( $this->getTitle() );
1210 * Record a file upload in the upload log and the image table
1211 * @param string $oldver
1212 * @param string $comment
1213 * @param string $pageText
1214 * @param bool|array $props
1215 * @param string|bool $timestamp
1216 * @param null|User $user
1217 * @param string[] $tags
1220 function recordUpload2(
1221 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1223 if ( is_null( $user ) ) {
1228 $dbw = $this->repo
->getMasterDB();
1230 # Imports or such might force a certain timestamp; otherwise we generate
1231 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1232 if ( $timestamp === false ) {
1233 $timestamp = $dbw->timestamp();
1234 $allowTimeKludge = true;
1236 $allowTimeKludge = false;
1239 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1240 $props['description'] = $comment;
1241 $props['user'] = $user->getId();
1242 $props['user_text'] = $user->getName();
1243 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1244 $this->setProps( $props );
1246 # Fail now if the file isn't there
1247 if ( !$this->fileExists
) {
1248 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1253 $dbw->startAtomic( __METHOD__
);
1255 # Test to see if the row exists using INSERT IGNORE
1256 # This avoids race conditions by locking the row until the commit, and also
1257 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1258 $dbw->insert( 'image',
1260 'img_name' => $this->getName(),
1261 'img_size' => $this->size
,
1262 'img_width' => intval( $this->width
),
1263 'img_height' => intval( $this->height
),
1264 'img_bits' => $this->bits
,
1265 'img_media_type' => $this->media_type
,
1266 'img_major_mime' => $this->major_mime
,
1267 'img_minor_mime' => $this->minor_mime
,
1268 'img_timestamp' => $timestamp,
1269 'img_description' => $comment,
1270 'img_user' => $user->getId(),
1271 'img_user_text' => $user->getName(),
1272 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1273 'img_sha1' => $this->sha1
1279 $reupload = ( $dbw->affectedRows() == 0 );
1281 if ( $allowTimeKludge ) {
1282 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1283 $ltimestamp = $dbw->selectField(
1286 [ 'img_name' => $this->getName() ],
1288 [ 'LOCK IN SHARE MODE' ]
1290 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1291 # Avoid a timestamp that is not newer than the last version
1292 # TODO: the image/oldimage tables should be like page/revision with an ID field
1293 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1294 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1295 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1296 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1300 # (bug 34993) Note: $oldver can be empty here, if the previous
1301 # version of the file was broken. Allow registration of the new
1302 # version to continue anyway, because that's better than having
1303 # an image that's not fixable by user operations.
1304 # Collision, this is an update of a file
1305 # Insert previous contents into oldimage
1306 $dbw->insertSelect( 'oldimage', 'image',
1308 'oi_name' => 'img_name',
1309 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1310 'oi_size' => 'img_size',
1311 'oi_width' => 'img_width',
1312 'oi_height' => 'img_height',
1313 'oi_bits' => 'img_bits',
1314 'oi_timestamp' => 'img_timestamp',
1315 'oi_description' => 'img_description',
1316 'oi_user' => 'img_user',
1317 'oi_user_text' => 'img_user_text',
1318 'oi_metadata' => 'img_metadata',
1319 'oi_media_type' => 'img_media_type',
1320 'oi_major_mime' => 'img_major_mime',
1321 'oi_minor_mime' => 'img_minor_mime',
1322 'oi_sha1' => 'img_sha1'
1324 [ 'img_name' => $this->getName() ],
1328 # Update the current image row
1329 $dbw->update( 'image',
1331 'img_size' => $this->size
,
1332 'img_width' => intval( $this->width
),
1333 'img_height' => intval( $this->height
),
1334 'img_bits' => $this->bits
,
1335 'img_media_type' => $this->media_type
,
1336 'img_major_mime' => $this->major_mime
,
1337 'img_minor_mime' => $this->minor_mime
,
1338 'img_timestamp' => $timestamp,
1339 'img_description' => $comment,
1340 'img_user' => $user->getId(),
1341 'img_user_text' => $user->getName(),
1342 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1343 'img_sha1' => $this->sha1
1345 [ 'img_name' => $this->getName() ],
1350 $descTitle = $this->getTitle();
1351 $descId = $descTitle->getArticleID();
1352 $wikiPage = new WikiFilePage( $descTitle );
1353 $wikiPage->setFile( $this );
1355 // Add the log entry...
1356 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1357 $logEntry->setTimestamp( $this->timestamp
);
1358 $logEntry->setPerformer( $user );
1359 $logEntry->setComment( $comment );
1360 $logEntry->setTarget( $descTitle );
1361 // Allow people using the api to associate log entries with the upload.
1362 // Log has a timestamp, but sometimes different from upload timestamp.
1363 $logEntry->setParameters(
1365 'img_sha1' => $this->sha1
,
1366 'img_timestamp' => $timestamp,
1369 // Note we keep $logId around since during new image
1370 // creation, page doesn't exist yet, so log_page = 0
1371 // but we want it to point to the page we're making,
1372 // so we later modify the log entry.
1373 // For a similar reason, we avoid making an RC entry
1374 // now and wait until the page exists.
1375 $logId = $logEntry->insert();
1377 if ( $descTitle->exists() ) {
1378 // Use own context to get the action text in content language
1379 $formatter = LogFormatter
::newFromEntry( $logEntry );
1380 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1381 $editSummary = $formatter->getPlainActionText();
1383 $nullRevision = Revision
::newNullRevision(
1390 if ( $nullRevision ) {
1391 $nullRevision->insertOn( $dbw );
1393 'NewRevisionFromEditComplete',
1394 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1396 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1397 // Associate null revision id
1398 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1401 $newPageContent = null;
1403 // Make the description page and RC log entry post-commit
1404 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1407 # Defer purges, page creation, and link updates in case they error out.
1408 # The most important thing is that files and the DB registry stay synced.
1409 $dbw->endAtomic( __METHOD__
);
1411 # Do some cache purges after final commit so that:
1412 # a) Changes are more likely to be seen post-purge
1413 # b) They won't cause rollback of the log publish/update above
1415 $dbw->onTransactionIdle( function () use (
1416 $that, $reupload, $wikiPage, $newPageContent, $comment, $user, $logEntry, $logId, $descId, $tags
1418 # Update memcache after the commit
1419 $that->invalidateCache();
1421 $updateLogPage = false;
1422 if ( $newPageContent ) {
1423 # New file page; create the description page.
1424 # There's already a log entry, so don't make a second RC entry
1425 # CDN and file cache for the description page are purged by doEditContent.
1426 $status = $wikiPage->doEditContent(
1429 EDIT_NEW | EDIT_SUPPRESS_RC
,
1434 if ( isset( $status->value
['revision'] ) ) {
1435 // Associate new page revision id
1436 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1438 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1439 // which is triggered on $descTitle by doEditContent() above.
1440 if ( isset( $status->value
['revision'] ) ) {
1441 /** @var $rev Revision */
1442 $rev = $status->value
['revision'];
1443 $updateLogPage = $rev->getPage();
1446 # Existing file page: invalidate description page cache
1447 $wikiPage->getTitle()->invalidateCache();
1448 $wikiPage->getTitle()->purgeSquid();
1449 # Allow the new file version to be patrolled from the page footer
1450 Article
::purgePatrolFooterCache( $descId );
1453 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1454 # but setAssociatedRevId() wasn't called at that point yet...
1455 $logParams = $logEntry->getParameters();
1456 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1457 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1458 if ( $updateLogPage ) {
1459 # Also log page, in case where we just created it above
1460 $update['log_page'] = $updateLogPage;
1462 $that->getRepo()->getMasterDB()->update(
1465 [ 'log_id' => $logId ],
1468 $that->getRepo()->getMasterDB()->insert(
1471 'ls_field' => 'associated_rev_id',
1472 'ls_value' => $logEntry->getAssociatedRevId(),
1473 'ls_log_id' => $logId,
1478 # Add change tags, if any
1480 $logEntry->setTags( $tags );
1483 # Uploads can be patrolled
1484 $logEntry->setIsPatrollable( true );
1486 # Now that the log entry is up-to-date, make an RC entry.
1487 $logEntry->publish( $logId );
1489 # Run hook for other updates (typically more cache purging)
1490 Hooks
::run( 'FileUpload', [ $that, $reupload, !$newPageContent ] );
1493 # Delete old thumbnails
1494 $that->purgeThumbnails();
1495 # Remove the old file from the CDN cache
1496 DeferredUpdates
::addUpdate(
1497 new CdnCacheUpdate( [ $that->getUrl() ] ),
1498 DeferredUpdates
::PRESEND
1501 # Update backlink pages pointing to this title if created
1502 LinksUpdate
::queueRecursiveJobsForTable( $that->getTitle(), 'imagelinks' );
1507 # This is a new file, so update the image count
1508 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1511 # Invalidate cache for all pages using this file
1512 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1518 * Move or copy a file to its public location. If a file exists at the
1519 * destination, move it to an archive. Returns a FileRepoStatus object with
1520 * the archive name in the "value" member on success.
1522 * The archive name should be passed through to recordUpload for database
1525 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1526 * @param int $flags A bitwise combination of:
1527 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1528 * @param array $options Optional additional parameters
1529 * @return FileRepoStatus On success, the value member contains the
1530 * archive name, or an empty string if it was a new file.
1532 function publish( $src, $flags = 0, array $options = [] ) {
1533 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1537 * Move or copy a file to a specified location. Returns a FileRepoStatus
1538 * object with the archive name in the "value" member on success.
1540 * The archive name should be passed through to recordUpload for database
1543 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1544 * @param string $dstRel Target relative path
1545 * @param int $flags A bitwise combination of:
1546 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1547 * @param array $options Optional additional parameters
1548 * @return FileRepoStatus On success, the value member contains the
1549 * archive name, or an empty string if it was a new file.
1551 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1552 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1554 $repo = $this->getRepo();
1555 if ( $repo->getReadOnlyReason() !== false ) {
1556 return $this->readOnlyFatalStatus();
1559 $this->lock(); // begin
1561 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1562 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1564 if ( $repo->hasSha1Storage() ) {
1565 $sha1 = $repo->isVirtualUrl( $srcPath )
1566 ?
$repo->getFileSha1( $srcPath )
1567 : FSFile
::getSha1Base36FromPath( $srcPath );
1568 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1569 $status = $repo->quickImport( $src, $dst );
1570 if ( $flags & File
::DELETE_SOURCE
) {
1574 if ( $this->exists() ) {
1575 $status->value
= $archiveName;
1578 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1579 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1581 if ( $status->value
== 'new' ) {
1582 $status->value
= '';
1584 $status->value
= $archiveName;
1588 $this->unlock(); // done
1593 /** getLinksTo inherited */
1594 /** getExifData inherited */
1595 /** isLocal inherited */
1596 /** wasDeleted inherited */
1599 * Move file to the new title
1601 * Move current, old version and all thumbnails
1602 * to the new filename. Old file is deleted.
1604 * Cache purging is done; checks for validity
1605 * and logging are caller's responsibility
1607 * @param Title $target New file name
1608 * @return FileRepoStatus
1610 function move( $target ) {
1611 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1612 return $this->readOnlyFatalStatus();
1615 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1616 $batch = new LocalFileMoveBatch( $this, $target );
1618 $this->lock(); // begin
1619 $batch->addCurrent();
1620 $archiveNames = $batch->addOlds();
1621 $status = $batch->execute();
1622 $this->unlock(); // done
1624 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1626 // Purge the source and target files...
1627 $oldTitleFile = wfLocalFile( $this->title
);
1628 $newTitleFile = wfLocalFile( $target );
1629 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1630 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1631 $this->getRepo()->getMasterDB()->onTransactionIdle(
1632 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1633 $oldTitleFile->purgeEverything();
1634 foreach ( $archiveNames as $archiveName ) {
1635 $oldTitleFile->purgeOldThumbnails( $archiveName );
1637 $newTitleFile->purgeEverything();
1641 if ( $status->isOK() ) {
1642 // Now switch the object
1643 $this->title
= $target;
1644 // Force regeneration of the name and hashpath
1645 unset( $this->name
);
1646 unset( $this->hashPath
);
1653 * Delete all versions of the file.
1655 * Moves the files into an archive directory (or deletes them)
1656 * and removes the database rows.
1658 * Cache purging is done; logging is caller's responsibility.
1660 * @param string $reason
1661 * @param bool $suppress
1662 * @param User|null $user
1663 * @return FileRepoStatus
1665 function delete( $reason, $suppress = false, $user = null ) {
1666 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1667 return $this->readOnlyFatalStatus();
1670 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1672 $this->lock(); // begin
1673 $batch->addCurrent();
1674 # Get old version relative paths
1675 $archiveNames = $batch->addOlds();
1676 $status = $batch->execute();
1677 $this->unlock(); // done
1679 if ( $status->isOK() ) {
1680 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1683 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1684 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1686 $this->getRepo()->getMasterDB()->onTransactionIdle(
1687 function () use ( $that, $archiveNames ) {
1688 $that->purgeEverything();
1689 foreach ( $archiveNames as $archiveName ) {
1690 $that->purgeOldThumbnails( $archiveName );
1697 foreach ( $archiveNames as $archiveName ) {
1698 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1700 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1706 * Delete an old version of the file.
1708 * Moves the file into an archive directory (or deletes it)
1709 * and removes the database row.
1711 * Cache purging is done; logging is caller's responsibility.
1713 * @param string $archiveName
1714 * @param string $reason
1715 * @param bool $suppress
1716 * @param User|null $user
1717 * @throws MWException Exception on database or file store failure
1718 * @return FileRepoStatus
1720 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1721 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1722 return $this->readOnlyFatalStatus();
1725 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1727 $this->lock(); // begin
1728 $batch->addOld( $archiveName );
1729 $status = $batch->execute();
1730 $this->unlock(); // done
1732 $this->purgeOldThumbnails( $archiveName );
1733 if ( $status->isOK() ) {
1734 $this->purgeDescription();
1737 DeferredUpdates
::addUpdate(
1738 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1739 DeferredUpdates
::PRESEND
1746 * Restore all or specified deleted revisions to the given file.
1747 * Permissions and logging are left to the caller.
1749 * May throw database exceptions on error.
1751 * @param array $versions Set of record ids of deleted items to restore,
1752 * or empty to restore all revisions.
1753 * @param bool $unsuppress
1754 * @return FileRepoStatus
1756 function restore( $versions = [], $unsuppress = false ) {
1757 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1758 return $this->readOnlyFatalStatus();
1761 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1763 $this->lock(); // begin
1767 $batch->addIds( $versions );
1769 $status = $batch->execute();
1770 if ( $status->isGood() ) {
1771 $cleanupStatus = $batch->cleanup();
1772 $cleanupStatus->successCount
= 0;
1773 $cleanupStatus->failCount
= 0;
1774 $status->merge( $cleanupStatus );
1776 $this->unlock(); // done
1781 /** isMultipage inherited */
1782 /** pageCount inherited */
1783 /** scaleHeight inherited */
1784 /** getImageSize inherited */
1787 * Get the URL of the file description page.
1790 function getDescriptionUrl() {
1791 return $this->title
->getLocalURL();
1795 * Get the HTML text of the description page
1796 * This is not used by ImagePage for local files, since (among other things)
1797 * it skips the parser cache.
1799 * @param Language $lang What language to get description in (Optional)
1800 * @return bool|mixed
1802 function getDescriptionText( $lang = null ) {
1803 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1807 $content = $revision->getContent();
1811 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1813 return $pout->getText();
1817 * @param int $audience
1821 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1823 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1825 } elseif ( $audience == self
::FOR_THIS_USER
1826 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1830 return $this->description
;
1835 * @return bool|string
1837 function getTimestamp() {
1840 return $this->timestamp
;
1844 * @return bool|string
1846 public function getDescriptionTouched() {
1847 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1848 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1849 // need to differentiate between null (uninitialized) and false (failed to load).
1850 if ( $this->descriptionTouched
=== null ) {
1852 'page_namespace' => $this->title
->getNamespace(),
1853 'page_title' => $this->title
->getDBkey()
1855 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1856 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1859 return $this->descriptionTouched
;
1865 function getSha1() {
1867 // Initialise now if necessary
1868 if ( $this->sha1
== '' && $this->fileExists
) {
1869 $this->lock(); // begin
1871 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1872 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1873 $dbw = $this->repo
->getMasterDB();
1874 $dbw->update( 'image',
1875 [ 'img_sha1' => $this->sha1
],
1876 [ 'img_name' => $this->getName() ],
1878 $this->invalidateCache();
1881 $this->unlock(); // done
1888 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1890 function isCacheable() {
1893 // If extra data (metadata) was not loaded then it must have been large
1894 return $this->extraDataLoaded
1895 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1899 * Start a transaction and lock the image for update
1900 * Increments a reference counter if the lock is already held
1901 * @throws MWException Throws an error if the lock was not acquired
1902 * @return bool Whether the file lock owns/spawned the DB transaction
1905 $dbw = $this->repo
->getMasterDB();
1907 if ( !$this->locked
) {
1908 if ( !$dbw->trxLevel() ) {
1909 $dbw->begin( __METHOD__
);
1910 $this->lockedOwnTrx
= true;
1913 // Bug 54736: use simple lock to handle when the file does not exist.
1914 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1915 // Also, that would cause contention on INSERT of similarly named rows.
1916 $backend = $this->getRepo()->getBackend();
1917 $lockPaths = [ $this->getPath() ]; // represents all versions of the file
1918 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1919 if ( !$status->isGood() ) {
1920 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1922 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1923 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1927 return $this->lockedOwnTrx
;
1931 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1932 * the transaction and thereby releases the image lock.
1935 if ( $this->locked
) {
1937 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1938 $dbw = $this->repo
->getMasterDB();
1939 $dbw->commit( __METHOD__
);
1940 $this->lockedOwnTrx
= false;
1946 * Roll back the DB transaction and mark the image unlocked
1948 function unlockAndRollback() {
1949 $this->locked
= false;
1950 $dbw = $this->repo
->getMasterDB();
1951 $dbw->rollback( __METHOD__
);
1952 $this->lockedOwnTrx
= false;
1958 protected function readOnlyFatalStatus() {
1959 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1960 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1964 * Clean up any dangling locks
1966 function __destruct() {
1969 } // LocalFile class
1971 # ------------------------------------------------------------------------------
1974 * Helper class for file deletion
1975 * @ingroup FileAbstraction
1977 class LocalFileDeleteBatch
{
1978 /** @var LocalFile */
1985 private $srcRels = [];
1988 private $archiveUrls = [];
1990 /** @var array Items to be processed in the deletion batch */
1991 private $deletionBatch;
1993 /** @var bool Whether to suppress all suppressable fields when deleting */
1996 /** @var FileRepoStatus */
2004 * @param string $reason
2005 * @param bool $suppress
2006 * @param User|null $user
2008 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2009 $this->file
= $file;
2010 $this->reason
= $reason;
2011 $this->suppress
= $suppress;
2013 $this->user
= $user;
2016 $this->user
= $wgUser;
2018 $this->status
= $file->repo
->newGood();
2021 public function addCurrent() {
2022 $this->srcRels
['.'] = $this->file
->getRel();
2026 * @param string $oldName
2028 public function addOld( $oldName ) {
2029 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2030 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2034 * Add the old versions of the image to the batch
2035 * @return array List of archive names from old versions
2037 public function addOlds() {
2040 $dbw = $this->file
->repo
->getMasterDB();
2041 $result = $dbw->select( 'oldimage',
2042 [ 'oi_archive_name' ],
2043 [ 'oi_name' => $this->file
->getName() ],
2047 foreach ( $result as $row ) {
2048 $this->addOld( $row->oi_archive_name
);
2049 $archiveNames[] = $row->oi_archive_name
;
2052 return $archiveNames;
2058 protected function getOldRels() {
2059 if ( !isset( $this->srcRels
['.'] ) ) {
2060 $oldRels =& $this->srcRels
;
2061 $deleteCurrent = false;
2063 $oldRels = $this->srcRels
;
2064 unset( $oldRels['.'] );
2065 $deleteCurrent = true;
2068 return [ $oldRels, $deleteCurrent ];
2074 protected function getHashes() {
2076 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2078 if ( $deleteCurrent ) {
2079 $hashes['.'] = $this->file
->getSha1();
2082 if ( count( $oldRels ) ) {
2083 $dbw = $this->file
->repo
->getMasterDB();
2084 $res = $dbw->select(
2086 [ 'oi_archive_name', 'oi_sha1' ],
2087 [ 'oi_archive_name' => array_keys( $oldRels ),
2088 'oi_name' => $this->file
->getName() ], // performance
2092 foreach ( $res as $row ) {
2093 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2094 // Get the hash from the file
2095 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2096 $props = $this->file
->repo
->getFileProps( $oldUrl );
2098 if ( $props['fileExists'] ) {
2099 // Upgrade the oldimage row
2100 $dbw->update( 'oldimage',
2101 [ 'oi_sha1' => $props['sha1'] ],
2102 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2104 $hashes[$row->oi_archive_name
] = $props['sha1'];
2106 $hashes[$row->oi_archive_name
] = false;
2109 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2114 $missing = array_diff_key( $this->srcRels
, $hashes );
2116 foreach ( $missing as $name => $rel ) {
2117 $this->status
->error( 'filedelete-old-unregistered', $name );
2120 foreach ( $hashes as $name => $hash ) {
2122 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2123 unset( $hashes[$name] );
2130 protected function doDBInserts() {
2131 $dbw = $this->file
->repo
->getMasterDB();
2132 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2133 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2134 $encReason = $dbw->addQuotes( $this->reason
);
2135 $encGroup = $dbw->addQuotes( 'deleted' );
2136 $ext = $this->file
->getExtension();
2137 $dotExt = $ext === '' ?
'' : ".$ext";
2138 $encExt = $dbw->addQuotes( $dotExt );
2139 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2141 // Bitfields to further suppress the content
2142 if ( $this->suppress
) {
2144 // This should be 15...
2145 $bitfield |
= Revision
::DELETED_TEXT
;
2146 $bitfield |
= Revision
::DELETED_COMMENT
;
2147 $bitfield |
= Revision
::DELETED_USER
;
2148 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2150 $bitfield = 'oi_deleted';
2153 if ( $deleteCurrent ) {
2154 $concat = $dbw->buildConcat( [ "img_sha1", $encExt ] );
2155 $where = [ 'img_name' => $this->file
->getName() ];
2156 $dbw->insertSelect( 'filearchive', 'image',
2158 'fa_storage_group' => $encGroup,
2159 'fa_storage_key' => $dbw->conditional(
2160 [ 'img_sha1' => '' ],
2161 $dbw->addQuotes( '' ),
2164 'fa_deleted_user' => $encUserId,
2165 'fa_deleted_timestamp' => $encTimestamp,
2166 'fa_deleted_reason' => $encReason,
2167 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2169 'fa_name' => 'img_name',
2170 'fa_archive_name' => 'NULL',
2171 'fa_size' => 'img_size',
2172 'fa_width' => 'img_width',
2173 'fa_height' => 'img_height',
2174 'fa_metadata' => 'img_metadata',
2175 'fa_bits' => 'img_bits',
2176 'fa_media_type' => 'img_media_type',
2177 'fa_major_mime' => 'img_major_mime',
2178 'fa_minor_mime' => 'img_minor_mime',
2179 'fa_description' => 'img_description',
2180 'fa_user' => 'img_user',
2181 'fa_user_text' => 'img_user_text',
2182 'fa_timestamp' => 'img_timestamp',
2183 'fa_sha1' => 'img_sha1',
2184 ], $where, __METHOD__
);
2187 if ( count( $oldRels ) ) {
2188 $concat = $dbw->buildConcat( [ "oi_sha1", $encExt ] );
2190 'oi_name' => $this->file
->getName(),
2191 'oi_archive_name' => array_keys( $oldRels ) ];
2192 $dbw->insertSelect( 'filearchive', 'oldimage',
2194 'fa_storage_group' => $encGroup,
2195 'fa_storage_key' => $dbw->conditional(
2196 [ 'oi_sha1' => '' ],
2197 $dbw->addQuotes( '' ),
2200 'fa_deleted_user' => $encUserId,
2201 'fa_deleted_timestamp' => $encTimestamp,
2202 'fa_deleted_reason' => $encReason,
2203 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2205 'fa_name' => 'oi_name',
2206 'fa_archive_name' => 'oi_archive_name',
2207 'fa_size' => 'oi_size',
2208 'fa_width' => 'oi_width',
2209 'fa_height' => 'oi_height',
2210 'fa_metadata' => 'oi_metadata',
2211 'fa_bits' => 'oi_bits',
2212 'fa_media_type' => 'oi_media_type',
2213 'fa_major_mime' => 'oi_major_mime',
2214 'fa_minor_mime' => 'oi_minor_mime',
2215 'fa_description' => 'oi_description',
2216 'fa_user' => 'oi_user',
2217 'fa_user_text' => 'oi_user_text',
2218 'fa_timestamp' => 'oi_timestamp',
2219 'fa_sha1' => 'oi_sha1',
2220 ], $where, __METHOD__
);
2224 function doDBDeletes() {
2225 $dbw = $this->file
->repo
->getMasterDB();
2226 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2228 if ( count( $oldRels ) ) {
2229 $dbw->delete( 'oldimage',
2231 'oi_name' => $this->file
->getName(),
2232 'oi_archive_name' => array_keys( $oldRels )
2236 if ( $deleteCurrent ) {
2237 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2242 * Run the transaction
2243 * @return FileRepoStatus
2245 public function execute() {
2246 $repo = $this->file
->getRepo();
2247 $this->file
->lock();
2249 // Prepare deletion batch
2250 $hashes = $this->getHashes();
2251 $this->deletionBatch
= [];
2252 $ext = $this->file
->getExtension();
2253 $dotExt = $ext === '' ?
'' : ".$ext";
2255 foreach ( $this->srcRels
as $name => $srcRel ) {
2256 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2257 if ( isset( $hashes[$name] ) ) {
2258 $hash = $hashes[$name];
2259 $key = $hash . $dotExt;
2260 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2261 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2265 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2266 // We acquire this lock by running the inserts now, before the file operations.
2267 // This potentially has poor lock contention characteristics -- an alternative
2268 // scheme would be to insert stub filearchive entries with no fa_name and commit
2269 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2270 $this->doDBInserts();
2272 if ( !$repo->hasSha1Storage() ) {
2273 // Removes non-existent file from the batch, so we don't get errors.
2274 // This also handles files in the 'deleted' zone deleted via revision deletion.
2275 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2276 if ( !$checkStatus->isGood() ) {
2277 $this->status
->merge( $checkStatus );
2278 return $this->status
;
2280 $this->deletionBatch
= $checkStatus->value
;
2282 // Execute the file deletion batch
2283 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2285 if ( !$status->isGood() ) {
2286 $this->status
->merge( $status );
2290 if ( !$this->status
->isOK() ) {
2291 // Critical file deletion error
2292 // Roll back inserts, release lock and abort
2293 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2294 $this->file
->unlockAndRollback();
2296 return $this->status
;
2299 // Delete image/oldimage rows
2300 $this->doDBDeletes();
2302 // Commit and return
2303 $this->file
->unlock();
2305 return $this->status
;
2309 * Removes non-existent files from a deletion batch.
2310 * @param array $batch
2313 protected function removeNonexistentFiles( $batch ) {
2314 $files = $newBatch = [];
2316 foreach ( $batch as $batchItem ) {
2317 list( $src, ) = $batchItem;
2318 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2321 $result = $this->file
->repo
->fileExistsBatch( $files );
2322 if ( in_array( null, $result, true ) ) {
2323 return Status
::newFatal( 'backend-fail-internal',
2324 $this->file
->repo
->getBackend()->getName() );
2327 foreach ( $batch as $batchItem ) {
2328 if ( $result[$batchItem[0]] ) {
2329 $newBatch[] = $batchItem;
2333 return Status
::newGood( $newBatch );
2337 # ------------------------------------------------------------------------------
2340 * Helper class for file undeletion
2341 * @ingroup FileAbstraction
2343 class LocalFileRestoreBatch
{
2344 /** @var LocalFile */
2347 /** @var array List of file IDs to restore */
2348 private $cleanupBatch;
2350 /** @var array List of file IDs to restore */
2353 /** @var bool Add all revisions of the file */
2356 /** @var bool Whether to remove all settings for suppressed fields */
2357 private $unsuppress = false;
2361 * @param bool $unsuppress
2363 function __construct( File
$file, $unsuppress = false ) {
2364 $this->file
= $file;
2365 $this->cleanupBatch
= $this->ids
= [];
2367 $this->unsuppress
= $unsuppress;
2374 public function addId( $fa_id ) {
2375 $this->ids
[] = $fa_id;
2379 * Add a whole lot of files by ID
2382 public function addIds( $ids ) {
2383 $this->ids
= array_merge( $this->ids
, $ids );
2387 * Add all revisions of the file
2389 public function addAll() {
2394 * Run the transaction, except the cleanup batch.
2395 * The cleanup batch should be run in a separate transaction, because it locks different
2396 * rows and there's no need to keep the image row locked while it's acquiring those locks
2397 * The caller may have its own transaction open.
2398 * So we save the batch and let the caller call cleanup()
2399 * @return FileRepoStatus
2401 public function execute() {
2404 $repo = $this->file
->getRepo();
2405 if ( !$this->all
&& !$this->ids
) {
2407 return $repo->newGood();
2410 $lockOwnsTrx = $this->file
->lock();
2412 $dbw = $this->file
->repo
->getMasterDB();
2413 $status = $this->file
->repo
->newGood();
2415 $exists = (bool)$dbw->selectField( 'image', '1',
2416 [ 'img_name' => $this->file
->getName() ],
2418 // The lock() should already prevents changes, but this still may need
2419 // to bypass any transaction snapshot. However, if lock() started the
2420 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2421 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2424 // Fetch all or selected archived revisions for the file,
2425 // sorted from the most recent to the oldest.
2426 $conditions = [ 'fa_name' => $this->file
->getName() ];
2428 if ( !$this->all
) {
2429 $conditions['fa_id'] = $this->ids
;
2432 $result = $dbw->select(
2434 ArchivedFile
::selectFields(),
2437 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2443 $insertCurrent = false;
2448 foreach ( $result as $row ) {
2449 $idsPresent[] = $row->fa_id
;
2451 if ( $row->fa_name
!= $this->file
->getName() ) {
2452 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2453 $status->failCount++
;
2457 if ( $row->fa_storage_key
== '' ) {
2458 // Revision was missing pre-deletion
2459 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2460 $status->failCount++
;
2464 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2465 $row->fa_storage_key
;
2466 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2468 if ( isset( $row->fa_sha1
) ) {
2469 $sha1 = $row->fa_sha1
;
2471 // old row, populate from key
2472 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2476 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2477 $sha1 = substr( $sha1, 1 );
2480 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2481 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2482 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2483 ||
is_null( $row->fa_metadata
)
2485 // Refresh our metadata
2486 // Required for a new current revision; nice for older ones too. :)
2487 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2490 'minor_mime' => $row->fa_minor_mime
,
2491 'major_mime' => $row->fa_major_mime
,
2492 'media_type' => $row->fa_media_type
,
2493 'metadata' => $row->fa_metadata
2497 if ( $first && !$exists ) {
2498 // This revision will be published as the new current version
2499 $destRel = $this->file
->getRel();
2501 'img_name' => $row->fa_name
,
2502 'img_size' => $row->fa_size
,
2503 'img_width' => $row->fa_width
,
2504 'img_height' => $row->fa_height
,
2505 'img_metadata' => $props['metadata'],
2506 'img_bits' => $row->fa_bits
,
2507 'img_media_type' => $props['media_type'],
2508 'img_major_mime' => $props['major_mime'],
2509 'img_minor_mime' => $props['minor_mime'],
2510 'img_description' => $row->fa_description
,
2511 'img_user' => $row->fa_user
,
2512 'img_user_text' => $row->fa_user_text
,
2513 'img_timestamp' => $row->fa_timestamp
,
2517 // The live (current) version cannot be hidden!
2518 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2519 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2520 $this->cleanupBatch
[] = $row->fa_storage_key
;
2523 $archiveName = $row->fa_archive_name
;
2525 if ( $archiveName == '' ) {
2526 // This was originally a current version; we
2527 // have to devise a new archive name for it.
2528 // Format is <timestamp of archiving>!<name>
2529 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2532 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2534 } while ( isset( $archiveNames[$archiveName] ) );
2537 $archiveNames[$archiveName] = true;
2538 $destRel = $this->file
->getArchiveRel( $archiveName );
2540 'oi_name' => $row->fa_name
,
2541 'oi_archive_name' => $archiveName,
2542 'oi_size' => $row->fa_size
,
2543 'oi_width' => $row->fa_width
,
2544 'oi_height' => $row->fa_height
,
2545 'oi_bits' => $row->fa_bits
,
2546 'oi_description' => $row->fa_description
,
2547 'oi_user' => $row->fa_user
,
2548 'oi_user_text' => $row->fa_user_text
,
2549 'oi_timestamp' => $row->fa_timestamp
,
2550 'oi_metadata' => $props['metadata'],
2551 'oi_media_type' => $props['media_type'],
2552 'oi_major_mime' => $props['major_mime'],
2553 'oi_minor_mime' => $props['minor_mime'],
2554 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2555 'oi_sha1' => $sha1 ];
2558 $deleteIds[] = $row->fa_id
;
2560 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2561 // private files can stay where they are
2562 $status->successCount++
;
2564 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2565 $this->cleanupBatch
[] = $row->fa_storage_key
;
2573 // Add a warning to the status object for missing IDs
2574 $missingIds = array_diff( $this->ids
, $idsPresent );
2576 foreach ( $missingIds as $id ) {
2577 $status->error( 'undelete-missing-filearchive', $id );
2580 if ( !$repo->hasSha1Storage() ) {
2581 // Remove missing files from batch, so we don't get errors when undeleting them
2582 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2583 if ( !$checkStatus->isGood() ) {
2584 $status->merge( $checkStatus );
2587 $storeBatch = $checkStatus->value
;
2589 // Run the store batch
2590 // Use the OVERWRITE_SAME flag to smooth over a common error
2591 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2592 $status->merge( $storeStatus );
2594 if ( !$status->isGood() ) {
2595 // Even if some files could be copied, fail entirely as that is the
2596 // easiest thing to do without data loss
2597 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2598 $status->ok
= false;
2599 $this->file
->unlock();
2605 // Run the DB updates
2606 // Because we have locked the image row, key conflicts should be rare.
2607 // If they do occur, we can roll back the transaction at this time with
2608 // no data loss, but leaving unregistered files scattered throughout the
2610 // This is not ideal, which is why it's important to lock the image row.
2611 if ( $insertCurrent ) {
2612 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2615 if ( $insertBatch ) {
2616 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2620 $dbw->delete( 'filearchive',
2621 [ 'fa_id' => $deleteIds ],
2625 // If store batch is empty (all files are missing), deletion is to be considered successful
2626 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2628 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2630 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2632 $this->file
->purgeEverything();
2634 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2635 $this->file
->purgeDescription();
2639 $this->file
->unlock();
2645 * Removes non-existent files from a store batch.
2646 * @param array $triplets
2649 protected function removeNonexistentFiles( $triplets ) {
2650 $files = $filteredTriplets = [];
2651 foreach ( $triplets as $file ) {
2652 $files[$file[0]] = $file[0];
2655 $result = $this->file
->repo
->fileExistsBatch( $files );
2656 if ( in_array( null, $result, true ) ) {
2657 return Status
::newFatal( 'backend-fail-internal',
2658 $this->file
->repo
->getBackend()->getName() );
2661 foreach ( $triplets as $file ) {
2662 if ( $result[$file[0]] ) {
2663 $filteredTriplets[] = $file;
2667 return Status
::newGood( $filteredTriplets );
2671 * Removes non-existent files from a cleanup batch.
2672 * @param array $batch
2675 protected function removeNonexistentFromCleanup( $batch ) {
2676 $files = $newBatch = [];
2677 $repo = $this->file
->repo
;
2679 foreach ( $batch as $file ) {
2680 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2681 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2684 $result = $repo->fileExistsBatch( $files );
2686 foreach ( $batch as $file ) {
2687 if ( $result[$file] ) {
2688 $newBatch[] = $file;
2696 * Delete unused files in the deleted zone.
2697 * This should be called from outside the transaction in which execute() was called.
2698 * @return FileRepoStatus
2700 public function cleanup() {
2701 if ( !$this->cleanupBatch
) {
2702 return $this->file
->repo
->newGood();
2705 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2707 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2713 * Cleanup a failed batch. The batch was only partially successful, so
2714 * rollback by removing all items that were succesfully copied.
2716 * @param Status $storeStatus
2717 * @param array $storeBatch
2719 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2722 foreach ( $storeStatus->success
as $i => $success ) {
2723 // Check if this item of the batch was successfully copied
2725 // Item was successfully copied and needs to be removed again
2726 // Extract ($dstZone, $dstRel) from the batch
2727 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2730 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2734 # ------------------------------------------------------------------------------
2737 * Helper class for file movement
2738 * @ingroup FileAbstraction
2740 class LocalFileMoveBatch
{
2741 /** @var LocalFile */
2751 protected $oldCount;
2755 /** @var DatabaseBase */
2760 * @param Title $target
2762 function __construct( File
$file, Title
$target ) {
2763 $this->file
= $file;
2764 $this->target
= $target;
2765 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2766 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2767 $this->oldName
= $this->file
->getName();
2768 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2769 $this->oldRel
= $this->oldHash
. $this->oldName
;
2770 $this->newRel
= $this->newHash
. $this->newName
;
2771 $this->db
= $file->getRepo()->getMasterDB();
2775 * Add the current image to the batch
2777 public function addCurrent() {
2778 $this->cur
= [ $this->oldRel
, $this->newRel
];
2782 * Add the old versions of the image to the batch
2783 * @return array List of archive names from old versions
2785 public function addOlds() {
2786 $archiveBase = 'archive';
2788 $this->oldCount
= 0;
2791 $result = $this->db
->select( 'oldimage',
2792 [ 'oi_archive_name', 'oi_deleted' ],
2793 [ 'oi_name' => $this->oldName
],
2795 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2798 foreach ( $result as $row ) {
2799 $archiveNames[] = $row->oi_archive_name
;
2800 $oldName = $row->oi_archive_name
;
2801 $bits = explode( '!', $oldName, 2 );
2803 if ( count( $bits ) != 2 ) {
2804 wfDebug( "Old file name missing !: '$oldName' \n" );
2808 list( $timestamp, $filename ) = $bits;
2810 if ( $this->oldName
!= $filename ) {
2811 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2817 // Do we want to add those to oldCount?
2818 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2823 "{$archiveBase}/{$this->oldHash}{$oldName}",
2824 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2828 return $archiveNames;
2833 * @return FileRepoStatus
2835 public function execute() {
2836 $repo = $this->file
->repo
;
2837 $status = $repo->newGood();
2839 $triplets = $this->getMoveTriplets();
2840 $checkStatus = $this->removeNonexistentFiles( $triplets );
2841 if ( !$checkStatus->isGood() ) {
2842 $status->merge( $checkStatus );
2845 $triplets = $checkStatus->value
;
2846 $destFile = wfLocalFile( $this->target
);
2848 $this->file
->lock(); // begin
2849 $destFile->lock(); // quickly fail if destination is not available
2850 // Rename the file versions metadata in the DB.
2851 // This implicitly locks the destination file, which avoids race conditions.
2852 // If we moved the files from A -> C before DB updates, another process could
2853 // move files from B -> C at this point, causing storeBatch() to fail and thus
2854 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2855 $statusDb = $this->doDBUpdates();
2856 if ( !$statusDb->isGood() ) {
2857 $destFile->unlock();
2858 $this->file
->unlockAndRollback();
2859 $statusDb->ok
= false;
2863 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2864 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2866 if ( !$repo->hasSha1Storage() ) {
2867 // Copy the files into their new location.
2868 // If a prior process fataled copying or cleaning up files we tolerate any
2869 // of the existing files if they are identical to the ones being stored.
2870 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2871 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2872 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2873 if ( !$statusMove->isGood() ) {
2874 // Delete any files copied over (while the destination is still locked)
2875 $this->cleanupTarget( $triplets );
2876 $destFile->unlock();
2877 $this->file
->unlockAndRollback(); // unlocks the destination
2878 wfDebugLog( 'imagemove', "Error in moving files: "
2879 . $statusMove->getWikiText( false, false, 'en' ) );
2880 $statusMove->ok
= false;
2884 $status->merge( $statusMove );
2887 $destFile->unlock();
2888 $this->file
->unlock(); // done
2890 // Everything went ok, remove the source files
2891 $this->cleanupSource( $triplets );
2893 $status->merge( $statusDb );
2899 * Do the database updates and return a new FileRepoStatus indicating how
2900 * many rows where updated.
2902 * @return FileRepoStatus
2904 protected function doDBUpdates() {
2905 $repo = $this->file
->repo
;
2906 $status = $repo->newGood();
2909 // Update current image
2912 [ 'img_name' => $this->newName
],
2913 [ 'img_name' => $this->oldName
],
2917 if ( $dbw->affectedRows() ) {
2918 $status->successCount++
;
2920 $status->failCount++
;
2921 $status->fatal( 'imageinvalidfilename' );
2926 // Update old images
2930 'oi_name' => $this->newName
,
2931 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2932 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2934 [ 'oi_name' => $this->oldName
],
2938 $affected = $dbw->affectedRows();
2939 $total = $this->oldCount
;
2940 $status->successCount +
= $affected;
2941 // Bug 34934: $total is based on files that actually exist.
2942 // There may be more DB rows than such files, in which case $affected
2943 // can be greater than $total. We use max() to avoid negatives here.
2944 $status->failCount +
= max( 0, $total - $affected );
2945 if ( $status->failCount
) {
2946 $status->error( 'imageinvalidfilename' );
2953 * Generate triplets for FileRepo::storeBatch().
2956 protected function getMoveTriplets() {
2957 $moves = array_merge( [ $this->cur
], $this->olds
);
2958 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
2960 foreach ( $moves as $move ) {
2961 // $move: (oldRelativePath, newRelativePath)
2962 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2963 $triplets[] = [ $srcUrl, 'public', $move[1] ];
2966 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2974 * Removes non-existent files from move batch.
2975 * @param array $triplets
2978 protected function removeNonexistentFiles( $triplets ) {
2981 foreach ( $triplets as $file ) {
2982 $files[$file[0]] = $file[0];
2985 $result = $this->file
->repo
->fileExistsBatch( $files );
2986 if ( in_array( null, $result, true ) ) {
2987 return Status
::newFatal( 'backend-fail-internal',
2988 $this->file
->repo
->getBackend()->getName() );
2991 $filteredTriplets = [];
2992 foreach ( $triplets as $file ) {
2993 if ( $result[$file[0]] ) {
2994 $filteredTriplets[] = $file;
2996 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3000 return Status
::newGood( $filteredTriplets );
3004 * Cleanup a partially moved array of triplets by deleting the target
3005 * files. Called if something went wrong half way.
3006 * @param array $triplets
3008 protected function cleanupTarget( $triplets ) {
3009 // Create dest pairs from the triplets
3011 foreach ( $triplets as $triplet ) {
3012 // $triplet: (old source virtual URL, dst zone, dest rel)
3013 $pairs[] = [ $triplet[1], $triplet[2] ];
3016 $this->file
->repo
->cleanupBatch( $pairs );
3020 * Cleanup a fully moved array of triplets by deleting the source files.
3021 * Called at the end of the move process if everything else went ok.
3022 * @param array $triplets
3024 protected function cleanupSource( $triplets ) {
3025 // Create source file names from the triplets
3027 foreach ( $triplets as $triplet ) {
3028 $files[] = $triplet[0];
3031 $this->file
->repo
->cleanupBatch( $files );