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 = array( '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 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 if ( $this->dataLoaded
) {
271 wfIncrStats( 'image_cache.hit' );
273 wfIncrStats( 'image_cache.miss' );
276 return $this->dataLoaded
;
280 * Save the file metadata to memcached
282 function saveToCache() {
285 $key = $this->getCacheKey();
290 $fields = $this->getCacheFields( '' );
291 $cacheVal = array( 'version' => MW_FILE_VERSION
);
292 $cacheVal['fileExists'] = $this->fileExists
;
294 if ( $this->fileExists
) {
295 foreach ( $fields as $field ) {
296 $cacheVal[$field] = $this->$field;
300 // Strip off excessive entries from the subset of fields that can become large.
301 // If the cache value gets to large it will not fit in memcached and nothing will
302 // get cached at all, causing master queries for any file access.
303 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
304 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
305 unset( $cacheVal[$field] ); // don't let the value get too big
309 // Cache presence for 1 week and negatives for 1 day
310 $ttl = $this->fileExists ?
86400 * 7 : 86400;
311 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
312 ObjectCache
::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
316 * Purge the file object/metadata cache
318 public function invalidateCache() {
319 $key = $this->getCacheKey();
324 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
325 ObjectCache
::getMainWANInstance()->delete( $key );
330 * Load metadata from the file itself
332 function loadFromFile() {
333 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
334 $this->setProps( $props );
338 * @param string $prefix
341 function getCacheFields( $prefix = 'img_' ) {
342 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
343 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
344 'user_text', 'description' );
345 static $results = array();
347 if ( $prefix == '' ) {
351 if ( !isset( $results[$prefix] ) ) {
352 $prefixedFields = array();
353 foreach ( $fields as $field ) {
354 $prefixedFields[] = $prefix . $field;
356 $results[$prefix] = $prefixedFields;
359 return $results[$prefix];
363 * @param string $prefix
366 function getLazyCacheFields( $prefix = 'img_' ) {
367 static $fields = array( 'metadata' );
368 static $results = array();
370 if ( $prefix == '' ) {
374 if ( !isset( $results[$prefix] ) ) {
375 $prefixedFields = array();
376 foreach ( $fields as $field ) {
377 $prefixedFields[] = $prefix . $field;
379 $results[$prefix] = $prefixedFields;
382 return $results[$prefix];
386 * Load file metadata from the DB
389 function loadFromDB( $flags = 0 ) {
390 $fname = get_class( $this ) . '::' . __FUNCTION__
;
392 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
393 $this->dataLoaded
= true;
394 $this->extraDataLoaded
= true;
396 $dbr = ( $flags & self
::READ_LATEST
)
397 ?
$this->repo
->getMasterDB()
398 : $this->repo
->getSlaveDB();
400 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
401 array( 'img_name' => $this->getName() ), $fname );
404 $this->loadFromRow( $row );
406 $this->fileExists
= false;
411 * Load lazy file metadata from the DB.
412 * This covers fields that are sometimes not cached.
414 protected function loadExtraFromDB() {
415 $fname = get_class( $this ) . '::' . __FUNCTION__
;
417 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
418 $this->extraDataLoaded
= true;
420 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
422 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
426 foreach ( $fieldMap as $name => $value ) {
427 $this->$name = $value;
430 throw new MWException( "Could not find data for image '{$this->getName()}'." );
435 * @param IDatabase $dbr
436 * @param string $fname
439 private function loadFieldsWithTimestamp( $dbr, $fname ) {
442 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
443 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
446 $fieldMap = $this->unprefixRow( $row, 'img_' );
448 # File may have been uploaded over in the meantime; check the old versions
449 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
450 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
453 $fieldMap = $this->unprefixRow( $row, 'oi_' );
461 * @param array|object $row
462 * @param string $prefix
463 * @throws MWException
466 protected function unprefixRow( $row, $prefix = 'img_' ) {
467 $array = (array)$row;
468 $prefixLength = strlen( $prefix );
470 // Sanity check prefix once
471 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
472 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
476 foreach ( $array as $name => $value ) {
477 $decoded[substr( $name, $prefixLength )] = $value;
484 * Decode a row from the database (either object or array) to an array
485 * with timestamps and MIME types decoded, and the field prefix removed.
487 * @param string $prefix
488 * @throws MWException
491 function decodeRow( $row, $prefix = 'img_' ) {
492 $decoded = $this->unprefixRow( $row, $prefix );
494 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
496 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
498 if ( empty( $decoded['major_mime'] ) ) {
499 $decoded['mime'] = 'unknown/unknown';
501 if ( !$decoded['minor_mime'] ) {
502 $decoded['minor_mime'] = 'unknown';
504 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
507 // Trim zero padding from char/binary field
508 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
510 // Normalize some fields to integer type, per their database definition.
511 // Use unary + so that overflows will be upgraded to double instead of
512 // being trucated as with intval(). This is important to allow >2GB
513 // files on 32-bit systems.
514 foreach ( array( 'size', 'width', 'height', 'bits' ) as $field ) {
515 $decoded[$field] = +
$decoded[$field];
522 * Load file metadata from a DB result row
525 * @param string $prefix
527 function loadFromRow( $row, $prefix = 'img_' ) {
528 $this->dataLoaded
= true;
529 $this->extraDataLoaded
= true;
531 $array = $this->decodeRow( $row, $prefix );
533 foreach ( $array as $name => $value ) {
534 $this->$name = $value;
537 $this->fileExists
= true;
538 $this->maybeUpgradeRow();
542 * Load file metadata from cache or DB, unless already loaded
545 function load( $flags = 0 ) {
546 if ( !$this->dataLoaded
) {
547 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
548 $this->loadFromDB( $flags );
549 $this->saveToCache();
551 $this->dataLoaded
= true;
553 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
554 // @note: loads on name/timestamp to reduce race condition problems
555 $this->loadExtraFromDB();
560 * Upgrade a row if it needs it
562 function maybeUpgradeRow() {
563 global $wgUpdateCompatibleMetadata;
564 if ( wfReadOnly() ) {
568 if ( is_null( $this->media_type
) ||
569 $this->mime
== 'image/svg'
572 $this->upgraded
= true;
574 $handler = $this->getHandler();
576 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
577 if ( $validity === MediaHandler
::METADATA_BAD
578 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
581 $this->upgraded
= true;
587 function getUpgraded() {
588 return $this->upgraded
;
592 * Fix assorted version-related problems with the image row by reloading it from the file
594 function upgradeRow() {
596 $this->lock(); // begin
598 $this->loadFromFile();
600 # Don't destroy file info of missing files
601 if ( !$this->fileExists
) {
603 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
608 $dbw = $this->repo
->getMasterDB();
609 list( $major, $minor ) = self
::splitMime( $this->mime
);
611 if ( wfReadOnly() ) {
616 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
618 $dbw->update( 'image',
620 'img_size' => $this->size
, // sanity
621 'img_width' => $this->width
,
622 'img_height' => $this->height
,
623 'img_bits' => $this->bits
,
624 'img_media_type' => $this->media_type
,
625 'img_major_mime' => $major,
626 'img_minor_mime' => $minor,
627 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
628 'img_sha1' => $this->sha1
,
630 array( 'img_name' => $this->getName() ),
634 $this->invalidateCache();
636 $this->unlock(); // done
641 * Set properties in this object to be equal to those given in the
642 * associative array $info. Only cacheable fields can be set.
643 * All fields *must* be set in $info except for getLazyCacheFields().
645 * If 'mime' is given, it will be split into major_mime/minor_mime.
646 * If major_mime/minor_mime are given, $this->mime will also be set.
650 function setProps( $info ) {
651 $this->dataLoaded
= true;
652 $fields = $this->getCacheFields( '' );
653 $fields[] = 'fileExists';
655 foreach ( $fields as $field ) {
656 if ( isset( $info[$field] ) ) {
657 $this->$field = $info[$field];
661 // Fix up mime fields
662 if ( isset( $info['major_mime'] ) ) {
663 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
664 } elseif ( isset( $info['mime'] ) ) {
665 $this->mime
= $info['mime'];
666 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
670 /** splitMime inherited */
671 /** getName inherited */
672 /** getTitle inherited */
673 /** getURL inherited */
674 /** getViewURL inherited */
675 /** getPath inherited */
676 /** isVisible inherited */
681 function isMissing() {
682 if ( $this->missing
=== null ) {
683 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
684 $this->missing
= !$fileExists;
687 return $this->missing
;
691 * Return the width of the image
696 public function getWidth( $page = 1 ) {
699 if ( $this->isMultipage() ) {
700 $handler = $this->getHandler();
704 $dim = $handler->getPageDimensions( $this, $page );
706 return $dim['width'];
708 // For non-paged media, the false goes through an
709 // intval, turning failure into 0, so do same here.
718 * Return the height of the image
723 public function getHeight( $page = 1 ) {
726 if ( $this->isMultipage() ) {
727 $handler = $this->getHandler();
731 $dim = $handler->getPageDimensions( $this, $page );
733 return $dim['height'];
735 // For non-paged media, the false goes through an
736 // intval, turning failure into 0, so do same here.
740 return $this->height
;
745 * Returns ID or name of user who uploaded the file
747 * @param string $type 'text' or 'id'
750 function getUser( $type = 'text' ) {
753 if ( $type == 'text' ) {
754 return $this->user_text
;
755 } elseif ( $type == 'id' ) {
756 return (int)$this->user
;
761 * Get short description URL for a file based on the page ID.
763 * @return string|null
764 * @throws MWException
767 public function getDescriptionShortUrl() {
768 $pageId = $this->title
->getArticleID();
770 if ( $pageId !== null ) {
771 $url = $this->repo
->makeUrl( array( 'curid' => $pageId ) );
772 if ( $url !== false ) {
780 * Get handler-specific metadata
783 function getMetadata() {
784 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
785 return $this->metadata
;
791 function getBitDepth() {
794 return (int)$this->bits
;
798 * Returns the size of the image file, in bytes
801 public function getSize() {
808 * Returns the MIME type of the file.
811 function getMimeType() {
818 * Returns the type of the media in the file.
819 * Use the value returned by this function with the MEDIATYPE_xxx constants.
822 function getMediaType() {
825 return $this->media_type
;
828 /** canRender inherited */
829 /** mustRender inherited */
830 /** allowInlineDisplay inherited */
831 /** isSafeFile inherited */
832 /** isTrustedFile inherited */
835 * Returns true if the file exists on disk.
836 * @return bool Whether file exist on disk.
838 public function exists() {
841 return $this->fileExists
;
844 /** getTransformScript inherited */
845 /** getUnscaledThumb inherited */
846 /** thumbName inherited */
847 /** createThumb inherited */
848 /** transform inherited */
850 /** getHandler inherited */
851 /** iconThumb inherited */
852 /** getLastError inherited */
855 * Get all thumbnail names previously generated for this file
856 * @param string|bool $archiveName Name of an archive file, default false
857 * @return array First element is the base dir, then files in that base dir.
859 function getThumbnails( $archiveName = false ) {
860 if ( $archiveName ) {
861 $dir = $this->getArchiveThumbPath( $archiveName );
863 $dir = $this->getThumbPath();
866 $backend = $this->repo
->getBackend();
867 $files = array( $dir );
869 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
870 foreach ( $iterator as $file ) {
873 } catch ( FileBackendError
$e ) {
874 } // suppress (bug 54674)
880 * Refresh metadata in memcached, but don't touch thumbnails or CDN
882 function purgeMetadataCache() {
883 $this->invalidateCache();
887 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
889 * @param array $options An array potentially with the key forThumbRefresh.
891 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
893 function purgeCache( $options = array() ) {
894 // Refresh metadata cache
895 $this->purgeMetadataCache();
898 $this->purgeThumbnails( $options );
900 // Purge CDN cache for this file
901 DeferredUpdates
::addUpdate(
902 new CdnCacheUpdate( array( $this->getUrl() ) ),
903 DeferredUpdates
::PRESEND
908 * Delete cached transformed files for an archived version only.
909 * @param string $archiveName Name of the archived file
911 function purgeOldThumbnails( $archiveName ) {
912 // Get a list of old thumbnails and URLs
913 $files = $this->getThumbnails( $archiveName );
915 // Purge any custom thumbnail caches
916 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
918 $dir = array_shift( $files );
919 $this->purgeThumbList( $dir, $files );
923 foreach ( $files as $file ) {
924 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
926 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
930 * Delete cached transformed files for the current version only.
931 * @param array $options
933 public function purgeThumbnails( $options = array() ) {
935 $files = $this->getThumbnails();
936 // Always purge all files from CDN regardless of handler filters
938 foreach ( $files as $file ) {
939 $urls[] = $this->getThumbUrl( $file );
941 array_shift( $urls ); // don't purge directory
943 // Give media handler a chance to filter the file purge list
944 if ( !empty( $options['forThumbRefresh'] ) ) {
945 $handler = $this->getHandler();
947 $handler->filterThumbnailPurgeList( $files, $options );
951 // Purge any custom thumbnail caches
952 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
954 $dir = array_shift( $files );
955 $this->purgeThumbList( $dir, $files );
958 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
962 * Delete a list of thumbnails visible at urls
963 * @param string $dir Base dir of the files.
964 * @param array $files Array of strings: relative filenames (to $dir)
966 protected function purgeThumbList( $dir, $files ) {
967 $fileListDebug = strtr(
968 var_export( $files, true ),
971 wfDebug( __METHOD__
. ": $fileListDebug\n" );
973 $purgeList = array();
974 foreach ( $files as $file ) {
975 # Check that the base file name is part of the thumb name
976 # This is a basic sanity check to avoid erasing unrelated directories
977 if ( strpos( $file, $this->getName() ) !== false
978 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
980 $purgeList[] = "{$dir}/{$file}";
984 # Delete the thumbnails
985 $this->repo
->quickPurgeBatch( $purgeList );
986 # Clear out the thumbnail directory if empty
987 $this->repo
->quickCleanDir( $dir );
990 /** purgeDescription inherited */
991 /** purgeEverything inherited */
994 * @param int $limit Optional: Limit to number of results
995 * @param int $start Optional: Timestamp, start from
996 * @param int $end Optional: Timestamp, end at
998 * @return OldLocalFile[]
1000 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1001 $dbr = $this->repo
->getSlaveDB();
1002 $tables = array( 'oldimage' );
1003 $fields = OldLocalFile
::selectFields();
1004 $conds = $opts = $join_conds = array();
1005 $eq = $inc ?
'=' : '';
1006 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1009 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1013 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1017 $opts['LIMIT'] = $limit;
1020 // Search backwards for time > x queries
1021 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1022 $opts['ORDER BY'] = "oi_timestamp $order";
1023 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1025 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1026 &$conds, &$opts, &$join_conds ) );
1028 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1031 foreach ( $res as $row ) {
1032 $r[] = $this->repo
->newFileFromRow( $row );
1035 if ( $order == 'ASC' ) {
1036 $r = array_reverse( $r ); // make sure it ends up descending
1043 * Returns the history of this file, line by line.
1044 * starts with current version, then old versions.
1045 * uses $this->historyLine to check which line to return:
1046 * 0 return line for current version
1047 * 1 query for old versions, return first one
1048 * 2, ... return next old version from above query
1051 public function nextHistoryLine() {
1052 # Polymorphic function name to distinguish foreign and local fetches
1053 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1055 $dbr = $this->repo
->getSlaveDB();
1057 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1058 $this->historyRes
= $dbr->select( 'image',
1061 "'' AS oi_archive_name",
1065 array( 'img_name' => $this->title
->getDBkey() ),
1069 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1070 $this->historyRes
= null;
1074 } elseif ( $this->historyLine
== 1 ) {
1075 $this->historyRes
= $dbr->select( 'oldimage', '*',
1076 array( 'oi_name' => $this->title
->getDBkey() ),
1078 array( 'ORDER BY' => 'oi_timestamp DESC' )
1081 $this->historyLine++
;
1083 return $dbr->fetchObject( $this->historyRes
);
1087 * Reset the history pointer to the first element of the history
1089 public function resetHistory() {
1090 $this->historyLine
= 0;
1092 if ( !is_null( $this->historyRes
) ) {
1093 $this->historyRes
= null;
1097 /** getHashPath inherited */
1098 /** getRel inherited */
1099 /** getUrlRel inherited */
1100 /** getArchiveRel inherited */
1101 /** getArchivePath inherited */
1102 /** getThumbPath inherited */
1103 /** getArchiveUrl inherited */
1104 /** getThumbUrl inherited */
1105 /** getArchiveVirtualUrl inherited */
1106 /** getThumbVirtualUrl inherited */
1107 /** isHashed inherited */
1110 * Upload a file and record it in the DB
1111 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1112 * @param string $comment Upload description
1113 * @param string $pageText Text to use for the new description page,
1114 * if a new description page is created
1115 * @param int|bool $flags Flags for publish()
1116 * @param array|bool $props File properties, if known. This can be used to
1117 * reduce the upload time when uploading virtual URLs for which the file
1118 * info is already known
1119 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1121 * @param User|null $user User object or null to use $wgUser
1123 * @return FileRepoStatus On success, the value member contains the
1124 * archive name, or an empty string if it was a new file.
1126 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1127 $timestamp = false, $user = null
1131 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1132 return $this->readOnlyFatalStatus();
1136 if ( $this->repo
->isVirtualUrl( $srcPath )
1137 || FileBackend
::isStoragePath( $srcPath )
1139 $props = $this->repo
->getFileProps( $srcPath );
1141 $props = FSFile
::getPropsFromPath( $srcPath );
1146 $handler = MediaHandler
::getHandler( $props['mime'] );
1148 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1150 $options['headers'] = array();
1153 // Trim spaces on user supplied text
1154 $comment = trim( $comment );
1156 // Truncate nicely or the DB will do it for us
1157 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1158 $comment = $wgContLang->truncate( $comment, 255 );
1159 $this->lock(); // begin
1160 $status = $this->publish( $srcPath, $flags, $options );
1162 if ( $status->successCount
>= 2 ) {
1163 // There will be a copy+(one of move,copy,store).
1164 // The first succeeding does not commit us to updating the DB
1165 // since it simply copied the current version to a timestamped file name.
1166 // It is only *preferable* to avoid leaving such files orphaned.
1167 // Once the second operation goes through, then the current version was
1168 // updated and we must therefore update the DB too.
1169 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1170 $status->fatal( 'filenotfound', $srcPath );
1174 $this->unlock(); // done
1180 * Record a file upload in the upload log and the image table
1181 * @param string $oldver
1182 * @param string $desc
1183 * @param string $license
1184 * @param string $copyStatus
1185 * @param string $source
1186 * @param bool $watch
1187 * @param string|bool $timestamp
1188 * @param User|null $user User object or null to use $wgUser
1191 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1192 $watch = false, $timestamp = false, User
$user = null ) {
1198 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1200 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1205 $user->addWatch( $this->getTitle() );
1212 * Record a file upload in the upload log and the image table
1213 * @param string $oldver
1214 * @param string $comment
1215 * @param string $pageText
1216 * @param bool|array $props
1217 * @param string|bool $timestamp
1218 * @param null|User $user
1221 function recordUpload2(
1222 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1224 if ( is_null( $user ) ) {
1229 $dbw = $this->repo
->getMasterDB();
1231 # Imports or such might force a certain timestamp; otherwise we generate
1232 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1233 if ( $timestamp === false ) {
1234 $timestamp = $dbw->timestamp();
1235 $allowTimeKludge = true;
1237 $allowTimeKludge = false;
1240 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1241 $props['description'] = $comment;
1242 $props['user'] = $user->getId();
1243 $props['user_text'] = $user->getName();
1244 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1245 $this->setProps( $props );
1247 # Fail now if the file isn't there
1248 if ( !$this->fileExists
) {
1249 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1254 $dbw->startAtomic( __METHOD__
);
1256 # Test to see if the row exists using INSERT IGNORE
1257 # This avoids race conditions by locking the row until the commit, and also
1258 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1259 $dbw->insert( 'image',
1261 'img_name' => $this->getName(),
1262 'img_size' => $this->size
,
1263 'img_width' => intval( $this->width
),
1264 'img_height' => intval( $this->height
),
1265 'img_bits' => $this->bits
,
1266 'img_media_type' => $this->media_type
,
1267 'img_major_mime' => $this->major_mime
,
1268 'img_minor_mime' => $this->minor_mime
,
1269 'img_timestamp' => $timestamp,
1270 'img_description' => $comment,
1271 'img_user' => $user->getId(),
1272 'img_user_text' => $user->getName(),
1273 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1274 'img_sha1' => $this->sha1
1280 $reupload = ( $dbw->affectedRows() == 0 );
1282 if ( $allowTimeKludge ) {
1283 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1284 $ltimestamp = $dbw->selectField(
1287 array( 'img_name' => $this->getName() ),
1289 array( 'LOCK IN SHARE MODE' )
1291 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1292 # Avoid a timestamp that is not newer than the last version
1293 # TODO: the image/oldimage tables should be like page/revision with an ID field
1294 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1295 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1296 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1297 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1301 # (bug 34993) Note: $oldver can be empty here, if the previous
1302 # version of the file was broken. Allow registration of the new
1303 # version to continue anyway, because that's better than having
1304 # an image that's not fixable by user operations.
1305 # Collision, this is an update of a file
1306 # Insert previous contents into oldimage
1307 $dbw->insertSelect( 'oldimage', 'image',
1309 'oi_name' => 'img_name',
1310 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1311 'oi_size' => 'img_size',
1312 'oi_width' => 'img_width',
1313 'oi_height' => 'img_height',
1314 'oi_bits' => 'img_bits',
1315 'oi_timestamp' => 'img_timestamp',
1316 'oi_description' => 'img_description',
1317 'oi_user' => 'img_user',
1318 'oi_user_text' => 'img_user_text',
1319 'oi_metadata' => 'img_metadata',
1320 'oi_media_type' => 'img_media_type',
1321 'oi_major_mime' => 'img_major_mime',
1322 'oi_minor_mime' => 'img_minor_mime',
1323 'oi_sha1' => 'img_sha1'
1325 array( 'img_name' => $this->getName() ),
1329 # Update the current image row
1330 $dbw->update( 'image',
1332 'img_size' => $this->size
,
1333 'img_width' => intval( $this->width
),
1334 'img_height' => intval( $this->height
),
1335 'img_bits' => $this->bits
,
1336 'img_media_type' => $this->media_type
,
1337 'img_major_mime' => $this->major_mime
,
1338 'img_minor_mime' => $this->minor_mime
,
1339 'img_timestamp' => $timestamp,
1340 'img_description' => $comment,
1341 'img_user' => $user->getId(),
1342 'img_user_text' => $user->getName(),
1343 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1344 'img_sha1' => $this->sha1
1346 array( 'img_name' => $this->getName() ),
1351 $descTitle = $this->getTitle();
1352 $descId = $descTitle->getArticleID();
1353 $wikiPage = new WikiFilePage( $descTitle );
1354 $wikiPage->setFile( $this );
1356 // Add the log entry...
1357 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1358 $logEntry->setTimestamp( $this->timestamp
);
1359 $logEntry->setPerformer( $user );
1360 $logEntry->setComment( $comment );
1361 $logEntry->setTarget( $descTitle );
1362 // Allow people using the api to associate log entries with the upload.
1363 // Log has a timestamp, but sometimes different from upload timestamp.
1364 $logEntry->setParameters(
1366 'img_sha1' => $this->sha1
,
1367 'img_timestamp' => $timestamp,
1370 // Note we keep $logId around since during new image
1371 // creation, page doesn't exist yet, so log_page = 0
1372 // but we want it to point to the page we're making,
1373 // so we later modify the log entry.
1374 // For a similar reason, we avoid making an RC entry
1375 // now and wait until the page exists.
1376 $logId = $logEntry->insert();
1378 if ( $descTitle->exists() ) {
1379 // Use own context to get the action text in content language
1380 $formatter = LogFormatter
::newFromEntry( $logEntry );
1381 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1382 $editSummary = $formatter->getPlainActionText();
1384 $nullRevision = Revision
::newNullRevision(
1391 if ( $nullRevision ) {
1392 $nullRevision->insertOn( $dbw );
1394 'NewRevisionFromEditComplete',
1395 array( $wikiPage, $nullRevision, $nullRevision->getParentId(), $user )
1397 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1398 // Associate null revision id
1399 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1402 $newPageContent = null;
1404 // Make the description page and RC log entry post-commit
1405 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1408 # Defer purges, page creation, and link updates in case they error out.
1409 # The most important thing is that files and the DB registry stay synced.
1410 $dbw->endAtomic( __METHOD__
);
1412 # Do some cache purges after final commit so that:
1413 # a) Changes are more likely to be seen post-purge
1414 # b) They won't cause rollback of the log publish/update above
1416 $dbw->onTransactionIdle( function () use (
1417 $that, $reupload, $wikiPage, $newPageContent, $comment, $user, $logEntry, $logId, $descId
1419 # Update memcache after the commit
1420 $that->invalidateCache();
1422 $updateLogPage = false;
1423 if ( $newPageContent ) {
1424 # New file page; create the description page.
1425 # There's already a log entry, so don't make a second RC entry
1426 # CDN and file cache for the description page are purged by doEditContent.
1427 $status = $wikiPage->doEditContent(
1430 EDIT_NEW | EDIT_SUPPRESS_RC
,
1435 if ( isset( $status->value
['revision'] ) ) {
1436 // Associate new page revision id
1437 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1439 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1440 // which is triggered on $descTitle by doEditContent() above.
1441 if ( isset( $status->value
['revision'] ) ) {
1442 /** @var $rev Revision */
1443 $rev = $status->value
['revision'];
1444 $updateLogPage = $rev->getPage();
1447 # Existing file page: invalidate description page cache
1448 $wikiPage->getTitle()->invalidateCache();
1449 $wikiPage->getTitle()->purgeSquid();
1450 # Allow the new file version to be patrolled from the page footer
1451 Article
::purgePatrolFooterCache( $descId );
1454 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1455 # but setAssociatedRevId() wasn't called at that point yet...
1456 $logParams = $logEntry->getParameters();
1457 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1458 $update = array( 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) );
1459 if ( $updateLogPage ) {
1460 # Also log page, in case where we just created it above
1461 $update['log_page'] = $updateLogPage;
1463 $that->getRepo()->getMasterDB()->update(
1466 array( 'log_id' => $logId ),
1469 $that->getRepo()->getMasterDB()->insert(
1472 'ls_field' => 'associated_rev_id',
1473 'ls_value' => $logEntry->getAssociatedRevId(),
1474 'ls_log_id' => $logId,
1479 # Now that the log entry is up-to-date, make an RC entry.
1480 $logEntry->publish( $logId );
1481 # Run hook for other updates (typically more cache purging)
1482 Hooks
::run( 'FileUpload', array( $that, $reupload, !$newPageContent ) );
1485 # Delete old thumbnails
1486 $that->purgeThumbnails();
1487 # Remove the old file from the CDN cache
1488 DeferredUpdates
::addUpdate(
1489 new CdnCacheUpdate( array( $that->getUrl() ) ),
1490 DeferredUpdates
::PRESEND
1493 # Update backlink pages pointing to this title if created
1494 LinksUpdate
::queueRecursiveJobsForTable( $that->getTitle(), 'imagelinks' );
1499 # This is a new file, so update the image count
1500 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1503 # Invalidate cache for all pages using this file
1504 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1510 * Move or copy a file to its public location. If a file exists at the
1511 * destination, move it to an archive. Returns a FileRepoStatus object with
1512 * the archive name in the "value" member on success.
1514 * The archive name should be passed through to recordUpload for database
1517 * @param string $srcPath Local filesystem path or virtual URL to the source image
1518 * @param int $flags A bitwise combination of:
1519 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1520 * @param array $options Optional additional parameters
1521 * @return FileRepoStatus On success, the value member contains the
1522 * archive name, or an empty string if it was a new file.
1524 function publish( $srcPath, $flags = 0, array $options = array() ) {
1525 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1529 * Move or copy a file to a specified location. Returns a FileRepoStatus
1530 * object with the archive name in the "value" member on success.
1532 * The archive name should be passed through to recordUpload for database
1535 * @param string $srcPath Local filesystem path or virtual URL to the source image
1536 * @param string $dstRel Target relative path
1537 * @param int $flags A bitwise combination of:
1538 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1539 * @param array $options Optional additional parameters
1540 * @return FileRepoStatus On success, the value member contains the
1541 * archive name, or an empty string if it was a new file.
1543 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1544 $repo = $this->getRepo();
1545 if ( $repo->getReadOnlyReason() !== false ) {
1546 return $this->readOnlyFatalStatus();
1549 $this->lock(); // begin
1551 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1552 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1554 if ( $repo->hasSha1Storage() ) {
1555 $sha1 = $repo->isVirtualUrl( $srcPath )
1556 ?
$repo->getFileSha1( $srcPath )
1557 : File
::sha1Base36( $srcPath );
1558 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1559 $status = $repo->quickImport( $srcPath, $dst );
1560 if ( $flags & File
::DELETE_SOURCE
) {
1564 if ( $this->exists() ) {
1565 $status->value
= $archiveName;
1568 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1569 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1571 if ( $status->value
== 'new' ) {
1572 $status->value
= '';
1574 $status->value
= $archiveName;
1578 $this->unlock(); // done
1583 /** getLinksTo inherited */
1584 /** getExifData inherited */
1585 /** isLocal inherited */
1586 /** wasDeleted inherited */
1589 * Move file to the new title
1591 * Move current, old version and all thumbnails
1592 * to the new filename. Old file is deleted.
1594 * Cache purging is done; checks for validity
1595 * and logging are caller's responsibility
1597 * @param Title $target New file name
1598 * @return FileRepoStatus
1600 function move( $target ) {
1601 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1602 return $this->readOnlyFatalStatus();
1605 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1606 $batch = new LocalFileMoveBatch( $this, $target );
1608 $this->lock(); // begin
1609 $batch->addCurrent();
1610 $archiveNames = $batch->addOlds();
1611 $status = $batch->execute();
1612 $this->unlock(); // done
1614 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1616 // Purge the source and target files...
1617 $oldTitleFile = wfLocalFile( $this->title
);
1618 $newTitleFile = wfLocalFile( $target );
1619 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1620 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1621 $this->getRepo()->getMasterDB()->onTransactionIdle(
1622 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1623 $oldTitleFile->purgeEverything();
1624 foreach ( $archiveNames as $archiveName ) {
1625 $oldTitleFile->purgeOldThumbnails( $archiveName );
1627 $newTitleFile->purgeEverything();
1631 if ( $status->isOK() ) {
1632 // Now switch the object
1633 $this->title
= $target;
1634 // Force regeneration of the name and hashpath
1635 unset( $this->name
);
1636 unset( $this->hashPath
);
1643 * Delete all versions of the file.
1645 * Moves the files into an archive directory (or deletes them)
1646 * and removes the database rows.
1648 * Cache purging is done; logging is caller's responsibility.
1650 * @param string $reason
1651 * @param bool $suppress
1652 * @param User|null $user
1653 * @return FileRepoStatus
1655 function delete( $reason, $suppress = false, $user = null ) {
1656 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1657 return $this->readOnlyFatalStatus();
1660 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1662 $this->lock(); // begin
1663 $batch->addCurrent();
1664 # Get old version relative paths
1665 $archiveNames = $batch->addOlds();
1666 $status = $batch->execute();
1667 $this->unlock(); // done
1669 if ( $status->isOK() ) {
1670 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1673 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1674 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1676 $this->getRepo()->getMasterDB()->onTransactionIdle(
1677 function () use ( $that, $archiveNames ) {
1678 $that->purgeEverything();
1679 foreach ( $archiveNames as $archiveName ) {
1680 $that->purgeOldThumbnails( $archiveName );
1686 $purgeUrls = array();
1687 foreach ( $archiveNames as $archiveName ) {
1688 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1690 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1696 * Delete an old version of the file.
1698 * Moves the file into an archive directory (or deletes it)
1699 * and removes the database row.
1701 * Cache purging is done; logging is caller's responsibility.
1703 * @param string $archiveName
1704 * @param string $reason
1705 * @param bool $suppress
1706 * @param User|null $user
1707 * @throws MWException Exception on database or file store failure
1708 * @return FileRepoStatus
1710 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1711 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1712 return $this->readOnlyFatalStatus();
1715 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1717 $this->lock(); // begin
1718 $batch->addOld( $archiveName );
1719 $status = $batch->execute();
1720 $this->unlock(); // done
1722 $this->purgeOldThumbnails( $archiveName );
1723 if ( $status->isOK() ) {
1724 $this->purgeDescription();
1727 DeferredUpdates
::addUpdate(
1728 new CdnCacheUpdate( array( $this->getArchiveUrl( $archiveName ) ) ),
1729 DeferredUpdates
::PRESEND
1736 * Restore all or specified deleted revisions to the given file.
1737 * Permissions and logging are left to the caller.
1739 * May throw database exceptions on error.
1741 * @param array $versions Set of record ids of deleted items to restore,
1742 * or empty to restore all revisions.
1743 * @param bool $unsuppress
1744 * @return FileRepoStatus
1746 function restore( $versions = array(), $unsuppress = false ) {
1747 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1748 return $this->readOnlyFatalStatus();
1751 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1753 $this->lock(); // begin
1757 $batch->addIds( $versions );
1759 $status = $batch->execute();
1760 if ( $status->isGood() ) {
1761 $cleanupStatus = $batch->cleanup();
1762 $cleanupStatus->successCount
= 0;
1763 $cleanupStatus->failCount
= 0;
1764 $status->merge( $cleanupStatus );
1766 $this->unlock(); // done
1771 /** isMultipage inherited */
1772 /** pageCount inherited */
1773 /** scaleHeight inherited */
1774 /** getImageSize inherited */
1777 * Get the URL of the file description page.
1780 function getDescriptionUrl() {
1781 return $this->title
->getLocalURL();
1785 * Get the HTML text of the description page
1786 * This is not used by ImagePage for local files, since (among other things)
1787 * it skips the parser cache.
1789 * @param Language $lang What language to get description in (Optional)
1790 * @return bool|mixed
1792 function getDescriptionText( $lang = null ) {
1793 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1797 $content = $revision->getContent();
1801 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1803 return $pout->getText();
1807 * @param int $audience
1811 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1813 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1815 } elseif ( $audience == self
::FOR_THIS_USER
1816 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1820 return $this->description
;
1825 * @return bool|string
1827 function getTimestamp() {
1830 return $this->timestamp
;
1834 * @return bool|string
1836 public function getDescriptionTouched() {
1837 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1838 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1839 // need to differentiate between null (uninitialized) and false (failed to load).
1840 if ( $this->descriptionTouched
=== null ) {
1842 'page_namespace' => $this->title
->getNamespace(),
1843 'page_title' => $this->title
->getDBkey()
1845 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1846 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1849 return $this->descriptionTouched
;
1855 function getSha1() {
1857 // Initialise now if necessary
1858 if ( $this->sha1
== '' && $this->fileExists
) {
1859 $this->lock(); // begin
1861 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1862 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1863 $dbw = $this->repo
->getMasterDB();
1864 $dbw->update( 'image',
1865 array( 'img_sha1' => $this->sha1
),
1866 array( 'img_name' => $this->getName() ),
1868 $this->invalidateCache();
1871 $this->unlock(); // done
1878 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1880 function isCacheable() {
1883 // If extra data (metadata) was not loaded then it must have been large
1884 return $this->extraDataLoaded
1885 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1889 * Start a transaction and lock the image for update
1890 * Increments a reference counter if the lock is already held
1891 * @throws MWException Throws an error if the lock was not acquired
1892 * @return bool Whether the file lock owns/spawned the DB transaction
1895 $dbw = $this->repo
->getMasterDB();
1897 if ( !$this->locked
) {
1898 if ( !$dbw->trxLevel() ) {
1899 $dbw->begin( __METHOD__
);
1900 $this->lockedOwnTrx
= true;
1903 // Bug 54736: use simple lock to handle when the file does not exist.
1904 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1905 // Also, that would cause contention on INSERT of similarly named rows.
1906 $backend = $this->getRepo()->getBackend();
1907 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1908 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1909 if ( !$status->isGood() ) {
1910 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1912 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1913 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1917 return $this->lockedOwnTrx
;
1921 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1922 * the transaction and thereby releases the image lock.
1925 if ( $this->locked
) {
1927 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1928 $dbw = $this->repo
->getMasterDB();
1929 $dbw->commit( __METHOD__
);
1930 $this->lockedOwnTrx
= false;
1936 * Roll back the DB transaction and mark the image unlocked
1938 function unlockAndRollback() {
1939 $this->locked
= false;
1940 $dbw = $this->repo
->getMasterDB();
1941 $dbw->rollback( __METHOD__
);
1942 $this->lockedOwnTrx
= false;
1948 protected function readOnlyFatalStatus() {
1949 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1950 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1954 * Clean up any dangling locks
1956 function __destruct() {
1959 } // LocalFile class
1961 # ------------------------------------------------------------------------------
1964 * Helper class for file deletion
1965 * @ingroup FileAbstraction
1967 class LocalFileDeleteBatch
{
1968 /** @var LocalFile */
1975 private $srcRels = array();
1978 private $archiveUrls = array();
1980 /** @var array Items to be processed in the deletion batch */
1981 private $deletionBatch;
1983 /** @var bool Whether to suppress all suppressable fields when deleting */
1986 /** @var FileRepoStatus */
1994 * @param string $reason
1995 * @param bool $suppress
1996 * @param User|null $user
1998 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1999 $this->file
= $file;
2000 $this->reason
= $reason;
2001 $this->suppress
= $suppress;
2003 $this->user
= $user;
2006 $this->user
= $wgUser;
2008 $this->status
= $file->repo
->newGood();
2011 public function addCurrent() {
2012 $this->srcRels
['.'] = $this->file
->getRel();
2016 * @param string $oldName
2018 public function addOld( $oldName ) {
2019 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2020 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2024 * Add the old versions of the image to the batch
2025 * @return array List of archive names from old versions
2027 public function addOlds() {
2028 $archiveNames = array();
2030 $dbw = $this->file
->repo
->getMasterDB();
2031 $result = $dbw->select( 'oldimage',
2032 array( 'oi_archive_name' ),
2033 array( 'oi_name' => $this->file
->getName() ),
2037 foreach ( $result as $row ) {
2038 $this->addOld( $row->oi_archive_name
);
2039 $archiveNames[] = $row->oi_archive_name
;
2042 return $archiveNames;
2048 protected function getOldRels() {
2049 if ( !isset( $this->srcRels
['.'] ) ) {
2050 $oldRels =& $this->srcRels
;
2051 $deleteCurrent = false;
2053 $oldRels = $this->srcRels
;
2054 unset( $oldRels['.'] );
2055 $deleteCurrent = true;
2058 return array( $oldRels, $deleteCurrent );
2064 protected function getHashes() {
2066 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2068 if ( $deleteCurrent ) {
2069 $hashes['.'] = $this->file
->getSha1();
2072 if ( count( $oldRels ) ) {
2073 $dbw = $this->file
->repo
->getMasterDB();
2074 $res = $dbw->select(
2076 array( 'oi_archive_name', 'oi_sha1' ),
2077 array( 'oi_archive_name' => array_keys( $oldRels ),
2078 'oi_name' => $this->file
->getName() ), // performance
2082 foreach ( $res as $row ) {
2083 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2084 // Get the hash from the file
2085 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2086 $props = $this->file
->repo
->getFileProps( $oldUrl );
2088 if ( $props['fileExists'] ) {
2089 // Upgrade the oldimage row
2090 $dbw->update( 'oldimage',
2091 array( 'oi_sha1' => $props['sha1'] ),
2092 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2094 $hashes[$row->oi_archive_name
] = $props['sha1'];
2096 $hashes[$row->oi_archive_name
] = false;
2099 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2104 $missing = array_diff_key( $this->srcRels
, $hashes );
2106 foreach ( $missing as $name => $rel ) {
2107 $this->status
->error( 'filedelete-old-unregistered', $name );
2110 foreach ( $hashes as $name => $hash ) {
2112 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2113 unset( $hashes[$name] );
2120 protected function doDBInserts() {
2121 $dbw = $this->file
->repo
->getMasterDB();
2122 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2123 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2124 $encReason = $dbw->addQuotes( $this->reason
);
2125 $encGroup = $dbw->addQuotes( 'deleted' );
2126 $ext = $this->file
->getExtension();
2127 $dotExt = $ext === '' ?
'' : ".$ext";
2128 $encExt = $dbw->addQuotes( $dotExt );
2129 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2131 // Bitfields to further suppress the content
2132 if ( $this->suppress
) {
2134 // This should be 15...
2135 $bitfield |
= Revision
::DELETED_TEXT
;
2136 $bitfield |
= Revision
::DELETED_COMMENT
;
2137 $bitfield |
= Revision
::DELETED_USER
;
2138 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2140 $bitfield = 'oi_deleted';
2143 if ( $deleteCurrent ) {
2144 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2145 $where = array( 'img_name' => $this->file
->getName() );
2146 $dbw->insertSelect( 'filearchive', 'image',
2148 'fa_storage_group' => $encGroup,
2149 'fa_storage_key' => $dbw->conditional(
2150 array( 'img_sha1' => '' ),
2151 $dbw->addQuotes( '' ),
2154 'fa_deleted_user' => $encUserId,
2155 'fa_deleted_timestamp' => $encTimestamp,
2156 'fa_deleted_reason' => $encReason,
2157 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2159 'fa_name' => 'img_name',
2160 'fa_archive_name' => 'NULL',
2161 'fa_size' => 'img_size',
2162 'fa_width' => 'img_width',
2163 'fa_height' => 'img_height',
2164 'fa_metadata' => 'img_metadata',
2165 'fa_bits' => 'img_bits',
2166 'fa_media_type' => 'img_media_type',
2167 'fa_major_mime' => 'img_major_mime',
2168 'fa_minor_mime' => 'img_minor_mime',
2169 'fa_description' => 'img_description',
2170 'fa_user' => 'img_user',
2171 'fa_user_text' => 'img_user_text',
2172 'fa_timestamp' => 'img_timestamp',
2173 'fa_sha1' => 'img_sha1',
2174 ), $where, __METHOD__
);
2177 if ( count( $oldRels ) ) {
2178 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2180 'oi_name' => $this->file
->getName(),
2181 'oi_archive_name' => array_keys( $oldRels ) );
2182 $dbw->insertSelect( 'filearchive', 'oldimage',
2184 'fa_storage_group' => $encGroup,
2185 'fa_storage_key' => $dbw->conditional(
2186 array( 'oi_sha1' => '' ),
2187 $dbw->addQuotes( '' ),
2190 'fa_deleted_user' => $encUserId,
2191 'fa_deleted_timestamp' => $encTimestamp,
2192 'fa_deleted_reason' => $encReason,
2193 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2195 'fa_name' => 'oi_name',
2196 'fa_archive_name' => 'oi_archive_name',
2197 'fa_size' => 'oi_size',
2198 'fa_width' => 'oi_width',
2199 'fa_height' => 'oi_height',
2200 'fa_metadata' => 'oi_metadata',
2201 'fa_bits' => 'oi_bits',
2202 'fa_media_type' => 'oi_media_type',
2203 'fa_major_mime' => 'oi_major_mime',
2204 'fa_minor_mime' => 'oi_minor_mime',
2205 'fa_description' => 'oi_description',
2206 'fa_user' => 'oi_user',
2207 'fa_user_text' => 'oi_user_text',
2208 'fa_timestamp' => 'oi_timestamp',
2209 'fa_sha1' => 'oi_sha1',
2210 ), $where, __METHOD__
);
2214 function doDBDeletes() {
2215 $dbw = $this->file
->repo
->getMasterDB();
2216 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2218 if ( count( $oldRels ) ) {
2219 $dbw->delete( 'oldimage',
2221 'oi_name' => $this->file
->getName(),
2222 'oi_archive_name' => array_keys( $oldRels )
2226 if ( $deleteCurrent ) {
2227 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2232 * Run the transaction
2233 * @return FileRepoStatus
2235 public function execute() {
2236 $repo = $this->file
->getRepo();
2237 $this->file
->lock();
2239 // Prepare deletion batch
2240 $hashes = $this->getHashes();
2241 $this->deletionBatch
= array();
2242 $ext = $this->file
->getExtension();
2243 $dotExt = $ext === '' ?
'' : ".$ext";
2245 foreach ( $this->srcRels
as $name => $srcRel ) {
2246 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2247 if ( isset( $hashes[$name] ) ) {
2248 $hash = $hashes[$name];
2249 $key = $hash . $dotExt;
2250 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2251 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2255 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2256 // We acquire this lock by running the inserts now, before the file operations.
2257 // This potentially has poor lock contention characteristics -- an alternative
2258 // scheme would be to insert stub filearchive entries with no fa_name and commit
2259 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2260 $this->doDBInserts();
2262 if ( !$repo->hasSha1Storage() ) {
2263 // Removes non-existent file from the batch, so we don't get errors.
2264 // This also handles files in the 'deleted' zone deleted via revision deletion.
2265 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2266 if ( !$checkStatus->isGood() ) {
2267 $this->status
->merge( $checkStatus );
2268 return $this->status
;
2270 $this->deletionBatch
= $checkStatus->value
;
2272 // Execute the file deletion batch
2273 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2275 if ( !$status->isGood() ) {
2276 $this->status
->merge( $status );
2280 if ( !$this->status
->isOK() ) {
2281 // Critical file deletion error
2282 // Roll back inserts, release lock and abort
2283 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2284 $this->file
->unlockAndRollback();
2286 return $this->status
;
2289 // Delete image/oldimage rows
2290 $this->doDBDeletes();
2292 // Commit and return
2293 $this->file
->unlock();
2295 return $this->status
;
2299 * Removes non-existent files from a deletion batch.
2300 * @param array $batch
2303 protected function removeNonexistentFiles( $batch ) {
2304 $files = $newBatch = array();
2306 foreach ( $batch as $batchItem ) {
2307 list( $src, ) = $batchItem;
2308 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2311 $result = $this->file
->repo
->fileExistsBatch( $files );
2312 if ( in_array( null, $result, true ) ) {
2313 return Status
::newFatal( 'backend-fail-internal',
2314 $this->file
->repo
->getBackend()->getName() );
2317 foreach ( $batch as $batchItem ) {
2318 if ( $result[$batchItem[0]] ) {
2319 $newBatch[] = $batchItem;
2323 return Status
::newGood( $newBatch );
2327 # ------------------------------------------------------------------------------
2330 * Helper class for file undeletion
2331 * @ingroup FileAbstraction
2333 class LocalFileRestoreBatch
{
2334 /** @var LocalFile */
2337 /** @var array List of file IDs to restore */
2338 private $cleanupBatch;
2340 /** @var array List of file IDs to restore */
2343 /** @var bool Add all revisions of the file */
2346 /** @var bool Whether to remove all settings for suppressed fields */
2347 private $unsuppress = false;
2351 * @param bool $unsuppress
2353 function __construct( File
$file, $unsuppress = false ) {
2354 $this->file
= $file;
2355 $this->cleanupBatch
= $this->ids
= array();
2356 $this->ids
= array();
2357 $this->unsuppress
= $unsuppress;
2364 public function addId( $fa_id ) {
2365 $this->ids
[] = $fa_id;
2369 * Add a whole lot of files by ID
2372 public function addIds( $ids ) {
2373 $this->ids
= array_merge( $this->ids
, $ids );
2377 * Add all revisions of the file
2379 public function addAll() {
2384 * Run the transaction, except the cleanup batch.
2385 * The cleanup batch should be run in a separate transaction, because it locks different
2386 * rows and there's no need to keep the image row locked while it's acquiring those locks
2387 * The caller may have its own transaction open.
2388 * So we save the batch and let the caller call cleanup()
2389 * @return FileRepoStatus
2391 public function execute() {
2394 $repo = $this->file
->getRepo();
2395 if ( !$this->all
&& !$this->ids
) {
2397 return $repo->newGood();
2400 $lockOwnsTrx = $this->file
->lock();
2402 $dbw = $this->file
->repo
->getMasterDB();
2403 $status = $this->file
->repo
->newGood();
2405 $exists = (bool)$dbw->selectField( 'image', '1',
2406 array( 'img_name' => $this->file
->getName() ),
2408 // The lock() should already prevents changes, but this still may need
2409 // to bypass any transaction snapshot. However, if lock() started the
2410 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2411 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2414 // Fetch all or selected archived revisions for the file,
2415 // sorted from the most recent to the oldest.
2416 $conditions = array( 'fa_name' => $this->file
->getName() );
2418 if ( !$this->all
) {
2419 $conditions['fa_id'] = $this->ids
;
2422 $result = $dbw->select(
2424 ArchivedFile
::selectFields(),
2427 array( 'ORDER BY' => 'fa_timestamp DESC' )
2430 $idsPresent = array();
2431 $storeBatch = array();
2432 $insertBatch = array();
2433 $insertCurrent = false;
2434 $deleteIds = array();
2436 $archiveNames = array();
2438 foreach ( $result as $row ) {
2439 $idsPresent[] = $row->fa_id
;
2441 if ( $row->fa_name
!= $this->file
->getName() ) {
2442 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2443 $status->failCount++
;
2447 if ( $row->fa_storage_key
== '' ) {
2448 // Revision was missing pre-deletion
2449 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2450 $status->failCount++
;
2454 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2455 $row->fa_storage_key
;
2456 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2458 if ( isset( $row->fa_sha1
) ) {
2459 $sha1 = $row->fa_sha1
;
2461 // old row, populate from key
2462 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2466 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2467 $sha1 = substr( $sha1, 1 );
2470 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2471 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2472 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2473 ||
is_null( $row->fa_metadata
)
2475 // Refresh our metadata
2476 // Required for a new current revision; nice for older ones too. :)
2477 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2480 'minor_mime' => $row->fa_minor_mime
,
2481 'major_mime' => $row->fa_major_mime
,
2482 'media_type' => $row->fa_media_type
,
2483 'metadata' => $row->fa_metadata
2487 if ( $first && !$exists ) {
2488 // This revision will be published as the new current version
2489 $destRel = $this->file
->getRel();
2490 $insertCurrent = array(
2491 'img_name' => $row->fa_name
,
2492 'img_size' => $row->fa_size
,
2493 'img_width' => $row->fa_width
,
2494 'img_height' => $row->fa_height
,
2495 'img_metadata' => $props['metadata'],
2496 'img_bits' => $row->fa_bits
,
2497 'img_media_type' => $props['media_type'],
2498 'img_major_mime' => $props['major_mime'],
2499 'img_minor_mime' => $props['minor_mime'],
2500 'img_description' => $row->fa_description
,
2501 'img_user' => $row->fa_user
,
2502 'img_user_text' => $row->fa_user_text
,
2503 'img_timestamp' => $row->fa_timestamp
,
2507 // The live (current) version cannot be hidden!
2508 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2509 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2510 $this->cleanupBatch
[] = $row->fa_storage_key
;
2513 $archiveName = $row->fa_archive_name
;
2515 if ( $archiveName == '' ) {
2516 // This was originally a current version; we
2517 // have to devise a new archive name for it.
2518 // Format is <timestamp of archiving>!<name>
2519 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2522 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2524 } while ( isset( $archiveNames[$archiveName] ) );
2527 $archiveNames[$archiveName] = true;
2528 $destRel = $this->file
->getArchiveRel( $archiveName );
2529 $insertBatch[] = array(
2530 'oi_name' => $row->fa_name
,
2531 'oi_archive_name' => $archiveName,
2532 'oi_size' => $row->fa_size
,
2533 'oi_width' => $row->fa_width
,
2534 'oi_height' => $row->fa_height
,
2535 'oi_bits' => $row->fa_bits
,
2536 'oi_description' => $row->fa_description
,
2537 'oi_user' => $row->fa_user
,
2538 'oi_user_text' => $row->fa_user_text
,
2539 'oi_timestamp' => $row->fa_timestamp
,
2540 'oi_metadata' => $props['metadata'],
2541 'oi_media_type' => $props['media_type'],
2542 'oi_major_mime' => $props['major_mime'],
2543 'oi_minor_mime' => $props['minor_mime'],
2544 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2545 'oi_sha1' => $sha1 );
2548 $deleteIds[] = $row->fa_id
;
2550 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2551 // private files can stay where they are
2552 $status->successCount++
;
2554 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2555 $this->cleanupBatch
[] = $row->fa_storage_key
;
2563 // Add a warning to the status object for missing IDs
2564 $missingIds = array_diff( $this->ids
, $idsPresent );
2566 foreach ( $missingIds as $id ) {
2567 $status->error( 'undelete-missing-filearchive', $id );
2570 if ( !$repo->hasSha1Storage() ) {
2571 // Remove missing files from batch, so we don't get errors when undeleting them
2572 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2573 if ( !$checkStatus->isGood() ) {
2574 $status->merge( $checkStatus );
2577 $storeBatch = $checkStatus->value
;
2579 // Run the store batch
2580 // Use the OVERWRITE_SAME flag to smooth over a common error
2581 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2582 $status->merge( $storeStatus );
2584 if ( !$status->isGood() ) {
2585 // Even if some files could be copied, fail entirely as that is the
2586 // easiest thing to do without data loss
2587 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2588 $status->ok
= false;
2589 $this->file
->unlock();
2595 // Run the DB updates
2596 // Because we have locked the image row, key conflicts should be rare.
2597 // If they do occur, we can roll back the transaction at this time with
2598 // no data loss, but leaving unregistered files scattered throughout the
2600 // This is not ideal, which is why it's important to lock the image row.
2601 if ( $insertCurrent ) {
2602 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2605 if ( $insertBatch ) {
2606 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2610 $dbw->delete( 'filearchive',
2611 array( 'fa_id' => $deleteIds ),
2615 // If store batch is empty (all files are missing), deletion is to be considered successful
2616 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2618 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2620 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2622 $this->file
->purgeEverything();
2624 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2625 $this->file
->purgeDescription();
2629 $this->file
->unlock();
2635 * Removes non-existent files from a store batch.
2636 * @param array $triplets
2639 protected function removeNonexistentFiles( $triplets ) {
2640 $files = $filteredTriplets = array();
2641 foreach ( $triplets as $file ) {
2642 $files[$file[0]] = $file[0];
2645 $result = $this->file
->repo
->fileExistsBatch( $files );
2646 if ( in_array( null, $result, true ) ) {
2647 return Status
::newFatal( 'backend-fail-internal',
2648 $this->file
->repo
->getBackend()->getName() );
2651 foreach ( $triplets as $file ) {
2652 if ( $result[$file[0]] ) {
2653 $filteredTriplets[] = $file;
2657 return Status
::newGood( $filteredTriplets );
2661 * Removes non-existent files from a cleanup batch.
2662 * @param array $batch
2665 protected function removeNonexistentFromCleanup( $batch ) {
2666 $files = $newBatch = array();
2667 $repo = $this->file
->repo
;
2669 foreach ( $batch as $file ) {
2670 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2671 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2674 $result = $repo->fileExistsBatch( $files );
2676 foreach ( $batch as $file ) {
2677 if ( $result[$file] ) {
2678 $newBatch[] = $file;
2686 * Delete unused files in the deleted zone.
2687 * This should be called from outside the transaction in which execute() was called.
2688 * @return FileRepoStatus
2690 public function cleanup() {
2691 if ( !$this->cleanupBatch
) {
2692 return $this->file
->repo
->newGood();
2695 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2697 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2703 * Cleanup a failed batch. The batch was only partially successful, so
2704 * rollback by removing all items that were succesfully copied.
2706 * @param Status $storeStatus
2707 * @param array $storeBatch
2709 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2710 $cleanupBatch = array();
2712 foreach ( $storeStatus->success
as $i => $success ) {
2713 // Check if this item of the batch was successfully copied
2715 // Item was successfully copied and needs to be removed again
2716 // Extract ($dstZone, $dstRel) from the batch
2717 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2720 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2724 # ------------------------------------------------------------------------------
2727 * Helper class for file movement
2728 * @ingroup FileAbstraction
2730 class LocalFileMoveBatch
{
2731 /** @var LocalFile */
2741 protected $oldCount;
2745 /** @var DatabaseBase */
2750 * @param Title $target
2752 function __construct( File
$file, Title
$target ) {
2753 $this->file
= $file;
2754 $this->target
= $target;
2755 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2756 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2757 $this->oldName
= $this->file
->getName();
2758 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2759 $this->oldRel
= $this->oldHash
. $this->oldName
;
2760 $this->newRel
= $this->newHash
. $this->newName
;
2761 $this->db
= $file->getRepo()->getMasterDb();
2765 * Add the current image to the batch
2767 public function addCurrent() {
2768 $this->cur
= array( $this->oldRel
, $this->newRel
);
2772 * Add the old versions of the image to the batch
2773 * @return array List of archive names from old versions
2775 public function addOlds() {
2776 $archiveBase = 'archive';
2777 $this->olds
= array();
2778 $this->oldCount
= 0;
2779 $archiveNames = array();
2781 $result = $this->db
->select( 'oldimage',
2782 array( 'oi_archive_name', 'oi_deleted' ),
2783 array( 'oi_name' => $this->oldName
),
2785 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2788 foreach ( $result as $row ) {
2789 $archiveNames[] = $row->oi_archive_name
;
2790 $oldName = $row->oi_archive_name
;
2791 $bits = explode( '!', $oldName, 2 );
2793 if ( count( $bits ) != 2 ) {
2794 wfDebug( "Old file name missing !: '$oldName' \n" );
2798 list( $timestamp, $filename ) = $bits;
2800 if ( $this->oldName
!= $filename ) {
2801 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2807 // Do we want to add those to oldCount?
2808 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2812 $this->olds
[] = array(
2813 "{$archiveBase}/{$this->oldHash}{$oldName}",
2814 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2818 return $archiveNames;
2823 * @return FileRepoStatus
2825 public function execute() {
2826 $repo = $this->file
->repo
;
2827 $status = $repo->newGood();
2829 $triplets = $this->getMoveTriplets();
2830 $checkStatus = $this->removeNonexistentFiles( $triplets );
2831 if ( !$checkStatus->isGood() ) {
2832 $status->merge( $checkStatus );
2835 $triplets = $checkStatus->value
;
2836 $destFile = wfLocalFile( $this->target
);
2838 $this->file
->lock(); // begin
2839 $destFile->lock(); // quickly fail if destination is not available
2840 // Rename the file versions metadata in the DB.
2841 // This implicitly locks the destination file, which avoids race conditions.
2842 // If we moved the files from A -> C before DB updates, another process could
2843 // move files from B -> C at this point, causing storeBatch() to fail and thus
2844 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2845 $statusDb = $this->doDBUpdates();
2846 if ( !$statusDb->isGood() ) {
2847 $destFile->unlock();
2848 $this->file
->unlockAndRollback();
2849 $statusDb->ok
= false;
2853 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2854 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2856 if ( !$repo->hasSha1Storage() ) {
2857 // Copy the files into their new location.
2858 // If a prior process fataled copying or cleaning up files we tolerate any
2859 // of the existing files if they are identical to the ones being stored.
2860 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2861 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2862 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2863 if ( !$statusMove->isGood() ) {
2864 // Delete any files copied over (while the destination is still locked)
2865 $this->cleanupTarget( $triplets );
2866 $destFile->unlock();
2867 $this->file
->unlockAndRollback(); // unlocks the destination
2868 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2869 $statusMove->ok
= false;
2873 $status->merge( $statusMove );
2876 $destFile->unlock();
2877 $this->file
->unlock(); // done
2879 // Everything went ok, remove the source files
2880 $this->cleanupSource( $triplets );
2882 $status->merge( $statusDb );
2888 * Do the database updates and return a new FileRepoStatus indicating how
2889 * many rows where updated.
2891 * @return FileRepoStatus
2893 protected function doDBUpdates() {
2894 $repo = $this->file
->repo
;
2895 $status = $repo->newGood();
2898 // Update current image
2901 array( 'img_name' => $this->newName
),
2902 array( 'img_name' => $this->oldName
),
2906 if ( $dbw->affectedRows() ) {
2907 $status->successCount++
;
2909 $status->failCount++
;
2910 $status->fatal( 'imageinvalidfilename' );
2915 // Update old images
2919 'oi_name' => $this->newName
,
2920 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2921 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2923 array( 'oi_name' => $this->oldName
),
2927 $affected = $dbw->affectedRows();
2928 $total = $this->oldCount
;
2929 $status->successCount +
= $affected;
2930 // Bug 34934: $total is based on files that actually exist.
2931 // There may be more DB rows than such files, in which case $affected
2932 // can be greater than $total. We use max() to avoid negatives here.
2933 $status->failCount +
= max( 0, $total - $affected );
2934 if ( $status->failCount
) {
2935 $status->error( 'imageinvalidfilename' );
2942 * Generate triplets for FileRepo::storeBatch().
2945 protected function getMoveTriplets() {
2946 $moves = array_merge( array( $this->cur
), $this->olds
);
2947 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2949 foreach ( $moves as $move ) {
2950 // $move: (oldRelativePath, newRelativePath)
2951 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2952 $triplets[] = array( $srcUrl, 'public', $move[1] );
2955 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2963 * Removes non-existent files from move batch.
2964 * @param array $triplets
2967 protected function removeNonexistentFiles( $triplets ) {
2970 foreach ( $triplets as $file ) {
2971 $files[$file[0]] = $file[0];
2974 $result = $this->file
->repo
->fileExistsBatch( $files );
2975 if ( in_array( null, $result, true ) ) {
2976 return Status
::newFatal( 'backend-fail-internal',
2977 $this->file
->repo
->getBackend()->getName() );
2980 $filteredTriplets = array();
2981 foreach ( $triplets as $file ) {
2982 if ( $result[$file[0]] ) {
2983 $filteredTriplets[] = $file;
2985 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2989 return Status
::newGood( $filteredTriplets );
2993 * Cleanup a partially moved array of triplets by deleting the target
2994 * files. Called if something went wrong half way.
2995 * @param array $triplets
2997 protected function cleanupTarget( $triplets ) {
2998 // Create dest pairs from the triplets
3000 foreach ( $triplets as $triplet ) {
3001 // $triplet: (old source virtual URL, dst zone, dest rel)
3002 $pairs[] = array( $triplet[1], $triplet[2] );
3005 $this->file
->repo
->cleanupBatch( $pairs );
3009 * Cleanup a fully moved array of triplets by deleting the source files.
3010 * Called at the end of the move process if everything else went ok.
3011 * @param array $triplets
3013 protected function cleanupSource( $triplets ) {
3014 // Create source file names from the triplets
3016 foreach ( $triplets as $triplet ) {
3017 $files[] = $triplet[0];
3020 $this->file
->repo
->cleanupBatch( $files );