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() {
248 $this->dataLoaded
= false;
249 $this->extraDataLoaded
= false;
250 $key = $this->getCacheKey();
257 $cachedValues = $wgMemc->get( $key );
259 // Check if the key existed and belongs to this version of MediaWiki
260 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
261 wfDebug( "Pulling file metadata from cache key $key\n" );
262 $this->fileExists
= $cachedValues['fileExists'];
263 if ( $this->fileExists
) {
264 $this->setProps( $cachedValues );
266 $this->dataLoaded
= true;
267 $this->extraDataLoaded
= true;
268 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
269 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
273 if ( $this->dataLoaded
) {
274 wfIncrStats( 'image_cache_hit' );
276 wfIncrStats( 'image_cache_miss' );
279 return $this->dataLoaded
;
283 * Save the file metadata to memcached
285 function saveToCache() {
289 $key = $this->getCacheKey();
295 $fields = $this->getCacheFields( '' );
296 $cache = array( 'version' => MW_FILE_VERSION
);
297 $cache['fileExists'] = $this->fileExists
;
299 if ( $this->fileExists
) {
300 foreach ( $fields as $field ) {
301 $cache[$field] = $this->$field;
305 // Strip off excessive entries from the subset of fields that can become large.
306 // If the cache value gets to large it will not fit in memcached and nothing will
307 // get cached at all, causing master queries for any file access.
308 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
309 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
310 unset( $cache[$field] ); // don't let the value get too big
314 // Cache presence for 1 week and negatives for 1 day
315 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
319 * Load metadata from the file itself
321 function loadFromFile() {
322 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
323 $this->setProps( $props );
327 * @param string $prefix
330 function getCacheFields( $prefix = 'img_' ) {
331 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
332 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
333 'user_text', 'description' );
334 static $results = array();
336 if ( $prefix == '' ) {
340 if ( !isset( $results[$prefix] ) ) {
341 $prefixedFields = array();
342 foreach ( $fields as $field ) {
343 $prefixedFields[] = $prefix . $field;
345 $results[$prefix] = $prefixedFields;
348 return $results[$prefix];
352 * @param string $prefix
355 function getLazyCacheFields( $prefix = 'img_' ) {
356 static $fields = array( 'metadata' );
357 static $results = array();
359 if ( $prefix == '' ) {
363 if ( !isset( $results[$prefix] ) ) {
364 $prefixedFields = array();
365 foreach ( $fields as $field ) {
366 $prefixedFields[] = $prefix . $field;
368 $results[$prefix] = $prefixedFields;
371 return $results[$prefix];
375 * Load file metadata from the DB
378 function loadFromDB( $flags = 0 ) {
379 $fname = get_class( $this ) . '::' . __FUNCTION__
;
381 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
382 $this->dataLoaded
= true;
383 $this->extraDataLoaded
= true;
385 $dbr = ( $flags & self
::READ_LATEST
)
386 ?
$this->repo
->getMasterDB()
387 : $this->repo
->getSlaveDB();
389 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
390 array( 'img_name' => $this->getName() ), $fname );
393 $this->loadFromRow( $row );
395 $this->fileExists
= false;
400 * Load lazy file metadata from the DB.
401 * This covers fields that are sometimes not cached.
403 protected function loadExtraFromDB() {
404 $fname = get_class( $this ) . '::' . __FUNCTION__
;
406 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
407 $this->extraDataLoaded
= true;
409 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
411 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
415 foreach ( $fieldMap as $name => $value ) {
416 $this->$name = $value;
419 throw new MWException( "Could not find data for image '{$this->getName()}'." );
424 * @param DatabaseBase $dbr
425 * @param string $fname
428 private function loadFieldsWithTimestamp( $dbr, $fname ) {
431 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
432 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
435 $fieldMap = $this->unprefixRow( $row, 'img_' );
437 # File may have been uploaded over in the meantime; check the old versions
438 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
439 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
442 $fieldMap = $this->unprefixRow( $row, 'oi_' );
450 * @param array $row Row
451 * @param string $prefix
452 * @throws MWException
455 protected function unprefixRow( $row, $prefix = 'img_' ) {
456 $array = (array)$row;
457 $prefixLength = strlen( $prefix );
459 // Sanity check prefix once
460 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
461 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
465 foreach ( $array as $name => $value ) {
466 $decoded[substr( $name, $prefixLength )] = $value;
473 * Decode a row from the database (either object or array) to an array
474 * with timestamps and MIME types decoded, and the field prefix removed.
476 * @param string $prefix
477 * @throws MWException
480 function decodeRow( $row, $prefix = 'img_' ) {
481 $decoded = $this->unprefixRow( $row, $prefix );
483 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
485 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
487 if ( empty( $decoded['major_mime'] ) ) {
488 $decoded['mime'] = 'unknown/unknown';
490 if ( !$decoded['minor_mime'] ) {
491 $decoded['minor_mime'] = 'unknown';
493 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
496 # Trim zero padding from char/binary field
497 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
503 * Load file metadata from a DB result row
506 * @param string $prefix
508 function loadFromRow( $row, $prefix = 'img_' ) {
509 $this->dataLoaded
= true;
510 $this->extraDataLoaded
= true;
512 $array = $this->decodeRow( $row, $prefix );
514 foreach ( $array as $name => $value ) {
515 $this->$name = $value;
518 $this->fileExists
= true;
519 $this->maybeUpgradeRow();
523 * Load file metadata from cache or DB, unless already loaded
526 function load( $flags = 0 ) {
527 if ( !$this->dataLoaded
) {
528 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
529 $this->loadFromDB( $flags );
530 $this->saveToCache();
532 $this->dataLoaded
= true;
534 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
535 // @note: loads on name/timestamp to reduce race condition problems
536 $this->loadExtraFromDB();
541 * Upgrade a row if it needs it
543 function maybeUpgradeRow() {
544 global $wgUpdateCompatibleMetadata;
545 if ( wfReadOnly() ) {
549 if ( is_null( $this->media_type
) ||
550 $this->mime
== 'image/svg'
553 $this->upgraded
= true;
555 $handler = $this->getHandler();
557 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
558 if ( $validity === MediaHandler
::METADATA_BAD
559 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
562 $this->upgraded
= true;
568 function getUpgraded() {
569 return $this->upgraded
;
573 * Fix assorted version-related problems with the image row by reloading it from the file
575 function upgradeRow() {
577 $this->lock(); // begin
579 $this->loadFromFile();
581 # Don't destroy file info of missing files
582 if ( !$this->fileExists
) {
584 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
589 $dbw = $this->repo
->getMasterDB();
590 list( $major, $minor ) = self
::splitMime( $this->mime
);
592 if ( wfReadOnly() ) {
597 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
599 $dbw->update( 'image',
601 'img_size' => $this->size
, // sanity
602 'img_width' => $this->width
,
603 'img_height' => $this->height
,
604 'img_bits' => $this->bits
,
605 'img_media_type' => $this->media_type
,
606 'img_major_mime' => $major,
607 'img_minor_mime' => $minor,
608 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
609 'img_sha1' => $this->sha1
,
611 array( 'img_name' => $this->getName() ),
615 $this->saveToCache();
617 $this->unlock(); // done
622 * Set properties in this object to be equal to those given in the
623 * associative array $info. Only cacheable fields can be set.
624 * All fields *must* be set in $info except for getLazyCacheFields().
626 * If 'mime' is given, it will be split into major_mime/minor_mime.
627 * If major_mime/minor_mime are given, $this->mime will also be set.
631 function setProps( $info ) {
632 $this->dataLoaded
= true;
633 $fields = $this->getCacheFields( '' );
634 $fields[] = 'fileExists';
636 foreach ( $fields as $field ) {
637 if ( isset( $info[$field] ) ) {
638 $this->$field = $info[$field];
642 // Fix up mime fields
643 if ( isset( $info['major_mime'] ) ) {
644 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
645 } elseif ( isset( $info['mime'] ) ) {
646 $this->mime
= $info['mime'];
647 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
651 /** splitMime inherited */
652 /** getName inherited */
653 /** getTitle inherited */
654 /** getURL inherited */
655 /** getViewURL inherited */
656 /** getPath inherited */
657 /** isVisible inherited */
662 function isMissing() {
663 if ( $this->missing
=== null ) {
664 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
665 $this->missing
= !$fileExists;
668 return $this->missing
;
672 * Return the width of the image
677 public function getWidth( $page = 1 ) {
680 if ( $this->isMultipage() ) {
681 $handler = $this->getHandler();
685 $dim = $handler->getPageDimensions( $this, $page );
687 return $dim['width'];
689 // For non-paged media, the false goes through an
690 // intval, turning failure into 0, so do same here.
699 * Return the height of the image
704 public function getHeight( $page = 1 ) {
707 if ( $this->isMultipage() ) {
708 $handler = $this->getHandler();
712 $dim = $handler->getPageDimensions( $this, $page );
714 return $dim['height'];
716 // For non-paged media, the false goes through an
717 // intval, turning failure into 0, so do same here.
721 return $this->height
;
726 * Returns ID or name of user who uploaded the file
728 * @param string $type 'text' or 'id'
731 function getUser( $type = 'text' ) {
734 if ( $type == 'text' ) {
735 return $this->user_text
;
736 } elseif ( $type == 'id' ) {
742 * Get handler-specific metadata
745 function getMetadata() {
746 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
747 return $this->metadata
;
753 function getBitDepth() {
760 * Returns the size of the image file, in bytes
763 public function getSize() {
770 * Returns the MIME type of the file.
773 function getMimeType() {
780 * Returns the type of the media in the file.
781 * Use the value returned by this function with the MEDIATYPE_xxx constants.
784 function getMediaType() {
787 return $this->media_type
;
790 /** canRender inherited */
791 /** mustRender inherited */
792 /** allowInlineDisplay inherited */
793 /** isSafeFile inherited */
794 /** isTrustedFile inherited */
797 * Returns true if the file exists on disk.
798 * @return bool Whether file exist on disk.
800 public function exists() {
803 return $this->fileExists
;
806 /** getTransformScript inherited */
807 /** getUnscaledThumb inherited */
808 /** thumbName inherited */
809 /** createThumb inherited */
810 /** transform inherited */
812 /** getHandler inherited */
813 /** iconThumb inherited */
814 /** getLastError inherited */
817 * Get all thumbnail names previously generated for this file
818 * @param string|bool $archiveName Name of an archive file, default false
819 * @return array First element is the base dir, then files in that base dir.
821 function getThumbnails( $archiveName = false ) {
822 if ( $archiveName ) {
823 $dir = $this->getArchiveThumbPath( $archiveName );
825 $dir = $this->getThumbPath();
828 $backend = $this->repo
->getBackend();
829 $files = array( $dir );
831 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
832 foreach ( $iterator as $file ) {
835 } catch ( FileBackendError
$e ) {
836 } // suppress (bug 54674)
842 * Refresh metadata in memcached, but don't touch thumbnails or squid
844 function purgeMetadataCache() {
846 $this->saveToCache();
847 $this->purgeHistory();
851 * Purge the shared history (OldLocalFile) cache.
853 * @note This used to purge old thumbnails as well.
855 function purgeHistory() {
858 $hashedName = md5( $this->getName() );
859 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
862 $wgMemc->delete( $oldKey );
867 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
869 * @param array $options An array potentially with the key forThumbRefresh.
871 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
873 function purgeCache( $options = array() ) {
874 // Refresh metadata cache
875 $this->purgeMetadataCache();
878 $this->purgeThumbnails( $options );
880 // Purge squid cache for this file
881 SquidUpdate
::purge( array( $this->getURL() ) );
885 * Delete cached transformed files for an archived version only.
886 * @param string $archiveName Name of the archived file
888 function purgeOldThumbnails( $archiveName ) {
891 // Get a list of old thumbnails and URLs
892 $files = $this->getThumbnails( $archiveName );
894 // Purge any custom thumbnail caches
895 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
897 $dir = array_shift( $files );
898 $this->purgeThumbList( $dir, $files );
903 foreach ( $files as $file ) {
904 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
906 SquidUpdate
::purge( $urls );
912 * Delete cached transformed files for the current version only.
913 * @param array $options
915 function purgeThumbnails( $options = array() ) {
919 $files = $this->getThumbnails();
920 // Always purge all files from squid regardless of handler filters
923 foreach ( $files as $file ) {
924 $urls[] = $this->getThumbUrl( $file );
926 array_shift( $urls ); // don't purge directory
929 // Give media handler a chance to filter the file purge list
930 if ( !empty( $options['forThumbRefresh'] ) ) {
931 $handler = $this->getHandler();
933 $handler->filterThumbnailPurgeList( $files, $options );
937 // Purge any custom thumbnail caches
938 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
940 $dir = array_shift( $files );
941 $this->purgeThumbList( $dir, $files );
945 SquidUpdate
::purge( $urls );
951 * Delete a list of thumbnails visible at urls
952 * @param string $dir Base dir of the files.
953 * @param array $files Array of strings: relative filenames (to $dir)
955 protected function purgeThumbList( $dir, $files ) {
956 $fileListDebug = strtr(
957 var_export( $files, true ),
960 wfDebug( __METHOD__
. ": $fileListDebug\n" );
962 $purgeList = array();
963 foreach ( $files as $file ) {
964 # Check that the base file name is part of the thumb name
965 # This is a basic sanity check to avoid erasing unrelated directories
966 if ( strpos( $file, $this->getName() ) !== false
967 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
969 $purgeList[] = "{$dir}/{$file}";
973 # Delete the thumbnails
974 $this->repo
->quickPurgeBatch( $purgeList );
975 # Clear out the thumbnail directory if empty
976 $this->repo
->quickCleanDir( $dir );
979 /** purgeDescription inherited */
980 /** purgeEverything inherited */
983 * @param int $limit Optional: Limit to number of results
984 * @param int $start Optional: Timestamp, start from
985 * @param int $end Optional: Timestamp, end at
989 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
990 $dbr = $this->repo
->getSlaveDB();
991 $tables = array( 'oldimage' );
992 $fields = OldLocalFile
::selectFields();
993 $conds = $opts = $join_conds = array();
994 $eq = $inc ?
'=' : '';
995 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
998 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1002 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1006 $opts['LIMIT'] = $limit;
1009 // Search backwards for time > x queries
1010 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1011 $opts['ORDER BY'] = "oi_timestamp $order";
1012 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1014 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1015 &$conds, &$opts, &$join_conds ) );
1017 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1020 foreach ( $res as $row ) {
1021 $r[] = $this->repo
->newFileFromRow( $row );
1024 if ( $order == 'ASC' ) {
1025 $r = array_reverse( $r ); // make sure it ends up descending
1032 * Returns the history of this file, line by line.
1033 * starts with current version, then old versions.
1034 * uses $this->historyLine to check which line to return:
1035 * 0 return line for current version
1036 * 1 query for old versions, return first one
1037 * 2, ... return next old version from above query
1040 public function nextHistoryLine() {
1041 # Polymorphic function name to distinguish foreign and local fetches
1042 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1044 $dbr = $this->repo
->getSlaveDB();
1046 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1047 $this->historyRes
= $dbr->select( 'image',
1050 "'' AS oi_archive_name",
1054 array( 'img_name' => $this->title
->getDBkey() ),
1058 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1059 $this->historyRes
= null;
1063 } elseif ( $this->historyLine
== 1 ) {
1064 $this->historyRes
= $dbr->select( 'oldimage', '*',
1065 array( 'oi_name' => $this->title
->getDBkey() ),
1067 array( 'ORDER BY' => 'oi_timestamp DESC' )
1070 $this->historyLine++
;
1072 return $dbr->fetchObject( $this->historyRes
);
1076 * Reset the history pointer to the first element of the history
1078 public function resetHistory() {
1079 $this->historyLine
= 0;
1081 if ( !is_null( $this->historyRes
) ) {
1082 $this->historyRes
= null;
1086 /** getHashPath inherited */
1087 /** getRel inherited */
1088 /** getUrlRel inherited */
1089 /** getArchiveRel inherited */
1090 /** getArchivePath inherited */
1091 /** getThumbPath inherited */
1092 /** getArchiveUrl inherited */
1093 /** getThumbUrl inherited */
1094 /** getArchiveVirtualUrl inherited */
1095 /** getThumbVirtualUrl inherited */
1096 /** isHashed inherited */
1099 * Upload a file and record it in the DB
1100 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1101 * @param string $comment Upload description
1102 * @param string $pageText Text to use for the new description page,
1103 * if a new description page is created
1104 * @param int|bool $flags Flags for publish()
1105 * @param array|bool $props File properties, if known. This can be used to
1106 * reduce the upload time when uploading virtual URLs for which the file
1107 * info is already known
1108 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1110 * @param User|null $user User object or null to use $wgUser
1112 * @return FileRepoStatus On success, the value member contains the
1113 * archive name, or an empty string if it was a new file.
1115 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1116 $timestamp = false, $user = null
1120 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1121 return $this->readOnlyFatalStatus();
1125 if ( $this->repo
->isVirtualUrl( $srcPath )
1126 || FileBackend
::isStoragePath( $srcPath )
1128 $props = $this->repo
->getFileProps( $srcPath );
1130 $props = FSFile
::getPropsFromPath( $srcPath );
1135 $handler = MediaHandler
::getHandler( $props['mime'] );
1137 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1139 $options['headers'] = array();
1142 // Trim spaces on user supplied text
1143 $comment = trim( $comment );
1145 // Truncate nicely or the DB will do it for us
1146 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1147 $comment = $wgContLang->truncate( $comment, 255 );
1148 $this->lock(); // begin
1149 $status = $this->publish( $srcPath, $flags, $options );
1151 if ( $status->successCount
>= 2 ) {
1152 // There will be a copy+(one of move,copy,store).
1153 // The first succeeding does not commit us to updating the DB
1154 // since it simply copied the current version to a timestamped file name.
1155 // It is only *preferable* to avoid leaving such files orphaned.
1156 // Once the second operation goes through, then the current version was
1157 // updated and we must therefore update the DB too.
1158 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1159 $status->fatal( 'filenotfound', $srcPath );
1163 $this->unlock(); // done
1169 * Record a file upload in the upload log and the image table
1170 * @param string $oldver
1171 * @param string $desc
1172 * @param string $license
1173 * @param string $copyStatus
1174 * @param string $source
1175 * @param bool $watch
1176 * @param string|bool $timestamp
1177 * @param User|null $user User object or null to use $wgUser
1180 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1181 $watch = false, $timestamp = false, User
$user = null ) {
1187 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1189 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1194 $user->addWatch( $this->getTitle() );
1201 * Record a file upload in the upload log and the image table
1202 * @param string $oldver
1203 * @param string $comment
1204 * @param string $pageText
1205 * @param bool|array $props
1206 * @param string|bool $timestamp
1207 * @param null|User $user
1210 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1214 if ( is_null( $user ) ) {
1219 $dbw = $this->repo
->getMasterDB();
1220 $dbw->begin( __METHOD__
);
1223 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1226 # Imports or such might force a certain timestamp; otherwise we generate
1227 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1228 if ( $timestamp === false ) {
1229 $timestamp = $dbw->timestamp();
1230 $allowTimeKludge = true;
1232 $allowTimeKludge = false;
1235 $props['description'] = $comment;
1236 $props['user'] = $user->getId();
1237 $props['user_text'] = $user->getName();
1238 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1239 $this->setProps( $props );
1241 # Fail now if the file isn't there
1242 if ( !$this->fileExists
) {
1243 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1244 $dbw->rollback( __METHOD__
);
1251 # Test to see if the row exists using INSERT IGNORE
1252 # This avoids race conditions by locking the row until the commit, and also
1253 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1254 $dbw->insert( 'image',
1256 'img_name' => $this->getName(),
1257 'img_size' => $this->size
,
1258 'img_width' => intval( $this->width
),
1259 'img_height' => intval( $this->height
),
1260 'img_bits' => $this->bits
,
1261 'img_media_type' => $this->media_type
,
1262 'img_major_mime' => $this->major_mime
,
1263 'img_minor_mime' => $this->minor_mime
,
1264 'img_timestamp' => $timestamp,
1265 'img_description' => $comment,
1266 'img_user' => $user->getId(),
1267 'img_user_text' => $user->getName(),
1268 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1269 'img_sha1' => $this->sha1
1274 if ( $dbw->affectedRows() == 0 ) {
1275 if ( $allowTimeKludge ) {
1276 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1277 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1278 array( 'img_name' => $this->getName() ),
1280 array( 'LOCK IN SHARE MODE' ) );
1281 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1282 # Avoid a timestamp that is not newer than the last version
1283 # TODO: the image/oldimage tables should be like page/revision with an ID field
1284 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1285 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1286 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1287 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1291 # (bug 34993) Note: $oldver can be empty here, if the previous
1292 # version of the file was broken. Allow registration of the new
1293 # version to continue anyway, because that's better than having
1294 # an image that's not fixable by user operations.
1297 # Collision, this is an update of a file
1298 # Insert previous contents into oldimage
1299 $dbw->insertSelect( 'oldimage', 'image',
1301 'oi_name' => 'img_name',
1302 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1303 'oi_size' => 'img_size',
1304 'oi_width' => 'img_width',
1305 'oi_height' => 'img_height',
1306 'oi_bits' => 'img_bits',
1307 'oi_timestamp' => 'img_timestamp',
1308 'oi_description' => 'img_description',
1309 'oi_user' => 'img_user',
1310 'oi_user_text' => 'img_user_text',
1311 'oi_metadata' => 'img_metadata',
1312 'oi_media_type' => 'img_media_type',
1313 'oi_major_mime' => 'img_major_mime',
1314 'oi_minor_mime' => 'img_minor_mime',
1315 'oi_sha1' => 'img_sha1'
1317 array( 'img_name' => $this->getName() ),
1321 # Update the current image row
1322 $dbw->update( 'image',
1324 'img_size' => $this->size
,
1325 'img_width' => intval( $this->width
),
1326 'img_height' => intval( $this->height
),
1327 'img_bits' => $this->bits
,
1328 'img_media_type' => $this->media_type
,
1329 'img_major_mime' => $this->major_mime
,
1330 'img_minor_mime' => $this->minor_mime
,
1331 'img_timestamp' => $timestamp,
1332 'img_description' => $comment,
1333 'img_user' => $user->getId(),
1334 'img_user_text' => $user->getName(),
1335 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1336 'img_sha1' => $this->sha1
1338 array( 'img_name' => $this->getName() ),
1342 # This is a new file, so update the image count
1343 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1346 $descTitle = $this->getTitle();
1347 $wikiPage = new WikiFilePage( $descTitle );
1348 $wikiPage->setFile( $this );
1351 $action = $reupload ?
'overwrite' : 'upload';
1353 $logEntry = new ManualLogEntry( 'upload', $action );
1354 $logEntry->setPerformer( $user );
1355 $logEntry->setComment( $comment );
1356 $logEntry->setTarget( $descTitle );
1358 // Allow people using the api to associate log entries with the upload.
1359 // Log has a timestamp, but sometimes different from upload timestamp.
1360 $logEntry->setParameters(
1362 'img_sha1' => $this->sha1
,
1363 'img_timestamp' => $timestamp,
1366 // Note we keep $logId around since during new image
1367 // creation, page doesn't exist yet, so log_page = 0
1368 // but we want it to point to the page we're making,
1369 // so we later modify the log entry.
1370 // For a similar reason, we avoid making an RC entry
1371 // now and wait until the page exists.
1372 $logId = $logEntry->insert();
1374 $exists = $descTitle->exists();
1376 // Page exists, do RC entry now (otherwise we wait for later).
1377 $logEntry->publish( $logId );
1381 # Create a null revision
1382 $latest = $descTitle->getLatestRevID();
1383 // Use own context to get the action text in content language
1384 $formatter = LogFormatter
::newFromEntry( $logEntry );
1385 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1386 $editSummary = $formatter->getPlainActionText();
1388 $nullRevision = Revision
::newNullRevision(
1390 $descTitle->getArticleID(),
1395 if ( !is_null( $nullRevision ) ) {
1396 $nullRevision->insertOn( $dbw );
1398 Hooks
::run( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1399 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1403 # Commit the transaction now, in case something goes wrong later
1404 # The most important thing is that files don't get lost, especially archives
1405 # NOTE: once we have support for nested transactions, the commit may be moved
1406 # to after $wikiPage->doEdit has been called.
1407 $dbw->commit( __METHOD__
);
1410 # We shall not saveToCache before the commit since otherwise
1411 # in case of a rollback there is an usable file from memcached
1412 # which in fact doesn't really exist (bug 24978)
1413 $this->saveToCache();
1416 # Invalidate the cache for the description page
1417 $descTitle->invalidateCache();
1418 $descTitle->purgeSquid();
1420 # New file; create the description page.
1421 # There's already a log entry, so don't make a second RC entry
1422 # Squid and file cache for the description page are purged by doEditContent.
1423 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1424 $status = $wikiPage->doEditContent(
1427 EDIT_NEW | EDIT_SUPPRESS_RC
,
1432 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1433 // Now that the page exists, make an RC entry.
1434 $logEntry->publish( $logId );
1435 if ( isset( $status->value
['revision'] ) ) {
1436 $dbw->update( 'logging',
1437 array( 'log_page' => $status->value
['revision']->getPage() ),
1438 array( 'log_id' => $logId ),
1442 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1446 # Delete old thumbnails
1447 $this->purgeThumbnails();
1449 # Remove the old file from the squid cache
1450 SquidUpdate
::purge( array( $this->getURL() ) );
1453 # Hooks, hooks, the magic of hooks...
1454 Hooks
::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1456 # Invalidate cache for all pages using this file
1457 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1458 $update->doUpdate();
1460 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1467 * Move or copy a file to its public location. If a file exists at the
1468 * destination, move it to an archive. Returns a FileRepoStatus object with
1469 * the archive name in the "value" member on success.
1471 * The archive name should be passed through to recordUpload for database
1474 * @param string $srcPath Local filesystem path to the source image
1475 * @param int $flags A bitwise combination of:
1476 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1477 * @param array $options Optional additional parameters
1478 * @return FileRepoStatus On success, the value member contains the
1479 * archive name, or an empty string if it was a new file.
1481 function publish( $srcPath, $flags = 0, array $options = array() ) {
1482 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1486 * Move or copy a file to a specified location. Returns a FileRepoStatus
1487 * object with the archive name in the "value" member on success.
1489 * The archive name should be passed through to recordUpload for database
1492 * @param string $srcPath Local filesystem path to the source image
1493 * @param string $dstRel Target relative path
1494 * @param int $flags A bitwise combination of:
1495 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1496 * @param array $options Optional additional parameters
1497 * @return FileRepoStatus On success, the value member contains the
1498 * archive name, or an empty string if it was a new file.
1500 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1501 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1502 return $this->readOnlyFatalStatus();
1505 $this->lock(); // begin
1507 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1508 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1509 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1510 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1512 if ( $status->value
== 'new' ) {
1513 $status->value
= '';
1515 $status->value
= $archiveName;
1518 $this->unlock(); // done
1523 /** getLinksTo inherited */
1524 /** getExifData inherited */
1525 /** isLocal inherited */
1526 /** wasDeleted inherited */
1529 * Move file to the new title
1531 * Move current, old version and all thumbnails
1532 * to the new filename. Old file is deleted.
1534 * Cache purging is done; checks for validity
1535 * and logging are caller's responsibility
1537 * @param Title $target New file name
1538 * @return FileRepoStatus
1540 function move( $target ) {
1541 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1542 return $this->readOnlyFatalStatus();
1545 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1546 $batch = new LocalFileMoveBatch( $this, $target );
1548 $this->lock(); // begin
1549 $batch->addCurrent();
1550 $archiveNames = $batch->addOlds();
1551 $status = $batch->execute();
1552 $this->unlock(); // done
1554 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1556 // Purge the source and target files...
1557 $oldTitleFile = wfLocalFile( $this->title
);
1558 $newTitleFile = wfLocalFile( $target );
1559 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1560 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1561 $this->getRepo()->getMasterDB()->onTransactionIdle(
1562 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1563 $oldTitleFile->purgeEverything();
1564 foreach ( $archiveNames as $archiveName ) {
1565 $oldTitleFile->purgeOldThumbnails( $archiveName );
1567 $newTitleFile->purgeEverything();
1571 if ( $status->isOK() ) {
1572 // Now switch the object
1573 $this->title
= $target;
1574 // Force regeneration of the name and hashpath
1575 unset( $this->name
);
1576 unset( $this->hashPath
);
1583 * Delete all versions of the file.
1585 * Moves the files into an archive directory (or deletes them)
1586 * and removes the database rows.
1588 * Cache purging is done; logging is caller's responsibility.
1590 * @param string $reason
1591 * @param bool $suppress
1592 * @param User|null $user
1593 * @return FileRepoStatus
1595 function delete( $reason, $suppress = false, $user = null ) {
1596 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1597 return $this->readOnlyFatalStatus();
1600 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1602 $this->lock(); // begin
1603 $batch->addCurrent();
1604 # Get old version relative paths
1605 $archiveNames = $batch->addOlds();
1606 $status = $batch->execute();
1607 $this->unlock(); // done
1609 if ( $status->isOK() ) {
1610 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1613 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1614 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1616 $this->getRepo()->getMasterDB()->onTransactionIdle(
1617 function () use ( $file, $archiveNames ) {
1620 $file->purgeEverything();
1621 foreach ( $archiveNames as $archiveName ) {
1622 $file->purgeOldThumbnails( $archiveName );
1625 if ( $wgUseSquid ) {
1627 $purgeUrls = array();
1628 foreach ( $archiveNames as $archiveName ) {
1629 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1631 SquidUpdate
::purge( $purgeUrls );
1640 * Delete an old version of the file.
1642 * Moves the file into an archive directory (or deletes it)
1643 * and removes the database row.
1645 * Cache purging is done; logging is caller's responsibility.
1647 * @param string $archiveName
1648 * @param string $reason
1649 * @param bool $suppress
1650 * @param User|null $user
1651 * @throws MWException Exception on database or file store failure
1652 * @return FileRepoStatus
1654 function deleteOld( $archiveName, $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->addOld( $archiveName );
1664 $status = $batch->execute();
1665 $this->unlock(); // done
1667 $this->purgeOldThumbnails( $archiveName );
1668 if ( $status->isOK() ) {
1669 $this->purgeDescription();
1670 $this->purgeHistory();
1673 if ( $wgUseSquid ) {
1675 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1682 * Restore all or specified deleted revisions to the given file.
1683 * Permissions and logging are left to the caller.
1685 * May throw database exceptions on error.
1687 * @param array $versions Set of record ids of deleted items to restore,
1688 * or empty to restore all revisions.
1689 * @param bool $unsuppress
1690 * @return FileRepoStatus
1692 function restore( $versions = array(), $unsuppress = false ) {
1693 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1694 return $this->readOnlyFatalStatus();
1697 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1699 $this->lock(); // begin
1703 $batch->addIds( $versions );
1705 $status = $batch->execute();
1706 if ( $status->isGood() ) {
1707 $cleanupStatus = $batch->cleanup();
1708 $cleanupStatus->successCount
= 0;
1709 $cleanupStatus->failCount
= 0;
1710 $status->merge( $cleanupStatus );
1712 $this->unlock(); // done
1717 /** isMultipage inherited */
1718 /** pageCount inherited */
1719 /** scaleHeight inherited */
1720 /** getImageSize inherited */
1723 * Get the URL of the file description page.
1726 function getDescriptionUrl() {
1727 return $this->title
->getLocalURL();
1731 * Get the HTML text of the description page
1732 * This is not used by ImagePage for local files, since (among other things)
1733 * it skips the parser cache.
1735 * @param Language $lang What language to get description in (Optional)
1736 * @return bool|mixed
1738 function getDescriptionText( $lang = null ) {
1739 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1743 $content = $revision->getContent();
1747 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1749 return $pout->getText();
1753 * @param int $audience
1757 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1759 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1761 } elseif ( $audience == self
::FOR_THIS_USER
1762 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1766 return $this->description
;
1771 * @return bool|string
1773 function getTimestamp() {
1776 return $this->timestamp
;
1780 * @return bool|string
1782 public function getDescriptionTouched() {
1783 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1784 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1785 // need to differentiate between null (uninitialized) and false (failed to load).
1786 if ( $this->descriptionTouched
=== null ) {
1787 $cond = array( 'page_namespace' => $this->title
->getNamespace(), 'page_title' => $this->title
->getDBkey() );
1788 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1789 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1792 return $this->descriptionTouched
;
1798 function getSha1() {
1800 // Initialise now if necessary
1801 if ( $this->sha1
== '' && $this->fileExists
) {
1802 $this->lock(); // begin
1804 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1805 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1806 $dbw = $this->repo
->getMasterDB();
1807 $dbw->update( 'image',
1808 array( 'img_sha1' => $this->sha1
),
1809 array( 'img_name' => $this->getName() ),
1811 $this->saveToCache();
1814 $this->unlock(); // done
1821 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1823 function isCacheable() {
1826 // If extra data (metadata) was not loaded then it must have been large
1827 return $this->extraDataLoaded
1828 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1832 * Start a transaction and lock the image for update
1833 * Increments a reference counter if the lock is already held
1834 * @throws MWException Throws an error if the lock was not acquired
1835 * @return bool Whether the file lock owns/spawned the DB transaction
1838 $dbw = $this->repo
->getMasterDB();
1840 if ( !$this->locked
) {
1841 if ( !$dbw->trxLevel() ) {
1842 $dbw->begin( __METHOD__
);
1843 $this->lockedOwnTrx
= true;
1846 // Bug 54736: use simple lock to handle when the file does not exist.
1847 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1848 // Also, that would cause contention on INSERT of similarly named rows.
1849 $backend = $this->getRepo()->getBackend();
1850 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1851 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1852 if ( !$status->isGood() ) {
1853 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1855 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1856 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1860 return $this->lockedOwnTrx
;
1864 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1865 * the transaction and thereby releases the image lock.
1868 if ( $this->locked
) {
1870 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1871 $dbw = $this->repo
->getMasterDB();
1872 $dbw->commit( __METHOD__
);
1873 $this->lockedOwnTrx
= false;
1879 * Roll back the DB transaction and mark the image unlocked
1881 function unlockAndRollback() {
1882 $this->locked
= false;
1883 $dbw = $this->repo
->getMasterDB();
1884 $dbw->rollback( __METHOD__
);
1885 $this->lockedOwnTrx
= false;
1891 protected function readOnlyFatalStatus() {
1892 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1893 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1897 * Clean up any dangling locks
1899 function __destruct() {
1902 } // LocalFile class
1904 # ------------------------------------------------------------------------------
1907 * Helper class for file deletion
1908 * @ingroup FileAbstraction
1910 class LocalFileDeleteBatch
{
1911 /** @var LocalFile */
1918 private $srcRels = array();
1921 private $archiveUrls = array();
1923 /** @var array Items to be processed in the deletion batch */
1924 private $deletionBatch;
1926 /** @var bool Whether to suppress all suppressable fields when deleting */
1929 /** @var FileRepoStatus */
1937 * @param string $reason
1938 * @param bool $suppress
1939 * @param User|null $user
1941 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1942 $this->file
= $file;
1943 $this->reason
= $reason;
1944 $this->suppress
= $suppress;
1946 $this->user
= $user;
1949 $this->user
= $wgUser;
1951 $this->status
= $file->repo
->newGood();
1954 function addCurrent() {
1955 $this->srcRels
['.'] = $this->file
->getRel();
1959 * @param string $oldName
1961 function addOld( $oldName ) {
1962 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1963 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1967 * Add the old versions of the image to the batch
1968 * @return array List of archive names from old versions
1970 function addOlds() {
1971 $archiveNames = array();
1973 $dbw = $this->file
->repo
->getMasterDB();
1974 $result = $dbw->select( 'oldimage',
1975 array( 'oi_archive_name' ),
1976 array( 'oi_name' => $this->file
->getName() ),
1980 foreach ( $result as $row ) {
1981 $this->addOld( $row->oi_archive_name
);
1982 $archiveNames[] = $row->oi_archive_name
;
1985 return $archiveNames;
1991 function getOldRels() {
1992 if ( !isset( $this->srcRels
['.'] ) ) {
1993 $oldRels =& $this->srcRels
;
1994 $deleteCurrent = false;
1996 $oldRels = $this->srcRels
;
1997 unset( $oldRels['.'] );
1998 $deleteCurrent = true;
2001 return array( $oldRels, $deleteCurrent );
2007 protected function getHashes() {
2009 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2011 if ( $deleteCurrent ) {
2012 $hashes['.'] = $this->file
->getSha1();
2015 if ( count( $oldRels ) ) {
2016 $dbw = $this->file
->repo
->getMasterDB();
2017 $res = $dbw->select(
2019 array( 'oi_archive_name', 'oi_sha1' ),
2020 array( 'oi_archive_name' => array_keys( $oldRels ),
2021 'oi_name' => $this->file
->getName() ), // performance
2025 foreach ( $res as $row ) {
2026 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2027 // Get the hash from the file
2028 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2029 $props = $this->file
->repo
->getFileProps( $oldUrl );
2031 if ( $props['fileExists'] ) {
2032 // Upgrade the oldimage row
2033 $dbw->update( 'oldimage',
2034 array( 'oi_sha1' => $props['sha1'] ),
2035 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2037 $hashes[$row->oi_archive_name
] = $props['sha1'];
2039 $hashes[$row->oi_archive_name
] = false;
2042 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2047 $missing = array_diff_key( $this->srcRels
, $hashes );
2049 foreach ( $missing as $name => $rel ) {
2050 $this->status
->error( 'filedelete-old-unregistered', $name );
2053 foreach ( $hashes as $name => $hash ) {
2055 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2056 unset( $hashes[$name] );
2063 function doDBInserts() {
2064 $dbw = $this->file
->repo
->getMasterDB();
2065 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2066 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2067 $encReason = $dbw->addQuotes( $this->reason
);
2068 $encGroup = $dbw->addQuotes( 'deleted' );
2069 $ext = $this->file
->getExtension();
2070 $dotExt = $ext === '' ?
'' : ".$ext";
2071 $encExt = $dbw->addQuotes( $dotExt );
2072 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2074 // Bitfields to further suppress the content
2075 if ( $this->suppress
) {
2077 // This should be 15...
2078 $bitfield |
= Revision
::DELETED_TEXT
;
2079 $bitfield |
= Revision
::DELETED_COMMENT
;
2080 $bitfield |
= Revision
::DELETED_USER
;
2081 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2083 $bitfield = 'oi_deleted';
2086 if ( $deleteCurrent ) {
2087 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2088 $where = array( 'img_name' => $this->file
->getName() );
2089 $dbw->insertSelect( 'filearchive', 'image',
2091 'fa_storage_group' => $encGroup,
2092 'fa_storage_key' => $dbw->conditional(
2093 array( 'img_sha1' => '' ),
2094 $dbw->addQuotes( '' ),
2097 'fa_deleted_user' => $encUserId,
2098 'fa_deleted_timestamp' => $encTimestamp,
2099 'fa_deleted_reason' => $encReason,
2100 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2102 'fa_name' => 'img_name',
2103 'fa_archive_name' => 'NULL',
2104 'fa_size' => 'img_size',
2105 'fa_width' => 'img_width',
2106 'fa_height' => 'img_height',
2107 'fa_metadata' => 'img_metadata',
2108 'fa_bits' => 'img_bits',
2109 'fa_media_type' => 'img_media_type',
2110 'fa_major_mime' => 'img_major_mime',
2111 'fa_minor_mime' => 'img_minor_mime',
2112 'fa_description' => 'img_description',
2113 'fa_user' => 'img_user',
2114 'fa_user_text' => 'img_user_text',
2115 'fa_timestamp' => 'img_timestamp',
2116 'fa_sha1' => 'img_sha1',
2117 ), $where, __METHOD__
);
2120 if ( count( $oldRels ) ) {
2121 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2123 'oi_name' => $this->file
->getName(),
2124 'oi_archive_name' => array_keys( $oldRels ) );
2125 $dbw->insertSelect( 'filearchive', 'oldimage',
2127 'fa_storage_group' => $encGroup,
2128 'fa_storage_key' => $dbw->conditional(
2129 array( 'oi_sha1' => '' ),
2130 $dbw->addQuotes( '' ),
2133 'fa_deleted_user' => $encUserId,
2134 'fa_deleted_timestamp' => $encTimestamp,
2135 'fa_deleted_reason' => $encReason,
2136 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2138 'fa_name' => 'oi_name',
2139 'fa_archive_name' => 'oi_archive_name',
2140 'fa_size' => 'oi_size',
2141 'fa_width' => 'oi_width',
2142 'fa_height' => 'oi_height',
2143 'fa_metadata' => 'oi_metadata',
2144 'fa_bits' => 'oi_bits',
2145 'fa_media_type' => 'oi_media_type',
2146 'fa_major_mime' => 'oi_major_mime',
2147 'fa_minor_mime' => 'oi_minor_mime',
2148 'fa_description' => 'oi_description',
2149 'fa_user' => 'oi_user',
2150 'fa_user_text' => 'oi_user_text',
2151 'fa_timestamp' => 'oi_timestamp',
2152 'fa_sha1' => 'oi_sha1',
2153 ), $where, __METHOD__
);
2157 function doDBDeletes() {
2158 $dbw = $this->file
->repo
->getMasterDB();
2159 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2161 if ( count( $oldRels ) ) {
2162 $dbw->delete( 'oldimage',
2164 'oi_name' => $this->file
->getName(),
2165 'oi_archive_name' => array_keys( $oldRels )
2169 if ( $deleteCurrent ) {
2170 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2175 * Run the transaction
2176 * @return FileRepoStatus
2178 function execute() {
2180 $this->file
->lock();
2182 // Prepare deletion batch
2183 $hashes = $this->getHashes();
2184 $this->deletionBatch
= array();
2185 $ext = $this->file
->getExtension();
2186 $dotExt = $ext === '' ?
'' : ".$ext";
2188 foreach ( $this->srcRels
as $name => $srcRel ) {
2189 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2190 if ( isset( $hashes[$name] ) ) {
2191 $hash = $hashes[$name];
2192 $key = $hash . $dotExt;
2193 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2194 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2198 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2199 // We acquire this lock by running the inserts now, before the file operations.
2201 // This potentially has poor lock contention characteristics -- an alternative
2202 // scheme would be to insert stub filearchive entries with no fa_name and commit
2203 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2204 $this->doDBInserts();
2206 // Removes non-existent file from the batch, so we don't get errors.
2207 // This also handles files in the 'deleted' zone deleted via revision deletion.
2208 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2209 if ( !$checkStatus->isGood() ) {
2210 $this->status
->merge( $checkStatus );
2211 return $this->status
;
2213 $this->deletionBatch
= $checkStatus->value
;
2215 // Execute the file deletion batch
2216 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2218 if ( !$status->isGood() ) {
2219 $this->status
->merge( $status );
2222 if ( !$this->status
->isOK() ) {
2223 // Critical file deletion error
2224 // Roll back inserts, release lock and abort
2225 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2226 $this->file
->unlockAndRollback();
2228 return $this->status
;
2231 // Delete image/oldimage rows
2232 $this->doDBDeletes();
2234 // Commit and return
2235 $this->file
->unlock();
2237 return $this->status
;
2241 * Removes non-existent files from a deletion batch.
2242 * @param array $batch
2245 function removeNonexistentFiles( $batch ) {
2246 $files = $newBatch = array();
2248 foreach ( $batch as $batchItem ) {
2249 list( $src, ) = $batchItem;
2250 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2253 $result = $this->file
->repo
->fileExistsBatch( $files );
2254 if ( in_array( null, $result, true ) ) {
2255 return Status
::newFatal( 'backend-fail-internal',
2256 $this->file
->repo
->getBackend()->getName() );
2259 foreach ( $batch as $batchItem ) {
2260 if ( $result[$batchItem[0]] ) {
2261 $newBatch[] = $batchItem;
2265 return Status
::newGood( $newBatch );
2269 # ------------------------------------------------------------------------------
2272 * Helper class for file undeletion
2273 * @ingroup FileAbstraction
2275 class LocalFileRestoreBatch
{
2276 /** @var LocalFile */
2279 /** @var array List of file IDs to restore */
2280 private $cleanupBatch;
2282 /** @var array List of file IDs to restore */
2285 /** @var bool Add all revisions of the file */
2288 /** @var bool Whether to remove all settings for suppressed fields */
2289 private $unsuppress = false;
2293 * @param bool $unsuppress
2295 function __construct( File
$file, $unsuppress = false ) {
2296 $this->file
= $file;
2297 $this->cleanupBatch
= $this->ids
= array();
2298 $this->ids
= array();
2299 $this->unsuppress
= $unsuppress;
2306 function addId( $fa_id ) {
2307 $this->ids
[] = $fa_id;
2311 * Add a whole lot of files by ID
2314 function addIds( $ids ) {
2315 $this->ids
= array_merge( $this->ids
, $ids );
2319 * Add all revisions of the file
2326 * Run the transaction, except the cleanup batch.
2327 * The cleanup batch should be run in a separate transaction, because it locks different
2328 * rows and there's no need to keep the image row locked while it's acquiring those locks
2329 * The caller may have its own transaction open.
2330 * So we save the batch and let the caller call cleanup()
2331 * @return FileRepoStatus
2333 function execute() {
2336 if ( !$this->all
&& !$this->ids
) {
2338 return $this->file
->repo
->newGood();
2341 $lockOwnsTrx = $this->file
->lock();
2343 $dbw = $this->file
->repo
->getMasterDB();
2344 $status = $this->file
->repo
->newGood();
2346 $exists = (bool)$dbw->selectField( 'image', '1',
2347 array( 'img_name' => $this->file
->getName() ),
2349 // The lock() should already prevents changes, but this still may need
2350 // to bypass any transaction snapshot. However, if lock() started the
2351 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2352 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2355 // Fetch all or selected archived revisions for the file,
2356 // sorted from the most recent to the oldest.
2357 $conditions = array( 'fa_name' => $this->file
->getName() );
2359 if ( !$this->all
) {
2360 $conditions['fa_id'] = $this->ids
;
2363 $result = $dbw->select(
2365 ArchivedFile
::selectFields(),
2368 array( 'ORDER BY' => 'fa_timestamp DESC' )
2371 $idsPresent = array();
2372 $storeBatch = array();
2373 $insertBatch = array();
2374 $insertCurrent = false;
2375 $deleteIds = array();
2377 $archiveNames = array();
2379 foreach ( $result as $row ) {
2380 $idsPresent[] = $row->fa_id
;
2382 if ( $row->fa_name
!= $this->file
->getName() ) {
2383 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2384 $status->failCount++
;
2388 if ( $row->fa_storage_key
== '' ) {
2389 // Revision was missing pre-deletion
2390 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2391 $status->failCount++
;
2395 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2396 $row->fa_storage_key
;
2397 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2399 if ( isset( $row->fa_sha1
) ) {
2400 $sha1 = $row->fa_sha1
;
2402 // old row, populate from key
2403 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2407 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2408 $sha1 = substr( $sha1, 1 );
2411 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2412 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2413 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2414 ||
is_null( $row->fa_metadata
)
2416 // Refresh our metadata
2417 // Required for a new current revision; nice for older ones too. :)
2418 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2421 'minor_mime' => $row->fa_minor_mime
,
2422 'major_mime' => $row->fa_major_mime
,
2423 'media_type' => $row->fa_media_type
,
2424 'metadata' => $row->fa_metadata
2428 if ( $first && !$exists ) {
2429 // This revision will be published as the new current version
2430 $destRel = $this->file
->getRel();
2431 $insertCurrent = array(
2432 'img_name' => $row->fa_name
,
2433 'img_size' => $row->fa_size
,
2434 'img_width' => $row->fa_width
,
2435 'img_height' => $row->fa_height
,
2436 'img_metadata' => $props['metadata'],
2437 'img_bits' => $row->fa_bits
,
2438 'img_media_type' => $props['media_type'],
2439 'img_major_mime' => $props['major_mime'],
2440 'img_minor_mime' => $props['minor_mime'],
2441 'img_description' => $row->fa_description
,
2442 'img_user' => $row->fa_user
,
2443 'img_user_text' => $row->fa_user_text
,
2444 'img_timestamp' => $row->fa_timestamp
,
2448 // The live (current) version cannot be hidden!
2449 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2450 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2451 $this->cleanupBatch
[] = $row->fa_storage_key
;
2454 $archiveName = $row->fa_archive_name
;
2456 if ( $archiveName == '' ) {
2457 // This was originally a current version; we
2458 // have to devise a new archive name for it.
2459 // Format is <timestamp of archiving>!<name>
2460 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2463 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2465 } while ( isset( $archiveNames[$archiveName] ) );
2468 $archiveNames[$archiveName] = true;
2469 $destRel = $this->file
->getArchiveRel( $archiveName );
2470 $insertBatch[] = array(
2471 'oi_name' => $row->fa_name
,
2472 'oi_archive_name' => $archiveName,
2473 'oi_size' => $row->fa_size
,
2474 'oi_width' => $row->fa_width
,
2475 'oi_height' => $row->fa_height
,
2476 'oi_bits' => $row->fa_bits
,
2477 'oi_description' => $row->fa_description
,
2478 'oi_user' => $row->fa_user
,
2479 'oi_user_text' => $row->fa_user_text
,
2480 'oi_timestamp' => $row->fa_timestamp
,
2481 'oi_metadata' => $props['metadata'],
2482 'oi_media_type' => $props['media_type'],
2483 'oi_major_mime' => $props['major_mime'],
2484 'oi_minor_mime' => $props['minor_mime'],
2485 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2486 'oi_sha1' => $sha1 );
2489 $deleteIds[] = $row->fa_id
;
2491 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2492 // private files can stay where they are
2493 $status->successCount++
;
2495 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2496 $this->cleanupBatch
[] = $row->fa_storage_key
;
2504 // Add a warning to the status object for missing IDs
2505 $missingIds = array_diff( $this->ids
, $idsPresent );
2507 foreach ( $missingIds as $id ) {
2508 $status->error( 'undelete-missing-filearchive', $id );
2511 // Remove missing files from batch, so we don't get errors when undeleting them
2512 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2513 if ( !$checkStatus->isGood() ) {
2514 $status->merge( $checkStatus );
2517 $storeBatch = $checkStatus->value
;
2519 // Run the store batch
2520 // Use the OVERWRITE_SAME flag to smooth over a common error
2521 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2522 $status->merge( $storeStatus );
2524 if ( !$status->isGood() ) {
2525 // Even if some files could be copied, fail entirely as that is the
2526 // easiest thing to do without data loss
2527 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2528 $status->ok
= false;
2529 $this->file
->unlock();
2534 // Run the DB updates
2535 // Because we have locked the image row, key conflicts should be rare.
2536 // If they do occur, we can roll back the transaction at this time with
2537 // no data loss, but leaving unregistered files scattered throughout the
2539 // This is not ideal, which is why it's important to lock the image row.
2540 if ( $insertCurrent ) {
2541 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2544 if ( $insertBatch ) {
2545 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2549 $dbw->delete( 'filearchive',
2550 array( 'fa_id' => $deleteIds ),
2554 // If store batch is empty (all files are missing), deletion is to be considered successful
2555 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2557 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2559 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2561 $this->file
->purgeEverything();
2563 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2564 $this->file
->purgeDescription();
2565 $this->file
->purgeHistory();
2569 $this->file
->unlock();
2575 * Removes non-existent files from a store batch.
2576 * @param array $triplets
2579 function removeNonexistentFiles( $triplets ) {
2580 $files = $filteredTriplets = array();
2581 foreach ( $triplets as $file ) {
2582 $files[$file[0]] = $file[0];
2585 $result = $this->file
->repo
->fileExistsBatch( $files );
2586 if ( in_array( null, $result, true ) ) {
2587 return Status
::newFatal( 'backend-fail-internal',
2588 $this->file
->repo
->getBackend()->getName() );
2591 foreach ( $triplets as $file ) {
2592 if ( $result[$file[0]] ) {
2593 $filteredTriplets[] = $file;
2597 return Status
::newGood( $filteredTriplets );
2601 * Removes non-existent files from a cleanup batch.
2602 * @param array $batch
2605 function removeNonexistentFromCleanup( $batch ) {
2606 $files = $newBatch = array();
2607 $repo = $this->file
->repo
;
2609 foreach ( $batch as $file ) {
2610 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2611 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2614 $result = $repo->fileExistsBatch( $files );
2616 foreach ( $batch as $file ) {
2617 if ( $result[$file] ) {
2618 $newBatch[] = $file;
2626 * Delete unused files in the deleted zone.
2627 * This should be called from outside the transaction in which execute() was called.
2628 * @return FileRepoStatus
2630 function cleanup() {
2631 if ( !$this->cleanupBatch
) {
2632 return $this->file
->repo
->newGood();
2635 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2637 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2643 * Cleanup a failed batch. The batch was only partially successful, so
2644 * rollback by removing all items that were succesfully copied.
2646 * @param Status $storeStatus
2647 * @param array $storeBatch
2649 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2650 $cleanupBatch = array();
2652 foreach ( $storeStatus->success
as $i => $success ) {
2653 // Check if this item of the batch was successfully copied
2655 // Item was successfully copied and needs to be removed again
2656 // Extract ($dstZone, $dstRel) from the batch
2657 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2660 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2664 # ------------------------------------------------------------------------------
2667 * Helper class for file movement
2668 * @ingroup FileAbstraction
2670 class LocalFileMoveBatch
{
2671 /** @var LocalFile */
2681 protected $oldCount;
2685 /** @var DatabaseBase */
2690 * @param Title $target
2692 function __construct( File
$file, Title
$target ) {
2693 $this->file
= $file;
2694 $this->target
= $target;
2695 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2696 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2697 $this->oldName
= $this->file
->getName();
2698 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2699 $this->oldRel
= $this->oldHash
. $this->oldName
;
2700 $this->newRel
= $this->newHash
. $this->newName
;
2701 $this->db
= $file->getRepo()->getMasterDb();
2705 * Add the current image to the batch
2707 function addCurrent() {
2708 $this->cur
= array( $this->oldRel
, $this->newRel
);
2712 * Add the old versions of the image to the batch
2713 * @return array List of archive names from old versions
2715 function addOlds() {
2716 $archiveBase = 'archive';
2717 $this->olds
= array();
2718 $this->oldCount
= 0;
2719 $archiveNames = array();
2721 $result = $this->db
->select( 'oldimage',
2722 array( 'oi_archive_name', 'oi_deleted' ),
2723 array( 'oi_name' => $this->oldName
),
2725 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2728 foreach ( $result as $row ) {
2729 $archiveNames[] = $row->oi_archive_name
;
2730 $oldName = $row->oi_archive_name
;
2731 $bits = explode( '!', $oldName, 2 );
2733 if ( count( $bits ) != 2 ) {
2734 wfDebug( "Old file name missing !: '$oldName' \n" );
2738 list( $timestamp, $filename ) = $bits;
2740 if ( $this->oldName
!= $filename ) {
2741 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2747 // Do we want to add those to oldCount?
2748 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2752 $this->olds
[] = array(
2753 "{$archiveBase}/{$this->oldHash}{$oldName}",
2754 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2758 return $archiveNames;
2763 * @return FileRepoStatus
2765 function execute() {
2766 $repo = $this->file
->repo
;
2767 $status = $repo->newGood();
2769 $triplets = $this->getMoveTriplets();
2770 $checkStatus = $this->removeNonexistentFiles( $triplets );
2771 if ( !$checkStatus->isGood() ) {
2772 $status->merge( $checkStatus );
2775 $triplets = $checkStatus->value
;
2776 $destFile = wfLocalFile( $this->target
);
2778 $this->file
->lock(); // begin
2779 $destFile->lock(); // quickly fail if destination is not available
2780 // Rename the file versions metadata in the DB.
2781 // This implicitly locks the destination file, which avoids race conditions.
2782 // If we moved the files from A -> C before DB updates, another process could
2783 // move files from B -> C at this point, causing storeBatch() to fail and thus
2784 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2785 $statusDb = $this->doDBUpdates();
2786 if ( !$statusDb->isGood() ) {
2787 $destFile->unlock();
2788 $this->file
->unlockAndRollback();
2789 $statusDb->ok
= false;
2793 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2794 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2796 // Copy the files into their new location.
2797 // If a prior process fataled copying or cleaning up files we tolerate any
2798 // of the existing files if they are identical to the ones being stored.
2799 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2800 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2801 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2802 if ( !$statusMove->isGood() ) {
2803 // Delete any files copied over (while the destination is still locked)
2804 $this->cleanupTarget( $triplets );
2805 $destFile->unlock();
2806 $this->file
->unlockAndRollback(); // unlocks the destination
2807 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2808 $statusMove->ok
= false;
2812 $destFile->unlock();
2813 $this->file
->unlock(); // done
2815 // Everything went ok, remove the source files
2816 $this->cleanupSource( $triplets );
2818 $status->merge( $statusDb );
2819 $status->merge( $statusMove );
2825 * Do the database updates and return a new FileRepoStatus indicating how
2826 * many rows where updated.
2828 * @return FileRepoStatus
2830 function doDBUpdates() {
2831 $repo = $this->file
->repo
;
2832 $status = $repo->newGood();
2835 // Update current image
2838 array( 'img_name' => $this->newName
),
2839 array( 'img_name' => $this->oldName
),
2843 if ( $dbw->affectedRows() ) {
2844 $status->successCount++
;
2846 $status->failCount++
;
2847 $status->fatal( 'imageinvalidfilename' );
2852 // Update old images
2856 'oi_name' => $this->newName
,
2857 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2858 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2860 array( 'oi_name' => $this->oldName
),
2864 $affected = $dbw->affectedRows();
2865 $total = $this->oldCount
;
2866 $status->successCount +
= $affected;
2867 // Bug 34934: $total is based on files that actually exist.
2868 // There may be more DB rows than such files, in which case $affected
2869 // can be greater than $total. We use max() to avoid negatives here.
2870 $status->failCount +
= max( 0, $total - $affected );
2871 if ( $status->failCount
) {
2872 $status->error( 'imageinvalidfilename' );
2879 * Generate triplets for FileRepo::storeBatch().
2882 function getMoveTriplets() {
2883 $moves = array_merge( array( $this->cur
), $this->olds
);
2884 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2886 foreach ( $moves as $move ) {
2887 // $move: (oldRelativePath, newRelativePath)
2888 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2889 $triplets[] = array( $srcUrl, 'public', $move[1] );
2892 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2900 * Removes non-existent files from move batch.
2901 * @param array $triplets
2904 function removeNonexistentFiles( $triplets ) {
2907 foreach ( $triplets as $file ) {
2908 $files[$file[0]] = $file[0];
2911 $result = $this->file
->repo
->fileExistsBatch( $files );
2912 if ( in_array( null, $result, true ) ) {
2913 return Status
::newFatal( 'backend-fail-internal',
2914 $this->file
->repo
->getBackend()->getName() );
2917 $filteredTriplets = array();
2918 foreach ( $triplets as $file ) {
2919 if ( $result[$file[0]] ) {
2920 $filteredTriplets[] = $file;
2922 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2926 return Status
::newGood( $filteredTriplets );
2930 * Cleanup a partially moved array of triplets by deleting the target
2931 * files. Called if something went wrong half way.
2932 * @param array $triplets
2934 function cleanupTarget( $triplets ) {
2935 // Create dest pairs from the triplets
2937 foreach ( $triplets as $triplet ) {
2938 // $triplet: (old source virtual URL, dst zone, dest rel)
2939 $pairs[] = array( $triplet[1], $triplet[2] );
2942 $this->file
->repo
->cleanupBatch( $pairs );
2946 * Cleanup a fully moved array of triplets by deleting the source files.
2947 * Called at the end of the move process if everything else went ok.
2948 * @param array $triplets
2950 function cleanupSource( $triplets ) {
2951 // Create source file names from the triplets
2953 foreach ( $triplets as $triplet ) {
2954 $files[] = $triplet[0];
2957 $this->file
->repo
->cleanupBatch( $files );