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' ) {
737 return (int)$this->user
;
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() {
756 return (int)$this->bits
;
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() {
845 $this->loadFromDB( File
::READ_LATEST
);
846 $this->saveToCache();
850 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
852 * @param array $options An array potentially with the key forThumbRefresh.
854 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
856 function purgeCache( $options = array() ) {
857 // Refresh metadata cache
858 $this->purgeMetadataCache();
861 $this->purgeThumbnails( $options );
863 // Purge squid cache for this file
864 SquidUpdate
::purge( array( $this->getURL() ) );
868 * Delete cached transformed files for an archived version only.
869 * @param string $archiveName Name of the archived file
871 function purgeOldThumbnails( $archiveName ) {
874 // Get a list of old thumbnails and URLs
875 $files = $this->getThumbnails( $archiveName );
877 // Purge any custom thumbnail caches
878 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
880 $dir = array_shift( $files );
881 $this->purgeThumbList( $dir, $files );
886 foreach ( $files as $file ) {
887 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
889 SquidUpdate
::purge( $urls );
895 * Delete cached transformed files for the current version only.
896 * @param array $options
898 function purgeThumbnails( $options = array() ) {
902 $files = $this->getThumbnails();
903 // Always purge all files from squid regardless of handler filters
906 foreach ( $files as $file ) {
907 $urls[] = $this->getThumbUrl( $file );
909 array_shift( $urls ); // don't purge directory
912 // Give media handler a chance to filter the file purge list
913 if ( !empty( $options['forThumbRefresh'] ) ) {
914 $handler = $this->getHandler();
916 $handler->filterThumbnailPurgeList( $files, $options );
920 // Purge any custom thumbnail caches
921 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
923 $dir = array_shift( $files );
924 $this->purgeThumbList( $dir, $files );
928 SquidUpdate
::purge( $urls );
934 * Delete a list of thumbnails visible at urls
935 * @param string $dir Base dir of the files.
936 * @param array $files Array of strings: relative filenames (to $dir)
938 protected function purgeThumbList( $dir, $files ) {
939 $fileListDebug = strtr(
940 var_export( $files, true ),
943 wfDebug( __METHOD__
. ": $fileListDebug\n" );
945 $purgeList = array();
946 foreach ( $files as $file ) {
947 # Check that the base file name is part of the thumb name
948 # This is a basic sanity check to avoid erasing unrelated directories
949 if ( strpos( $file, $this->getName() ) !== false
950 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
952 $purgeList[] = "{$dir}/{$file}";
956 # Delete the thumbnails
957 $this->repo
->quickPurgeBatch( $purgeList );
958 # Clear out the thumbnail directory if empty
959 $this->repo
->quickCleanDir( $dir );
962 /** purgeDescription inherited */
963 /** purgeEverything inherited */
966 * @param int $limit Optional: Limit to number of results
967 * @param int $start Optional: Timestamp, start from
968 * @param int $end Optional: Timestamp, end at
972 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
973 $dbr = $this->repo
->getSlaveDB();
974 $tables = array( 'oldimage' );
975 $fields = OldLocalFile
::selectFields();
976 $conds = $opts = $join_conds = array();
977 $eq = $inc ?
'=' : '';
978 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
981 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
985 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
989 $opts['LIMIT'] = $limit;
992 // Search backwards for time > x queries
993 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
994 $opts['ORDER BY'] = "oi_timestamp $order";
995 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
997 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
998 &$conds, &$opts, &$join_conds ) );
1000 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1003 foreach ( $res as $row ) {
1004 $r[] = $this->repo
->newFileFromRow( $row );
1007 if ( $order == 'ASC' ) {
1008 $r = array_reverse( $r ); // make sure it ends up descending
1015 * Returns the history of this file, line by line.
1016 * starts with current version, then old versions.
1017 * uses $this->historyLine to check which line to return:
1018 * 0 return line for current version
1019 * 1 query for old versions, return first one
1020 * 2, ... return next old version from above query
1023 public function nextHistoryLine() {
1024 # Polymorphic function name to distinguish foreign and local fetches
1025 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1027 $dbr = $this->repo
->getSlaveDB();
1029 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1030 $this->historyRes
= $dbr->select( 'image',
1033 "'' AS oi_archive_name",
1037 array( 'img_name' => $this->title
->getDBkey() ),
1041 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1042 $this->historyRes
= null;
1046 } elseif ( $this->historyLine
== 1 ) {
1047 $this->historyRes
= $dbr->select( 'oldimage', '*',
1048 array( 'oi_name' => $this->title
->getDBkey() ),
1050 array( 'ORDER BY' => 'oi_timestamp DESC' )
1053 $this->historyLine++
;
1055 return $dbr->fetchObject( $this->historyRes
);
1059 * Reset the history pointer to the first element of the history
1061 public function resetHistory() {
1062 $this->historyLine
= 0;
1064 if ( !is_null( $this->historyRes
) ) {
1065 $this->historyRes
= null;
1069 /** getHashPath inherited */
1070 /** getRel inherited */
1071 /** getUrlRel inherited */
1072 /** getArchiveRel inherited */
1073 /** getArchivePath inherited */
1074 /** getThumbPath inherited */
1075 /** getArchiveUrl inherited */
1076 /** getThumbUrl inherited */
1077 /** getArchiveVirtualUrl inherited */
1078 /** getThumbVirtualUrl inherited */
1079 /** isHashed inherited */
1082 * Upload a file and record it in the DB
1083 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1084 * @param string $comment Upload description
1085 * @param string $pageText Text to use for the new description page,
1086 * if a new description page is created
1087 * @param int|bool $flags Flags for publish()
1088 * @param array|bool $props File properties, if known. This can be used to
1089 * reduce the upload time when uploading virtual URLs for which the file
1090 * info is already known
1091 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1093 * @param User|null $user User object or null to use $wgUser
1095 * @return FileRepoStatus On success, the value member contains the
1096 * archive name, or an empty string if it was a new file.
1098 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1099 $timestamp = false, $user = null
1103 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1104 return $this->readOnlyFatalStatus();
1108 if ( $this->repo
->isVirtualUrl( $srcPath )
1109 || FileBackend
::isStoragePath( $srcPath )
1111 $props = $this->repo
->getFileProps( $srcPath );
1113 $props = FSFile
::getPropsFromPath( $srcPath );
1118 $handler = MediaHandler
::getHandler( $props['mime'] );
1120 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1122 $options['headers'] = array();
1125 // Trim spaces on user supplied text
1126 $comment = trim( $comment );
1128 // Truncate nicely or the DB will do it for us
1129 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1130 $comment = $wgContLang->truncate( $comment, 255 );
1131 $this->lock(); // begin
1132 $status = $this->publish( $srcPath, $flags, $options );
1134 if ( $status->successCount
>= 2 ) {
1135 // There will be a copy+(one of move,copy,store).
1136 // The first succeeding does not commit us to updating the DB
1137 // since it simply copied the current version to a timestamped file name.
1138 // It is only *preferable* to avoid leaving such files orphaned.
1139 // Once the second operation goes through, then the current version was
1140 // updated and we must therefore update the DB too.
1141 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1142 $status->fatal( 'filenotfound', $srcPath );
1146 $this->unlock(); // done
1152 * Record a file upload in the upload log and the image table
1153 * @param string $oldver
1154 * @param string $desc
1155 * @param string $license
1156 * @param string $copyStatus
1157 * @param string $source
1158 * @param bool $watch
1159 * @param string|bool $timestamp
1160 * @param User|null $user User object or null to use $wgUser
1163 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1164 $watch = false, $timestamp = false, User
$user = null ) {
1170 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1172 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1177 $user->addWatch( $this->getTitle() );
1184 * Record a file upload in the upload log and the image table
1185 * @param string $oldver
1186 * @param string $comment
1187 * @param string $pageText
1188 * @param bool|array $props
1189 * @param string|bool $timestamp
1190 * @param null|User $user
1193 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1197 if ( is_null( $user ) ) {
1202 $dbw = $this->repo
->getMasterDB();
1203 $dbw->begin( __METHOD__
);
1206 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1209 # Imports or such might force a certain timestamp; otherwise we generate
1210 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1211 if ( $timestamp === false ) {
1212 $timestamp = $dbw->timestamp();
1213 $allowTimeKludge = true;
1215 $allowTimeKludge = false;
1218 $props['description'] = $comment;
1219 $props['user'] = $user->getId();
1220 $props['user_text'] = $user->getName();
1221 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1222 $this->setProps( $props );
1224 # Fail now if the file isn't there
1225 if ( !$this->fileExists
) {
1226 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1227 $dbw->rollback( __METHOD__
);
1234 # Test to see if the row exists using INSERT IGNORE
1235 # This avoids race conditions by locking the row until the commit, and also
1236 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1237 $dbw->insert( 'image',
1239 'img_name' => $this->getName(),
1240 'img_size' => $this->size
,
1241 'img_width' => intval( $this->width
),
1242 'img_height' => intval( $this->height
),
1243 'img_bits' => $this->bits
,
1244 'img_media_type' => $this->media_type
,
1245 'img_major_mime' => $this->major_mime
,
1246 'img_minor_mime' => $this->minor_mime
,
1247 'img_timestamp' => $timestamp,
1248 'img_description' => $comment,
1249 'img_user' => $user->getId(),
1250 'img_user_text' => $user->getName(),
1251 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1252 'img_sha1' => $this->sha1
1257 if ( $dbw->affectedRows() == 0 ) {
1258 if ( $allowTimeKludge ) {
1259 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1260 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1261 array( 'img_name' => $this->getName() ),
1263 array( 'LOCK IN SHARE MODE' ) );
1264 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1265 # Avoid a timestamp that is not newer than the last version
1266 # TODO: the image/oldimage tables should be like page/revision with an ID field
1267 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1268 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1269 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1270 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1274 # (bug 34993) Note: $oldver can be empty here, if the previous
1275 # version of the file was broken. Allow registration of the new
1276 # version to continue anyway, because that's better than having
1277 # an image that's not fixable by user operations.
1280 # Collision, this is an update of a file
1281 # Insert previous contents into oldimage
1282 $dbw->insertSelect( 'oldimage', 'image',
1284 'oi_name' => 'img_name',
1285 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1286 'oi_size' => 'img_size',
1287 'oi_width' => 'img_width',
1288 'oi_height' => 'img_height',
1289 'oi_bits' => 'img_bits',
1290 'oi_timestamp' => 'img_timestamp',
1291 'oi_description' => 'img_description',
1292 'oi_user' => 'img_user',
1293 'oi_user_text' => 'img_user_text',
1294 'oi_metadata' => 'img_metadata',
1295 'oi_media_type' => 'img_media_type',
1296 'oi_major_mime' => 'img_major_mime',
1297 'oi_minor_mime' => 'img_minor_mime',
1298 'oi_sha1' => 'img_sha1'
1300 array( 'img_name' => $this->getName() ),
1304 # Update the current image row
1305 $dbw->update( 'image',
1307 'img_size' => $this->size
,
1308 'img_width' => intval( $this->width
),
1309 'img_height' => intval( $this->height
),
1310 'img_bits' => $this->bits
,
1311 'img_media_type' => $this->media_type
,
1312 'img_major_mime' => $this->major_mime
,
1313 'img_minor_mime' => $this->minor_mime
,
1314 'img_timestamp' => $timestamp,
1315 'img_description' => $comment,
1316 'img_user' => $user->getId(),
1317 'img_user_text' => $user->getName(),
1318 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1319 'img_sha1' => $this->sha1
1321 array( 'img_name' => $this->getName() ),
1325 # This is a new file, so update the image count
1326 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1329 $descTitle = $this->getTitle();
1330 $wikiPage = new WikiFilePage( $descTitle );
1331 $wikiPage->setFile( $this );
1334 $action = $reupload ?
'overwrite' : 'upload';
1336 $logEntry = new ManualLogEntry( 'upload', $action );
1337 $logEntry->setPerformer( $user );
1338 $logEntry->setComment( $comment );
1339 $logEntry->setTarget( $descTitle );
1341 // Allow people using the api to associate log entries with the upload.
1342 // Log has a timestamp, but sometimes different from upload timestamp.
1343 $logEntry->setParameters(
1345 'img_sha1' => $this->sha1
,
1346 'img_timestamp' => $timestamp,
1349 // Note we keep $logId around since during new image
1350 // creation, page doesn't exist yet, so log_page = 0
1351 // but we want it to point to the page we're making,
1352 // so we later modify the log entry.
1353 // For a similar reason, we avoid making an RC entry
1354 // now and wait until the page exists.
1355 $logId = $logEntry->insert();
1357 $exists = $descTitle->exists();
1359 // Page exists, do RC entry now (otherwise we wait for later).
1360 $logEntry->publish( $logId );
1364 # Create a null revision
1365 $latest = $descTitle->getLatestRevID();
1366 // Use own context to get the action text in content language
1367 $formatter = LogFormatter
::newFromEntry( $logEntry );
1368 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1369 $editSummary = $formatter->getPlainActionText();
1371 $nullRevision = Revision
::newNullRevision(
1373 $descTitle->getArticleID(),
1378 if ( !is_null( $nullRevision ) ) {
1379 $nullRevision->insertOn( $dbw );
1381 Hooks
::run( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1382 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1386 # Commit the transaction now, in case something goes wrong later
1387 # The most important thing is that files don't get lost, especially archives
1388 # NOTE: once we have support for nested transactions, the commit may be moved
1389 # to after $wikiPage->doEdit has been called.
1390 $dbw->commit( __METHOD__
);
1393 # We shall not saveToCache before the commit since otherwise
1394 # in case of a rollback there is an usable file from memcached
1395 # which in fact doesn't really exist (bug 24978)
1396 $this->saveToCache();
1399 # Invalidate the cache for the description page
1400 $descTitle->invalidateCache();
1401 $descTitle->purgeSquid();
1403 # New file; create the description page.
1404 # There's already a log entry, so don't make a second RC entry
1405 # Squid and file cache for the description page are purged by doEditContent.
1406 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1407 $status = $wikiPage->doEditContent(
1410 EDIT_NEW | EDIT_SUPPRESS_RC
,
1415 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1416 // Now that the page exists, make an RC entry.
1417 $logEntry->publish( $logId );
1418 if ( isset( $status->value
['revision'] ) ) {
1419 $dbw->update( 'logging',
1420 array( 'log_page' => $status->value
['revision']->getPage() ),
1421 array( 'log_id' => $logId ),
1425 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1429 # Delete old thumbnails
1430 $this->purgeThumbnails();
1432 # Remove the old file from the squid cache
1433 SquidUpdate
::purge( array( $this->getURL() ) );
1436 # Hooks, hooks, the magic of hooks...
1437 Hooks
::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1439 # Invalidate cache for all pages using this file
1440 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1441 $update->doUpdate();
1443 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1450 * Move or copy a file to its public location. If a file exists at the
1451 * destination, move it to an archive. Returns a FileRepoStatus object with
1452 * the archive name in the "value" member on success.
1454 * The archive name should be passed through to recordUpload for database
1457 * @param string $srcPath Local filesystem path to the source image
1458 * @param int $flags A bitwise combination of:
1459 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1460 * @param array $options Optional additional parameters
1461 * @return FileRepoStatus On success, the value member contains the
1462 * archive name, or an empty string if it was a new file.
1464 function publish( $srcPath, $flags = 0, array $options = array() ) {
1465 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1469 * Move or copy a file to a specified location. Returns a FileRepoStatus
1470 * object with the archive name in the "value" member on success.
1472 * The archive name should be passed through to recordUpload for database
1475 * @param string $srcPath Local filesystem path to the source image
1476 * @param string $dstRel Target relative path
1477 * @param int $flags A bitwise combination of:
1478 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1479 * @param array $options Optional additional parameters
1480 * @return FileRepoStatus On success, the value member contains the
1481 * archive name, or an empty string if it was a new file.
1483 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1484 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1485 return $this->readOnlyFatalStatus();
1488 $this->lock(); // begin
1490 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1491 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1492 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1493 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1495 if ( $status->value
== 'new' ) {
1496 $status->value
= '';
1498 $status->value
= $archiveName;
1501 $this->unlock(); // done
1506 /** getLinksTo inherited */
1507 /** getExifData inherited */
1508 /** isLocal inherited */
1509 /** wasDeleted inherited */
1512 * Move file to the new title
1514 * Move current, old version and all thumbnails
1515 * to the new filename. Old file is deleted.
1517 * Cache purging is done; checks for validity
1518 * and logging are caller's responsibility
1520 * @param Title $target New file name
1521 * @return FileRepoStatus
1523 function move( $target ) {
1524 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1525 return $this->readOnlyFatalStatus();
1528 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1529 $batch = new LocalFileMoveBatch( $this, $target );
1531 $this->lock(); // begin
1532 $batch->addCurrent();
1533 $archiveNames = $batch->addOlds();
1534 $status = $batch->execute();
1535 $this->unlock(); // done
1537 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1539 // Purge the source and target files...
1540 $oldTitleFile = wfLocalFile( $this->title
);
1541 $newTitleFile = wfLocalFile( $target );
1542 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1543 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1544 $this->getRepo()->getMasterDB()->onTransactionIdle(
1545 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1546 $oldTitleFile->purgeEverything();
1547 foreach ( $archiveNames as $archiveName ) {
1548 $oldTitleFile->purgeOldThumbnails( $archiveName );
1550 $newTitleFile->purgeEverything();
1554 if ( $status->isOK() ) {
1555 // Now switch the object
1556 $this->title
= $target;
1557 // Force regeneration of the name and hashpath
1558 unset( $this->name
);
1559 unset( $this->hashPath
);
1566 * Delete all versions of the file.
1568 * Moves the files into an archive directory (or deletes them)
1569 * and removes the database rows.
1571 * Cache purging is done; logging is caller's responsibility.
1573 * @param string $reason
1574 * @param bool $suppress
1575 * @param User|null $user
1576 * @return FileRepoStatus
1578 function delete( $reason, $suppress = false, $user = null ) {
1579 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1580 return $this->readOnlyFatalStatus();
1583 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1585 $this->lock(); // begin
1586 $batch->addCurrent();
1587 # Get old version relative paths
1588 $archiveNames = $batch->addOlds();
1589 $status = $batch->execute();
1590 $this->unlock(); // done
1592 if ( $status->isOK() ) {
1593 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1596 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1597 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1599 $this->getRepo()->getMasterDB()->onTransactionIdle(
1600 function () use ( $file, $archiveNames ) {
1603 $file->purgeEverything();
1604 foreach ( $archiveNames as $archiveName ) {
1605 $file->purgeOldThumbnails( $archiveName );
1608 if ( $wgUseSquid ) {
1610 $purgeUrls = array();
1611 foreach ( $archiveNames as $archiveName ) {
1612 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1614 SquidUpdate
::purge( $purgeUrls );
1623 * Delete an old version of the file.
1625 * Moves the file into an archive directory (or deletes it)
1626 * and removes the database row.
1628 * Cache purging is done; logging is caller's responsibility.
1630 * @param string $archiveName
1631 * @param string $reason
1632 * @param bool $suppress
1633 * @param User|null $user
1634 * @throws MWException Exception on database or file store failure
1635 * @return FileRepoStatus
1637 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1639 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1640 return $this->readOnlyFatalStatus();
1643 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1645 $this->lock(); // begin
1646 $batch->addOld( $archiveName );
1647 $status = $batch->execute();
1648 $this->unlock(); // done
1650 $this->purgeOldThumbnails( $archiveName );
1651 if ( $status->isOK() ) {
1652 $this->purgeDescription();
1655 if ( $wgUseSquid ) {
1657 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1664 * Restore all or specified deleted revisions to the given file.
1665 * Permissions and logging are left to the caller.
1667 * May throw database exceptions on error.
1669 * @param array $versions Set of record ids of deleted items to restore,
1670 * or empty to restore all revisions.
1671 * @param bool $unsuppress
1672 * @return FileRepoStatus
1674 function restore( $versions = array(), $unsuppress = false ) {
1675 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1676 return $this->readOnlyFatalStatus();
1679 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1681 $this->lock(); // begin
1685 $batch->addIds( $versions );
1687 $status = $batch->execute();
1688 if ( $status->isGood() ) {
1689 $cleanupStatus = $batch->cleanup();
1690 $cleanupStatus->successCount
= 0;
1691 $cleanupStatus->failCount
= 0;
1692 $status->merge( $cleanupStatus );
1694 $this->unlock(); // done
1699 /** isMultipage inherited */
1700 /** pageCount inherited */
1701 /** scaleHeight inherited */
1702 /** getImageSize inherited */
1705 * Get the URL of the file description page.
1708 function getDescriptionUrl() {
1709 return $this->title
->getLocalURL();
1713 * Get the HTML text of the description page
1714 * This is not used by ImagePage for local files, since (among other things)
1715 * it skips the parser cache.
1717 * @param Language $lang What language to get description in (Optional)
1718 * @return bool|mixed
1720 function getDescriptionText( $lang = null ) {
1721 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1725 $content = $revision->getContent();
1729 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1731 return $pout->getText();
1735 * @param int $audience
1739 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1741 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1743 } elseif ( $audience == self
::FOR_THIS_USER
1744 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1748 return $this->description
;
1753 * @return bool|string
1755 function getTimestamp() {
1758 return $this->timestamp
;
1762 * @return bool|string
1764 public function getDescriptionTouched() {
1765 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1766 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1767 // need to differentiate between null (uninitialized) and false (failed to load).
1768 if ( $this->descriptionTouched
=== null ) {
1770 'page_namespace' => $this->title
->getNamespace(),
1771 'page_title' => $this->title
->getDBkey()
1773 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1774 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1777 return $this->descriptionTouched
;
1783 function getSha1() {
1785 // Initialise now if necessary
1786 if ( $this->sha1
== '' && $this->fileExists
) {
1787 $this->lock(); // begin
1789 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1790 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1791 $dbw = $this->repo
->getMasterDB();
1792 $dbw->update( 'image',
1793 array( 'img_sha1' => $this->sha1
),
1794 array( 'img_name' => $this->getName() ),
1796 $this->saveToCache();
1799 $this->unlock(); // done
1806 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1808 function isCacheable() {
1811 // If extra data (metadata) was not loaded then it must have been large
1812 return $this->extraDataLoaded
1813 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1817 * Start a transaction and lock the image for update
1818 * Increments a reference counter if the lock is already held
1819 * @throws MWException Throws an error if the lock was not acquired
1820 * @return bool Whether the file lock owns/spawned the DB transaction
1823 $dbw = $this->repo
->getMasterDB();
1825 if ( !$this->locked
) {
1826 if ( !$dbw->trxLevel() ) {
1827 $dbw->begin( __METHOD__
);
1828 $this->lockedOwnTrx
= true;
1831 // Bug 54736: use simple lock to handle when the file does not exist.
1832 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1833 // Also, that would cause contention on INSERT of similarly named rows.
1834 $backend = $this->getRepo()->getBackend();
1835 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1836 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1837 if ( !$status->isGood() ) {
1838 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1840 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1841 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1845 return $this->lockedOwnTrx
;
1849 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1850 * the transaction and thereby releases the image lock.
1853 if ( $this->locked
) {
1855 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1856 $dbw = $this->repo
->getMasterDB();
1857 $dbw->commit( __METHOD__
);
1858 $this->lockedOwnTrx
= false;
1864 * Roll back the DB transaction and mark the image unlocked
1866 function unlockAndRollback() {
1867 $this->locked
= false;
1868 $dbw = $this->repo
->getMasterDB();
1869 $dbw->rollback( __METHOD__
);
1870 $this->lockedOwnTrx
= false;
1876 protected function readOnlyFatalStatus() {
1877 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1878 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1882 * Clean up any dangling locks
1884 function __destruct() {
1887 } // LocalFile class
1889 # ------------------------------------------------------------------------------
1892 * Helper class for file deletion
1893 * @ingroup FileAbstraction
1895 class LocalFileDeleteBatch
{
1896 /** @var LocalFile */
1903 private $srcRels = array();
1906 private $archiveUrls = array();
1908 /** @var array Items to be processed in the deletion batch */
1909 private $deletionBatch;
1911 /** @var bool Whether to suppress all suppressable fields when deleting */
1914 /** @var FileRepoStatus */
1922 * @param string $reason
1923 * @param bool $suppress
1924 * @param User|null $user
1926 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1927 $this->file
= $file;
1928 $this->reason
= $reason;
1929 $this->suppress
= $suppress;
1931 $this->user
= $user;
1934 $this->user
= $wgUser;
1936 $this->status
= $file->repo
->newGood();
1939 function addCurrent() {
1940 $this->srcRels
['.'] = $this->file
->getRel();
1944 * @param string $oldName
1946 function addOld( $oldName ) {
1947 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1948 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1952 * Add the old versions of the image to the batch
1953 * @return array List of archive names from old versions
1955 function addOlds() {
1956 $archiveNames = array();
1958 $dbw = $this->file
->repo
->getMasterDB();
1959 $result = $dbw->select( 'oldimage',
1960 array( 'oi_archive_name' ),
1961 array( 'oi_name' => $this->file
->getName() ),
1965 foreach ( $result as $row ) {
1966 $this->addOld( $row->oi_archive_name
);
1967 $archiveNames[] = $row->oi_archive_name
;
1970 return $archiveNames;
1976 function getOldRels() {
1977 if ( !isset( $this->srcRels
['.'] ) ) {
1978 $oldRels =& $this->srcRels
;
1979 $deleteCurrent = false;
1981 $oldRels = $this->srcRels
;
1982 unset( $oldRels['.'] );
1983 $deleteCurrent = true;
1986 return array( $oldRels, $deleteCurrent );
1992 protected function getHashes() {
1994 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1996 if ( $deleteCurrent ) {
1997 $hashes['.'] = $this->file
->getSha1();
2000 if ( count( $oldRels ) ) {
2001 $dbw = $this->file
->repo
->getMasterDB();
2002 $res = $dbw->select(
2004 array( 'oi_archive_name', 'oi_sha1' ),
2005 array( 'oi_archive_name' => array_keys( $oldRels ),
2006 'oi_name' => $this->file
->getName() ), // performance
2010 foreach ( $res as $row ) {
2011 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2012 // Get the hash from the file
2013 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2014 $props = $this->file
->repo
->getFileProps( $oldUrl );
2016 if ( $props['fileExists'] ) {
2017 // Upgrade the oldimage row
2018 $dbw->update( 'oldimage',
2019 array( 'oi_sha1' => $props['sha1'] ),
2020 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2022 $hashes[$row->oi_archive_name
] = $props['sha1'];
2024 $hashes[$row->oi_archive_name
] = false;
2027 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2032 $missing = array_diff_key( $this->srcRels
, $hashes );
2034 foreach ( $missing as $name => $rel ) {
2035 $this->status
->error( 'filedelete-old-unregistered', $name );
2038 foreach ( $hashes as $name => $hash ) {
2040 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2041 unset( $hashes[$name] );
2048 function doDBInserts() {
2049 $dbw = $this->file
->repo
->getMasterDB();
2050 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2051 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2052 $encReason = $dbw->addQuotes( $this->reason
);
2053 $encGroup = $dbw->addQuotes( 'deleted' );
2054 $ext = $this->file
->getExtension();
2055 $dotExt = $ext === '' ?
'' : ".$ext";
2056 $encExt = $dbw->addQuotes( $dotExt );
2057 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2059 // Bitfields to further suppress the content
2060 if ( $this->suppress
) {
2062 // This should be 15...
2063 $bitfield |
= Revision
::DELETED_TEXT
;
2064 $bitfield |
= Revision
::DELETED_COMMENT
;
2065 $bitfield |
= Revision
::DELETED_USER
;
2066 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2068 $bitfield = 'oi_deleted';
2071 if ( $deleteCurrent ) {
2072 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2073 $where = array( 'img_name' => $this->file
->getName() );
2074 $dbw->insertSelect( 'filearchive', 'image',
2076 'fa_storage_group' => $encGroup,
2077 'fa_storage_key' => $dbw->conditional(
2078 array( 'img_sha1' => '' ),
2079 $dbw->addQuotes( '' ),
2082 'fa_deleted_user' => $encUserId,
2083 'fa_deleted_timestamp' => $encTimestamp,
2084 'fa_deleted_reason' => $encReason,
2085 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2087 'fa_name' => 'img_name',
2088 'fa_archive_name' => 'NULL',
2089 'fa_size' => 'img_size',
2090 'fa_width' => 'img_width',
2091 'fa_height' => 'img_height',
2092 'fa_metadata' => 'img_metadata',
2093 'fa_bits' => 'img_bits',
2094 'fa_media_type' => 'img_media_type',
2095 'fa_major_mime' => 'img_major_mime',
2096 'fa_minor_mime' => 'img_minor_mime',
2097 'fa_description' => 'img_description',
2098 'fa_user' => 'img_user',
2099 'fa_user_text' => 'img_user_text',
2100 'fa_timestamp' => 'img_timestamp',
2101 'fa_sha1' => 'img_sha1',
2102 ), $where, __METHOD__
);
2105 if ( count( $oldRels ) ) {
2106 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2108 'oi_name' => $this->file
->getName(),
2109 'oi_archive_name' => array_keys( $oldRels ) );
2110 $dbw->insertSelect( 'filearchive', 'oldimage',
2112 'fa_storage_group' => $encGroup,
2113 'fa_storage_key' => $dbw->conditional(
2114 array( 'oi_sha1' => '' ),
2115 $dbw->addQuotes( '' ),
2118 'fa_deleted_user' => $encUserId,
2119 'fa_deleted_timestamp' => $encTimestamp,
2120 'fa_deleted_reason' => $encReason,
2121 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2123 'fa_name' => 'oi_name',
2124 'fa_archive_name' => 'oi_archive_name',
2125 'fa_size' => 'oi_size',
2126 'fa_width' => 'oi_width',
2127 'fa_height' => 'oi_height',
2128 'fa_metadata' => 'oi_metadata',
2129 'fa_bits' => 'oi_bits',
2130 'fa_media_type' => 'oi_media_type',
2131 'fa_major_mime' => 'oi_major_mime',
2132 'fa_minor_mime' => 'oi_minor_mime',
2133 'fa_description' => 'oi_description',
2134 'fa_user' => 'oi_user',
2135 'fa_user_text' => 'oi_user_text',
2136 'fa_timestamp' => 'oi_timestamp',
2137 'fa_sha1' => 'oi_sha1',
2138 ), $where, __METHOD__
);
2142 function doDBDeletes() {
2143 $dbw = $this->file
->repo
->getMasterDB();
2144 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2146 if ( count( $oldRels ) ) {
2147 $dbw->delete( 'oldimage',
2149 'oi_name' => $this->file
->getName(),
2150 'oi_archive_name' => array_keys( $oldRels )
2154 if ( $deleteCurrent ) {
2155 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2160 * Run the transaction
2161 * @return FileRepoStatus
2163 function execute() {
2165 $this->file
->lock();
2167 // Prepare deletion batch
2168 $hashes = $this->getHashes();
2169 $this->deletionBatch
= array();
2170 $ext = $this->file
->getExtension();
2171 $dotExt = $ext === '' ?
'' : ".$ext";
2173 foreach ( $this->srcRels
as $name => $srcRel ) {
2174 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2175 if ( isset( $hashes[$name] ) ) {
2176 $hash = $hashes[$name];
2177 $key = $hash . $dotExt;
2178 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2179 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2183 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2184 // We acquire this lock by running the inserts now, before the file operations.
2186 // This potentially has poor lock contention characteristics -- an alternative
2187 // scheme would be to insert stub filearchive entries with no fa_name and commit
2188 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2189 $this->doDBInserts();
2191 // Removes non-existent file from the batch, so we don't get errors.
2192 // This also handles files in the 'deleted' zone deleted via revision deletion.
2193 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2194 if ( !$checkStatus->isGood() ) {
2195 $this->status
->merge( $checkStatus );
2196 return $this->status
;
2198 $this->deletionBatch
= $checkStatus->value
;
2200 // Execute the file deletion batch
2201 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2203 if ( !$status->isGood() ) {
2204 $this->status
->merge( $status );
2207 if ( !$this->status
->isOK() ) {
2208 // Critical file deletion error
2209 // Roll back inserts, release lock and abort
2210 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2211 $this->file
->unlockAndRollback();
2213 return $this->status
;
2216 // Delete image/oldimage rows
2217 $this->doDBDeletes();
2219 // Commit and return
2220 $this->file
->unlock();
2222 return $this->status
;
2226 * Removes non-existent files from a deletion batch.
2227 * @param array $batch
2230 function removeNonexistentFiles( $batch ) {
2231 $files = $newBatch = array();
2233 foreach ( $batch as $batchItem ) {
2234 list( $src, ) = $batchItem;
2235 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2238 $result = $this->file
->repo
->fileExistsBatch( $files );
2239 if ( in_array( null, $result, true ) ) {
2240 return Status
::newFatal( 'backend-fail-internal',
2241 $this->file
->repo
->getBackend()->getName() );
2244 foreach ( $batch as $batchItem ) {
2245 if ( $result[$batchItem[0]] ) {
2246 $newBatch[] = $batchItem;
2250 return Status
::newGood( $newBatch );
2254 # ------------------------------------------------------------------------------
2257 * Helper class for file undeletion
2258 * @ingroup FileAbstraction
2260 class LocalFileRestoreBatch
{
2261 /** @var LocalFile */
2264 /** @var array List of file IDs to restore */
2265 private $cleanupBatch;
2267 /** @var array List of file IDs to restore */
2270 /** @var bool Add all revisions of the file */
2273 /** @var bool Whether to remove all settings for suppressed fields */
2274 private $unsuppress = false;
2278 * @param bool $unsuppress
2280 function __construct( File
$file, $unsuppress = false ) {
2281 $this->file
= $file;
2282 $this->cleanupBatch
= $this->ids
= array();
2283 $this->ids
= array();
2284 $this->unsuppress
= $unsuppress;
2291 function addId( $fa_id ) {
2292 $this->ids
[] = $fa_id;
2296 * Add a whole lot of files by ID
2299 function addIds( $ids ) {
2300 $this->ids
= array_merge( $this->ids
, $ids );
2304 * Add all revisions of the file
2311 * Run the transaction, except the cleanup batch.
2312 * The cleanup batch should be run in a separate transaction, because it locks different
2313 * rows and there's no need to keep the image row locked while it's acquiring those locks
2314 * The caller may have its own transaction open.
2315 * So we save the batch and let the caller call cleanup()
2316 * @return FileRepoStatus
2318 function execute() {
2321 if ( !$this->all
&& !$this->ids
) {
2323 return $this->file
->repo
->newGood();
2326 $lockOwnsTrx = $this->file
->lock();
2328 $dbw = $this->file
->repo
->getMasterDB();
2329 $status = $this->file
->repo
->newGood();
2331 $exists = (bool)$dbw->selectField( 'image', '1',
2332 array( 'img_name' => $this->file
->getName() ),
2334 // The lock() should already prevents changes, but this still may need
2335 // to bypass any transaction snapshot. However, if lock() started the
2336 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2337 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2340 // Fetch all or selected archived revisions for the file,
2341 // sorted from the most recent to the oldest.
2342 $conditions = array( 'fa_name' => $this->file
->getName() );
2344 if ( !$this->all
) {
2345 $conditions['fa_id'] = $this->ids
;
2348 $result = $dbw->select(
2350 ArchivedFile
::selectFields(),
2353 array( 'ORDER BY' => 'fa_timestamp DESC' )
2356 $idsPresent = array();
2357 $storeBatch = array();
2358 $insertBatch = array();
2359 $insertCurrent = false;
2360 $deleteIds = array();
2362 $archiveNames = array();
2364 foreach ( $result as $row ) {
2365 $idsPresent[] = $row->fa_id
;
2367 if ( $row->fa_name
!= $this->file
->getName() ) {
2368 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2369 $status->failCount++
;
2373 if ( $row->fa_storage_key
== '' ) {
2374 // Revision was missing pre-deletion
2375 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2376 $status->failCount++
;
2380 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2381 $row->fa_storage_key
;
2382 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2384 if ( isset( $row->fa_sha1
) ) {
2385 $sha1 = $row->fa_sha1
;
2387 // old row, populate from key
2388 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2392 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2393 $sha1 = substr( $sha1, 1 );
2396 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2397 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2398 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2399 ||
is_null( $row->fa_metadata
)
2401 // Refresh our metadata
2402 // Required for a new current revision; nice for older ones too. :)
2403 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2406 'minor_mime' => $row->fa_minor_mime
,
2407 'major_mime' => $row->fa_major_mime
,
2408 'media_type' => $row->fa_media_type
,
2409 'metadata' => $row->fa_metadata
2413 if ( $first && !$exists ) {
2414 // This revision will be published as the new current version
2415 $destRel = $this->file
->getRel();
2416 $insertCurrent = array(
2417 'img_name' => $row->fa_name
,
2418 'img_size' => $row->fa_size
,
2419 'img_width' => $row->fa_width
,
2420 'img_height' => $row->fa_height
,
2421 'img_metadata' => $props['metadata'],
2422 'img_bits' => $row->fa_bits
,
2423 'img_media_type' => $props['media_type'],
2424 'img_major_mime' => $props['major_mime'],
2425 'img_minor_mime' => $props['minor_mime'],
2426 'img_description' => $row->fa_description
,
2427 'img_user' => $row->fa_user
,
2428 'img_user_text' => $row->fa_user_text
,
2429 'img_timestamp' => $row->fa_timestamp
,
2433 // The live (current) version cannot be hidden!
2434 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2435 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2436 $this->cleanupBatch
[] = $row->fa_storage_key
;
2439 $archiveName = $row->fa_archive_name
;
2441 if ( $archiveName == '' ) {
2442 // This was originally a current version; we
2443 // have to devise a new archive name for it.
2444 // Format is <timestamp of archiving>!<name>
2445 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2448 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2450 } while ( isset( $archiveNames[$archiveName] ) );
2453 $archiveNames[$archiveName] = true;
2454 $destRel = $this->file
->getArchiveRel( $archiveName );
2455 $insertBatch[] = array(
2456 'oi_name' => $row->fa_name
,
2457 'oi_archive_name' => $archiveName,
2458 'oi_size' => $row->fa_size
,
2459 'oi_width' => $row->fa_width
,
2460 'oi_height' => $row->fa_height
,
2461 'oi_bits' => $row->fa_bits
,
2462 'oi_description' => $row->fa_description
,
2463 'oi_user' => $row->fa_user
,
2464 'oi_user_text' => $row->fa_user_text
,
2465 'oi_timestamp' => $row->fa_timestamp
,
2466 'oi_metadata' => $props['metadata'],
2467 'oi_media_type' => $props['media_type'],
2468 'oi_major_mime' => $props['major_mime'],
2469 'oi_minor_mime' => $props['minor_mime'],
2470 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2471 'oi_sha1' => $sha1 );
2474 $deleteIds[] = $row->fa_id
;
2476 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2477 // private files can stay where they are
2478 $status->successCount++
;
2480 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2481 $this->cleanupBatch
[] = $row->fa_storage_key
;
2489 // Add a warning to the status object for missing IDs
2490 $missingIds = array_diff( $this->ids
, $idsPresent );
2492 foreach ( $missingIds as $id ) {
2493 $status->error( 'undelete-missing-filearchive', $id );
2496 // Remove missing files from batch, so we don't get errors when undeleting them
2497 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2498 if ( !$checkStatus->isGood() ) {
2499 $status->merge( $checkStatus );
2502 $storeBatch = $checkStatus->value
;
2504 // Run the store batch
2505 // Use the OVERWRITE_SAME flag to smooth over a common error
2506 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2507 $status->merge( $storeStatus );
2509 if ( !$status->isGood() ) {
2510 // Even if some files could be copied, fail entirely as that is the
2511 // easiest thing to do without data loss
2512 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2513 $status->ok
= false;
2514 $this->file
->unlock();
2519 // Run the DB updates
2520 // Because we have locked the image row, key conflicts should be rare.
2521 // If they do occur, we can roll back the transaction at this time with
2522 // no data loss, but leaving unregistered files scattered throughout the
2524 // This is not ideal, which is why it's important to lock the image row.
2525 if ( $insertCurrent ) {
2526 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2529 if ( $insertBatch ) {
2530 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2534 $dbw->delete( 'filearchive',
2535 array( 'fa_id' => $deleteIds ),
2539 // If store batch is empty (all files are missing), deletion is to be considered successful
2540 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2542 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2544 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2546 $this->file
->purgeEverything();
2548 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2549 $this->file
->purgeDescription();
2553 $this->file
->unlock();
2559 * Removes non-existent files from a store batch.
2560 * @param array $triplets
2563 function removeNonexistentFiles( $triplets ) {
2564 $files = $filteredTriplets = array();
2565 foreach ( $triplets as $file ) {
2566 $files[$file[0]] = $file[0];
2569 $result = $this->file
->repo
->fileExistsBatch( $files );
2570 if ( in_array( null, $result, true ) ) {
2571 return Status
::newFatal( 'backend-fail-internal',
2572 $this->file
->repo
->getBackend()->getName() );
2575 foreach ( $triplets as $file ) {
2576 if ( $result[$file[0]] ) {
2577 $filteredTriplets[] = $file;
2581 return Status
::newGood( $filteredTriplets );
2585 * Removes non-existent files from a cleanup batch.
2586 * @param array $batch
2589 function removeNonexistentFromCleanup( $batch ) {
2590 $files = $newBatch = array();
2591 $repo = $this->file
->repo
;
2593 foreach ( $batch as $file ) {
2594 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2595 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2598 $result = $repo->fileExistsBatch( $files );
2600 foreach ( $batch as $file ) {
2601 if ( $result[$file] ) {
2602 $newBatch[] = $file;
2610 * Delete unused files in the deleted zone.
2611 * This should be called from outside the transaction in which execute() was called.
2612 * @return FileRepoStatus
2614 function cleanup() {
2615 if ( !$this->cleanupBatch
) {
2616 return $this->file
->repo
->newGood();
2619 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2621 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2627 * Cleanup a failed batch. The batch was only partially successful, so
2628 * rollback by removing all items that were succesfully copied.
2630 * @param Status $storeStatus
2631 * @param array $storeBatch
2633 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2634 $cleanupBatch = array();
2636 foreach ( $storeStatus->success
as $i => $success ) {
2637 // Check if this item of the batch was successfully copied
2639 // Item was successfully copied and needs to be removed again
2640 // Extract ($dstZone, $dstRel) from the batch
2641 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2644 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2648 # ------------------------------------------------------------------------------
2651 * Helper class for file movement
2652 * @ingroup FileAbstraction
2654 class LocalFileMoveBatch
{
2655 /** @var LocalFile */
2665 protected $oldCount;
2669 /** @var DatabaseBase */
2674 * @param Title $target
2676 function __construct( File
$file, Title
$target ) {
2677 $this->file
= $file;
2678 $this->target
= $target;
2679 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2680 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2681 $this->oldName
= $this->file
->getName();
2682 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2683 $this->oldRel
= $this->oldHash
. $this->oldName
;
2684 $this->newRel
= $this->newHash
. $this->newName
;
2685 $this->db
= $file->getRepo()->getMasterDb();
2689 * Add the current image to the batch
2691 function addCurrent() {
2692 $this->cur
= array( $this->oldRel
, $this->newRel
);
2696 * Add the old versions of the image to the batch
2697 * @return array List of archive names from old versions
2699 function addOlds() {
2700 $archiveBase = 'archive';
2701 $this->olds
= array();
2702 $this->oldCount
= 0;
2703 $archiveNames = array();
2705 $result = $this->db
->select( 'oldimage',
2706 array( 'oi_archive_name', 'oi_deleted' ),
2707 array( 'oi_name' => $this->oldName
),
2709 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2712 foreach ( $result as $row ) {
2713 $archiveNames[] = $row->oi_archive_name
;
2714 $oldName = $row->oi_archive_name
;
2715 $bits = explode( '!', $oldName, 2 );
2717 if ( count( $bits ) != 2 ) {
2718 wfDebug( "Old file name missing !: '$oldName' \n" );
2722 list( $timestamp, $filename ) = $bits;
2724 if ( $this->oldName
!= $filename ) {
2725 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2731 // Do we want to add those to oldCount?
2732 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2736 $this->olds
[] = array(
2737 "{$archiveBase}/{$this->oldHash}{$oldName}",
2738 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2742 return $archiveNames;
2747 * @return FileRepoStatus
2749 function execute() {
2750 $repo = $this->file
->repo
;
2751 $status = $repo->newGood();
2753 $triplets = $this->getMoveTriplets();
2754 $checkStatus = $this->removeNonexistentFiles( $triplets );
2755 if ( !$checkStatus->isGood() ) {
2756 $status->merge( $checkStatus );
2759 $triplets = $checkStatus->value
;
2760 $destFile = wfLocalFile( $this->target
);
2762 $this->file
->lock(); // begin
2763 $destFile->lock(); // quickly fail if destination is not available
2764 // Rename the file versions metadata in the DB.
2765 // This implicitly locks the destination file, which avoids race conditions.
2766 // If we moved the files from A -> C before DB updates, another process could
2767 // move files from B -> C at this point, causing storeBatch() to fail and thus
2768 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2769 $statusDb = $this->doDBUpdates();
2770 if ( !$statusDb->isGood() ) {
2771 $destFile->unlock();
2772 $this->file
->unlockAndRollback();
2773 $statusDb->ok
= false;
2777 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2778 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2780 // Copy the files into their new location.
2781 // If a prior process fataled copying or cleaning up files we tolerate any
2782 // of the existing files if they are identical to the ones being stored.
2783 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2784 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2785 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2786 if ( !$statusMove->isGood() ) {
2787 // Delete any files copied over (while the destination is still locked)
2788 $this->cleanupTarget( $triplets );
2789 $destFile->unlock();
2790 $this->file
->unlockAndRollback(); // unlocks the destination
2791 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2792 $statusMove->ok
= false;
2796 $destFile->unlock();
2797 $this->file
->unlock(); // done
2799 // Everything went ok, remove the source files
2800 $this->cleanupSource( $triplets );
2802 $status->merge( $statusDb );
2803 $status->merge( $statusMove );
2809 * Do the database updates and return a new FileRepoStatus indicating how
2810 * many rows where updated.
2812 * @return FileRepoStatus
2814 function doDBUpdates() {
2815 $repo = $this->file
->repo
;
2816 $status = $repo->newGood();
2819 // Update current image
2822 array( 'img_name' => $this->newName
),
2823 array( 'img_name' => $this->oldName
),
2827 if ( $dbw->affectedRows() ) {
2828 $status->successCount++
;
2830 $status->failCount++
;
2831 $status->fatal( 'imageinvalidfilename' );
2836 // Update old images
2840 'oi_name' => $this->newName
,
2841 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2842 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2844 array( 'oi_name' => $this->oldName
),
2848 $affected = $dbw->affectedRows();
2849 $total = $this->oldCount
;
2850 $status->successCount +
= $affected;
2851 // Bug 34934: $total is based on files that actually exist.
2852 // There may be more DB rows than such files, in which case $affected
2853 // can be greater than $total. We use max() to avoid negatives here.
2854 $status->failCount +
= max( 0, $total - $affected );
2855 if ( $status->failCount
) {
2856 $status->error( 'imageinvalidfilename' );
2863 * Generate triplets for FileRepo::storeBatch().
2866 function getMoveTriplets() {
2867 $moves = array_merge( array( $this->cur
), $this->olds
);
2868 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2870 foreach ( $moves as $move ) {
2871 // $move: (oldRelativePath, newRelativePath)
2872 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2873 $triplets[] = array( $srcUrl, 'public', $move[1] );
2876 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2884 * Removes non-existent files from move batch.
2885 * @param array $triplets
2888 function removeNonexistentFiles( $triplets ) {
2891 foreach ( $triplets as $file ) {
2892 $files[$file[0]] = $file[0];
2895 $result = $this->file
->repo
->fileExistsBatch( $files );
2896 if ( in_array( null, $result, true ) ) {
2897 return Status
::newFatal( 'backend-fail-internal',
2898 $this->file
->repo
->getBackend()->getName() );
2901 $filteredTriplets = array();
2902 foreach ( $triplets as $file ) {
2903 if ( $result[$file[0]] ) {
2904 $filteredTriplets[] = $file;
2906 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2910 return Status
::newGood( $filteredTriplets );
2914 * Cleanup a partially moved array of triplets by deleting the target
2915 * files. Called if something went wrong half way.
2916 * @param array $triplets
2918 function cleanupTarget( $triplets ) {
2919 // Create dest pairs from the triplets
2921 foreach ( $triplets as $triplet ) {
2922 // $triplet: (old source virtual URL, dst zone, dest rel)
2923 $pairs[] = array( $triplet[1], $triplet[2] );
2926 $this->file
->repo
->cleanupBatch( $pairs );
2930 * Cleanup a fully moved array of triplets by deleting the source files.
2931 * Called at the end of the move process if everything else went ok.
2932 * @param array $triplets
2934 function cleanupSource( $triplets ) {
2935 // Create source file names from the triplets
2937 foreach ( $triplets as $triplet ) {
2938 $files[] = $triplet[0];
2941 $this->file
->repo
->cleanupBatch( $files );