3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 9 );
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const CACHE_FIELD_MAX_LEN
= 1000;
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
52 /** @var int Image width */
55 /** @var int Image height */
58 /** @var int Returned by getimagesize (loadFromXxx) */
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
67 /** @var int Size in bytes (loadFromXxx) */
70 /** @var string Handler-specific metadata */
73 /** @var string SHA-1 base 36 content hash */
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
82 /** @var int Bitfield akin to rev_deleted */
86 protected $repoClass = 'LocalRepo';
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
94 /** @var string Major MIME type */
97 /** @var string Minor MIME type */
100 /** @var string Upload timestamp */
103 /** @var int User ID of uploader */
106 /** @var string User name of uploader */
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var string TS_MW timestamp of the last change of the file description */
113 private $descriptionTouched;
115 /** @var bool Whether the row was upgraded on load */
118 /** @var bool True if the image row is locked */
121 /** @var bool True if the image row is locked with a lock initiated transaction */
122 private $lockedOwnTrx;
124 /** @var bool True if file is not present in file system. Not to be cached in memcached */
127 // @note: higher than IDBAccessObject constants
128 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
131 * Create a LocalFile from a title
132 * Do not call this except from inside a repo class.
134 * Note: $unused param is only here to avoid an E_STRICT
136 * @param Title $title
137 * @param FileRepo $repo
138 * @param null $unused
142 static function newFromTitle( $title, $repo, $unused = null ) {
143 return new self( $title, $repo );
147 * Create a LocalFile from a title
148 * Do not call this except from inside a repo class.
150 * @param stdClass $row
151 * @param FileRepo $repo
155 static function newFromRow( $row, $repo ) {
156 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
157 $file = new self( $title, $repo );
158 $file->loadFromRow( $row );
164 * Create a LocalFile from a SHA-1 key
165 * Do not call this except from inside a repo class.
167 * @param string $sha1 Base-36 SHA-1
168 * @param LocalRepo $repo
169 * @param string|bool $timestamp MW_timestamp (optional)
170 * @return bool|LocalFile
172 static function newFromKey( $sha1, $repo, $timestamp = false ) {
173 $dbr = $repo->getSlaveDB();
175 $conds = array( 'img_sha1' => $sha1 );
177 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
180 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
182 return self
::newFromRow( $row, $repo );
189 * Fields in the image table
192 static function selectFields() {
213 * Do not call this except from inside a repo class.
214 * @param Title $title
215 * @param FileRepo $repo
217 function __construct( $title, $repo ) {
218 parent
::__construct( $title, $repo );
220 $this->metadata
= '';
221 $this->historyLine
= 0;
222 $this->historyRes
= null;
223 $this->dataLoaded
= false;
224 $this->extraDataLoaded
= false;
226 $this->assertRepoDefined();
227 $this->assertTitleDefined();
231 * Get the memcached key for the main data for this file, or false if
232 * there is no access to the shared cache.
233 * @return string|bool
235 function getCacheKey() {
236 $hashedName = md5( $this->getName() );
238 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
242 * Try to load file metadata from memcached. Returns true on success.
245 function loadFromCache() {
246 $this->dataLoaded
= false;
247 $this->extraDataLoaded
= false;
248 $key = $this->getCacheKey();
254 $cache = ObjectCache
::getMainWANInstance();
255 $cachedValues = $cache->get( $key );
257 // Check if the key existed and belongs to this version of MediaWiki
258 if ( is_array( $cachedValues ) && $cachedValues['version'] == MW_FILE_VERSION
) {
259 wfDebug( "Pulling file metadata from cache key $key\n" );
260 $this->fileExists
= $cachedValues['fileExists'];
261 if ( $this->fileExists
) {
262 $this->setProps( $cachedValues );
264 $this->dataLoaded
= true;
265 $this->extraDataLoaded
= true;
266 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
267 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
271 if ( $this->dataLoaded
) {
272 wfIncrStats( 'image_cache.hit' );
274 wfIncrStats( 'image_cache.miss' );
277 return $this->dataLoaded
;
281 * Save the file metadata to memcached
283 function saveToCache() {
286 $key = $this->getCacheKey();
291 $fields = $this->getCacheFields( '' );
292 $cacheVal = array( 'version' => MW_FILE_VERSION
);
293 $cacheVal['fileExists'] = $this->fileExists
;
295 if ( $this->fileExists
) {
296 foreach ( $fields as $field ) {
297 $cacheVal[$field] = $this->$field;
301 // Strip off excessive entries from the subset of fields that can become large.
302 // If the cache value gets to large it will not fit in memcached and nothing will
303 // get cached at all, causing master queries for any file access.
304 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
305 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
306 unset( $cacheVal[$field] ); // don't let the value get too big
310 // Cache presence for 1 week and negatives for 1 day
311 $cache = ObjectCache
::getMainWANInstance();
312 $cache->set( $key, $cacheVal, $this->fileExists ?
86400 * 7 : 86400 );
316 * Purge the file object/metadata cache
318 function invalidateCache() {
319 $key = $this->getCacheKey();
324 ObjectCache
::getMainWANInstance()->delete( $key );
328 * Load metadata from the file itself
330 function loadFromFile() {
331 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
332 $this->setProps( $props );
336 * @param string $prefix
339 function getCacheFields( $prefix = 'img_' ) {
340 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
341 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
342 'user_text', 'description' );
343 static $results = array();
345 if ( $prefix == '' ) {
349 if ( !isset( $results[$prefix] ) ) {
350 $prefixedFields = array();
351 foreach ( $fields as $field ) {
352 $prefixedFields[] = $prefix . $field;
354 $results[$prefix] = $prefixedFields;
357 return $results[$prefix];
361 * @param string $prefix
364 function getLazyCacheFields( $prefix = 'img_' ) {
365 static $fields = array( 'metadata' );
366 static $results = array();
368 if ( $prefix == '' ) {
372 if ( !isset( $results[$prefix] ) ) {
373 $prefixedFields = array();
374 foreach ( $fields as $field ) {
375 $prefixedFields[] = $prefix . $field;
377 $results[$prefix] = $prefixedFields;
380 return $results[$prefix];
384 * Load file metadata from the DB
387 function loadFromDB( $flags = 0 ) {
388 $fname = get_class( $this ) . '::' . __FUNCTION__
;
390 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
391 $this->dataLoaded
= true;
392 $this->extraDataLoaded
= true;
394 $dbr = ( $flags & self
::READ_LATEST
)
395 ?
$this->repo
->getMasterDB()
396 : $this->repo
->getSlaveDB();
398 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
399 array( 'img_name' => $this->getName() ), $fname );
402 $this->loadFromRow( $row );
404 $this->fileExists
= false;
409 * Load lazy file metadata from the DB.
410 * This covers fields that are sometimes not cached.
412 protected function loadExtraFromDB() {
413 $fname = get_class( $this ) . '::' . __FUNCTION__
;
415 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
416 $this->extraDataLoaded
= true;
418 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
420 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
424 foreach ( $fieldMap as $name => $value ) {
425 $this->$name = $value;
428 throw new MWException( "Could not find data for image '{$this->getName()}'." );
433 * @param DatabaseBase $dbr
434 * @param string $fname
437 private function loadFieldsWithTimestamp( $dbr, $fname ) {
440 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
441 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
444 $fieldMap = $this->unprefixRow( $row, 'img_' );
446 # File may have been uploaded over in the meantime; check the old versions
447 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
448 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
451 $fieldMap = $this->unprefixRow( $row, 'oi_' );
459 * @param array $row Row
460 * @param string $prefix
461 * @throws MWException
464 protected function unprefixRow( $row, $prefix = 'img_' ) {
465 $array = (array)$row;
466 $prefixLength = strlen( $prefix );
468 // Sanity check prefix once
469 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
470 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
474 foreach ( $array as $name => $value ) {
475 $decoded[substr( $name, $prefixLength )] = $value;
482 * Decode a row from the database (either object or array) to an array
483 * with timestamps and MIME types decoded, and the field prefix removed.
485 * @param string $prefix
486 * @throws MWException
489 function decodeRow( $row, $prefix = 'img_' ) {
490 $decoded = $this->unprefixRow( $row, $prefix );
492 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
494 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
496 if ( empty( $decoded['major_mime'] ) ) {
497 $decoded['mime'] = 'unknown/unknown';
499 if ( !$decoded['minor_mime'] ) {
500 $decoded['minor_mime'] = 'unknown';
502 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
505 # Trim zero padding from char/binary field
506 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
512 * Load file metadata from a DB result row
515 * @param string $prefix
517 function loadFromRow( $row, $prefix = 'img_' ) {
518 $this->dataLoaded
= true;
519 $this->extraDataLoaded
= true;
521 $array = $this->decodeRow( $row, $prefix );
523 foreach ( $array as $name => $value ) {
524 $this->$name = $value;
527 $this->fileExists
= true;
528 $this->maybeUpgradeRow();
532 * Load file metadata from cache or DB, unless already loaded
535 function load( $flags = 0 ) {
536 if ( !$this->dataLoaded
) {
537 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
538 $this->loadFromDB( $flags );
539 $this->saveToCache();
541 $this->dataLoaded
= true;
543 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
544 // @note: loads on name/timestamp to reduce race condition problems
545 $this->loadExtraFromDB();
550 * Upgrade a row if it needs it
552 function maybeUpgradeRow() {
553 global $wgUpdateCompatibleMetadata;
554 if ( wfReadOnly() ) {
558 if ( is_null( $this->media_type
) ||
559 $this->mime
== 'image/svg'
562 $this->upgraded
= true;
564 $handler = $this->getHandler();
566 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
567 if ( $validity === MediaHandler
::METADATA_BAD
568 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
571 $this->upgraded
= true;
577 function getUpgraded() {
578 return $this->upgraded
;
582 * Fix assorted version-related problems with the image row by reloading it from the file
584 function upgradeRow() {
586 $this->lock(); // begin
588 $this->loadFromFile();
590 # Don't destroy file info of missing files
591 if ( !$this->fileExists
) {
593 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
598 $dbw = $this->repo
->getMasterDB();
599 list( $major, $minor ) = self
::splitMime( $this->mime
);
601 if ( wfReadOnly() ) {
606 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
608 $dbw->update( 'image',
610 'img_size' => $this->size
, // sanity
611 'img_width' => $this->width
,
612 'img_height' => $this->height
,
613 'img_bits' => $this->bits
,
614 'img_media_type' => $this->media_type
,
615 'img_major_mime' => $major,
616 'img_minor_mime' => $minor,
617 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
618 'img_sha1' => $this->sha1
,
620 array( 'img_name' => $this->getName() ),
624 $this->invalidateCache();
626 $this->unlock(); // done
631 * Set properties in this object to be equal to those given in the
632 * associative array $info. Only cacheable fields can be set.
633 * All fields *must* be set in $info except for getLazyCacheFields().
635 * If 'mime' is given, it will be split into major_mime/minor_mime.
636 * If major_mime/minor_mime are given, $this->mime will also be set.
640 function setProps( $info ) {
641 $this->dataLoaded
= true;
642 $fields = $this->getCacheFields( '' );
643 $fields[] = 'fileExists';
645 foreach ( $fields as $field ) {
646 if ( isset( $info[$field] ) ) {
647 $this->$field = $info[$field];
651 // Fix up mime fields
652 if ( isset( $info['major_mime'] ) ) {
653 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
654 } elseif ( isset( $info['mime'] ) ) {
655 $this->mime
= $info['mime'];
656 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
660 /** splitMime inherited */
661 /** getName inherited */
662 /** getTitle inherited */
663 /** getURL inherited */
664 /** getViewURL inherited */
665 /** getPath inherited */
666 /** isVisible inherited */
671 function isMissing() {
672 if ( $this->missing
=== null ) {
673 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
674 $this->missing
= !$fileExists;
677 return $this->missing
;
681 * Return the width of the image
686 public function getWidth( $page = 1 ) {
689 if ( $this->isMultipage() ) {
690 $handler = $this->getHandler();
694 $dim = $handler->getPageDimensions( $this, $page );
696 return $dim['width'];
698 // For non-paged media, the false goes through an
699 // intval, turning failure into 0, so do same here.
708 * Return the height of the image
713 public function getHeight( $page = 1 ) {
716 if ( $this->isMultipage() ) {
717 $handler = $this->getHandler();
721 $dim = $handler->getPageDimensions( $this, $page );
723 return $dim['height'];
725 // For non-paged media, the false goes through an
726 // intval, turning failure into 0, so do same here.
730 return $this->height
;
735 * Returns ID or name of user who uploaded the file
737 * @param string $type 'text' or 'id'
740 function getUser( $type = 'text' ) {
743 if ( $type == 'text' ) {
744 return $this->user_text
;
745 } elseif ( $type == 'id' ) {
746 return (int)$this->user
;
751 * Get handler-specific metadata
754 function getMetadata() {
755 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
756 return $this->metadata
;
762 function getBitDepth() {
765 return (int)$this->bits
;
769 * Returns the size of the image file, in bytes
772 public function getSize() {
779 * Returns the MIME type of the file.
782 function getMimeType() {
789 * Returns the type of the media in the file.
790 * Use the value returned by this function with the MEDIATYPE_xxx constants.
793 function getMediaType() {
796 return $this->media_type
;
799 /** canRender inherited */
800 /** mustRender inherited */
801 /** allowInlineDisplay inherited */
802 /** isSafeFile inherited */
803 /** isTrustedFile inherited */
806 * Returns true if the file exists on disk.
807 * @return bool Whether file exist on disk.
809 public function exists() {
812 return $this->fileExists
;
815 /** getTransformScript inherited */
816 /** getUnscaledThumb inherited */
817 /** thumbName inherited */
818 /** createThumb inherited */
819 /** transform inherited */
821 /** getHandler inherited */
822 /** iconThumb inherited */
823 /** getLastError inherited */
826 * Get all thumbnail names previously generated for this file
827 * @param string|bool $archiveName Name of an archive file, default false
828 * @return array First element is the base dir, then files in that base dir.
830 function getThumbnails( $archiveName = false ) {
831 if ( $archiveName ) {
832 $dir = $this->getArchiveThumbPath( $archiveName );
834 $dir = $this->getThumbPath();
837 $backend = $this->repo
->getBackend();
838 $files = array( $dir );
840 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
841 foreach ( $iterator as $file ) {
844 } catch ( FileBackendError
$e ) {
845 } // suppress (bug 54674)
851 * Refresh metadata in memcached, but don't touch thumbnails or squid
853 function purgeMetadataCache() {
854 $this->invalidateCache();
858 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
860 * @param array $options An array potentially with the key forThumbRefresh.
862 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
864 function purgeCache( $options = array() ) {
865 // Refresh metadata cache
866 $this->purgeMetadataCache();
869 $this->purgeThumbnails( $options );
871 // Purge squid cache for this file
872 SquidUpdate
::purge( array( $this->getURL() ) );
876 * Delete cached transformed files for an archived version only.
877 * @param string $archiveName Name of the archived file
879 function purgeOldThumbnails( $archiveName ) {
882 // Get a list of old thumbnails and URLs
883 $files = $this->getThumbnails( $archiveName );
885 // Purge any custom thumbnail caches
886 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
888 $dir = array_shift( $files );
889 $this->purgeThumbList( $dir, $files );
894 foreach ( $files as $file ) {
895 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
897 SquidUpdate
::purge( $urls );
903 * Delete cached transformed files for the current version only.
904 * @param array $options
906 function purgeThumbnails( $options = array() ) {
910 $files = $this->getThumbnails();
911 // Always purge all files from squid regardless of handler filters
914 foreach ( $files as $file ) {
915 $urls[] = $this->getThumbUrl( $file );
917 array_shift( $urls ); // don't purge directory
920 // Give media handler a chance to filter the file purge list
921 if ( !empty( $options['forThumbRefresh'] ) ) {
922 $handler = $this->getHandler();
924 $handler->filterThumbnailPurgeList( $files, $options );
928 // Purge any custom thumbnail caches
929 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
931 $dir = array_shift( $files );
932 $this->purgeThumbList( $dir, $files );
936 SquidUpdate
::purge( $urls );
942 * Delete a list of thumbnails visible at urls
943 * @param string $dir Base dir of the files.
944 * @param array $files Array of strings: relative filenames (to $dir)
946 protected function purgeThumbList( $dir, $files ) {
947 $fileListDebug = strtr(
948 var_export( $files, true ),
951 wfDebug( __METHOD__
. ": $fileListDebug\n" );
953 $purgeList = array();
954 foreach ( $files as $file ) {
955 # Check that the base file name is part of the thumb name
956 # This is a basic sanity check to avoid erasing unrelated directories
957 if ( strpos( $file, $this->getName() ) !== false
958 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
960 $purgeList[] = "{$dir}/{$file}";
964 # Delete the thumbnails
965 $this->repo
->quickPurgeBatch( $purgeList );
966 # Clear out the thumbnail directory if empty
967 $this->repo
->quickCleanDir( $dir );
970 /** purgeDescription inherited */
971 /** purgeEverything inherited */
974 * @param int $limit Optional: Limit to number of results
975 * @param int $start Optional: Timestamp, start from
976 * @param int $end Optional: Timestamp, end at
980 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
981 $dbr = $this->repo
->getSlaveDB();
982 $tables = array( 'oldimage' );
983 $fields = OldLocalFile
::selectFields();
984 $conds = $opts = $join_conds = array();
985 $eq = $inc ?
'=' : '';
986 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
989 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
993 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
997 $opts['LIMIT'] = $limit;
1000 // Search backwards for time > x queries
1001 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1002 $opts['ORDER BY'] = "oi_timestamp $order";
1003 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1005 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1006 &$conds, &$opts, &$join_conds ) );
1008 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1011 foreach ( $res as $row ) {
1012 $r[] = $this->repo
->newFileFromRow( $row );
1015 if ( $order == 'ASC' ) {
1016 $r = array_reverse( $r ); // make sure it ends up descending
1023 * Returns the history of this file, line by line.
1024 * starts with current version, then old versions.
1025 * uses $this->historyLine to check which line to return:
1026 * 0 return line for current version
1027 * 1 query for old versions, return first one
1028 * 2, ... return next old version from above query
1031 public function nextHistoryLine() {
1032 # Polymorphic function name to distinguish foreign and local fetches
1033 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1035 $dbr = $this->repo
->getSlaveDB();
1037 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1038 $this->historyRes
= $dbr->select( 'image',
1041 "'' AS oi_archive_name",
1045 array( 'img_name' => $this->title
->getDBkey() ),
1049 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1050 $this->historyRes
= null;
1054 } elseif ( $this->historyLine
== 1 ) {
1055 $this->historyRes
= $dbr->select( 'oldimage', '*',
1056 array( 'oi_name' => $this->title
->getDBkey() ),
1058 array( 'ORDER BY' => 'oi_timestamp DESC' )
1061 $this->historyLine++
;
1063 return $dbr->fetchObject( $this->historyRes
);
1067 * Reset the history pointer to the first element of the history
1069 public function resetHistory() {
1070 $this->historyLine
= 0;
1072 if ( !is_null( $this->historyRes
) ) {
1073 $this->historyRes
= null;
1077 /** getHashPath inherited */
1078 /** getRel inherited */
1079 /** getUrlRel inherited */
1080 /** getArchiveRel inherited */
1081 /** getArchivePath inherited */
1082 /** getThumbPath inherited */
1083 /** getArchiveUrl inherited */
1084 /** getThumbUrl inherited */
1085 /** getArchiveVirtualUrl inherited */
1086 /** getThumbVirtualUrl inherited */
1087 /** isHashed inherited */
1090 * Upload a file and record it in the DB
1091 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1092 * @param string $comment Upload description
1093 * @param string $pageText Text to use for the new description page,
1094 * if a new description page is created
1095 * @param int|bool $flags Flags for publish()
1096 * @param array|bool $props File properties, if known. This can be used to
1097 * reduce the upload time when uploading virtual URLs for which the file
1098 * info is already known
1099 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1101 * @param User|null $user User object or null to use $wgUser
1103 * @return FileRepoStatus On success, the value member contains the
1104 * archive name, or an empty string if it was a new file.
1106 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1107 $timestamp = false, $user = null
1111 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1112 return $this->readOnlyFatalStatus();
1116 if ( $this->repo
->isVirtualUrl( $srcPath )
1117 || FileBackend
::isStoragePath( $srcPath )
1119 $props = $this->repo
->getFileProps( $srcPath );
1121 $props = FSFile
::getPropsFromPath( $srcPath );
1126 $handler = MediaHandler
::getHandler( $props['mime'] );
1128 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1130 $options['headers'] = array();
1133 // Trim spaces on user supplied text
1134 $comment = trim( $comment );
1136 // Truncate nicely or the DB will do it for us
1137 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1138 $comment = $wgContLang->truncate( $comment, 255 );
1139 $this->lock(); // begin
1140 $status = $this->publish( $srcPath, $flags, $options );
1142 if ( $status->successCount
>= 2 ) {
1143 // There will be a copy+(one of move,copy,store).
1144 // The first succeeding does not commit us to updating the DB
1145 // since it simply copied the current version to a timestamped file name.
1146 // It is only *preferable* to avoid leaving such files orphaned.
1147 // Once the second operation goes through, then the current version was
1148 // updated and we must therefore update the DB too.
1149 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1150 $status->fatal( 'filenotfound', $srcPath );
1154 $this->unlock(); // done
1160 * Record a file upload in the upload log and the image table
1161 * @param string $oldver
1162 * @param string $desc
1163 * @param string $license
1164 * @param string $copyStatus
1165 * @param string $source
1166 * @param bool $watch
1167 * @param string|bool $timestamp
1168 * @param User|null $user User object or null to use $wgUser
1171 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1172 $watch = false, $timestamp = false, User
$user = null ) {
1178 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1180 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1185 $user->addWatch( $this->getTitle() );
1192 * Record a file upload in the upload log and the image table
1193 * @param string $oldver
1194 * @param string $comment
1195 * @param string $pageText
1196 * @param bool|array $props
1197 * @param string|bool $timestamp
1198 * @param null|User $user
1201 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1205 if ( is_null( $user ) ) {
1210 $dbw = $this->repo
->getMasterDB();
1211 $dbw->begin( __METHOD__
);
1214 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1217 # Imports or such might force a certain timestamp; otherwise we generate
1218 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1219 if ( $timestamp === false ) {
1220 $timestamp = $dbw->timestamp();
1221 $allowTimeKludge = true;
1223 $allowTimeKludge = false;
1226 $props['description'] = $comment;
1227 $props['user'] = $user->getId();
1228 $props['user_text'] = $user->getName();
1229 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1230 $this->setProps( $props );
1232 # Fail now if the file isn't there
1233 if ( !$this->fileExists
) {
1234 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1235 $dbw->rollback( __METHOD__
);
1242 # Test to see if the row exists using INSERT IGNORE
1243 # This avoids race conditions by locking the row until the commit, and also
1244 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1245 $dbw->insert( 'image',
1247 'img_name' => $this->getName(),
1248 'img_size' => $this->size
,
1249 'img_width' => intval( $this->width
),
1250 'img_height' => intval( $this->height
),
1251 'img_bits' => $this->bits
,
1252 'img_media_type' => $this->media_type
,
1253 'img_major_mime' => $this->major_mime
,
1254 'img_minor_mime' => $this->minor_mime
,
1255 'img_timestamp' => $timestamp,
1256 'img_description' => $comment,
1257 'img_user' => $user->getId(),
1258 'img_user_text' => $user->getName(),
1259 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1260 'img_sha1' => $this->sha1
1265 if ( $dbw->affectedRows() == 0 ) {
1266 if ( $allowTimeKludge ) {
1267 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1268 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1269 array( 'img_name' => $this->getName() ),
1271 array( 'LOCK IN SHARE MODE' ) );
1272 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1273 # Avoid a timestamp that is not newer than the last version
1274 # TODO: the image/oldimage tables should be like page/revision with an ID field
1275 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1276 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1277 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1278 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1282 # (bug 34993) Note: $oldver can be empty here, if the previous
1283 # version of the file was broken. Allow registration of the new
1284 # version to continue anyway, because that's better than having
1285 # an image that's not fixable by user operations.
1288 # Collision, this is an update of a file
1289 # Insert previous contents into oldimage
1290 $dbw->insertSelect( 'oldimage', 'image',
1292 'oi_name' => 'img_name',
1293 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1294 'oi_size' => 'img_size',
1295 'oi_width' => 'img_width',
1296 'oi_height' => 'img_height',
1297 'oi_bits' => 'img_bits',
1298 'oi_timestamp' => 'img_timestamp',
1299 'oi_description' => 'img_description',
1300 'oi_user' => 'img_user',
1301 'oi_user_text' => 'img_user_text',
1302 'oi_metadata' => 'img_metadata',
1303 'oi_media_type' => 'img_media_type',
1304 'oi_major_mime' => 'img_major_mime',
1305 'oi_minor_mime' => 'img_minor_mime',
1306 'oi_sha1' => 'img_sha1'
1308 array( 'img_name' => $this->getName() ),
1312 # Update the current image row
1313 $dbw->update( 'image',
1315 'img_size' => $this->size
,
1316 'img_width' => intval( $this->width
),
1317 'img_height' => intval( $this->height
),
1318 'img_bits' => $this->bits
,
1319 'img_media_type' => $this->media_type
,
1320 'img_major_mime' => $this->major_mime
,
1321 'img_minor_mime' => $this->minor_mime
,
1322 'img_timestamp' => $timestamp,
1323 'img_description' => $comment,
1324 'img_user' => $user->getId(),
1325 'img_user_text' => $user->getName(),
1326 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1327 'img_sha1' => $this->sha1
1329 array( 'img_name' => $this->getName() ),
1333 # This is a new file, so update the image count
1334 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1337 $descTitle = $this->getTitle();
1338 $wikiPage = new WikiFilePage( $descTitle );
1339 $wikiPage->setFile( $this );
1342 $action = $reupload ?
'overwrite' : 'upload';
1344 $logEntry = new ManualLogEntry( 'upload', $action );
1345 $logEntry->setPerformer( $user );
1346 $logEntry->setComment( $comment );
1347 $logEntry->setTarget( $descTitle );
1349 // Allow people using the api to associate log entries with the upload.
1350 // Log has a timestamp, but sometimes different from upload timestamp.
1351 $logEntry->setParameters(
1353 'img_sha1' => $this->sha1
,
1354 'img_timestamp' => $timestamp,
1357 // Note we keep $logId around since during new image
1358 // creation, page doesn't exist yet, so log_page = 0
1359 // but we want it to point to the page we're making,
1360 // so we later modify the log entry.
1361 // For a similar reason, we avoid making an RC entry
1362 // now and wait until the page exists.
1363 $logId = $logEntry->insert();
1365 $exists = $descTitle->exists();
1367 // Page exists, do RC entry now (otherwise we wait for later).
1368 $logEntry->publish( $logId );
1372 # Create a null revision
1373 $latest = $descTitle->getLatestRevID();
1374 // Use own context to get the action text in content language
1375 $formatter = LogFormatter
::newFromEntry( $logEntry );
1376 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1377 $editSummary = $formatter->getPlainActionText();
1379 $nullRevision = Revision
::newNullRevision(
1381 $descTitle->getArticleID(),
1386 if ( !is_null( $nullRevision ) ) {
1387 $nullRevision->insertOn( $dbw );
1389 Hooks
::run( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1390 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1394 # Commit the transaction now, in case something goes wrong later
1395 # The most important thing is that files don't get lost, especially archives
1396 # NOTE: once we have support for nested transactions, the commit may be moved
1397 # to after $wikiPage->doEdit has been called.
1398 $dbw->commit( __METHOD__
);
1400 # Update memcache after the commit
1401 $this->invalidateCache();
1404 # Invalidate the cache for the description page
1405 $descTitle->invalidateCache();
1406 $descTitle->purgeSquid();
1408 # New file; create the description page.
1409 # There's already a log entry, so don't make a second RC entry
1410 # Squid and file cache for the description page are purged by doEditContent.
1411 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1412 $status = $wikiPage->doEditContent(
1415 EDIT_NEW | EDIT_SUPPRESS_RC
,
1420 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1421 // Now that the page exists, make an RC entry.
1422 $logEntry->publish( $logId );
1423 if ( isset( $status->value
['revision'] ) ) {
1424 $dbw->update( 'logging',
1425 array( 'log_page' => $status->value
['revision']->getPage() ),
1426 array( 'log_id' => $logId ),
1430 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1434 # Delete old thumbnails
1435 $this->purgeThumbnails();
1437 # Remove the old file from the squid cache
1438 SquidUpdate
::purge( array( $this->getURL() ) );
1441 # Hooks, hooks, the magic of hooks...
1442 Hooks
::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1444 # Invalidate cache for all pages using this file
1445 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1446 $update->doUpdate();
1448 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1455 * Move or copy a file to its public location. If a file exists at the
1456 * destination, move it to an archive. Returns a FileRepoStatus object with
1457 * the archive name in the "value" member on success.
1459 * The archive name should be passed through to recordUpload for database
1462 * @param string $srcPath Local filesystem path to the source image
1463 * @param int $flags A bitwise combination of:
1464 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1465 * @param array $options Optional additional parameters
1466 * @return FileRepoStatus On success, the value member contains the
1467 * archive name, or an empty string if it was a new file.
1469 function publish( $srcPath, $flags = 0, array $options = array() ) {
1470 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1474 * Move or copy a file to a specified location. Returns a FileRepoStatus
1475 * object with the archive name in the "value" member on success.
1477 * The archive name should be passed through to recordUpload for database
1480 * @param string $srcPath Local filesystem path to the source image
1481 * @param string $dstRel Target relative path
1482 * @param int $flags A bitwise combination of:
1483 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1484 * @param array $options Optional additional parameters
1485 * @return FileRepoStatus On success, the value member contains the
1486 * archive name, or an empty string if it was a new file.
1488 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1489 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1490 return $this->readOnlyFatalStatus();
1493 $this->lock(); // begin
1495 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1496 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1497 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1498 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1500 if ( $status->value
== 'new' ) {
1501 $status->value
= '';
1503 $status->value
= $archiveName;
1506 $this->unlock(); // done
1511 /** getLinksTo inherited */
1512 /** getExifData inherited */
1513 /** isLocal inherited */
1514 /** wasDeleted inherited */
1517 * Move file to the new title
1519 * Move current, old version and all thumbnails
1520 * to the new filename. Old file is deleted.
1522 * Cache purging is done; checks for validity
1523 * and logging are caller's responsibility
1525 * @param Title $target New file name
1526 * @return FileRepoStatus
1528 function move( $target ) {
1529 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1530 return $this->readOnlyFatalStatus();
1533 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1534 $batch = new LocalFileMoveBatch( $this, $target );
1536 $this->lock(); // begin
1537 $batch->addCurrent();
1538 $archiveNames = $batch->addOlds();
1539 $status = $batch->execute();
1540 $this->unlock(); // done
1542 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1544 // Purge the source and target files...
1545 $oldTitleFile = wfLocalFile( $this->title
);
1546 $newTitleFile = wfLocalFile( $target );
1547 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1548 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1549 $this->getRepo()->getMasterDB()->onTransactionIdle(
1550 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1551 $oldTitleFile->purgeEverything();
1552 foreach ( $archiveNames as $archiveName ) {
1553 $oldTitleFile->purgeOldThumbnails( $archiveName );
1555 $newTitleFile->purgeEverything();
1559 if ( $status->isOK() ) {
1560 // Now switch the object
1561 $this->title
= $target;
1562 // Force regeneration of the name and hashpath
1563 unset( $this->name
);
1564 unset( $this->hashPath
);
1571 * Delete all versions of the file.
1573 * Moves the files into an archive directory (or deletes them)
1574 * and removes the database rows.
1576 * Cache purging is done; logging is caller's responsibility.
1578 * @param string $reason
1579 * @param bool $suppress
1580 * @param User|null $user
1581 * @return FileRepoStatus
1583 function delete( $reason, $suppress = false, $user = null ) {
1584 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1585 return $this->readOnlyFatalStatus();
1588 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1590 $this->lock(); // begin
1591 $batch->addCurrent();
1592 # Get old version relative paths
1593 $archiveNames = $batch->addOlds();
1594 $status = $batch->execute();
1595 $this->unlock(); // done
1597 if ( $status->isOK() ) {
1598 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1601 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1602 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1604 $this->getRepo()->getMasterDB()->onTransactionIdle(
1605 function () use ( $that, $archiveNames ) {
1608 $that->purgeEverything();
1609 foreach ( $archiveNames as $archiveName ) {
1610 $that->purgeOldThumbnails( $archiveName );
1613 if ( $wgUseSquid ) {
1615 $purgeUrls = array();
1616 foreach ( $archiveNames as $archiveName ) {
1617 $purgeUrls[] = $that->getArchiveUrl( $archiveName );
1619 SquidUpdate
::purge( $purgeUrls );
1628 * Delete an old version of the file.
1630 * Moves the file into an archive directory (or deletes it)
1631 * and removes the database row.
1633 * Cache purging is done; logging is caller's responsibility.
1635 * @param string $archiveName
1636 * @param string $reason
1637 * @param bool $suppress
1638 * @param User|null $user
1639 * @throws MWException Exception on database or file store failure
1640 * @return FileRepoStatus
1642 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1644 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1645 return $this->readOnlyFatalStatus();
1648 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1650 $this->lock(); // begin
1651 $batch->addOld( $archiveName );
1652 $status = $batch->execute();
1653 $this->unlock(); // done
1655 $this->purgeOldThumbnails( $archiveName );
1656 if ( $status->isOK() ) {
1657 $this->purgeDescription();
1660 if ( $wgUseSquid ) {
1662 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1669 * Restore all or specified deleted revisions to the given file.
1670 * Permissions and logging are left to the caller.
1672 * May throw database exceptions on error.
1674 * @param array $versions Set of record ids of deleted items to restore,
1675 * or empty to restore all revisions.
1676 * @param bool $unsuppress
1677 * @return FileRepoStatus
1679 function restore( $versions = array(), $unsuppress = false ) {
1680 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1681 return $this->readOnlyFatalStatus();
1684 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1686 $this->lock(); // begin
1690 $batch->addIds( $versions );
1692 $status = $batch->execute();
1693 if ( $status->isGood() ) {
1694 $cleanupStatus = $batch->cleanup();
1695 $cleanupStatus->successCount
= 0;
1696 $cleanupStatus->failCount
= 0;
1697 $status->merge( $cleanupStatus );
1699 $this->unlock(); // done
1704 /** isMultipage inherited */
1705 /** pageCount inherited */
1706 /** scaleHeight inherited */
1707 /** getImageSize inherited */
1710 * Get the URL of the file description page.
1713 function getDescriptionUrl() {
1714 return $this->title
->getLocalURL();
1718 * Get the HTML text of the description page
1719 * This is not used by ImagePage for local files, since (among other things)
1720 * it skips the parser cache.
1722 * @param Language $lang What language to get description in (Optional)
1723 * @return bool|mixed
1725 function getDescriptionText( $lang = null ) {
1726 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1730 $content = $revision->getContent();
1734 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1736 return $pout->getText();
1740 * @param int $audience
1744 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1746 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1748 } elseif ( $audience == self
::FOR_THIS_USER
1749 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1753 return $this->description
;
1758 * @return bool|string
1760 function getTimestamp() {
1763 return $this->timestamp
;
1767 * @return bool|string
1769 public function getDescriptionTouched() {
1770 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1771 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1772 // need to differentiate between null (uninitialized) and false (failed to load).
1773 if ( $this->descriptionTouched
=== null ) {
1775 'page_namespace' => $this->title
->getNamespace(),
1776 'page_title' => $this->title
->getDBkey()
1778 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1779 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1782 return $this->descriptionTouched
;
1788 function getSha1() {
1790 // Initialise now if necessary
1791 if ( $this->sha1
== '' && $this->fileExists
) {
1792 $this->lock(); // begin
1794 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1795 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1796 $dbw = $this->repo
->getMasterDB();
1797 $dbw->update( 'image',
1798 array( 'img_sha1' => $this->sha1
),
1799 array( 'img_name' => $this->getName() ),
1801 $this->invalidateCache();
1804 $this->unlock(); // done
1811 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1813 function isCacheable() {
1816 // If extra data (metadata) was not loaded then it must have been large
1817 return $this->extraDataLoaded
1818 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1822 * Start a transaction and lock the image for update
1823 * Increments a reference counter if the lock is already held
1824 * @throws MWException Throws an error if the lock was not acquired
1825 * @return bool Whether the file lock owns/spawned the DB transaction
1828 $dbw = $this->repo
->getMasterDB();
1830 if ( !$this->locked
) {
1831 if ( !$dbw->trxLevel() ) {
1832 $dbw->begin( __METHOD__
);
1833 $this->lockedOwnTrx
= true;
1836 // Bug 54736: use simple lock to handle when the file does not exist.
1837 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1838 // Also, that would cause contention on INSERT of similarly named rows.
1839 $backend = $this->getRepo()->getBackend();
1840 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1841 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1842 if ( !$status->isGood() ) {
1843 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1845 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1846 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1850 return $this->lockedOwnTrx
;
1854 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1855 * the transaction and thereby releases the image lock.
1858 if ( $this->locked
) {
1860 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1861 $dbw = $this->repo
->getMasterDB();
1862 $dbw->commit( __METHOD__
);
1863 $this->lockedOwnTrx
= false;
1869 * Roll back the DB transaction and mark the image unlocked
1871 function unlockAndRollback() {
1872 $this->locked
= false;
1873 $dbw = $this->repo
->getMasterDB();
1874 $dbw->rollback( __METHOD__
);
1875 $this->lockedOwnTrx
= false;
1881 protected function readOnlyFatalStatus() {
1882 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1883 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1887 * Clean up any dangling locks
1889 function __destruct() {
1892 } // LocalFile class
1894 # ------------------------------------------------------------------------------
1897 * Helper class for file deletion
1898 * @ingroup FileAbstraction
1900 class LocalFileDeleteBatch
{
1901 /** @var LocalFile */
1908 private $srcRels = array();
1911 private $archiveUrls = array();
1913 /** @var array Items to be processed in the deletion batch */
1914 private $deletionBatch;
1916 /** @var bool Whether to suppress all suppressable fields when deleting */
1919 /** @var FileRepoStatus */
1927 * @param string $reason
1928 * @param bool $suppress
1929 * @param User|null $user
1931 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1932 $this->file
= $file;
1933 $this->reason
= $reason;
1934 $this->suppress
= $suppress;
1936 $this->user
= $user;
1939 $this->user
= $wgUser;
1941 $this->status
= $file->repo
->newGood();
1944 function addCurrent() {
1945 $this->srcRels
['.'] = $this->file
->getRel();
1949 * @param string $oldName
1951 function addOld( $oldName ) {
1952 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1953 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1957 * Add the old versions of the image to the batch
1958 * @return array List of archive names from old versions
1960 function addOlds() {
1961 $archiveNames = array();
1963 $dbw = $this->file
->repo
->getMasterDB();
1964 $result = $dbw->select( 'oldimage',
1965 array( 'oi_archive_name' ),
1966 array( 'oi_name' => $this->file
->getName() ),
1970 foreach ( $result as $row ) {
1971 $this->addOld( $row->oi_archive_name
);
1972 $archiveNames[] = $row->oi_archive_name
;
1975 return $archiveNames;
1981 function getOldRels() {
1982 if ( !isset( $this->srcRels
['.'] ) ) {
1983 $oldRels =& $this->srcRels
;
1984 $deleteCurrent = false;
1986 $oldRels = $this->srcRels
;
1987 unset( $oldRels['.'] );
1988 $deleteCurrent = true;
1991 return array( $oldRels, $deleteCurrent );
1997 protected function getHashes() {
1999 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2001 if ( $deleteCurrent ) {
2002 $hashes['.'] = $this->file
->getSha1();
2005 if ( count( $oldRels ) ) {
2006 $dbw = $this->file
->repo
->getMasterDB();
2007 $res = $dbw->select(
2009 array( 'oi_archive_name', 'oi_sha1' ),
2010 array( 'oi_archive_name' => array_keys( $oldRels ),
2011 'oi_name' => $this->file
->getName() ), // performance
2015 foreach ( $res as $row ) {
2016 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2017 // Get the hash from the file
2018 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2019 $props = $this->file
->repo
->getFileProps( $oldUrl );
2021 if ( $props['fileExists'] ) {
2022 // Upgrade the oldimage row
2023 $dbw->update( 'oldimage',
2024 array( 'oi_sha1' => $props['sha1'] ),
2025 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2027 $hashes[$row->oi_archive_name
] = $props['sha1'];
2029 $hashes[$row->oi_archive_name
] = false;
2032 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2037 $missing = array_diff_key( $this->srcRels
, $hashes );
2039 foreach ( $missing as $name => $rel ) {
2040 $this->status
->error( 'filedelete-old-unregistered', $name );
2043 foreach ( $hashes as $name => $hash ) {
2045 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2046 unset( $hashes[$name] );
2053 function doDBInserts() {
2054 $dbw = $this->file
->repo
->getMasterDB();
2055 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2056 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2057 $encReason = $dbw->addQuotes( $this->reason
);
2058 $encGroup = $dbw->addQuotes( 'deleted' );
2059 $ext = $this->file
->getExtension();
2060 $dotExt = $ext === '' ?
'' : ".$ext";
2061 $encExt = $dbw->addQuotes( $dotExt );
2062 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2064 // Bitfields to further suppress the content
2065 if ( $this->suppress
) {
2067 // This should be 15...
2068 $bitfield |
= Revision
::DELETED_TEXT
;
2069 $bitfield |
= Revision
::DELETED_COMMENT
;
2070 $bitfield |
= Revision
::DELETED_USER
;
2071 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2073 $bitfield = 'oi_deleted';
2076 if ( $deleteCurrent ) {
2077 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2078 $where = array( 'img_name' => $this->file
->getName() );
2079 $dbw->insertSelect( 'filearchive', 'image',
2081 'fa_storage_group' => $encGroup,
2082 'fa_storage_key' => $dbw->conditional(
2083 array( 'img_sha1' => '' ),
2084 $dbw->addQuotes( '' ),
2087 'fa_deleted_user' => $encUserId,
2088 'fa_deleted_timestamp' => $encTimestamp,
2089 'fa_deleted_reason' => $encReason,
2090 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2092 'fa_name' => 'img_name',
2093 'fa_archive_name' => 'NULL',
2094 'fa_size' => 'img_size',
2095 'fa_width' => 'img_width',
2096 'fa_height' => 'img_height',
2097 'fa_metadata' => 'img_metadata',
2098 'fa_bits' => 'img_bits',
2099 'fa_media_type' => 'img_media_type',
2100 'fa_major_mime' => 'img_major_mime',
2101 'fa_minor_mime' => 'img_minor_mime',
2102 'fa_description' => 'img_description',
2103 'fa_user' => 'img_user',
2104 'fa_user_text' => 'img_user_text',
2105 'fa_timestamp' => 'img_timestamp',
2106 'fa_sha1' => 'img_sha1',
2107 ), $where, __METHOD__
);
2110 if ( count( $oldRels ) ) {
2111 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2113 'oi_name' => $this->file
->getName(),
2114 'oi_archive_name' => array_keys( $oldRels ) );
2115 $dbw->insertSelect( 'filearchive', 'oldimage',
2117 'fa_storage_group' => $encGroup,
2118 'fa_storage_key' => $dbw->conditional(
2119 array( 'oi_sha1' => '' ),
2120 $dbw->addQuotes( '' ),
2123 'fa_deleted_user' => $encUserId,
2124 'fa_deleted_timestamp' => $encTimestamp,
2125 'fa_deleted_reason' => $encReason,
2126 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2128 'fa_name' => 'oi_name',
2129 'fa_archive_name' => 'oi_archive_name',
2130 'fa_size' => 'oi_size',
2131 'fa_width' => 'oi_width',
2132 'fa_height' => 'oi_height',
2133 'fa_metadata' => 'oi_metadata',
2134 'fa_bits' => 'oi_bits',
2135 'fa_media_type' => 'oi_media_type',
2136 'fa_major_mime' => 'oi_major_mime',
2137 'fa_minor_mime' => 'oi_minor_mime',
2138 'fa_description' => 'oi_description',
2139 'fa_user' => 'oi_user',
2140 'fa_user_text' => 'oi_user_text',
2141 'fa_timestamp' => 'oi_timestamp',
2142 'fa_sha1' => 'oi_sha1',
2143 ), $where, __METHOD__
);
2147 function doDBDeletes() {
2148 $dbw = $this->file
->repo
->getMasterDB();
2149 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2151 if ( count( $oldRels ) ) {
2152 $dbw->delete( 'oldimage',
2154 'oi_name' => $this->file
->getName(),
2155 'oi_archive_name' => array_keys( $oldRels )
2159 if ( $deleteCurrent ) {
2160 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2165 * Run the transaction
2166 * @return FileRepoStatus
2168 function execute() {
2170 $this->file
->lock();
2172 // Prepare deletion batch
2173 $hashes = $this->getHashes();
2174 $this->deletionBatch
= array();
2175 $ext = $this->file
->getExtension();
2176 $dotExt = $ext === '' ?
'' : ".$ext";
2178 foreach ( $this->srcRels
as $name => $srcRel ) {
2179 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2180 if ( isset( $hashes[$name] ) ) {
2181 $hash = $hashes[$name];
2182 $key = $hash . $dotExt;
2183 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2184 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2188 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2189 // We acquire this lock by running the inserts now, before the file operations.
2191 // This potentially has poor lock contention characteristics -- an alternative
2192 // scheme would be to insert stub filearchive entries with no fa_name and commit
2193 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2194 $this->doDBInserts();
2196 // Removes non-existent file from the batch, so we don't get errors.
2197 // This also handles files in the 'deleted' zone deleted via revision deletion.
2198 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2199 if ( !$checkStatus->isGood() ) {
2200 $this->status
->merge( $checkStatus );
2201 return $this->status
;
2203 $this->deletionBatch
= $checkStatus->value
;
2205 // Execute the file deletion batch
2206 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2208 if ( !$status->isGood() ) {
2209 $this->status
->merge( $status );
2212 if ( !$this->status
->isOK() ) {
2213 // Critical file deletion error
2214 // Roll back inserts, release lock and abort
2215 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2216 $this->file
->unlockAndRollback();
2218 return $this->status
;
2221 // Delete image/oldimage rows
2222 $this->doDBDeletes();
2224 // Commit and return
2225 $this->file
->unlock();
2227 return $this->status
;
2231 * Removes non-existent files from a deletion batch.
2232 * @param array $batch
2235 function removeNonexistentFiles( $batch ) {
2236 $files = $newBatch = array();
2238 foreach ( $batch as $batchItem ) {
2239 list( $src, ) = $batchItem;
2240 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2243 $result = $this->file
->repo
->fileExistsBatch( $files );
2244 if ( in_array( null, $result, true ) ) {
2245 return Status
::newFatal( 'backend-fail-internal',
2246 $this->file
->repo
->getBackend()->getName() );
2249 foreach ( $batch as $batchItem ) {
2250 if ( $result[$batchItem[0]] ) {
2251 $newBatch[] = $batchItem;
2255 return Status
::newGood( $newBatch );
2259 # ------------------------------------------------------------------------------
2262 * Helper class for file undeletion
2263 * @ingroup FileAbstraction
2265 class LocalFileRestoreBatch
{
2266 /** @var LocalFile */
2269 /** @var array List of file IDs to restore */
2270 private $cleanupBatch;
2272 /** @var array List of file IDs to restore */
2275 /** @var bool Add all revisions of the file */
2278 /** @var bool Whether to remove all settings for suppressed fields */
2279 private $unsuppress = false;
2283 * @param bool $unsuppress
2285 function __construct( File
$file, $unsuppress = false ) {
2286 $this->file
= $file;
2287 $this->cleanupBatch
= $this->ids
= array();
2288 $this->ids
= array();
2289 $this->unsuppress
= $unsuppress;
2296 function addId( $fa_id ) {
2297 $this->ids
[] = $fa_id;
2301 * Add a whole lot of files by ID
2304 function addIds( $ids ) {
2305 $this->ids
= array_merge( $this->ids
, $ids );
2309 * Add all revisions of the file
2316 * Run the transaction, except the cleanup batch.
2317 * The cleanup batch should be run in a separate transaction, because it locks different
2318 * rows and there's no need to keep the image row locked while it's acquiring those locks
2319 * The caller may have its own transaction open.
2320 * So we save the batch and let the caller call cleanup()
2321 * @return FileRepoStatus
2323 function execute() {
2326 if ( !$this->all
&& !$this->ids
) {
2328 return $this->file
->repo
->newGood();
2331 $lockOwnsTrx = $this->file
->lock();
2333 $dbw = $this->file
->repo
->getMasterDB();
2334 $status = $this->file
->repo
->newGood();
2336 $exists = (bool)$dbw->selectField( 'image', '1',
2337 array( 'img_name' => $this->file
->getName() ),
2339 // The lock() should already prevents changes, but this still may need
2340 // to bypass any transaction snapshot. However, if lock() started the
2341 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2342 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2345 // Fetch all or selected archived revisions for the file,
2346 // sorted from the most recent to the oldest.
2347 $conditions = array( 'fa_name' => $this->file
->getName() );
2349 if ( !$this->all
) {
2350 $conditions['fa_id'] = $this->ids
;
2353 $result = $dbw->select(
2355 ArchivedFile
::selectFields(),
2358 array( 'ORDER BY' => 'fa_timestamp DESC' )
2361 $idsPresent = array();
2362 $storeBatch = array();
2363 $insertBatch = array();
2364 $insertCurrent = false;
2365 $deleteIds = array();
2367 $archiveNames = array();
2369 foreach ( $result as $row ) {
2370 $idsPresent[] = $row->fa_id
;
2372 if ( $row->fa_name
!= $this->file
->getName() ) {
2373 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2374 $status->failCount++
;
2378 if ( $row->fa_storage_key
== '' ) {
2379 // Revision was missing pre-deletion
2380 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2381 $status->failCount++
;
2385 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2386 $row->fa_storage_key
;
2387 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2389 if ( isset( $row->fa_sha1
) ) {
2390 $sha1 = $row->fa_sha1
;
2392 // old row, populate from key
2393 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2397 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2398 $sha1 = substr( $sha1, 1 );
2401 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2402 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2403 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2404 ||
is_null( $row->fa_metadata
)
2406 // Refresh our metadata
2407 // Required for a new current revision; nice for older ones too. :)
2408 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2411 'minor_mime' => $row->fa_minor_mime
,
2412 'major_mime' => $row->fa_major_mime
,
2413 'media_type' => $row->fa_media_type
,
2414 'metadata' => $row->fa_metadata
2418 if ( $first && !$exists ) {
2419 // This revision will be published as the new current version
2420 $destRel = $this->file
->getRel();
2421 $insertCurrent = array(
2422 'img_name' => $row->fa_name
,
2423 'img_size' => $row->fa_size
,
2424 'img_width' => $row->fa_width
,
2425 'img_height' => $row->fa_height
,
2426 'img_metadata' => $props['metadata'],
2427 'img_bits' => $row->fa_bits
,
2428 'img_media_type' => $props['media_type'],
2429 'img_major_mime' => $props['major_mime'],
2430 'img_minor_mime' => $props['minor_mime'],
2431 'img_description' => $row->fa_description
,
2432 'img_user' => $row->fa_user
,
2433 'img_user_text' => $row->fa_user_text
,
2434 'img_timestamp' => $row->fa_timestamp
,
2438 // The live (current) version cannot be hidden!
2439 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2440 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2441 $this->cleanupBatch
[] = $row->fa_storage_key
;
2444 $archiveName = $row->fa_archive_name
;
2446 if ( $archiveName == '' ) {
2447 // This was originally a current version; we
2448 // have to devise a new archive name for it.
2449 // Format is <timestamp of archiving>!<name>
2450 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2453 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2455 } while ( isset( $archiveNames[$archiveName] ) );
2458 $archiveNames[$archiveName] = true;
2459 $destRel = $this->file
->getArchiveRel( $archiveName );
2460 $insertBatch[] = array(
2461 'oi_name' => $row->fa_name
,
2462 'oi_archive_name' => $archiveName,
2463 'oi_size' => $row->fa_size
,
2464 'oi_width' => $row->fa_width
,
2465 'oi_height' => $row->fa_height
,
2466 'oi_bits' => $row->fa_bits
,
2467 'oi_description' => $row->fa_description
,
2468 'oi_user' => $row->fa_user
,
2469 'oi_user_text' => $row->fa_user_text
,
2470 'oi_timestamp' => $row->fa_timestamp
,
2471 'oi_metadata' => $props['metadata'],
2472 'oi_media_type' => $props['media_type'],
2473 'oi_major_mime' => $props['major_mime'],
2474 'oi_minor_mime' => $props['minor_mime'],
2475 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2476 'oi_sha1' => $sha1 );
2479 $deleteIds[] = $row->fa_id
;
2481 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2482 // private files can stay where they are
2483 $status->successCount++
;
2485 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2486 $this->cleanupBatch
[] = $row->fa_storage_key
;
2494 // Add a warning to the status object for missing IDs
2495 $missingIds = array_diff( $this->ids
, $idsPresent );
2497 foreach ( $missingIds as $id ) {
2498 $status->error( 'undelete-missing-filearchive', $id );
2501 // Remove missing files from batch, so we don't get errors when undeleting them
2502 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2503 if ( !$checkStatus->isGood() ) {
2504 $status->merge( $checkStatus );
2507 $storeBatch = $checkStatus->value
;
2509 // Run the store batch
2510 // Use the OVERWRITE_SAME flag to smooth over a common error
2511 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2512 $status->merge( $storeStatus );
2514 if ( !$status->isGood() ) {
2515 // Even if some files could be copied, fail entirely as that is the
2516 // easiest thing to do without data loss
2517 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2518 $status->ok
= false;
2519 $this->file
->unlock();
2524 // Run the DB updates
2525 // Because we have locked the image row, key conflicts should be rare.
2526 // If they do occur, we can roll back the transaction at this time with
2527 // no data loss, but leaving unregistered files scattered throughout the
2529 // This is not ideal, which is why it's important to lock the image row.
2530 if ( $insertCurrent ) {
2531 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2534 if ( $insertBatch ) {
2535 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2539 $dbw->delete( 'filearchive',
2540 array( 'fa_id' => $deleteIds ),
2544 // If store batch is empty (all files are missing), deletion is to be considered successful
2545 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2547 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2549 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2551 $this->file
->purgeEverything();
2553 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2554 $this->file
->purgeDescription();
2558 $this->file
->unlock();
2564 * Removes non-existent files from a store batch.
2565 * @param array $triplets
2568 function removeNonexistentFiles( $triplets ) {
2569 $files = $filteredTriplets = array();
2570 foreach ( $triplets as $file ) {
2571 $files[$file[0]] = $file[0];
2574 $result = $this->file
->repo
->fileExistsBatch( $files );
2575 if ( in_array( null, $result, true ) ) {
2576 return Status
::newFatal( 'backend-fail-internal',
2577 $this->file
->repo
->getBackend()->getName() );
2580 foreach ( $triplets as $file ) {
2581 if ( $result[$file[0]] ) {
2582 $filteredTriplets[] = $file;
2586 return Status
::newGood( $filteredTriplets );
2590 * Removes non-existent files from a cleanup batch.
2591 * @param array $batch
2594 function removeNonexistentFromCleanup( $batch ) {
2595 $files = $newBatch = array();
2596 $repo = $this->file
->repo
;
2598 foreach ( $batch as $file ) {
2599 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2600 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2603 $result = $repo->fileExistsBatch( $files );
2605 foreach ( $batch as $file ) {
2606 if ( $result[$file] ) {
2607 $newBatch[] = $file;
2615 * Delete unused files in the deleted zone.
2616 * This should be called from outside the transaction in which execute() was called.
2617 * @return FileRepoStatus
2619 function cleanup() {
2620 if ( !$this->cleanupBatch
) {
2621 return $this->file
->repo
->newGood();
2624 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2626 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2632 * Cleanup a failed batch. The batch was only partially successful, so
2633 * rollback by removing all items that were succesfully copied.
2635 * @param Status $storeStatus
2636 * @param array $storeBatch
2638 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2639 $cleanupBatch = array();
2641 foreach ( $storeStatus->success
as $i => $success ) {
2642 // Check if this item of the batch was successfully copied
2644 // Item was successfully copied and needs to be removed again
2645 // Extract ($dstZone, $dstRel) from the batch
2646 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2649 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2653 # ------------------------------------------------------------------------------
2656 * Helper class for file movement
2657 * @ingroup FileAbstraction
2659 class LocalFileMoveBatch
{
2660 /** @var LocalFile */
2670 protected $oldCount;
2674 /** @var DatabaseBase */
2679 * @param Title $target
2681 function __construct( File
$file, Title
$target ) {
2682 $this->file
= $file;
2683 $this->target
= $target;
2684 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2685 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2686 $this->oldName
= $this->file
->getName();
2687 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2688 $this->oldRel
= $this->oldHash
. $this->oldName
;
2689 $this->newRel
= $this->newHash
. $this->newName
;
2690 $this->db
= $file->getRepo()->getMasterDb();
2694 * Add the current image to the batch
2696 function addCurrent() {
2697 $this->cur
= array( $this->oldRel
, $this->newRel
);
2701 * Add the old versions of the image to the batch
2702 * @return array List of archive names from old versions
2704 function addOlds() {
2705 $archiveBase = 'archive';
2706 $this->olds
= array();
2707 $this->oldCount
= 0;
2708 $archiveNames = array();
2710 $result = $this->db
->select( 'oldimage',
2711 array( 'oi_archive_name', 'oi_deleted' ),
2712 array( 'oi_name' => $this->oldName
),
2714 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2717 foreach ( $result as $row ) {
2718 $archiveNames[] = $row->oi_archive_name
;
2719 $oldName = $row->oi_archive_name
;
2720 $bits = explode( '!', $oldName, 2 );
2722 if ( count( $bits ) != 2 ) {
2723 wfDebug( "Old file name missing !: '$oldName' \n" );
2727 list( $timestamp, $filename ) = $bits;
2729 if ( $this->oldName
!= $filename ) {
2730 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2736 // Do we want to add those to oldCount?
2737 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2741 $this->olds
[] = array(
2742 "{$archiveBase}/{$this->oldHash}{$oldName}",
2743 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2747 return $archiveNames;
2752 * @return FileRepoStatus
2754 function execute() {
2755 $repo = $this->file
->repo
;
2756 $status = $repo->newGood();
2758 $triplets = $this->getMoveTriplets();
2759 $checkStatus = $this->removeNonexistentFiles( $triplets );
2760 if ( !$checkStatus->isGood() ) {
2761 $status->merge( $checkStatus );
2764 $triplets = $checkStatus->value
;
2765 $destFile = wfLocalFile( $this->target
);
2767 $this->file
->lock(); // begin
2768 $destFile->lock(); // quickly fail if destination is not available
2769 // Rename the file versions metadata in the DB.
2770 // This implicitly locks the destination file, which avoids race conditions.
2771 // If we moved the files from A -> C before DB updates, another process could
2772 // move files from B -> C at this point, causing storeBatch() to fail and thus
2773 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2774 $statusDb = $this->doDBUpdates();
2775 if ( !$statusDb->isGood() ) {
2776 $destFile->unlock();
2777 $this->file
->unlockAndRollback();
2778 $statusDb->ok
= false;
2782 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2783 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2785 // Copy the files into their new location.
2786 // If a prior process fataled copying or cleaning up files we tolerate any
2787 // of the existing files if they are identical to the ones being stored.
2788 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2789 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2790 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2791 if ( !$statusMove->isGood() ) {
2792 // Delete any files copied over (while the destination is still locked)
2793 $this->cleanupTarget( $triplets );
2794 $destFile->unlock();
2795 $this->file
->unlockAndRollback(); // unlocks the destination
2796 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2797 $statusMove->ok
= false;
2801 $destFile->unlock();
2802 $this->file
->unlock(); // done
2804 // Everything went ok, remove the source files
2805 $this->cleanupSource( $triplets );
2807 $status->merge( $statusDb );
2808 $status->merge( $statusMove );
2814 * Do the database updates and return a new FileRepoStatus indicating how
2815 * many rows where updated.
2817 * @return FileRepoStatus
2819 function doDBUpdates() {
2820 $repo = $this->file
->repo
;
2821 $status = $repo->newGood();
2824 // Update current image
2827 array( 'img_name' => $this->newName
),
2828 array( 'img_name' => $this->oldName
),
2832 if ( $dbw->affectedRows() ) {
2833 $status->successCount++
;
2835 $status->failCount++
;
2836 $status->fatal( 'imageinvalidfilename' );
2841 // Update old images
2845 'oi_name' => $this->newName
,
2846 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2847 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2849 array( 'oi_name' => $this->oldName
),
2853 $affected = $dbw->affectedRows();
2854 $total = $this->oldCount
;
2855 $status->successCount +
= $affected;
2856 // Bug 34934: $total is based on files that actually exist.
2857 // There may be more DB rows than such files, in which case $affected
2858 // can be greater than $total. We use max() to avoid negatives here.
2859 $status->failCount +
= max( 0, $total - $affected );
2860 if ( $status->failCount
) {
2861 $status->error( 'imageinvalidfilename' );
2868 * Generate triplets for FileRepo::storeBatch().
2871 function getMoveTriplets() {
2872 $moves = array_merge( array( $this->cur
), $this->olds
);
2873 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2875 foreach ( $moves as $move ) {
2876 // $move: (oldRelativePath, newRelativePath)
2877 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2878 $triplets[] = array( $srcUrl, 'public', $move[1] );
2881 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2889 * Removes non-existent files from move batch.
2890 * @param array $triplets
2893 function removeNonexistentFiles( $triplets ) {
2896 foreach ( $triplets as $file ) {
2897 $files[$file[0]] = $file[0];
2900 $result = $this->file
->repo
->fileExistsBatch( $files );
2901 if ( in_array( null, $result, true ) ) {
2902 return Status
::newFatal( 'backend-fail-internal',
2903 $this->file
->repo
->getBackend()->getName() );
2906 $filteredTriplets = array();
2907 foreach ( $triplets as $file ) {
2908 if ( $result[$file[0]] ) {
2909 $filteredTriplets[] = $file;
2911 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2915 return Status
::newGood( $filteredTriplets );
2919 * Cleanup a partially moved array of triplets by deleting the target
2920 * files. Called if something went wrong half way.
2921 * @param array $triplets
2923 function cleanupTarget( $triplets ) {
2924 // Create dest pairs from the triplets
2926 foreach ( $triplets as $triplet ) {
2927 // $triplet: (old source virtual URL, dst zone, dest rel)
2928 $pairs[] = array( $triplet[1], $triplet[2] );
2931 $this->file
->repo
->cleanupBatch( $pairs );
2935 * Cleanup a fully moved array of triplets by deleting the source files.
2936 * Called at the end of the move process if everything else went ok.
2937 * @param array $triplets
2939 function cleanupSource( $triplets ) {
2940 // Create source file names from the triplets
2942 foreach ( $triplets as $triplet ) {
2943 $files[] = $triplet[0];
2946 $this->file
->repo
->cleanupBatch( $files );