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 wfDebug( "Pulling file metadata from cache key $key\n" );
260 $this->fileExists
= $cachedValues['fileExists'];
261 if ( $this->fileExists
) {
262 $this->setProps( $cachedValues );
264 $this->dataLoaded
= true;
265 $this->extraDataLoaded
= true;
266 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
267 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
271 if ( $this->dataLoaded
) {
272 wfIncrStats( 'image_cache.hit' );
274 wfIncrStats( 'image_cache.miss' );
277 return $this->dataLoaded
;
281 * Save the file metadata to memcached
283 function saveToCache() {
286 $key = $this->getCacheKey();
291 $fields = $this->getCacheFields( '' );
292 $cacheVal = array( 'version' => MW_FILE_VERSION
);
293 $cacheVal['fileExists'] = $this->fileExists
;
295 if ( $this->fileExists
) {
296 foreach ( $fields as $field ) {
297 $cacheVal[$field] = $this->$field;
301 // Strip off excessive entries from the subset of fields that can become large.
302 // If the cache value gets to large it will not fit in memcached and nothing will
303 // get cached at all, causing master queries for any file access.
304 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
305 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
306 unset( $cacheVal[$field] ); // don't let the value get too big
310 // Cache presence for 1 week and negatives for 1 day
311 $cache = ObjectCache
::getMainWANInstance();
312 $cache->set( $key, $cacheVal, $this->fileExists ?
86400 * 7 : 86400 );
316 * Purge the file object/metadata cache
318 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 DatabaseBase $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 handler-specific metadata
764 function getMetadata() {
765 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
766 return $this->metadata
;
772 function getBitDepth() {
775 return (int)$this->bits
;
779 * Returns the size of the image file, in bytes
782 public function getSize() {
789 * Returns the MIME type of the file.
792 function getMimeType() {
799 * Returns the type of the media in the file.
800 * Use the value returned by this function with the MEDIATYPE_xxx constants.
803 function getMediaType() {
806 return $this->media_type
;
809 /** canRender inherited */
810 /** mustRender inherited */
811 /** allowInlineDisplay inherited */
812 /** isSafeFile inherited */
813 /** isTrustedFile inherited */
816 * Returns true if the file exists on disk.
817 * @return bool Whether file exist on disk.
819 public function exists() {
822 return $this->fileExists
;
825 /** getTransformScript inherited */
826 /** getUnscaledThumb inherited */
827 /** thumbName inherited */
828 /** createThumb inherited */
829 /** transform inherited */
831 /** getHandler inherited */
832 /** iconThumb inherited */
833 /** getLastError inherited */
836 * Get all thumbnail names previously generated for this file
837 * @param string|bool $archiveName Name of an archive file, default false
838 * @return array First element is the base dir, then files in that base dir.
840 function getThumbnails( $archiveName = false ) {
841 if ( $archiveName ) {
842 $dir = $this->getArchiveThumbPath( $archiveName );
844 $dir = $this->getThumbPath();
847 $backend = $this->repo
->getBackend();
848 $files = array( $dir );
850 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
851 foreach ( $iterator as $file ) {
854 } catch ( FileBackendError
$e ) {
855 } // suppress (bug 54674)
861 * Refresh metadata in memcached, but don't touch thumbnails or squid
863 function purgeMetadataCache() {
864 $this->invalidateCache();
868 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
870 * @param array $options An array potentially with the key forThumbRefresh.
872 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
874 function purgeCache( $options = array() ) {
875 // Refresh metadata cache
876 $this->purgeMetadataCache();
879 $this->purgeThumbnails( $options );
881 // Purge squid cache for this file
882 SquidUpdate
::purge( array( $this->getURL() ) );
886 * Delete cached transformed files for an archived version only.
887 * @param string $archiveName Name of the archived file
889 function purgeOldThumbnails( $archiveName ) {
892 // Get a list of old thumbnails and URLs
893 $files = $this->getThumbnails( $archiveName );
895 // Purge any custom thumbnail caches
896 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
898 $dir = array_shift( $files );
899 $this->purgeThumbList( $dir, $files );
904 foreach ( $files as $file ) {
905 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
907 SquidUpdate
::purge( $urls );
913 * Delete cached transformed files for the current version only.
914 * @param array $options
916 function purgeThumbnails( $options = array() ) {
920 $files = $this->getThumbnails();
921 // Always purge all files from squid regardless of handler filters
924 foreach ( $files as $file ) {
925 $urls[] = $this->getThumbUrl( $file );
927 array_shift( $urls ); // don't purge directory
930 // Give media handler a chance to filter the file purge list
931 if ( !empty( $options['forThumbRefresh'] ) ) {
932 $handler = $this->getHandler();
934 $handler->filterThumbnailPurgeList( $files, $options );
938 // Purge any custom thumbnail caches
939 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
941 $dir = array_shift( $files );
942 $this->purgeThumbList( $dir, $files );
946 SquidUpdate
::purge( $urls );
952 * Delete a list of thumbnails visible at urls
953 * @param string $dir Base dir of the files.
954 * @param array $files Array of strings: relative filenames (to $dir)
956 protected function purgeThumbList( $dir, $files ) {
957 $fileListDebug = strtr(
958 var_export( $files, true ),
961 wfDebug( __METHOD__
. ": $fileListDebug\n" );
963 $purgeList = array();
964 foreach ( $files as $file ) {
965 # Check that the base file name is part of the thumb name
966 # This is a basic sanity check to avoid erasing unrelated directories
967 if ( strpos( $file, $this->getName() ) !== false
968 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
970 $purgeList[] = "{$dir}/{$file}";
974 # Delete the thumbnails
975 $this->repo
->quickPurgeBatch( $purgeList );
976 # Clear out the thumbnail directory if empty
977 $this->repo
->quickCleanDir( $dir );
980 /** purgeDescription inherited */
981 /** purgeEverything inherited */
984 * @param int $limit Optional: Limit to number of results
985 * @param int $start Optional: Timestamp, start from
986 * @param int $end Optional: Timestamp, end at
990 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
991 $dbr = $this->repo
->getSlaveDB();
992 $tables = array( 'oldimage' );
993 $fields = OldLocalFile
::selectFields();
994 $conds = $opts = $join_conds = array();
995 $eq = $inc ?
'=' : '';
996 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
999 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1003 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1007 $opts['LIMIT'] = $limit;
1010 // Search backwards for time > x queries
1011 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1012 $opts['ORDER BY'] = "oi_timestamp $order";
1013 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1015 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1016 &$conds, &$opts, &$join_conds ) );
1018 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1021 foreach ( $res as $row ) {
1022 $r[] = $this->repo
->newFileFromRow( $row );
1025 if ( $order == 'ASC' ) {
1026 $r = array_reverse( $r ); // make sure it ends up descending
1033 * Returns the history of this file, line by line.
1034 * starts with current version, then old versions.
1035 * uses $this->historyLine to check which line to return:
1036 * 0 return line for current version
1037 * 1 query for old versions, return first one
1038 * 2, ... return next old version from above query
1041 public function nextHistoryLine() {
1042 # Polymorphic function name to distinguish foreign and local fetches
1043 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1045 $dbr = $this->repo
->getSlaveDB();
1047 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1048 $this->historyRes
= $dbr->select( 'image',
1051 "'' AS oi_archive_name",
1055 array( 'img_name' => $this->title
->getDBkey() ),
1059 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1060 $this->historyRes
= null;
1064 } elseif ( $this->historyLine
== 1 ) {
1065 $this->historyRes
= $dbr->select( 'oldimage', '*',
1066 array( 'oi_name' => $this->title
->getDBkey() ),
1068 array( 'ORDER BY' => 'oi_timestamp DESC' )
1071 $this->historyLine++
;
1073 return $dbr->fetchObject( $this->historyRes
);
1077 * Reset the history pointer to the first element of the history
1079 public function resetHistory() {
1080 $this->historyLine
= 0;
1082 if ( !is_null( $this->historyRes
) ) {
1083 $this->historyRes
= null;
1087 /** getHashPath inherited */
1088 /** getRel inherited */
1089 /** getUrlRel inherited */
1090 /** getArchiveRel inherited */
1091 /** getArchivePath inherited */
1092 /** getThumbPath inherited */
1093 /** getArchiveUrl inherited */
1094 /** getThumbUrl inherited */
1095 /** getArchiveVirtualUrl inherited */
1096 /** getThumbVirtualUrl inherited */
1097 /** isHashed inherited */
1100 * Upload a file and record it in the DB
1101 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1102 * @param string $comment Upload description
1103 * @param string $pageText Text to use for the new description page,
1104 * if a new description page is created
1105 * @param int|bool $flags Flags for publish()
1106 * @param array|bool $props File properties, if known. This can be used to
1107 * reduce the upload time when uploading virtual URLs for which the file
1108 * info is already known
1109 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1111 * @param User|null $user User object or null to use $wgUser
1113 * @return FileRepoStatus On success, the value member contains the
1114 * archive name, or an empty string if it was a new file.
1116 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1117 $timestamp = false, $user = null
1121 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1122 return $this->readOnlyFatalStatus();
1126 if ( $this->repo
->isVirtualUrl( $srcPath )
1127 || FileBackend
::isStoragePath( $srcPath )
1129 $props = $this->repo
->getFileProps( $srcPath );
1131 $props = FSFile
::getPropsFromPath( $srcPath );
1136 $handler = MediaHandler
::getHandler( $props['mime'] );
1138 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1140 $options['headers'] = array();
1143 // Trim spaces on user supplied text
1144 $comment = trim( $comment );
1146 // Truncate nicely or the DB will do it for us
1147 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1148 $comment = $wgContLang->truncate( $comment, 255 );
1149 $this->lock(); // begin
1150 $status = $this->publish( $srcPath, $flags, $options );
1152 if ( $status->successCount
>= 2 ) {
1153 // There will be a copy+(one of move,copy,store).
1154 // The first succeeding does not commit us to updating the DB
1155 // since it simply copied the current version to a timestamped file name.
1156 // It is only *preferable* to avoid leaving such files orphaned.
1157 // Once the second operation goes through, then the current version was
1158 // updated and we must therefore update the DB too.
1159 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1160 $status->fatal( 'filenotfound', $srcPath );
1164 $this->unlock(); // done
1170 * Record a file upload in the upload log and the image table
1171 * @param string $oldver
1172 * @param string $desc
1173 * @param string $license
1174 * @param string $copyStatus
1175 * @param string $source
1176 * @param bool $watch
1177 * @param string|bool $timestamp
1178 * @param User|null $user User object or null to use $wgUser
1181 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1182 $watch = false, $timestamp = false, User
$user = null ) {
1188 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1190 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1195 $user->addWatch( $this->getTitle() );
1202 * Record a file upload in the upload log and the image table
1203 * @param string $oldver
1204 * @param string $comment
1205 * @param string $pageText
1206 * @param bool|array $props
1207 * @param string|bool $timestamp
1208 * @param null|User $user
1211 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1215 if ( is_null( $user ) ) {
1220 $dbw = $this->repo
->getMasterDB();
1221 $dbw->begin( __METHOD__
);
1224 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1227 # Imports or such might force a certain timestamp; otherwise we generate
1228 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1229 if ( $timestamp === false ) {
1230 $timestamp = $dbw->timestamp();
1231 $allowTimeKludge = true;
1233 $allowTimeKludge = false;
1236 $props['description'] = $comment;
1237 $props['user'] = $user->getId();
1238 $props['user_text'] = $user->getName();
1239 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1240 $this->setProps( $props );
1242 # Fail now if the file isn't there
1243 if ( !$this->fileExists
) {
1244 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1245 $dbw->rollback( __METHOD__
);
1252 # Test to see if the row exists using INSERT IGNORE
1253 # This avoids race conditions by locking the row until the commit, and also
1254 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1255 $dbw->insert( 'image',
1257 'img_name' => $this->getName(),
1258 'img_size' => $this->size
,
1259 'img_width' => intval( $this->width
),
1260 'img_height' => intval( $this->height
),
1261 'img_bits' => $this->bits
,
1262 'img_media_type' => $this->media_type
,
1263 'img_major_mime' => $this->major_mime
,
1264 'img_minor_mime' => $this->minor_mime
,
1265 'img_timestamp' => $timestamp,
1266 'img_description' => $comment,
1267 'img_user' => $user->getId(),
1268 'img_user_text' => $user->getName(),
1269 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1270 'img_sha1' => $this->sha1
1275 if ( $dbw->affectedRows() == 0 ) {
1276 if ( $allowTimeKludge ) {
1277 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1278 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1279 array( 'img_name' => $this->getName() ),
1281 array( 'LOCK IN SHARE MODE' ) );
1282 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1283 # Avoid a timestamp that is not newer than the last version
1284 # TODO: the image/oldimage tables should be like page/revision with an ID field
1285 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1286 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1287 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1288 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1292 # (bug 34993) Note: $oldver can be empty here, if the previous
1293 # version of the file was broken. Allow registration of the new
1294 # version to continue anyway, because that's better than having
1295 # an image that's not fixable by user operations.
1298 # Collision, this is an update of a file
1299 # Insert previous contents into oldimage
1300 $dbw->insertSelect( 'oldimage', 'image',
1302 'oi_name' => 'img_name',
1303 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1304 'oi_size' => 'img_size',
1305 'oi_width' => 'img_width',
1306 'oi_height' => 'img_height',
1307 'oi_bits' => 'img_bits',
1308 'oi_timestamp' => 'img_timestamp',
1309 'oi_description' => 'img_description',
1310 'oi_user' => 'img_user',
1311 'oi_user_text' => 'img_user_text',
1312 'oi_metadata' => 'img_metadata',
1313 'oi_media_type' => 'img_media_type',
1314 'oi_major_mime' => 'img_major_mime',
1315 'oi_minor_mime' => 'img_minor_mime',
1316 'oi_sha1' => 'img_sha1'
1318 array( 'img_name' => $this->getName() ),
1322 # Update the current image row
1323 $dbw->update( 'image',
1325 'img_size' => $this->size
,
1326 'img_width' => intval( $this->width
),
1327 'img_height' => intval( $this->height
),
1328 'img_bits' => $this->bits
,
1329 'img_media_type' => $this->media_type
,
1330 'img_major_mime' => $this->major_mime
,
1331 'img_minor_mime' => $this->minor_mime
,
1332 'img_timestamp' => $timestamp,
1333 'img_description' => $comment,
1334 'img_user' => $user->getId(),
1335 'img_user_text' => $user->getName(),
1336 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1337 'img_sha1' => $this->sha1
1339 array( 'img_name' => $this->getName() ),
1343 # This is a new file, so update the image count
1344 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1347 $descTitle = $this->getTitle();
1348 $wikiPage = new WikiFilePage( $descTitle );
1349 $wikiPage->setFile( $this );
1352 $action = $reupload ?
'overwrite' : 'upload';
1354 $logEntry = new ManualLogEntry( 'upload', $action );
1355 $logEntry->setPerformer( $user );
1356 $logEntry->setComment( $comment );
1357 $logEntry->setTarget( $descTitle );
1359 // Allow people using the api to associate log entries with the upload.
1360 // Log has a timestamp, but sometimes different from upload timestamp.
1361 $logEntry->setParameters(
1363 'img_sha1' => $this->sha1
,
1364 'img_timestamp' => $timestamp,
1367 // Note we keep $logId around since during new image
1368 // creation, page doesn't exist yet, so log_page = 0
1369 // but we want it to point to the page we're making,
1370 // so we later modify the log entry.
1371 // For a similar reason, we avoid making an RC entry
1372 // now and wait until the page exists.
1373 $logId = $logEntry->insert();
1375 $exists = $descTitle->exists();
1377 // Page exists, do RC entry now (otherwise we wait for later).
1378 $logEntry->publish( $logId );
1382 # Create a null revision
1383 $latest = $descTitle->getLatestRevID();
1384 // Use own context to get the action text in content language
1385 $formatter = LogFormatter
::newFromEntry( $logEntry );
1386 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1387 $editSummary = $formatter->getPlainActionText();
1389 $nullRevision = Revision
::newNullRevision(
1391 $descTitle->getArticleID(),
1396 if ( !is_null( $nullRevision ) ) {
1397 $nullRevision->insertOn( $dbw );
1399 Hooks
::run( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1400 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1404 # Commit the transaction now, in case something goes wrong later
1405 # The most important thing is that files don't get lost, especially archives
1406 # NOTE: once we have support for nested transactions, the commit may be moved
1407 # to after $wikiPage->doEdit has been called.
1408 $dbw->commit( __METHOD__
);
1410 # Update memcache after the commit
1411 $this->invalidateCache();
1414 # Invalidate the cache for the description page
1415 $descTitle->invalidateCache();
1416 $descTitle->purgeSquid();
1418 # New file; create the description page.
1419 # There's already a log entry, so don't make a second RC entry
1420 # Squid and file cache for the description page are purged by doEditContent.
1421 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1422 $status = $wikiPage->doEditContent(
1425 EDIT_NEW | EDIT_SUPPRESS_RC
,
1430 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1431 // Now that the page exists, make an RC entry.
1432 $logEntry->publish( $logId );
1433 if ( isset( $status->value
['revision'] ) ) {
1434 $dbw->update( 'logging',
1435 array( 'log_page' => $status->value
['revision']->getPage() ),
1436 array( 'log_id' => $logId ),
1440 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1444 # Delete old thumbnails
1445 $this->purgeThumbnails();
1447 # Remove the old file from the squid cache
1448 SquidUpdate
::purge( array( $this->getURL() ) );
1451 # Hooks, hooks, the magic of hooks...
1452 Hooks
::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1454 # Invalidate cache for all pages using this file
1455 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1456 $update->doUpdate();
1458 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1465 * Move or copy a file to its public location. If a file exists at the
1466 * destination, move it to an archive. Returns a FileRepoStatus object with
1467 * the archive name in the "value" member on success.
1469 * The archive name should be passed through to recordUpload for database
1472 * @param string $srcPath Local filesystem path or virtual URL to the source image
1473 * @param int $flags A bitwise combination of:
1474 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1475 * @param array $options Optional additional parameters
1476 * @return FileRepoStatus On success, the value member contains the
1477 * archive name, or an empty string if it was a new file.
1479 function publish( $srcPath, $flags = 0, array $options = array() ) {
1480 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1484 * Move or copy a file to a specified location. Returns a FileRepoStatus
1485 * object with the archive name in the "value" member on success.
1487 * The archive name should be passed through to recordUpload for database
1490 * @param string $srcPath Local filesystem path or virtual URL to the source image
1491 * @param string $dstRel Target relative path
1492 * @param int $flags A bitwise combination of:
1493 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1494 * @param array $options Optional additional parameters
1495 * @return FileRepoStatus On success, the value member contains the
1496 * archive name, or an empty string if it was a new file.
1498 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1499 $repo = $this->getRepo();
1500 if ( $repo->getReadOnlyReason() !== false ) {
1501 return $this->readOnlyFatalStatus();
1504 $this->lock(); // begin
1506 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1507 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1509 if ( $repo->hasSha1Storage() ) {
1510 $sha1 = $repo->isVirtualUrl( $srcPath )
1511 ?
$repo->getFileSha1( $srcPath )
1512 : File
::sha1Base36( $srcPath );
1513 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1514 $status = $repo->quickImport( $srcPath, $dst );
1515 if ( $flags & File
::DELETE_SOURCE
) {
1519 if ( $this->exists() ) {
1520 $status->value
= $archiveName;
1523 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1524 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1526 if ( $status->value
== 'new' ) {
1527 $status->value
= '';
1529 $status->value
= $archiveName;
1533 $this->unlock(); // done
1538 /** getLinksTo inherited */
1539 /** getExifData inherited */
1540 /** isLocal inherited */
1541 /** wasDeleted inherited */
1544 * Move file to the new title
1546 * Move current, old version and all thumbnails
1547 * to the new filename. Old file is deleted.
1549 * Cache purging is done; checks for validity
1550 * and logging are caller's responsibility
1552 * @param Title $target New file name
1553 * @return FileRepoStatus
1555 function move( $target ) {
1556 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1557 return $this->readOnlyFatalStatus();
1560 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1561 $batch = new LocalFileMoveBatch( $this, $target );
1563 $this->lock(); // begin
1564 $batch->addCurrent();
1565 $archiveNames = $batch->addOlds();
1566 $status = $batch->execute();
1567 $this->unlock(); // done
1569 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1571 // Purge the source and target files...
1572 $oldTitleFile = wfLocalFile( $this->title
);
1573 $newTitleFile = wfLocalFile( $target );
1574 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1575 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1576 $this->getRepo()->getMasterDB()->onTransactionIdle(
1577 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1578 $oldTitleFile->purgeEverything();
1579 foreach ( $archiveNames as $archiveName ) {
1580 $oldTitleFile->purgeOldThumbnails( $archiveName );
1582 $newTitleFile->purgeEverything();
1586 if ( $status->isOK() ) {
1587 // Now switch the object
1588 $this->title
= $target;
1589 // Force regeneration of the name and hashpath
1590 unset( $this->name
);
1591 unset( $this->hashPath
);
1598 * Delete all versions of the file.
1600 * Moves the files into an archive directory (or deletes them)
1601 * and removes the database rows.
1603 * Cache purging is done; logging is caller's responsibility.
1605 * @param string $reason
1606 * @param bool $suppress
1607 * @param User|null $user
1608 * @return FileRepoStatus
1610 function delete( $reason, $suppress = false, $user = null ) {
1611 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1612 return $this->readOnlyFatalStatus();
1615 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1617 $this->lock(); // begin
1618 $batch->addCurrent();
1619 # Get old version relative paths
1620 $archiveNames = $batch->addOlds();
1621 $status = $batch->execute();
1622 $this->unlock(); // done
1624 if ( $status->isOK() ) {
1625 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1628 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1629 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1631 $this->getRepo()->getMasterDB()->onTransactionIdle(
1632 function () use ( $that, $archiveNames ) {
1635 $that->purgeEverything();
1636 foreach ( $archiveNames as $archiveName ) {
1637 $that->purgeOldThumbnails( $archiveName );
1640 if ( $wgUseSquid ) {
1642 $purgeUrls = array();
1643 foreach ( $archiveNames as $archiveName ) {
1644 $purgeUrls[] = $that->getArchiveUrl( $archiveName );
1646 SquidUpdate
::purge( $purgeUrls );
1655 * Delete an old version of the file.
1657 * Moves the file into an archive directory (or deletes it)
1658 * and removes the database row.
1660 * Cache purging is done; logging is caller's responsibility.
1662 * @param string $archiveName
1663 * @param string $reason
1664 * @param bool $suppress
1665 * @param User|null $user
1666 * @throws MWException Exception on database or file store failure
1667 * @return FileRepoStatus
1669 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1671 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1672 return $this->readOnlyFatalStatus();
1675 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1677 $this->lock(); // begin
1678 $batch->addOld( $archiveName );
1679 $status = $batch->execute();
1680 $this->unlock(); // done
1682 $this->purgeOldThumbnails( $archiveName );
1683 if ( $status->isOK() ) {
1684 $this->purgeDescription();
1687 if ( $wgUseSquid ) {
1689 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1696 * Restore all or specified deleted revisions to the given file.
1697 * Permissions and logging are left to the caller.
1699 * May throw database exceptions on error.
1701 * @param array $versions Set of record ids of deleted items to restore,
1702 * or empty to restore all revisions.
1703 * @param bool $unsuppress
1704 * @return FileRepoStatus
1706 function restore( $versions = array(), $unsuppress = false ) {
1707 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1708 return $this->readOnlyFatalStatus();
1711 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1713 $this->lock(); // begin
1717 $batch->addIds( $versions );
1719 $status = $batch->execute();
1720 if ( $status->isGood() ) {
1721 $cleanupStatus = $batch->cleanup();
1722 $cleanupStatus->successCount
= 0;
1723 $cleanupStatus->failCount
= 0;
1724 $status->merge( $cleanupStatus );
1726 $this->unlock(); // done
1731 /** isMultipage inherited */
1732 /** pageCount inherited */
1733 /** scaleHeight inherited */
1734 /** getImageSize inherited */
1737 * Get the URL of the file description page.
1740 function getDescriptionUrl() {
1741 return $this->title
->getLocalURL();
1745 * Get the HTML text of the description page
1746 * This is not used by ImagePage for local files, since (among other things)
1747 * it skips the parser cache.
1749 * @param Language $lang What language to get description in (Optional)
1750 * @return bool|mixed
1752 function getDescriptionText( $lang = null ) {
1753 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1757 $content = $revision->getContent();
1761 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1763 return $pout->getText();
1767 * @param int $audience
1771 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1773 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1775 } elseif ( $audience == self
::FOR_THIS_USER
1776 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1780 return $this->description
;
1785 * @return bool|string
1787 function getTimestamp() {
1790 return $this->timestamp
;
1794 * @return bool|string
1796 public function getDescriptionTouched() {
1797 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1798 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1799 // need to differentiate between null (uninitialized) and false (failed to load).
1800 if ( $this->descriptionTouched
=== null ) {
1802 'page_namespace' => $this->title
->getNamespace(),
1803 'page_title' => $this->title
->getDBkey()
1805 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1806 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1809 return $this->descriptionTouched
;
1815 function getSha1() {
1817 // Initialise now if necessary
1818 if ( $this->sha1
== '' && $this->fileExists
) {
1819 $this->lock(); // begin
1821 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1822 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1823 $dbw = $this->repo
->getMasterDB();
1824 $dbw->update( 'image',
1825 array( 'img_sha1' => $this->sha1
),
1826 array( 'img_name' => $this->getName() ),
1828 $this->invalidateCache();
1831 $this->unlock(); // done
1838 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1840 function isCacheable() {
1843 // If extra data (metadata) was not loaded then it must have been large
1844 return $this->extraDataLoaded
1845 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1849 * Start a transaction and lock the image for update
1850 * Increments a reference counter if the lock is already held
1851 * @throws MWException Throws an error if the lock was not acquired
1852 * @return bool Whether the file lock owns/spawned the DB transaction
1855 $dbw = $this->repo
->getMasterDB();
1857 if ( !$this->locked
) {
1858 if ( !$dbw->trxLevel() ) {
1859 $dbw->begin( __METHOD__
);
1860 $this->lockedOwnTrx
= true;
1863 // Bug 54736: use simple lock to handle when the file does not exist.
1864 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1865 // Also, that would cause contention on INSERT of similarly named rows.
1866 $backend = $this->getRepo()->getBackend();
1867 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1868 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1869 if ( !$status->isGood() ) {
1870 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1872 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1873 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1877 return $this->lockedOwnTrx
;
1881 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1882 * the transaction and thereby releases the image lock.
1885 if ( $this->locked
) {
1887 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1888 $dbw = $this->repo
->getMasterDB();
1889 $dbw->commit( __METHOD__
);
1890 $this->lockedOwnTrx
= false;
1896 * Roll back the DB transaction and mark the image unlocked
1898 function unlockAndRollback() {
1899 $this->locked
= false;
1900 $dbw = $this->repo
->getMasterDB();
1901 $dbw->rollback( __METHOD__
);
1902 $this->lockedOwnTrx
= false;
1908 protected function readOnlyFatalStatus() {
1909 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1910 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1914 * Clean up any dangling locks
1916 function __destruct() {
1919 } // LocalFile class
1921 # ------------------------------------------------------------------------------
1924 * Helper class for file deletion
1925 * @ingroup FileAbstraction
1927 class LocalFileDeleteBatch
{
1928 /** @var LocalFile */
1935 private $srcRels = array();
1938 private $archiveUrls = array();
1940 /** @var array Items to be processed in the deletion batch */
1941 private $deletionBatch;
1943 /** @var bool Whether to suppress all suppressable fields when deleting */
1946 /** @var FileRepoStatus */
1954 * @param string $reason
1955 * @param bool $suppress
1956 * @param User|null $user
1958 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1959 $this->file
= $file;
1960 $this->reason
= $reason;
1961 $this->suppress
= $suppress;
1963 $this->user
= $user;
1966 $this->user
= $wgUser;
1968 $this->status
= $file->repo
->newGood();
1971 public function addCurrent() {
1972 $this->srcRels
['.'] = $this->file
->getRel();
1976 * @param string $oldName
1978 public function addOld( $oldName ) {
1979 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1980 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1984 * Add the old versions of the image to the batch
1985 * @return array List of archive names from old versions
1987 public function addOlds() {
1988 $archiveNames = array();
1990 $dbw = $this->file
->repo
->getMasterDB();
1991 $result = $dbw->select( 'oldimage',
1992 array( 'oi_archive_name' ),
1993 array( 'oi_name' => $this->file
->getName() ),
1997 foreach ( $result as $row ) {
1998 $this->addOld( $row->oi_archive_name
);
1999 $archiveNames[] = $row->oi_archive_name
;
2002 return $archiveNames;
2008 protected function getOldRels() {
2009 if ( !isset( $this->srcRels
['.'] ) ) {
2010 $oldRels =& $this->srcRels
;
2011 $deleteCurrent = false;
2013 $oldRels = $this->srcRels
;
2014 unset( $oldRels['.'] );
2015 $deleteCurrent = true;
2018 return array( $oldRels, $deleteCurrent );
2024 protected function getHashes() {
2026 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2028 if ( $deleteCurrent ) {
2029 $hashes['.'] = $this->file
->getSha1();
2032 if ( count( $oldRels ) ) {
2033 $dbw = $this->file
->repo
->getMasterDB();
2034 $res = $dbw->select(
2036 array( 'oi_archive_name', 'oi_sha1' ),
2037 array( 'oi_archive_name' => array_keys( $oldRels ),
2038 'oi_name' => $this->file
->getName() ), // performance
2042 foreach ( $res as $row ) {
2043 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2044 // Get the hash from the file
2045 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2046 $props = $this->file
->repo
->getFileProps( $oldUrl );
2048 if ( $props['fileExists'] ) {
2049 // Upgrade the oldimage row
2050 $dbw->update( 'oldimage',
2051 array( 'oi_sha1' => $props['sha1'] ),
2052 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2054 $hashes[$row->oi_archive_name
] = $props['sha1'];
2056 $hashes[$row->oi_archive_name
] = false;
2059 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2064 $missing = array_diff_key( $this->srcRels
, $hashes );
2066 foreach ( $missing as $name => $rel ) {
2067 $this->status
->error( 'filedelete-old-unregistered', $name );
2070 foreach ( $hashes as $name => $hash ) {
2072 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2073 unset( $hashes[$name] );
2080 protected function doDBInserts() {
2081 $dbw = $this->file
->repo
->getMasterDB();
2082 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2083 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2084 $encReason = $dbw->addQuotes( $this->reason
);
2085 $encGroup = $dbw->addQuotes( 'deleted' );
2086 $ext = $this->file
->getExtension();
2087 $dotExt = $ext === '' ?
'' : ".$ext";
2088 $encExt = $dbw->addQuotes( $dotExt );
2089 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2091 // Bitfields to further suppress the content
2092 if ( $this->suppress
) {
2094 // This should be 15...
2095 $bitfield |
= Revision
::DELETED_TEXT
;
2096 $bitfield |
= Revision
::DELETED_COMMENT
;
2097 $bitfield |
= Revision
::DELETED_USER
;
2098 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2100 $bitfield = 'oi_deleted';
2103 if ( $deleteCurrent ) {
2104 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2105 $where = array( 'img_name' => $this->file
->getName() );
2106 $dbw->insertSelect( 'filearchive', 'image',
2108 'fa_storage_group' => $encGroup,
2109 'fa_storage_key' => $dbw->conditional(
2110 array( 'img_sha1' => '' ),
2111 $dbw->addQuotes( '' ),
2114 'fa_deleted_user' => $encUserId,
2115 'fa_deleted_timestamp' => $encTimestamp,
2116 'fa_deleted_reason' => $encReason,
2117 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2119 'fa_name' => 'img_name',
2120 'fa_archive_name' => 'NULL',
2121 'fa_size' => 'img_size',
2122 'fa_width' => 'img_width',
2123 'fa_height' => 'img_height',
2124 'fa_metadata' => 'img_metadata',
2125 'fa_bits' => 'img_bits',
2126 'fa_media_type' => 'img_media_type',
2127 'fa_major_mime' => 'img_major_mime',
2128 'fa_minor_mime' => 'img_minor_mime',
2129 'fa_description' => 'img_description',
2130 'fa_user' => 'img_user',
2131 'fa_user_text' => 'img_user_text',
2132 'fa_timestamp' => 'img_timestamp',
2133 'fa_sha1' => 'img_sha1',
2134 ), $where, __METHOD__
);
2137 if ( count( $oldRels ) ) {
2138 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2140 'oi_name' => $this->file
->getName(),
2141 'oi_archive_name' => array_keys( $oldRels ) );
2142 $dbw->insertSelect( 'filearchive', 'oldimage',
2144 'fa_storage_group' => $encGroup,
2145 'fa_storage_key' => $dbw->conditional(
2146 array( 'oi_sha1' => '' ),
2147 $dbw->addQuotes( '' ),
2150 'fa_deleted_user' => $encUserId,
2151 'fa_deleted_timestamp' => $encTimestamp,
2152 'fa_deleted_reason' => $encReason,
2153 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2155 'fa_name' => 'oi_name',
2156 'fa_archive_name' => 'oi_archive_name',
2157 'fa_size' => 'oi_size',
2158 'fa_width' => 'oi_width',
2159 'fa_height' => 'oi_height',
2160 'fa_metadata' => 'oi_metadata',
2161 'fa_bits' => 'oi_bits',
2162 'fa_media_type' => 'oi_media_type',
2163 'fa_major_mime' => 'oi_major_mime',
2164 'fa_minor_mime' => 'oi_minor_mime',
2165 'fa_description' => 'oi_description',
2166 'fa_user' => 'oi_user',
2167 'fa_user_text' => 'oi_user_text',
2168 'fa_timestamp' => 'oi_timestamp',
2169 'fa_sha1' => 'oi_sha1',
2170 ), $where, __METHOD__
);
2174 function doDBDeletes() {
2175 $dbw = $this->file
->repo
->getMasterDB();
2176 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2178 if ( count( $oldRels ) ) {
2179 $dbw->delete( 'oldimage',
2181 'oi_name' => $this->file
->getName(),
2182 'oi_archive_name' => array_keys( $oldRels )
2186 if ( $deleteCurrent ) {
2187 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2192 * Run the transaction
2193 * @return FileRepoStatus
2195 public function execute() {
2196 $repo = $this->file
->getRepo();
2197 $this->file
->lock();
2199 // Prepare deletion batch
2200 $hashes = $this->getHashes();
2201 $this->deletionBatch
= array();
2202 $ext = $this->file
->getExtension();
2203 $dotExt = $ext === '' ?
'' : ".$ext";
2205 foreach ( $this->srcRels
as $name => $srcRel ) {
2206 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2207 if ( isset( $hashes[$name] ) ) {
2208 $hash = $hashes[$name];
2209 $key = $hash . $dotExt;
2210 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2211 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2215 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2216 // We acquire this lock by running the inserts now, before the file operations.
2217 // This potentially has poor lock contention characteristics -- an alternative
2218 // scheme would be to insert stub filearchive entries with no fa_name and commit
2219 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2220 $this->doDBInserts();
2222 if ( !$repo->hasSha1Storage() ) {
2223 // Removes non-existent file from the batch, so we don't get errors.
2224 // This also handles files in the 'deleted' zone deleted via revision deletion.
2225 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2226 if ( !$checkStatus->isGood() ) {
2227 $this->status
->merge( $checkStatus );
2228 return $this->status
;
2230 $this->deletionBatch
= $checkStatus->value
;
2232 // Execute the file deletion batch
2233 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2235 if ( !$status->isGood() ) {
2236 $this->status
->merge( $status );
2240 if ( !$this->status
->isOK() ) {
2241 // Critical file deletion error
2242 // Roll back inserts, release lock and abort
2243 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2244 $this->file
->unlockAndRollback();
2246 return $this->status
;
2249 // Delete image/oldimage rows
2250 $this->doDBDeletes();
2252 // Commit and return
2253 $this->file
->unlock();
2255 return $this->status
;
2259 * Removes non-existent files from a deletion batch.
2260 * @param array $batch
2263 protected function removeNonexistentFiles( $batch ) {
2264 $files = $newBatch = array();
2266 foreach ( $batch as $batchItem ) {
2267 list( $src, ) = $batchItem;
2268 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2271 $result = $this->file
->repo
->fileExistsBatch( $files );
2272 if ( in_array( null, $result, true ) ) {
2273 return Status
::newFatal( 'backend-fail-internal',
2274 $this->file
->repo
->getBackend()->getName() );
2277 foreach ( $batch as $batchItem ) {
2278 if ( $result[$batchItem[0]] ) {
2279 $newBatch[] = $batchItem;
2283 return Status
::newGood( $newBatch );
2287 # ------------------------------------------------------------------------------
2290 * Helper class for file undeletion
2291 * @ingroup FileAbstraction
2293 class LocalFileRestoreBatch
{
2294 /** @var LocalFile */
2297 /** @var array List of file IDs to restore */
2298 private $cleanupBatch;
2300 /** @var array List of file IDs to restore */
2303 /** @var bool Add all revisions of the file */
2306 /** @var bool Whether to remove all settings for suppressed fields */
2307 private $unsuppress = false;
2311 * @param bool $unsuppress
2313 function __construct( File
$file, $unsuppress = false ) {
2314 $this->file
= $file;
2315 $this->cleanupBatch
= $this->ids
= array();
2316 $this->ids
= array();
2317 $this->unsuppress
= $unsuppress;
2324 public function addId( $fa_id ) {
2325 $this->ids
[] = $fa_id;
2329 * Add a whole lot of files by ID
2332 public function addIds( $ids ) {
2333 $this->ids
= array_merge( $this->ids
, $ids );
2337 * Add all revisions of the file
2339 public function addAll() {
2344 * Run the transaction, except the cleanup batch.
2345 * The cleanup batch should be run in a separate transaction, because it locks different
2346 * rows and there's no need to keep the image row locked while it's acquiring those locks
2347 * The caller may have its own transaction open.
2348 * So we save the batch and let the caller call cleanup()
2349 * @return FileRepoStatus
2351 public function execute() {
2354 $repo = $this->file
->getRepo();
2355 if ( !$this->all
&& !$this->ids
) {
2357 return $repo->newGood();
2360 $lockOwnsTrx = $this->file
->lock();
2362 $dbw = $this->file
->repo
->getMasterDB();
2363 $status = $this->file
->repo
->newGood();
2365 $exists = (bool)$dbw->selectField( 'image', '1',
2366 array( 'img_name' => $this->file
->getName() ),
2368 // The lock() should already prevents changes, but this still may need
2369 // to bypass any transaction snapshot. However, if lock() started the
2370 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2371 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2374 // Fetch all or selected archived revisions for the file,
2375 // sorted from the most recent to the oldest.
2376 $conditions = array( 'fa_name' => $this->file
->getName() );
2378 if ( !$this->all
) {
2379 $conditions['fa_id'] = $this->ids
;
2382 $result = $dbw->select(
2384 ArchivedFile
::selectFields(),
2387 array( 'ORDER BY' => 'fa_timestamp DESC' )
2390 $idsPresent = array();
2391 $storeBatch = array();
2392 $insertBatch = array();
2393 $insertCurrent = false;
2394 $deleteIds = array();
2396 $archiveNames = array();
2398 foreach ( $result as $row ) {
2399 $idsPresent[] = $row->fa_id
;
2401 if ( $row->fa_name
!= $this->file
->getName() ) {
2402 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2403 $status->failCount++
;
2407 if ( $row->fa_storage_key
== '' ) {
2408 // Revision was missing pre-deletion
2409 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2410 $status->failCount++
;
2414 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2415 $row->fa_storage_key
;
2416 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2418 if ( isset( $row->fa_sha1
) ) {
2419 $sha1 = $row->fa_sha1
;
2421 // old row, populate from key
2422 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2426 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2427 $sha1 = substr( $sha1, 1 );
2430 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2431 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2432 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2433 ||
is_null( $row->fa_metadata
)
2435 // Refresh our metadata
2436 // Required for a new current revision; nice for older ones too. :)
2437 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2440 'minor_mime' => $row->fa_minor_mime
,
2441 'major_mime' => $row->fa_major_mime
,
2442 'media_type' => $row->fa_media_type
,
2443 'metadata' => $row->fa_metadata
2447 if ( $first && !$exists ) {
2448 // This revision will be published as the new current version
2449 $destRel = $this->file
->getRel();
2450 $insertCurrent = array(
2451 'img_name' => $row->fa_name
,
2452 'img_size' => $row->fa_size
,
2453 'img_width' => $row->fa_width
,
2454 'img_height' => $row->fa_height
,
2455 'img_metadata' => $props['metadata'],
2456 'img_bits' => $row->fa_bits
,
2457 'img_media_type' => $props['media_type'],
2458 'img_major_mime' => $props['major_mime'],
2459 'img_minor_mime' => $props['minor_mime'],
2460 'img_description' => $row->fa_description
,
2461 'img_user' => $row->fa_user
,
2462 'img_user_text' => $row->fa_user_text
,
2463 'img_timestamp' => $row->fa_timestamp
,
2467 // The live (current) version cannot be hidden!
2468 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2469 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2470 $this->cleanupBatch
[] = $row->fa_storage_key
;
2473 $archiveName = $row->fa_archive_name
;
2475 if ( $archiveName == '' ) {
2476 // This was originally a current version; we
2477 // have to devise a new archive name for it.
2478 // Format is <timestamp of archiving>!<name>
2479 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2482 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2484 } while ( isset( $archiveNames[$archiveName] ) );
2487 $archiveNames[$archiveName] = true;
2488 $destRel = $this->file
->getArchiveRel( $archiveName );
2489 $insertBatch[] = array(
2490 'oi_name' => $row->fa_name
,
2491 'oi_archive_name' => $archiveName,
2492 'oi_size' => $row->fa_size
,
2493 'oi_width' => $row->fa_width
,
2494 'oi_height' => $row->fa_height
,
2495 'oi_bits' => $row->fa_bits
,
2496 'oi_description' => $row->fa_description
,
2497 'oi_user' => $row->fa_user
,
2498 'oi_user_text' => $row->fa_user_text
,
2499 'oi_timestamp' => $row->fa_timestamp
,
2500 'oi_metadata' => $props['metadata'],
2501 'oi_media_type' => $props['media_type'],
2502 'oi_major_mime' => $props['major_mime'],
2503 'oi_minor_mime' => $props['minor_mime'],
2504 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2505 'oi_sha1' => $sha1 );
2508 $deleteIds[] = $row->fa_id
;
2510 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2511 // private files can stay where they are
2512 $status->successCount++
;
2514 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2515 $this->cleanupBatch
[] = $row->fa_storage_key
;
2523 // Add a warning to the status object for missing IDs
2524 $missingIds = array_diff( $this->ids
, $idsPresent );
2526 foreach ( $missingIds as $id ) {
2527 $status->error( 'undelete-missing-filearchive', $id );
2530 if ( !$repo->hasSha1Storage() ) {
2531 // Remove missing files from batch, so we don't get errors when undeleting them
2532 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2533 if ( !$checkStatus->isGood() ) {
2534 $status->merge( $checkStatus );
2537 $storeBatch = $checkStatus->value
;
2539 // Run the store batch
2540 // Use the OVERWRITE_SAME flag to smooth over a common error
2541 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2542 $status->merge( $storeStatus );
2544 if ( !$status->isGood() ) {
2545 // Even if some files could be copied, fail entirely as that is the
2546 // easiest thing to do without data loss
2547 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2548 $status->ok
= false;
2549 $this->file
->unlock();
2555 // Run the DB updates
2556 // Because we have locked the image row, key conflicts should be rare.
2557 // If they do occur, we can roll back the transaction at this time with
2558 // no data loss, but leaving unregistered files scattered throughout the
2560 // This is not ideal, which is why it's important to lock the image row.
2561 if ( $insertCurrent ) {
2562 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2565 if ( $insertBatch ) {
2566 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2570 $dbw->delete( 'filearchive',
2571 array( 'fa_id' => $deleteIds ),
2575 // If store batch is empty (all files are missing), deletion is to be considered successful
2576 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2578 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2580 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2582 $this->file
->purgeEverything();
2584 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2585 $this->file
->purgeDescription();
2589 $this->file
->unlock();
2595 * Removes non-existent files from a store batch.
2596 * @param array $triplets
2599 protected function removeNonexistentFiles( $triplets ) {
2600 $files = $filteredTriplets = array();
2601 foreach ( $triplets as $file ) {
2602 $files[$file[0]] = $file[0];
2605 $result = $this->file
->repo
->fileExistsBatch( $files );
2606 if ( in_array( null, $result, true ) ) {
2607 return Status
::newFatal( 'backend-fail-internal',
2608 $this->file
->repo
->getBackend()->getName() );
2611 foreach ( $triplets as $file ) {
2612 if ( $result[$file[0]] ) {
2613 $filteredTriplets[] = $file;
2617 return Status
::newGood( $filteredTriplets );
2621 * Removes non-existent files from a cleanup batch.
2622 * @param array $batch
2625 protected function removeNonexistentFromCleanup( $batch ) {
2626 $files = $newBatch = array();
2627 $repo = $this->file
->repo
;
2629 foreach ( $batch as $file ) {
2630 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2631 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2634 $result = $repo->fileExistsBatch( $files );
2636 foreach ( $batch as $file ) {
2637 if ( $result[$file] ) {
2638 $newBatch[] = $file;
2646 * Delete unused files in the deleted zone.
2647 * This should be called from outside the transaction in which execute() was called.
2648 * @return FileRepoStatus
2650 public function cleanup() {
2651 if ( !$this->cleanupBatch
) {
2652 return $this->file
->repo
->newGood();
2655 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2657 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2663 * Cleanup a failed batch. The batch was only partially successful, so
2664 * rollback by removing all items that were succesfully copied.
2666 * @param Status $storeStatus
2667 * @param array $storeBatch
2669 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2670 $cleanupBatch = array();
2672 foreach ( $storeStatus->success
as $i => $success ) {
2673 // Check if this item of the batch was successfully copied
2675 // Item was successfully copied and needs to be removed again
2676 // Extract ($dstZone, $dstRel) from the batch
2677 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2680 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2684 # ------------------------------------------------------------------------------
2687 * Helper class for file movement
2688 * @ingroup FileAbstraction
2690 class LocalFileMoveBatch
{
2691 /** @var LocalFile */
2701 protected $oldCount;
2705 /** @var DatabaseBase */
2710 * @param Title $target
2712 function __construct( File
$file, Title
$target ) {
2713 $this->file
= $file;
2714 $this->target
= $target;
2715 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2716 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2717 $this->oldName
= $this->file
->getName();
2718 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2719 $this->oldRel
= $this->oldHash
. $this->oldName
;
2720 $this->newRel
= $this->newHash
. $this->newName
;
2721 $this->db
= $file->getRepo()->getMasterDb();
2725 * Add the current image to the batch
2727 public function addCurrent() {
2728 $this->cur
= array( $this->oldRel
, $this->newRel
);
2732 * Add the old versions of the image to the batch
2733 * @return array List of archive names from old versions
2735 public function addOlds() {
2736 $archiveBase = 'archive';
2737 $this->olds
= array();
2738 $this->oldCount
= 0;
2739 $archiveNames = array();
2741 $result = $this->db
->select( 'oldimage',
2742 array( 'oi_archive_name', 'oi_deleted' ),
2743 array( 'oi_name' => $this->oldName
),
2745 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2748 foreach ( $result as $row ) {
2749 $archiveNames[] = $row->oi_archive_name
;
2750 $oldName = $row->oi_archive_name
;
2751 $bits = explode( '!', $oldName, 2 );
2753 if ( count( $bits ) != 2 ) {
2754 wfDebug( "Old file name missing !: '$oldName' \n" );
2758 list( $timestamp, $filename ) = $bits;
2760 if ( $this->oldName
!= $filename ) {
2761 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2767 // Do we want to add those to oldCount?
2768 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2772 $this->olds
[] = array(
2773 "{$archiveBase}/{$this->oldHash}{$oldName}",
2774 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2778 return $archiveNames;
2783 * @return FileRepoStatus
2785 public function execute() {
2786 $repo = $this->file
->repo
;
2787 $status = $repo->newGood();
2789 $triplets = $this->getMoveTriplets();
2790 $checkStatus = $this->removeNonexistentFiles( $triplets );
2791 if ( !$checkStatus->isGood() ) {
2792 $status->merge( $checkStatus );
2795 $triplets = $checkStatus->value
;
2796 $destFile = wfLocalFile( $this->target
);
2798 $this->file
->lock(); // begin
2799 $destFile->lock(); // quickly fail if destination is not available
2800 // Rename the file versions metadata in the DB.
2801 // This implicitly locks the destination file, which avoids race conditions.
2802 // If we moved the files from A -> C before DB updates, another process could
2803 // move files from B -> C at this point, causing storeBatch() to fail and thus
2804 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2805 $statusDb = $this->doDBUpdates();
2806 if ( !$statusDb->isGood() ) {
2807 $destFile->unlock();
2808 $this->file
->unlockAndRollback();
2809 $statusDb->ok
= false;
2813 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2814 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2816 if ( !$repo->hasSha1Storage() ) {
2817 // Copy the files into their new location.
2818 // If a prior process fataled copying or cleaning up files we tolerate any
2819 // of the existing files if they are identical to the ones being stored.
2820 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2821 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2822 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2823 if ( !$statusMove->isGood() ) {
2824 // Delete any files copied over (while the destination is still locked)
2825 $this->cleanupTarget( $triplets );
2826 $destFile->unlock();
2827 $this->file
->unlockAndRollback(); // unlocks the destination
2828 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2829 $statusMove->ok
= false;
2833 $status->merge( $statusMove );
2836 $destFile->unlock();
2837 $this->file
->unlock(); // done
2839 // Everything went ok, remove the source files
2840 $this->cleanupSource( $triplets );
2842 $status->merge( $statusDb );
2848 * Do the database updates and return a new FileRepoStatus indicating how
2849 * many rows where updated.
2851 * @return FileRepoStatus
2853 protected function doDBUpdates() {
2854 $repo = $this->file
->repo
;
2855 $status = $repo->newGood();
2858 // Update current image
2861 array( 'img_name' => $this->newName
),
2862 array( 'img_name' => $this->oldName
),
2866 if ( $dbw->affectedRows() ) {
2867 $status->successCount++
;
2869 $status->failCount++
;
2870 $status->fatal( 'imageinvalidfilename' );
2875 // Update old images
2879 'oi_name' => $this->newName
,
2880 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2881 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2883 array( 'oi_name' => $this->oldName
),
2887 $affected = $dbw->affectedRows();
2888 $total = $this->oldCount
;
2889 $status->successCount +
= $affected;
2890 // Bug 34934: $total is based on files that actually exist.
2891 // There may be more DB rows than such files, in which case $affected
2892 // can be greater than $total. We use max() to avoid negatives here.
2893 $status->failCount +
= max( 0, $total - $affected );
2894 if ( $status->failCount
) {
2895 $status->error( 'imageinvalidfilename' );
2902 * Generate triplets for FileRepo::storeBatch().
2905 protected function getMoveTriplets() {
2906 $moves = array_merge( array( $this->cur
), $this->olds
);
2907 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2909 foreach ( $moves as $move ) {
2910 // $move: (oldRelativePath, newRelativePath)
2911 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2912 $triplets[] = array( $srcUrl, 'public', $move[1] );
2915 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2923 * Removes non-existent files from move batch.
2924 * @param array $triplets
2927 protected function removeNonexistentFiles( $triplets ) {
2930 foreach ( $triplets as $file ) {
2931 $files[$file[0]] = $file[0];
2934 $result = $this->file
->repo
->fileExistsBatch( $files );
2935 if ( in_array( null, $result, true ) ) {
2936 return Status
::newFatal( 'backend-fail-internal',
2937 $this->file
->repo
->getBackend()->getName() );
2940 $filteredTriplets = array();
2941 foreach ( $triplets as $file ) {
2942 if ( $result[$file[0]] ) {
2943 $filteredTriplets[] = $file;
2945 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2949 return Status
::newGood( $filteredTriplets );
2953 * Cleanup a partially moved array of triplets by deleting the target
2954 * files. Called if something went wrong half way.
2955 * @param array $triplets
2957 protected function cleanupTarget( $triplets ) {
2958 // Create dest pairs from the triplets
2960 foreach ( $triplets as $triplet ) {
2961 // $triplet: (old source virtual URL, dst zone, dest rel)
2962 $pairs[] = array( $triplet[1], $triplet[2] );
2965 $this->file
->repo
->cleanupBatch( $pairs );
2969 * Cleanup a fully moved array of triplets by deleting the source files.
2970 * Called at the end of the move process if everything else went ok.
2971 * @param array $triplets
2973 protected function cleanupSource( $triplets ) {
2974 // Create source file names from the triplets
2976 foreach ( $triplets as $triplet ) {
2977 $files[] = $triplet[0];
2980 $this->file
->repo
->cleanupBatch( $files );