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 bool Whether the row was upgraded on load */
115 /** @var bool True if the image row is locked */
118 /** @var bool True if the image row is locked with a lock initiated transaction */
119 private $lockedOwnTrx;
121 /** @var bool True if file is not present in file system. Not to be cached in memcached */
124 /** @var int UNIX timestamp of last markVolatile() call */
125 private $lastMarkedVolatile = 0;
127 const LOAD_ALL
= 1; // integer; load all the lazy fields too (like metadata)
128 const LOAD_VIA_SLAVE
= 2; // integer; use a slave to load the data
130 const VOLATILE_TTL
= 300; // integer; seconds
133 * Create a LocalFile from a title
134 * Do not call this except from inside a repo class.
136 * Note: $unused param is only here to avoid an E_STRICT
138 * @param Title $title
139 * @param FileRepo $repo
140 * @param null $unused
144 static function newFromTitle( $title, $repo, $unused = null ) {
145 return new self( $title, $repo );
149 * Create a LocalFile from a title
150 * Do not call this except from inside a repo class.
152 * @param stdClass $row
153 * @param FileRepo $repo
157 static function newFromRow( $row, $repo ) {
158 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
159 $file = new self( $title, $repo );
160 $file->loadFromRow( $row );
166 * Create a LocalFile from a SHA-1 key
167 * Do not call this except from inside a repo class.
169 * @param string $sha1 Base-36 SHA-1
170 * @param LocalRepo $repo
171 * @param string|bool $timestamp MW_timestamp (optional)
172 * @return bool|LocalFile
174 static function newFromKey( $sha1, $repo, $timestamp = false ) {
175 $dbr = $repo->getSlaveDB();
177 $conds = array( 'img_sha1' => $sha1 );
179 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
182 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
184 return self
::newFromRow( $row, $repo );
191 * Fields in the image table
194 static function selectFields() {
215 * Do not call this except from inside a repo class.
216 * @param Title $title
217 * @param FileRepo $repo
219 function __construct( $title, $repo ) {
220 parent
::__construct( $title, $repo );
222 $this->metadata
= '';
223 $this->historyLine
= 0;
224 $this->historyRes
= null;
225 $this->dataLoaded
= false;
226 $this->extraDataLoaded
= false;
228 $this->assertRepoDefined();
229 $this->assertTitleDefined();
233 * Get the memcached key for the main data for this file, or false if
234 * there is no access to the shared cache.
235 * @return string|bool
237 function getCacheKey() {
238 $hashedName = md5( $this->getName() );
240 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
244 * Try to load file metadata from memcached. Returns true on success.
247 function loadFromCache() {
250 $this->dataLoaded
= false;
251 $this->extraDataLoaded
= false;
252 $key = $this->getCacheKey();
259 $cachedValues = $wgMemc->get( $key );
261 // Check if the key existed and belongs to this version of MediaWiki
262 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
263 wfDebug( "Pulling file metadata from cache key $key\n" );
264 $this->fileExists
= $cachedValues['fileExists'];
265 if ( $this->fileExists
) {
266 $this->setProps( $cachedValues );
268 $this->dataLoaded
= true;
269 $this->extraDataLoaded
= true;
270 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
271 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
275 if ( $this->dataLoaded
) {
276 wfIncrStats( 'image_cache_hit' );
278 wfIncrStats( 'image_cache_miss' );
281 return $this->dataLoaded
;
285 * Save the file metadata to memcached
287 function saveToCache() {
291 $key = $this->getCacheKey();
297 $fields = $this->getCacheFields( '' );
298 $cache = array( 'version' => MW_FILE_VERSION
);
299 $cache['fileExists'] = $this->fileExists
;
301 if ( $this->fileExists
) {
302 foreach ( $fields as $field ) {
303 $cache[$field] = $this->$field;
307 // Strip off excessive entries from the subset of fields that can become large.
308 // If the cache value gets to large it will not fit in memcached and nothing will
309 // get cached at all, causing master queries for any file access.
310 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
311 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
312 unset( $cache[$field] ); // don't let the value get too big
316 // Cache presence for 1 week and negatives for 1 day
317 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
321 * Load metadata from the file itself
323 function loadFromFile() {
324 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
325 $this->setProps( $props );
329 * @param string $prefix
332 function getCacheFields( $prefix = 'img_' ) {
333 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
334 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
335 'user_text', 'description' );
336 static $results = array();
338 if ( $prefix == '' ) {
342 if ( !isset( $results[$prefix] ) ) {
343 $prefixedFields = array();
344 foreach ( $fields as $field ) {
345 $prefixedFields[] = $prefix . $field;
347 $results[$prefix] = $prefixedFields;
350 return $results[$prefix];
354 * @param string $prefix
357 function getLazyCacheFields( $prefix = 'img_' ) {
358 static $fields = array( 'metadata' );
359 static $results = array();
361 if ( $prefix == '' ) {
365 if ( !isset( $results[$prefix] ) ) {
366 $prefixedFields = array();
367 foreach ( $fields as $field ) {
368 $prefixedFields[] = $prefix . $field;
370 $results[$prefix] = $prefixedFields;
373 return $results[$prefix];
377 * Load file metadata from the DB
380 function loadFromDB( $flags = 0 ) {
381 $fname = get_class( $this ) . '::' . __FUNCTION__
;
383 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
384 $this->dataLoaded
= true;
385 $this->extraDataLoaded
= true;
387 $dbr = ( $flags & self
::LOAD_VIA_SLAVE
)
388 ?
$this->repo
->getSlaveDB()
389 : $this->repo
->getMasterDB();
391 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
392 array( 'img_name' => $this->getName() ), $fname );
395 $this->loadFromRow( $row );
397 $this->fileExists
= false;
402 * Load lazy file metadata from the DB.
403 * This covers fields that are sometimes not cached.
405 protected function loadExtraFromDB() {
406 $fname = get_class( $this ) . '::' . __FUNCTION__
;
408 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
409 $this->extraDataLoaded
= true;
411 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
413 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
417 foreach ( $fieldMap as $name => $value ) {
418 $this->$name = $value;
421 throw new MWException( "Could not find data for image '{$this->getName()}'." );
426 * @param DatabaseBase $dbr
427 * @param string $fname
430 private function loadFieldsWithTimestamp( $dbr, $fname ) {
433 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
434 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
437 $fieldMap = $this->unprefixRow( $row, 'img_' );
439 # File may have been uploaded over in the meantime; check the old versions
440 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
441 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
444 $fieldMap = $this->unprefixRow( $row, 'oi_' );
452 * @param array $row Row
453 * @param string $prefix
454 * @throws MWException
457 protected function unprefixRow( $row, $prefix = 'img_' ) {
458 $array = (array)$row;
459 $prefixLength = strlen( $prefix );
461 // Sanity check prefix once
462 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
463 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
467 foreach ( $array as $name => $value ) {
468 $decoded[substr( $name, $prefixLength )] = $value;
475 * Decode a row from the database (either object or array) to an array
476 * with timestamps and MIME types decoded, and the field prefix removed.
478 * @param string $prefix
479 * @throws MWException
482 function decodeRow( $row, $prefix = 'img_' ) {
483 $decoded = $this->unprefixRow( $row, $prefix );
485 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
487 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
489 if ( empty( $decoded['major_mime'] ) ) {
490 $decoded['mime'] = 'unknown/unknown';
492 if ( !$decoded['minor_mime'] ) {
493 $decoded['minor_mime'] = 'unknown';
495 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
498 # Trim zero padding from char/binary field
499 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
505 * Load file metadata from a DB result row
508 * @param string $prefix
510 function loadFromRow( $row, $prefix = 'img_' ) {
511 $this->dataLoaded
= true;
512 $this->extraDataLoaded
= true;
514 $array = $this->decodeRow( $row, $prefix );
516 foreach ( $array as $name => $value ) {
517 $this->$name = $value;
520 $this->fileExists
= true;
521 $this->maybeUpgradeRow();
525 * Load file metadata from cache or DB, unless already loaded
528 function load( $flags = 0 ) {
529 if ( !$this->dataLoaded
) {
530 if ( !$this->loadFromCache() ) {
531 $this->loadFromDB( $this->isVolatile() ?
0 : self
::LOAD_VIA_SLAVE
);
532 $this->saveToCache();
534 $this->dataLoaded
= true;
536 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
537 $this->loadExtraFromDB();
542 * Upgrade a row if it needs it
544 function maybeUpgradeRow() {
545 global $wgUpdateCompatibleMetadata;
546 if ( wfReadOnly() ) {
550 if ( is_null( $this->media_type
) ||
551 $this->mime
== 'image/svg'
554 $this->upgraded
= true;
556 $handler = $this->getHandler();
558 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
559 if ( $validity === MediaHandler
::METADATA_BAD
560 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
563 $this->upgraded
= true;
569 function getUpgraded() {
570 return $this->upgraded
;
574 * Fix assorted version-related problems with the image row by reloading it from the file
576 function upgradeRow() {
578 $this->lock(); // begin
580 $this->loadFromFile();
582 # Don't destroy file info of missing files
583 if ( !$this->fileExists
) {
585 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
590 $dbw = $this->repo
->getMasterDB();
591 list( $major, $minor ) = self
::splitMime( $this->mime
);
593 if ( wfReadOnly() ) {
598 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
600 $dbw->update( 'image',
602 'img_size' => $this->size
, // sanity
603 'img_width' => $this->width
,
604 'img_height' => $this->height
,
605 'img_bits' => $this->bits
,
606 'img_media_type' => $this->media_type
,
607 'img_major_mime' => $major,
608 'img_minor_mime' => $minor,
609 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
610 'img_sha1' => $this->sha1
,
612 array( 'img_name' => $this->getName() ),
616 $this->saveToCache();
618 $this->unlock(); // done
623 * Set properties in this object to be equal to those given in the
624 * associative array $info. Only cacheable fields can be set.
625 * All fields *must* be set in $info except for getLazyCacheFields().
627 * If 'mime' is given, it will be split into major_mime/minor_mime.
628 * If major_mime/minor_mime are given, $this->mime will also be set.
632 function setProps( $info ) {
633 $this->dataLoaded
= true;
634 $fields = $this->getCacheFields( '' );
635 $fields[] = 'fileExists';
637 foreach ( $fields as $field ) {
638 if ( isset( $info[$field] ) ) {
639 $this->$field = $info[$field];
643 // Fix up mime fields
644 if ( isset( $info['major_mime'] ) ) {
645 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
646 } elseif ( isset( $info['mime'] ) ) {
647 $this->mime
= $info['mime'];
648 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
652 /** splitMime inherited */
653 /** getName inherited */
654 /** getTitle inherited */
655 /** getURL inherited */
656 /** getViewURL inherited */
657 /** getPath inherited */
658 /** isVisible inherited */
663 function isMissing() {
664 if ( $this->missing
=== null ) {
665 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
666 $this->missing
= !$fileExists;
669 return $this->missing
;
673 * Return the width of the image
678 public function getWidth( $page = 1 ) {
681 if ( $this->isMultipage() ) {
682 $handler = $this->getHandler();
686 $dim = $handler->getPageDimensions( $this, $page );
688 return $dim['width'];
690 // For non-paged media, the false goes through an
691 // intval, turning failure into 0, so do same here.
700 * Return the height of the image
705 public function getHeight( $page = 1 ) {
708 if ( $this->isMultipage() ) {
709 $handler = $this->getHandler();
713 $dim = $handler->getPageDimensions( $this, $page );
715 return $dim['height'];
717 // For non-paged media, the false goes through an
718 // intval, turning failure into 0, so do same here.
722 return $this->height
;
727 * Returns ID or name of user who uploaded the file
729 * @param string $type 'text' or 'id'
732 function getUser( $type = 'text' ) {
735 if ( $type == 'text' ) {
736 return $this->user_text
;
737 } elseif ( $type == 'id' ) {
743 * Get handler-specific metadata
746 function getMetadata() {
747 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
748 return $this->metadata
;
754 function getBitDepth() {
761 * Returns the size of the image file, in bytes
764 public function getSize() {
771 * Returns the MIME type of the file.
774 function getMimeType() {
781 * Returns the type of the media in the file.
782 * Use the value returned by this function with the MEDIATYPE_xxx constants.
785 function getMediaType() {
788 return $this->media_type
;
791 /** canRender inherited */
792 /** mustRender inherited */
793 /** allowInlineDisplay inherited */
794 /** isSafeFile inherited */
795 /** isTrustedFile inherited */
798 * Returns true if the file exists on disk.
799 * @return bool Whether file exist on disk.
801 public function exists() {
804 return $this->fileExists
;
807 /** getTransformScript inherited */
808 /** getUnscaledThumb inherited */
809 /** thumbName inherited */
810 /** createThumb inherited */
811 /** transform inherited */
813 /** getHandler inherited */
814 /** iconThumb inherited */
815 /** getLastError inherited */
818 * Get all thumbnail names previously generated for this file
819 * @param string|bool $archiveName Name of an archive file, default false
820 * @return array First element is the base dir, then files in that base dir.
822 function getThumbnails( $archiveName = false ) {
823 if ( $archiveName ) {
824 $dir = $this->getArchiveThumbPath( $archiveName );
826 $dir = $this->getThumbPath();
829 $backend = $this->repo
->getBackend();
830 $files = array( $dir );
832 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
833 foreach ( $iterator as $file ) {
836 } catch ( FileBackendError
$e ) {
837 } // suppress (bug 54674)
843 * Refresh metadata in memcached, but don't touch thumbnails or squid
845 function purgeMetadataCache() {
847 $this->saveToCache();
848 $this->purgeHistory();
852 * Purge the shared history (OldLocalFile) cache.
854 * @note This used to purge old thumbnails as well.
856 function purgeHistory() {
859 $hashedName = md5( $this->getName() );
860 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
863 $wgMemc->delete( $oldKey );
868 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
870 * @param array $options An array potentially with the key forThumbRefresh.
872 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
874 function purgeCache( $options = array() ) {
875 // Refresh metadata cache
876 $this->purgeMetadataCache();
879 $this->purgeThumbnails( $options );
881 // Purge squid cache for this file
882 SquidUpdate
::purge( array( $this->getURL() ) );
886 * Delete cached transformed files for an archived version only.
887 * @param string $archiveName Name of the archived file
889 function purgeOldThumbnails( $archiveName ) {
892 // Get a list of old thumbnails and URLs
893 $files = $this->getThumbnails( $archiveName );
895 // Purge any custom thumbnail caches
896 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
898 $dir = array_shift( $files );
899 $this->purgeThumbList( $dir, $files );
904 foreach ( $files as $file ) {
905 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
907 SquidUpdate
::purge( $urls );
913 * Delete cached transformed files for the current version only.
914 * @param array $options
916 function purgeThumbnails( $options = array() ) {
920 $files = $this->getThumbnails();
921 // Always purge all files from squid regardless of handler filters
924 foreach ( $files as $file ) {
925 $urls[] = $this->getThumbUrl( $file );
927 array_shift( $urls ); // don't purge directory
930 // Give media handler a chance to filter the file purge list
931 if ( !empty( $options['forThumbRefresh'] ) ) {
932 $handler = $this->getHandler();
934 $handler->filterThumbnailPurgeList( $files, $options );
938 // Purge any custom thumbnail caches
939 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
941 $dir = array_shift( $files );
942 $this->purgeThumbList( $dir, $files );
946 SquidUpdate
::purge( $urls );
952 * Delete a list of thumbnails visible at urls
953 * @param string $dir Base dir of the files.
954 * @param array $files Array of strings: relative filenames (to $dir)
956 protected function purgeThumbList( $dir, $files ) {
957 $fileListDebug = strtr(
958 var_export( $files, true ),
961 wfDebug( __METHOD__
. ": $fileListDebug\n" );
963 $purgeList = array();
964 foreach ( $files as $file ) {
965 # Check that the base file name is part of the thumb name
966 # This is a basic sanity check to avoid erasing unrelated directories
967 if ( strpos( $file, $this->getName() ) !== false
968 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
970 $purgeList[] = "{$dir}/{$file}";
974 # Delete the thumbnails
975 $this->repo
->quickPurgeBatch( $purgeList );
976 # Clear out the thumbnail directory if empty
977 $this->repo
->quickCleanDir( $dir );
980 /** purgeDescription inherited */
981 /** purgeEverything inherited */
984 * @param int $limit Optional: Limit to number of results
985 * @param int $start Optional: Timestamp, start from
986 * @param int $end Optional: Timestamp, end at
990 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
991 $dbr = $this->repo
->getSlaveDB();
992 $tables = array( 'oldimage' );
993 $fields = OldLocalFile
::selectFields();
994 $conds = $opts = $join_conds = array();
995 $eq = $inc ?
'=' : '';
996 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
999 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1003 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1007 $opts['LIMIT'] = $limit;
1010 // Search backwards for time > x queries
1011 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1012 $opts['ORDER BY'] = "oi_timestamp $order";
1013 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1015 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1016 &$conds, &$opts, &$join_conds ) );
1018 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1021 foreach ( $res as $row ) {
1022 $r[] = $this->repo
->newFileFromRow( $row );
1025 if ( $order == 'ASC' ) {
1026 $r = array_reverse( $r ); // make sure it ends up descending
1033 * Returns the history of this file, line by line.
1034 * starts with current version, then old versions.
1035 * uses $this->historyLine to check which line to return:
1036 * 0 return line for current version
1037 * 1 query for old versions, return first one
1038 * 2, ... return next old version from above query
1041 public function nextHistoryLine() {
1042 # Polymorphic function name to distinguish foreign and local fetches
1043 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1045 $dbr = $this->repo
->getSlaveDB();
1047 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1048 $this->historyRes
= $dbr->select( 'image',
1051 "'' AS oi_archive_name",
1055 array( 'img_name' => $this->title
->getDBkey() ),
1059 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1060 $this->historyRes
= null;
1064 } elseif ( $this->historyLine
== 1 ) {
1065 $this->historyRes
= $dbr->select( 'oldimage', '*',
1066 array( 'oi_name' => $this->title
->getDBkey() ),
1068 array( 'ORDER BY' => 'oi_timestamp DESC' )
1071 $this->historyLine++
;
1073 return $dbr->fetchObject( $this->historyRes
);
1077 * Reset the history pointer to the first element of the history
1079 public function resetHistory() {
1080 $this->historyLine
= 0;
1082 if ( !is_null( $this->historyRes
) ) {
1083 $this->historyRes
= null;
1087 /** getHashPath inherited */
1088 /** getRel inherited */
1089 /** getUrlRel inherited */
1090 /** getArchiveRel inherited */
1091 /** getArchivePath inherited */
1092 /** getThumbPath inherited */
1093 /** getArchiveUrl inherited */
1094 /** getThumbUrl inherited */
1095 /** getArchiveVirtualUrl inherited */
1096 /** getThumbVirtualUrl inherited */
1097 /** isHashed inherited */
1100 * Upload a file and record it in the DB
1101 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1102 * @param string $comment Upload description
1103 * @param string $pageText Text to use for the new description page,
1104 * if a new description page is created
1105 * @param int|bool $flags Flags for publish()
1106 * @param array|bool $props File properties, if known. This can be used to
1107 * reduce the upload time when uploading virtual URLs for which the file
1108 * info is already known
1109 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1111 * @param User|null $user User object or null to use $wgUser
1113 * @return FileRepoStatus On success, the value member contains the
1114 * archive name, or an empty string if it was a new file.
1116 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1117 $timestamp = false, $user = null
1121 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1122 return $this->readOnlyFatalStatus();
1126 if ( $this->repo
->isVirtualUrl( $srcPath )
1127 || FileBackend
::isStoragePath( $srcPath )
1129 $props = $this->repo
->getFileProps( $srcPath );
1131 $props = FSFile
::getPropsFromPath( $srcPath );
1136 $handler = MediaHandler
::getHandler( $props['mime'] );
1138 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1140 $options['headers'] = array();
1143 // Trim spaces on user supplied text
1144 $comment = trim( $comment );
1146 // Truncate nicely or the DB will do it for us
1147 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1148 $comment = $wgContLang->truncate( $comment, 255 );
1149 $this->lock(); // begin
1150 $status = $this->publish( $srcPath, $flags, $options );
1152 if ( $status->successCount
>= 2 ) {
1153 // There will be a copy+(one of move,copy,store).
1154 // The first succeeding does not commit us to updating the DB
1155 // since it simply copied the current version to a timestamped file name.
1156 // It is only *preferable* to avoid leaving such files orphaned.
1157 // Once the second operation goes through, then the current version was
1158 // updated and we must therefore update the DB too.
1159 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1160 $status->fatal( 'filenotfound', $srcPath );
1164 $this->unlock(); // done
1170 * Record a file upload in the upload log and the image table
1171 * @param string $oldver
1172 * @param string $desc
1173 * @param string $license
1174 * @param string $copyStatus
1175 * @param string $source
1176 * @param bool $watch
1177 * @param string|bool $timestamp
1178 * @param User|null $user User object or null to use $wgUser
1181 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1182 $watch = false, $timestamp = false, User
$user = null ) {
1188 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1190 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1195 $user->addWatch( $this->getTitle() );
1202 * Record a file upload in the upload log and the image table
1203 * @param string $oldver
1204 * @param string $comment
1205 * @param string $pageText
1206 * @param bool|array $props
1207 * @param string|bool $timestamp
1208 * @param null|User $user
1211 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1215 if ( is_null( $user ) ) {
1220 $dbw = $this->repo
->getMasterDB();
1221 $dbw->begin( __METHOD__
);
1224 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1227 # Imports or such might force a certain timestamp; otherwise we generate
1228 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1229 if ( $timestamp === false ) {
1230 $timestamp = $dbw->timestamp();
1231 $allowTimeKludge = true;
1233 $allowTimeKludge = false;
1236 $props['description'] = $comment;
1237 $props['user'] = $user->getId();
1238 $props['user_text'] = $user->getName();
1239 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1240 $this->setProps( $props );
1242 # Fail now if the file isn't there
1243 if ( !$this->fileExists
) {
1244 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1245 $dbw->rollback( __METHOD__
);
1252 # Test to see if the row exists using INSERT IGNORE
1253 # This avoids race conditions by locking the row until the commit, and also
1254 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1255 $dbw->insert( 'image',
1257 'img_name' => $this->getName(),
1258 'img_size' => $this->size
,
1259 'img_width' => intval( $this->width
),
1260 'img_height' => intval( $this->height
),
1261 'img_bits' => $this->bits
,
1262 'img_media_type' => $this->media_type
,
1263 'img_major_mime' => $this->major_mime
,
1264 'img_minor_mime' => $this->minor_mime
,
1265 'img_timestamp' => $timestamp,
1266 'img_description' => $comment,
1267 'img_user' => $user->getId(),
1268 'img_user_text' => $user->getName(),
1269 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1270 'img_sha1' => $this->sha1
1275 if ( $dbw->affectedRows() == 0 ) {
1276 if ( $allowTimeKludge ) {
1277 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1278 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1279 array( 'img_name' => $this->getName() ),
1281 array( 'LOCK IN SHARE MODE' ) );
1282 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1283 # Avoid a timestamp that is not newer than the last version
1284 # TODO: the image/oldimage tables should be like page/revision with an ID field
1285 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1286 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1287 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1288 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1292 # (bug 34993) Note: $oldver can be empty here, if the previous
1293 # version of the file was broken. Allow registration of the new
1294 # version to continue anyway, because that's better than having
1295 # an image that's not fixable by user operations.
1298 # Collision, this is an update of a file
1299 # Insert previous contents into oldimage
1300 $dbw->insertSelect( 'oldimage', 'image',
1302 'oi_name' => 'img_name',
1303 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1304 'oi_size' => 'img_size',
1305 'oi_width' => 'img_width',
1306 'oi_height' => 'img_height',
1307 'oi_bits' => 'img_bits',
1308 'oi_timestamp' => 'img_timestamp',
1309 'oi_description' => 'img_description',
1310 'oi_user' => 'img_user',
1311 'oi_user_text' => 'img_user_text',
1312 'oi_metadata' => 'img_metadata',
1313 'oi_media_type' => 'img_media_type',
1314 'oi_major_mime' => 'img_major_mime',
1315 'oi_minor_mime' => 'img_minor_mime',
1316 'oi_sha1' => 'img_sha1'
1318 array( 'img_name' => $this->getName() ),
1322 # Update the current image row
1323 $dbw->update( 'image',
1325 'img_size' => $this->size
,
1326 'img_width' => intval( $this->width
),
1327 'img_height' => intval( $this->height
),
1328 'img_bits' => $this->bits
,
1329 'img_media_type' => $this->media_type
,
1330 'img_major_mime' => $this->major_mime
,
1331 'img_minor_mime' => $this->minor_mime
,
1332 'img_timestamp' => $timestamp,
1333 'img_description' => $comment,
1334 'img_user' => $user->getId(),
1335 'img_user_text' => $user->getName(),
1336 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1337 'img_sha1' => $this->sha1
1339 array( 'img_name' => $this->getName() ),
1343 # This is a new file, so update the image count
1344 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1347 $descTitle = $this->getTitle();
1348 $wikiPage = new WikiFilePage( $descTitle );
1349 $wikiPage->setFile( $this );
1352 $action = $reupload ?
'overwrite' : 'upload';
1354 $logEntry = new ManualLogEntry( 'upload', $action );
1355 $logEntry->setPerformer( $user );
1356 $logEntry->setComment( $comment );
1357 $logEntry->setTarget( $descTitle );
1359 // Allow people using the api to associate log entries with the upload.
1360 // Log has a timestamp, but sometimes different from upload timestamp.
1361 $logEntry->setParameters(
1363 'img_sha1' => $this->sha1
,
1364 'img_timestamp' => $timestamp,
1367 // Note we keep $logId around since during new image
1368 // creation, page doesn't exist yet, so log_page = 0
1369 // but we want it to point to the page we're making,
1370 // so we later modify the log entry.
1371 // For a similar reason, we avoid making an RC entry
1372 // now and wait until the page exists.
1373 $logId = $logEntry->insert();
1375 $exists = $descTitle->exists();
1377 // Page exists, do RC entry now (otherwise we wait for later).
1378 $logEntry->publish( $logId );
1382 # Create a null revision
1383 $latest = $descTitle->getLatestRevID();
1384 // Use own context to get the action text in content language
1385 $formatter = LogFormatter
::newFromEntry( $logEntry );
1386 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1387 $editSummary = $formatter->getPlainActionText();
1389 $nullRevision = Revision
::newNullRevision(
1391 $descTitle->getArticleID(),
1396 if ( !is_null( $nullRevision ) ) {
1397 $nullRevision->insertOn( $dbw );
1399 Hooks
::run( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1400 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1404 # Commit the transaction now, in case something goes wrong later
1405 # The most important thing is that files don't get lost, especially archives
1406 # NOTE: once we have support for nested transactions, the commit may be moved
1407 # to after $wikiPage->doEdit has been called.
1408 $dbw->commit( __METHOD__
);
1411 # We shall not saveToCache before the commit since otherwise
1412 # in case of a rollback there is an usable file from memcached
1413 # which in fact doesn't really exist (bug 24978)
1414 $this->saveToCache();
1417 # Invalidate the cache for the description page
1418 $descTitle->invalidateCache();
1419 $descTitle->purgeSquid();
1421 # New file; create the description page.
1422 # There's already a log entry, so don't make a second RC entry
1423 # Squid and file cache for the description page are purged by doEditContent.
1424 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1425 $status = $wikiPage->doEditContent(
1428 EDIT_NEW | EDIT_SUPPRESS_RC
,
1433 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1434 // Now that the page exists, make an RC entry.
1435 $logEntry->publish( $logId );
1436 if ( isset( $status->value
['revision'] ) ) {
1437 $dbw->update( 'logging',
1438 array( 'log_page' => $status->value
['revision']->getPage() ),
1439 array( 'log_id' => $logId ),
1443 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1447 # Delete old thumbnails
1448 $this->purgeThumbnails();
1450 # Remove the old file from the squid cache
1451 SquidUpdate
::purge( array( $this->getURL() ) );
1454 # Hooks, hooks, the magic of hooks...
1455 Hooks
::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1457 # Invalidate cache for all pages using this file
1458 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1459 $update->doUpdate();
1461 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1468 * Move or copy a file to its public location. If a file exists at the
1469 * destination, move it to an archive. Returns a FileRepoStatus object with
1470 * 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 int $flags A bitwise combination of:
1477 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1478 * @param array $options Optional additional parameters
1479 * @return FileRepoStatus On success, the value member contains the
1480 * archive name, or an empty string if it was a new file.
1482 function publish( $srcPath, $flags = 0, array $options = array() ) {
1483 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1487 * Move or copy a file to a specified location. Returns a FileRepoStatus
1488 * object with the archive name in the "value" member on success.
1490 * The archive name should be passed through to recordUpload for database
1493 * @param string $srcPath Local filesystem path to the source image
1494 * @param string $dstRel Target relative path
1495 * @param int $flags A bitwise combination of:
1496 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1497 * @param array $options Optional additional parameters
1498 * @return FileRepoStatus On success, the value member contains the
1499 * archive name, or an empty string if it was a new file.
1501 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1502 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1503 return $this->readOnlyFatalStatus();
1506 $this->lock(); // begin
1508 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1509 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1510 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1511 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1513 if ( $status->value
== 'new' ) {
1514 $status->value
= '';
1516 $status->value
= $archiveName;
1519 $this->unlock(); // done
1524 /** getLinksTo inherited */
1525 /** getExifData inherited */
1526 /** isLocal inherited */
1527 /** wasDeleted inherited */
1530 * Move file to the new title
1532 * Move current, old version and all thumbnails
1533 * to the new filename. Old file is deleted.
1535 * Cache purging is done; checks for validity
1536 * and logging are caller's responsibility
1538 * @param Title $target New file name
1539 * @return FileRepoStatus
1541 function move( $target ) {
1542 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1543 return $this->readOnlyFatalStatus();
1546 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1547 $batch = new LocalFileMoveBatch( $this, $target );
1549 $this->lock(); // begin
1550 $batch->addCurrent();
1551 $archiveNames = $batch->addOlds();
1552 $status = $batch->execute();
1553 $this->unlock(); // done
1555 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1557 // Purge the source and target files...
1558 $oldTitleFile = wfLocalFile( $this->title
);
1559 $newTitleFile = wfLocalFile( $target );
1560 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1561 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1562 $this->getRepo()->getMasterDB()->onTransactionIdle(
1563 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1564 $oldTitleFile->purgeEverything();
1565 foreach ( $archiveNames as $archiveName ) {
1566 $oldTitleFile->purgeOldThumbnails( $archiveName );
1568 $newTitleFile->purgeEverything();
1572 if ( $status->isOK() ) {
1573 // Now switch the object
1574 $this->title
= $target;
1575 // Force regeneration of the name and hashpath
1576 unset( $this->name
);
1577 unset( $this->hashPath
);
1584 * Delete all versions of the file.
1586 * Moves the files into an archive directory (or deletes them)
1587 * and removes the database rows.
1589 * Cache purging is done; logging is caller's responsibility.
1591 * @param string $reason
1592 * @param bool $suppress
1593 * @param User|null $user
1594 * @return FileRepoStatus
1596 function delete( $reason, $suppress = false, $user = null ) {
1597 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1598 return $this->readOnlyFatalStatus();
1601 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1603 $this->lock(); // begin
1604 $batch->addCurrent();
1605 # Get old version relative paths
1606 $archiveNames = $batch->addOlds();
1607 $status = $batch->execute();
1608 $this->unlock(); // done
1610 if ( $status->isOK() ) {
1611 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1614 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1615 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1617 $this->getRepo()->getMasterDB()->onTransactionIdle(
1618 function () use ( $file, $archiveNames ) {
1621 $file->purgeEverything();
1622 foreach ( $archiveNames as $archiveName ) {
1623 $file->purgeOldThumbnails( $archiveName );
1626 if ( $wgUseSquid ) {
1628 $purgeUrls = array();
1629 foreach ( $archiveNames as $archiveName ) {
1630 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1632 SquidUpdate
::purge( $purgeUrls );
1641 * Delete an old version of the file.
1643 * Moves the file into an archive directory (or deletes it)
1644 * and removes the database row.
1646 * Cache purging is done; logging is caller's responsibility.
1648 * @param string $archiveName
1649 * @param string $reason
1650 * @param bool $suppress
1651 * @param User|null $user
1652 * @throws MWException Exception on database or file store failure
1653 * @return FileRepoStatus
1655 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1657 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1658 return $this->readOnlyFatalStatus();
1661 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1663 $this->lock(); // begin
1664 $batch->addOld( $archiveName );
1665 $status = $batch->execute();
1666 $this->unlock(); // done
1668 $this->purgeOldThumbnails( $archiveName );
1669 if ( $status->isOK() ) {
1670 $this->purgeDescription();
1671 $this->purgeHistory();
1674 if ( $wgUseSquid ) {
1676 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1683 * Restore all or specified deleted revisions to the given file.
1684 * Permissions and logging are left to the caller.
1686 * May throw database exceptions on error.
1688 * @param array $versions Set of record ids of deleted items to restore,
1689 * or empty to restore all revisions.
1690 * @param bool $unsuppress
1691 * @return FileRepoStatus
1693 function restore( $versions = array(), $unsuppress = false ) {
1694 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1695 return $this->readOnlyFatalStatus();
1698 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1700 $this->lock(); // begin
1704 $batch->addIds( $versions );
1706 $status = $batch->execute();
1707 if ( $status->isGood() ) {
1708 $cleanupStatus = $batch->cleanup();
1709 $cleanupStatus->successCount
= 0;
1710 $cleanupStatus->failCount
= 0;
1711 $status->merge( $cleanupStatus );
1713 $this->unlock(); // done
1718 /** isMultipage inherited */
1719 /** pageCount inherited */
1720 /** scaleHeight inherited */
1721 /** getImageSize inherited */
1724 * Get the URL of the file description page.
1727 function getDescriptionUrl() {
1728 return $this->title
->getLocalURL();
1732 * Get the HTML text of the description page
1733 * This is not used by ImagePage for local files, since (among other things)
1734 * it skips the parser cache.
1736 * @param Language $lang What language to get description in (Optional)
1737 * @return bool|mixed
1739 function getDescriptionText( $lang = null ) {
1740 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1744 $content = $revision->getContent();
1748 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1750 return $pout->getText();
1754 * @param int $audience
1758 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1760 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1762 } elseif ( $audience == self
::FOR_THIS_USER
1763 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1767 return $this->description
;
1772 * @return bool|string
1774 function getTimestamp() {
1777 return $this->timestamp
;
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 $this->markVolatile(); // file may change soon
1847 return $this->lockedOwnTrx
;
1851 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1852 * the transaction and thereby releases the image lock.
1855 if ( $this->locked
) {
1857 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1858 $dbw = $this->repo
->getMasterDB();
1859 $dbw->commit( __METHOD__
);
1860 $this->lockedOwnTrx
= false;
1866 * Mark a file as about to be changed
1868 * This sets a cache key that alters master/slave DB loading behavior
1870 * @return bool Success
1872 protected function markVolatile() {
1875 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1877 $this->lastMarkedVolatile
= time();
1878 return $wgMemc->set( $key, $this->lastMarkedVolatile
, self
::VOLATILE_TTL
);
1885 * Check if a file is about to be changed or has been changed recently
1887 * @see LocalFile::isVolatile()
1888 * @return bool Whether the file is volatile
1890 protected function isVolatile() {
1893 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1895 // repo unavailable; bail.
1899 if ( $this->lastMarkedVolatile
=== 0 ) {
1900 $this->lastMarkedVolatile
= $wgMemc->get( $key ) ?
: 0;
1903 $volatileDuration = time() - $this->lastMarkedVolatile
;
1904 return $volatileDuration <= self
::VOLATILE_TTL
;
1908 * Roll back the DB transaction and mark the image unlocked
1910 function unlockAndRollback() {
1911 $this->locked
= false;
1912 $dbw = $this->repo
->getMasterDB();
1913 $dbw->rollback( __METHOD__
);
1914 $this->lockedOwnTrx
= false;
1920 protected function readOnlyFatalStatus() {
1921 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1922 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1926 * Clean up any dangling locks
1928 function __destruct() {
1931 } // LocalFile class
1933 # ------------------------------------------------------------------------------
1936 * Helper class for file deletion
1937 * @ingroup FileAbstraction
1939 class LocalFileDeleteBatch
{
1940 /** @var LocalFile */
1947 private $srcRels = array();
1950 private $archiveUrls = array();
1952 /** @var array Items to be processed in the deletion batch */
1953 private $deletionBatch;
1955 /** @var bool Whether to suppress all suppressable fields when deleting */
1958 /** @var FileRepoStatus */
1966 * @param string $reason
1967 * @param bool $suppress
1968 * @param User|null $user
1970 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1971 $this->file
= $file;
1972 $this->reason
= $reason;
1973 $this->suppress
= $suppress;
1975 $this->user
= $user;
1978 $this->user
= $wgUser;
1980 $this->status
= $file->repo
->newGood();
1983 function addCurrent() {
1984 $this->srcRels
['.'] = $this->file
->getRel();
1988 * @param string $oldName
1990 function addOld( $oldName ) {
1991 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1992 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1996 * Add the old versions of the image to the batch
1997 * @return array List of archive names from old versions
1999 function addOlds() {
2000 $archiveNames = array();
2002 $dbw = $this->file
->repo
->getMasterDB();
2003 $result = $dbw->select( 'oldimage',
2004 array( 'oi_archive_name' ),
2005 array( 'oi_name' => $this->file
->getName() ),
2009 foreach ( $result as $row ) {
2010 $this->addOld( $row->oi_archive_name
);
2011 $archiveNames[] = $row->oi_archive_name
;
2014 return $archiveNames;
2020 function getOldRels() {
2021 if ( !isset( $this->srcRels
['.'] ) ) {
2022 $oldRels =& $this->srcRels
;
2023 $deleteCurrent = false;
2025 $oldRels = $this->srcRels
;
2026 unset( $oldRels['.'] );
2027 $deleteCurrent = true;
2030 return array( $oldRels, $deleteCurrent );
2036 protected function getHashes() {
2038 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2040 if ( $deleteCurrent ) {
2041 $hashes['.'] = $this->file
->getSha1();
2044 if ( count( $oldRels ) ) {
2045 $dbw = $this->file
->repo
->getMasterDB();
2046 $res = $dbw->select(
2048 array( 'oi_archive_name', 'oi_sha1' ),
2049 array( 'oi_archive_name' => array_keys( $oldRels ),
2050 'oi_name' => $this->file
->getName() ), // performance
2054 foreach ( $res as $row ) {
2055 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2056 // Get the hash from the file
2057 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2058 $props = $this->file
->repo
->getFileProps( $oldUrl );
2060 if ( $props['fileExists'] ) {
2061 // Upgrade the oldimage row
2062 $dbw->update( 'oldimage',
2063 array( 'oi_sha1' => $props['sha1'] ),
2064 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2066 $hashes[$row->oi_archive_name
] = $props['sha1'];
2068 $hashes[$row->oi_archive_name
] = false;
2071 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2076 $missing = array_diff_key( $this->srcRels
, $hashes );
2078 foreach ( $missing as $name => $rel ) {
2079 $this->status
->error( 'filedelete-old-unregistered', $name );
2082 foreach ( $hashes as $name => $hash ) {
2084 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2085 unset( $hashes[$name] );
2092 function doDBInserts() {
2093 $dbw = $this->file
->repo
->getMasterDB();
2094 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2095 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2096 $encReason = $dbw->addQuotes( $this->reason
);
2097 $encGroup = $dbw->addQuotes( 'deleted' );
2098 $ext = $this->file
->getExtension();
2099 $dotExt = $ext === '' ?
'' : ".$ext";
2100 $encExt = $dbw->addQuotes( $dotExt );
2101 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2103 // Bitfields to further suppress the content
2104 if ( $this->suppress
) {
2106 // This should be 15...
2107 $bitfield |
= Revision
::DELETED_TEXT
;
2108 $bitfield |
= Revision
::DELETED_COMMENT
;
2109 $bitfield |
= Revision
::DELETED_USER
;
2110 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2112 $bitfield = 'oi_deleted';
2115 if ( $deleteCurrent ) {
2116 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2117 $where = array( 'img_name' => $this->file
->getName() );
2118 $dbw->insertSelect( 'filearchive', 'image',
2120 'fa_storage_group' => $encGroup,
2121 'fa_storage_key' => $dbw->conditional(
2122 array( 'img_sha1' => '' ),
2123 $dbw->addQuotes( '' ),
2126 'fa_deleted_user' => $encUserId,
2127 'fa_deleted_timestamp' => $encTimestamp,
2128 'fa_deleted_reason' => $encReason,
2129 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2131 'fa_name' => 'img_name',
2132 'fa_archive_name' => 'NULL',
2133 'fa_size' => 'img_size',
2134 'fa_width' => 'img_width',
2135 'fa_height' => 'img_height',
2136 'fa_metadata' => 'img_metadata',
2137 'fa_bits' => 'img_bits',
2138 'fa_media_type' => 'img_media_type',
2139 'fa_major_mime' => 'img_major_mime',
2140 'fa_minor_mime' => 'img_minor_mime',
2141 'fa_description' => 'img_description',
2142 'fa_user' => 'img_user',
2143 'fa_user_text' => 'img_user_text',
2144 'fa_timestamp' => 'img_timestamp',
2145 'fa_sha1' => 'img_sha1',
2146 ), $where, __METHOD__
);
2149 if ( count( $oldRels ) ) {
2150 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2152 'oi_name' => $this->file
->getName(),
2153 'oi_archive_name' => array_keys( $oldRels ) );
2154 $dbw->insertSelect( 'filearchive', 'oldimage',
2156 'fa_storage_group' => $encGroup,
2157 'fa_storage_key' => $dbw->conditional(
2158 array( 'oi_sha1' => '' ),
2159 $dbw->addQuotes( '' ),
2162 'fa_deleted_user' => $encUserId,
2163 'fa_deleted_timestamp' => $encTimestamp,
2164 'fa_deleted_reason' => $encReason,
2165 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2167 'fa_name' => 'oi_name',
2168 'fa_archive_name' => 'oi_archive_name',
2169 'fa_size' => 'oi_size',
2170 'fa_width' => 'oi_width',
2171 'fa_height' => 'oi_height',
2172 'fa_metadata' => 'oi_metadata',
2173 'fa_bits' => 'oi_bits',
2174 'fa_media_type' => 'oi_media_type',
2175 'fa_major_mime' => 'oi_major_mime',
2176 'fa_minor_mime' => 'oi_minor_mime',
2177 'fa_description' => 'oi_description',
2178 'fa_user' => 'oi_user',
2179 'fa_user_text' => 'oi_user_text',
2180 'fa_timestamp' => 'oi_timestamp',
2181 'fa_sha1' => 'oi_sha1',
2182 ), $where, __METHOD__
);
2186 function doDBDeletes() {
2187 $dbw = $this->file
->repo
->getMasterDB();
2188 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2190 if ( count( $oldRels ) ) {
2191 $dbw->delete( 'oldimage',
2193 'oi_name' => $this->file
->getName(),
2194 'oi_archive_name' => array_keys( $oldRels )
2198 if ( $deleteCurrent ) {
2199 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2204 * Run the transaction
2205 * @return FileRepoStatus
2207 function execute() {
2209 $this->file
->lock();
2211 // Prepare deletion batch
2212 $hashes = $this->getHashes();
2213 $this->deletionBatch
= array();
2214 $ext = $this->file
->getExtension();
2215 $dotExt = $ext === '' ?
'' : ".$ext";
2217 foreach ( $this->srcRels
as $name => $srcRel ) {
2218 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2219 if ( isset( $hashes[$name] ) ) {
2220 $hash = $hashes[$name];
2221 $key = $hash . $dotExt;
2222 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2223 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2227 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2228 // We acquire this lock by running the inserts now, before the file operations.
2230 // This potentially has poor lock contention characteristics -- an alternative
2231 // scheme would be to insert stub filearchive entries with no fa_name and commit
2232 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2233 $this->doDBInserts();
2235 // Removes non-existent file from the batch, so we don't get errors.
2236 // This also handles files in the 'deleted' zone deleted via revision deletion.
2237 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2238 if ( !$checkStatus->isGood() ) {
2239 $this->status
->merge( $checkStatus );
2240 return $this->status
;
2242 $this->deletionBatch
= $checkStatus->value
;
2244 // Execute the file deletion batch
2245 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2247 if ( !$status->isGood() ) {
2248 $this->status
->merge( $status );
2251 if ( !$this->status
->isOK() ) {
2252 // Critical file deletion error
2253 // Roll back inserts, release lock and abort
2254 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2255 $this->file
->unlockAndRollback();
2257 return $this->status
;
2260 // Delete image/oldimage rows
2261 $this->doDBDeletes();
2263 // Commit and return
2264 $this->file
->unlock();
2266 return $this->status
;
2270 * Removes non-existent files from a deletion batch.
2271 * @param array $batch
2274 function removeNonexistentFiles( $batch ) {
2275 $files = $newBatch = array();
2277 foreach ( $batch as $batchItem ) {
2278 list( $src, ) = $batchItem;
2279 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2282 $result = $this->file
->repo
->fileExistsBatch( $files );
2283 if ( in_array( null, $result, true ) ) {
2284 return Status
::newFatal( 'backend-fail-internal',
2285 $this->file
->repo
->getBackend()->getName() );
2288 foreach ( $batch as $batchItem ) {
2289 if ( $result[$batchItem[0]] ) {
2290 $newBatch[] = $batchItem;
2294 return Status
::newGood( $newBatch );
2298 # ------------------------------------------------------------------------------
2301 * Helper class for file undeletion
2302 * @ingroup FileAbstraction
2304 class LocalFileRestoreBatch
{
2305 /** @var LocalFile */
2308 /** @var array List of file IDs to restore */
2309 private $cleanupBatch;
2311 /** @var array List of file IDs to restore */
2314 /** @var bool Add all revisions of the file */
2317 /** @var bool Whether to remove all settings for suppressed fields */
2318 private $unsuppress = false;
2322 * @param bool $unsuppress
2324 function __construct( File
$file, $unsuppress = false ) {
2325 $this->file
= $file;
2326 $this->cleanupBatch
= $this->ids
= array();
2327 $this->ids
= array();
2328 $this->unsuppress
= $unsuppress;
2335 function addId( $fa_id ) {
2336 $this->ids
[] = $fa_id;
2340 * Add a whole lot of files by ID
2343 function addIds( $ids ) {
2344 $this->ids
= array_merge( $this->ids
, $ids );
2348 * Add all revisions of the file
2355 * Run the transaction, except the cleanup batch.
2356 * The cleanup batch should be run in a separate transaction, because it locks different
2357 * rows and there's no need to keep the image row locked while it's acquiring those locks
2358 * The caller may have its own transaction open.
2359 * So we save the batch and let the caller call cleanup()
2360 * @return FileRepoStatus
2362 function execute() {
2365 if ( !$this->all
&& !$this->ids
) {
2367 return $this->file
->repo
->newGood();
2370 $lockOwnsTrx = $this->file
->lock();
2372 $dbw = $this->file
->repo
->getMasterDB();
2373 $status = $this->file
->repo
->newGood();
2375 $exists = (bool)$dbw->selectField( 'image', '1',
2376 array( 'img_name' => $this->file
->getName() ),
2378 // The lock() should already prevents changes, but this still may need
2379 // to bypass any transaction snapshot. However, if lock() started the
2380 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2381 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2384 // Fetch all or selected archived revisions for the file,
2385 // sorted from the most recent to the oldest.
2386 $conditions = array( 'fa_name' => $this->file
->getName() );
2388 if ( !$this->all
) {
2389 $conditions['fa_id'] = $this->ids
;
2392 $result = $dbw->select(
2394 ArchivedFile
::selectFields(),
2397 array( 'ORDER BY' => 'fa_timestamp DESC' )
2400 $idsPresent = array();
2401 $storeBatch = array();
2402 $insertBatch = array();
2403 $insertCurrent = false;
2404 $deleteIds = array();
2406 $archiveNames = array();
2408 foreach ( $result as $row ) {
2409 $idsPresent[] = $row->fa_id
;
2411 if ( $row->fa_name
!= $this->file
->getName() ) {
2412 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2413 $status->failCount++
;
2417 if ( $row->fa_storage_key
== '' ) {
2418 // Revision was missing pre-deletion
2419 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2420 $status->failCount++
;
2424 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2425 $row->fa_storage_key
;
2426 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2428 if ( isset( $row->fa_sha1
) ) {
2429 $sha1 = $row->fa_sha1
;
2431 // old row, populate from key
2432 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2436 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2437 $sha1 = substr( $sha1, 1 );
2440 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2441 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2442 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2443 ||
is_null( $row->fa_metadata
)
2445 // Refresh our metadata
2446 // Required for a new current revision; nice for older ones too. :)
2447 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2450 'minor_mime' => $row->fa_minor_mime
,
2451 'major_mime' => $row->fa_major_mime
,
2452 'media_type' => $row->fa_media_type
,
2453 'metadata' => $row->fa_metadata
2457 if ( $first && !$exists ) {
2458 // This revision will be published as the new current version
2459 $destRel = $this->file
->getRel();
2460 $insertCurrent = array(
2461 'img_name' => $row->fa_name
,
2462 'img_size' => $row->fa_size
,
2463 'img_width' => $row->fa_width
,
2464 'img_height' => $row->fa_height
,
2465 'img_metadata' => $props['metadata'],
2466 'img_bits' => $row->fa_bits
,
2467 'img_media_type' => $props['media_type'],
2468 'img_major_mime' => $props['major_mime'],
2469 'img_minor_mime' => $props['minor_mime'],
2470 'img_description' => $row->fa_description
,
2471 'img_user' => $row->fa_user
,
2472 'img_user_text' => $row->fa_user_text
,
2473 'img_timestamp' => $row->fa_timestamp
,
2477 // The live (current) version cannot be hidden!
2478 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2479 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2480 $this->cleanupBatch
[] = $row->fa_storage_key
;
2483 $archiveName = $row->fa_archive_name
;
2485 if ( $archiveName == '' ) {
2486 // This was originally a current version; we
2487 // have to devise a new archive name for it.
2488 // Format is <timestamp of archiving>!<name>
2489 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2492 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2494 } while ( isset( $archiveNames[$archiveName] ) );
2497 $archiveNames[$archiveName] = true;
2498 $destRel = $this->file
->getArchiveRel( $archiveName );
2499 $insertBatch[] = array(
2500 'oi_name' => $row->fa_name
,
2501 'oi_archive_name' => $archiveName,
2502 'oi_size' => $row->fa_size
,
2503 'oi_width' => $row->fa_width
,
2504 'oi_height' => $row->fa_height
,
2505 'oi_bits' => $row->fa_bits
,
2506 'oi_description' => $row->fa_description
,
2507 'oi_user' => $row->fa_user
,
2508 'oi_user_text' => $row->fa_user_text
,
2509 'oi_timestamp' => $row->fa_timestamp
,
2510 'oi_metadata' => $props['metadata'],
2511 'oi_media_type' => $props['media_type'],
2512 'oi_major_mime' => $props['major_mime'],
2513 'oi_minor_mime' => $props['minor_mime'],
2514 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2515 'oi_sha1' => $sha1 );
2518 $deleteIds[] = $row->fa_id
;
2520 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2521 // private files can stay where they are
2522 $status->successCount++
;
2524 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2525 $this->cleanupBatch
[] = $row->fa_storage_key
;
2533 // Add a warning to the status object for missing IDs
2534 $missingIds = array_diff( $this->ids
, $idsPresent );
2536 foreach ( $missingIds as $id ) {
2537 $status->error( 'undelete-missing-filearchive', $id );
2540 // Remove missing files from batch, so we don't get errors when undeleting them
2541 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2542 if ( !$checkStatus->isGood() ) {
2543 $status->merge( $checkStatus );
2546 $storeBatch = $checkStatus->value
;
2548 // Run the store batch
2549 // Use the OVERWRITE_SAME flag to smooth over a common error
2550 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2551 $status->merge( $storeStatus );
2553 if ( !$status->isGood() ) {
2554 // Even if some files could be copied, fail entirely as that is the
2555 // easiest thing to do without data loss
2556 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2557 $status->ok
= false;
2558 $this->file
->unlock();
2563 // Run the DB updates
2564 // Because we have locked the image row, key conflicts should be rare.
2565 // If they do occur, we can roll back the transaction at this time with
2566 // no data loss, but leaving unregistered files scattered throughout the
2568 // This is not ideal, which is why it's important to lock the image row.
2569 if ( $insertCurrent ) {
2570 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2573 if ( $insertBatch ) {
2574 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2578 $dbw->delete( 'filearchive',
2579 array( 'fa_id' => $deleteIds ),
2583 // If store batch is empty (all files are missing), deletion is to be considered successful
2584 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2586 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2588 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2590 $this->file
->purgeEverything();
2592 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2593 $this->file
->purgeDescription();
2594 $this->file
->purgeHistory();
2598 $this->file
->unlock();
2604 * Removes non-existent files from a store batch.
2605 * @param array $triplets
2608 function removeNonexistentFiles( $triplets ) {
2609 $files = $filteredTriplets = array();
2610 foreach ( $triplets as $file ) {
2611 $files[$file[0]] = $file[0];
2614 $result = $this->file
->repo
->fileExistsBatch( $files );
2615 if ( in_array( null, $result, true ) ) {
2616 return Status
::newFatal( 'backend-fail-internal',
2617 $this->file
->repo
->getBackend()->getName() );
2620 foreach ( $triplets as $file ) {
2621 if ( $result[$file[0]] ) {
2622 $filteredTriplets[] = $file;
2626 return Status
::newGood( $filteredTriplets );
2630 * Removes non-existent files from a cleanup batch.
2631 * @param array $batch
2634 function removeNonexistentFromCleanup( $batch ) {
2635 $files = $newBatch = array();
2636 $repo = $this->file
->repo
;
2638 foreach ( $batch as $file ) {
2639 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2640 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2643 $result = $repo->fileExistsBatch( $files );
2645 foreach ( $batch as $file ) {
2646 if ( $result[$file] ) {
2647 $newBatch[] = $file;
2655 * Delete unused files in the deleted zone.
2656 * This should be called from outside the transaction in which execute() was called.
2657 * @return FileRepoStatus
2659 function cleanup() {
2660 if ( !$this->cleanupBatch
) {
2661 return $this->file
->repo
->newGood();
2664 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2666 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2672 * Cleanup a failed batch. The batch was only partially successful, so
2673 * rollback by removing all items that were succesfully copied.
2675 * @param Status $storeStatus
2676 * @param array $storeBatch
2678 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2679 $cleanupBatch = array();
2681 foreach ( $storeStatus->success
as $i => $success ) {
2682 // Check if this item of the batch was successfully copied
2684 // Item was successfully copied and needs to be removed again
2685 // Extract ($dstZone, $dstRel) from the batch
2686 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2689 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2693 # ------------------------------------------------------------------------------
2696 * Helper class for file movement
2697 * @ingroup FileAbstraction
2699 class LocalFileMoveBatch
{
2700 /** @var LocalFile */
2710 protected $oldCount;
2714 /** @var DatabaseBase */
2719 * @param Title $target
2721 function __construct( File
$file, Title
$target ) {
2722 $this->file
= $file;
2723 $this->target
= $target;
2724 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2725 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2726 $this->oldName
= $this->file
->getName();
2727 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2728 $this->oldRel
= $this->oldHash
. $this->oldName
;
2729 $this->newRel
= $this->newHash
. $this->newName
;
2730 $this->db
= $file->getRepo()->getMasterDb();
2734 * Add the current image to the batch
2736 function addCurrent() {
2737 $this->cur
= array( $this->oldRel
, $this->newRel
);
2741 * Add the old versions of the image to the batch
2742 * @return array List of archive names from old versions
2744 function addOlds() {
2745 $archiveBase = 'archive';
2746 $this->olds
= array();
2747 $this->oldCount
= 0;
2748 $archiveNames = array();
2750 $result = $this->db
->select( 'oldimage',
2751 array( 'oi_archive_name', 'oi_deleted' ),
2752 array( 'oi_name' => $this->oldName
),
2754 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2757 foreach ( $result as $row ) {
2758 $archiveNames[] = $row->oi_archive_name
;
2759 $oldName = $row->oi_archive_name
;
2760 $bits = explode( '!', $oldName, 2 );
2762 if ( count( $bits ) != 2 ) {
2763 wfDebug( "Old file name missing !: '$oldName' \n" );
2767 list( $timestamp, $filename ) = $bits;
2769 if ( $this->oldName
!= $filename ) {
2770 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2776 // Do we want to add those to oldCount?
2777 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2781 $this->olds
[] = array(
2782 "{$archiveBase}/{$this->oldHash}{$oldName}",
2783 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2787 return $archiveNames;
2792 * @return FileRepoStatus
2794 function execute() {
2795 $repo = $this->file
->repo
;
2796 $status = $repo->newGood();
2798 $triplets = $this->getMoveTriplets();
2799 $checkStatus = $this->removeNonexistentFiles( $triplets );
2800 if ( !$checkStatus->isGood() ) {
2801 $status->merge( $checkStatus );
2804 $triplets = $checkStatus->value
;
2805 $destFile = wfLocalFile( $this->target
);
2807 $this->file
->lock(); // begin
2808 $destFile->lock(); // quickly fail if destination is not available
2809 // Rename the file versions metadata in the DB.
2810 // This implicitly locks the destination file, which avoids race conditions.
2811 // If we moved the files from A -> C before DB updates, another process could
2812 // move files from B -> C at this point, causing storeBatch() to fail and thus
2813 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2814 $statusDb = $this->doDBUpdates();
2815 if ( !$statusDb->isGood() ) {
2816 $destFile->unlock();
2817 $this->file
->unlockAndRollback();
2818 $statusDb->ok
= false;
2822 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2823 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2825 // Copy the files into their new location.
2826 // If a prior process fataled copying or cleaning up files we tolerate any
2827 // of the existing files if they are identical to the ones being stored.
2828 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2829 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2830 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2831 if ( !$statusMove->isGood() ) {
2832 // Delete any files copied over (while the destination is still locked)
2833 $this->cleanupTarget( $triplets );
2834 $destFile->unlock();
2835 $this->file
->unlockAndRollback(); // unlocks the destination
2836 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2837 $statusMove->ok
= false;
2841 $destFile->unlock();
2842 $this->file
->unlock(); // done
2844 // Everything went ok, remove the source files
2845 $this->cleanupSource( $triplets );
2847 $status->merge( $statusDb );
2848 $status->merge( $statusMove );
2854 * Do the database updates and return a new FileRepoStatus indicating how
2855 * many rows where updated.
2857 * @return FileRepoStatus
2859 function doDBUpdates() {
2860 $repo = $this->file
->repo
;
2861 $status = $repo->newGood();
2864 // Update current image
2867 array( 'img_name' => $this->newName
),
2868 array( 'img_name' => $this->oldName
),
2872 if ( $dbw->affectedRows() ) {
2873 $status->successCount++
;
2875 $status->failCount++
;
2876 $status->fatal( 'imageinvalidfilename' );
2881 // Update old images
2885 'oi_name' => $this->newName
,
2886 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2887 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2889 array( 'oi_name' => $this->oldName
),
2893 $affected = $dbw->affectedRows();
2894 $total = $this->oldCount
;
2895 $status->successCount +
= $affected;
2896 // Bug 34934: $total is based on files that actually exist.
2897 // There may be more DB rows than such files, in which case $affected
2898 // can be greater than $total. We use max() to avoid negatives here.
2899 $status->failCount +
= max( 0, $total - $affected );
2900 if ( $status->failCount
) {
2901 $status->error( 'imageinvalidfilename' );
2908 * Generate triplets for FileRepo::storeBatch().
2911 function getMoveTriplets() {
2912 $moves = array_merge( array( $this->cur
), $this->olds
);
2913 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2915 foreach ( $moves as $move ) {
2916 // $move: (oldRelativePath, newRelativePath)
2917 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2918 $triplets[] = array( $srcUrl, 'public', $move[1] );
2921 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2929 * Removes non-existent files from move batch.
2930 * @param array $triplets
2933 function removeNonexistentFiles( $triplets ) {
2936 foreach ( $triplets as $file ) {
2937 $files[$file[0]] = $file[0];
2940 $result = $this->file
->repo
->fileExistsBatch( $files );
2941 if ( in_array( null, $result, true ) ) {
2942 return Status
::newFatal( 'backend-fail-internal',
2943 $this->file
->repo
->getBackend()->getName() );
2946 $filteredTriplets = array();
2947 foreach ( $triplets as $file ) {
2948 if ( $result[$file[0]] ) {
2949 $filteredTriplets[] = $file;
2951 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2955 return Status
::newGood( $filteredTriplets );
2959 * Cleanup a partially moved array of triplets by deleting the target
2960 * files. Called if something went wrong half way.
2961 * @param array $triplets
2963 function cleanupTarget( $triplets ) {
2964 // Create dest pairs from the triplets
2966 foreach ( $triplets as $triplet ) {
2967 // $triplet: (old source virtual URL, dst zone, dest rel)
2968 $pairs[] = array( $triplet[1], $triplet[2] );
2971 $this->file
->repo
->cleanupBatch( $pairs );
2975 * Cleanup a fully moved array of triplets by deleting the source files.
2976 * Called at the end of the move process if everything else went ok.
2977 * @param array $triplets
2979 function cleanupSource( $triplets ) {
2980 // Create source file names from the triplets
2982 foreach ( $triplets as $triplet ) {
2983 $files[] = $triplet[0];
2986 $this->file
->repo
->cleanupBatch( $files );