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 or virtual URL 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 or virtual URL 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 $repo = $this->getRepo();
1490 if ( $repo->getReadOnlyReason() !== false ) {
1491 return $this->readOnlyFatalStatus();
1494 $this->lock(); // begin
1496 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1497 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1499 if ( $repo->hasSha1Storage() ) {
1500 $sha1 = $repo->isVirtualUrl( $srcPath )
1501 ?
$repo->getFileSha1( $srcPath )
1502 : File
::sha1Base36( $srcPath );
1503 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1504 $status = $repo->quickImport( $srcPath, $dst );
1505 if ( $flags & File
::DELETE_SOURCE
) {
1509 if ( $this->exists() ) {
1510 $status->value
= $archiveName;
1513 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1514 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1516 if ( $status->value
== 'new' ) {
1517 $status->value
= '';
1519 $status->value
= $archiveName;
1523 $this->unlock(); // done
1528 /** getLinksTo inherited */
1529 /** getExifData inherited */
1530 /** isLocal inherited */
1531 /** wasDeleted inherited */
1534 * Move file to the new title
1536 * Move current, old version and all thumbnails
1537 * to the new filename. Old file is deleted.
1539 * Cache purging is done; checks for validity
1540 * and logging are caller's responsibility
1542 * @param Title $target New file name
1543 * @return FileRepoStatus
1545 function move( $target ) {
1546 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1547 return $this->readOnlyFatalStatus();
1550 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1551 $batch = new LocalFileMoveBatch( $this, $target );
1553 $this->lock(); // begin
1554 $batch->addCurrent();
1555 $archiveNames = $batch->addOlds();
1556 $status = $batch->execute();
1557 $this->unlock(); // done
1559 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1561 // Purge the source and target files...
1562 $oldTitleFile = wfLocalFile( $this->title
);
1563 $newTitleFile = wfLocalFile( $target );
1564 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1565 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1566 $this->getRepo()->getMasterDB()->onTransactionIdle(
1567 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1568 $oldTitleFile->purgeEverything();
1569 foreach ( $archiveNames as $archiveName ) {
1570 $oldTitleFile->purgeOldThumbnails( $archiveName );
1572 $newTitleFile->purgeEverything();
1576 if ( $status->isOK() ) {
1577 // Now switch the object
1578 $this->title
= $target;
1579 // Force regeneration of the name and hashpath
1580 unset( $this->name
);
1581 unset( $this->hashPath
);
1588 * Delete all versions of the file.
1590 * Moves the files into an archive directory (or deletes them)
1591 * and removes the database rows.
1593 * Cache purging is done; logging is caller's responsibility.
1595 * @param string $reason
1596 * @param bool $suppress
1597 * @param User|null $user
1598 * @return FileRepoStatus
1600 function delete( $reason, $suppress = false, $user = null ) {
1601 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1602 return $this->readOnlyFatalStatus();
1605 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1607 $this->lock(); // begin
1608 $batch->addCurrent();
1609 # Get old version relative paths
1610 $archiveNames = $batch->addOlds();
1611 $status = $batch->execute();
1612 $this->unlock(); // done
1614 if ( $status->isOK() ) {
1615 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1618 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1619 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1621 $this->getRepo()->getMasterDB()->onTransactionIdle(
1622 function () use ( $that, $archiveNames ) {
1625 $that->purgeEverything();
1626 foreach ( $archiveNames as $archiveName ) {
1627 $that->purgeOldThumbnails( $archiveName );
1630 if ( $wgUseSquid ) {
1632 $purgeUrls = array();
1633 foreach ( $archiveNames as $archiveName ) {
1634 $purgeUrls[] = $that->getArchiveUrl( $archiveName );
1636 SquidUpdate
::purge( $purgeUrls );
1645 * Delete an old version of the file.
1647 * Moves the file into an archive directory (or deletes it)
1648 * and removes the database row.
1650 * Cache purging is done; logging is caller's responsibility.
1652 * @param string $archiveName
1653 * @param string $reason
1654 * @param bool $suppress
1655 * @param User|null $user
1656 * @throws MWException Exception on database or file store failure
1657 * @return FileRepoStatus
1659 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1661 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1662 return $this->readOnlyFatalStatus();
1665 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1667 $this->lock(); // begin
1668 $batch->addOld( $archiveName );
1669 $status = $batch->execute();
1670 $this->unlock(); // done
1672 $this->purgeOldThumbnails( $archiveName );
1673 if ( $status->isOK() ) {
1674 $this->purgeDescription();
1677 if ( $wgUseSquid ) {
1679 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1686 * Restore all or specified deleted revisions to the given file.
1687 * Permissions and logging are left to the caller.
1689 * May throw database exceptions on error.
1691 * @param array $versions Set of record ids of deleted items to restore,
1692 * or empty to restore all revisions.
1693 * @param bool $unsuppress
1694 * @return FileRepoStatus
1696 function restore( $versions = array(), $unsuppress = false ) {
1697 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1698 return $this->readOnlyFatalStatus();
1701 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1703 $this->lock(); // begin
1707 $batch->addIds( $versions );
1709 $status = $batch->execute();
1710 if ( $status->isGood() ) {
1711 $cleanupStatus = $batch->cleanup();
1712 $cleanupStatus->successCount
= 0;
1713 $cleanupStatus->failCount
= 0;
1714 $status->merge( $cleanupStatus );
1716 $this->unlock(); // done
1721 /** isMultipage inherited */
1722 /** pageCount inherited */
1723 /** scaleHeight inherited */
1724 /** getImageSize inherited */
1727 * Get the URL of the file description page.
1730 function getDescriptionUrl() {
1731 return $this->title
->getLocalURL();
1735 * Get the HTML text of the description page
1736 * This is not used by ImagePage for local files, since (among other things)
1737 * it skips the parser cache.
1739 * @param Language $lang What language to get description in (Optional)
1740 * @return bool|mixed
1742 function getDescriptionText( $lang = null ) {
1743 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1747 $content = $revision->getContent();
1751 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1753 return $pout->getText();
1757 * @param int $audience
1761 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1763 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1765 } elseif ( $audience == self
::FOR_THIS_USER
1766 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1770 return $this->description
;
1775 * @return bool|string
1777 function getTimestamp() {
1780 return $this->timestamp
;
1784 * @return bool|string
1786 public function getDescriptionTouched() {
1787 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1788 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1789 // need to differentiate between null (uninitialized) and false (failed to load).
1790 if ( $this->descriptionTouched
=== null ) {
1792 'page_namespace' => $this->title
->getNamespace(),
1793 'page_title' => $this->title
->getDBkey()
1795 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1796 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1799 return $this->descriptionTouched
;
1805 function getSha1() {
1807 // Initialise now if necessary
1808 if ( $this->sha1
== '' && $this->fileExists
) {
1809 $this->lock(); // begin
1811 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1812 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1813 $dbw = $this->repo
->getMasterDB();
1814 $dbw->update( 'image',
1815 array( 'img_sha1' => $this->sha1
),
1816 array( 'img_name' => $this->getName() ),
1818 $this->invalidateCache();
1821 $this->unlock(); // done
1828 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1830 function isCacheable() {
1833 // If extra data (metadata) was not loaded then it must have been large
1834 return $this->extraDataLoaded
1835 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1839 * Start a transaction and lock the image for update
1840 * Increments a reference counter if the lock is already held
1841 * @throws MWException Throws an error if the lock was not acquired
1842 * @return bool Whether the file lock owns/spawned the DB transaction
1845 $dbw = $this->repo
->getMasterDB();
1847 if ( !$this->locked
) {
1848 if ( !$dbw->trxLevel() ) {
1849 $dbw->begin( __METHOD__
);
1850 $this->lockedOwnTrx
= true;
1853 // Bug 54736: use simple lock to handle when the file does not exist.
1854 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1855 // Also, that would cause contention on INSERT of similarly named rows.
1856 $backend = $this->getRepo()->getBackend();
1857 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1858 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1859 if ( !$status->isGood() ) {
1860 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1862 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1863 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1867 return $this->lockedOwnTrx
;
1871 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1872 * the transaction and thereby releases the image lock.
1875 if ( $this->locked
) {
1877 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1878 $dbw = $this->repo
->getMasterDB();
1879 $dbw->commit( __METHOD__
);
1880 $this->lockedOwnTrx
= false;
1886 * Roll back the DB transaction and mark the image unlocked
1888 function unlockAndRollback() {
1889 $this->locked
= false;
1890 $dbw = $this->repo
->getMasterDB();
1891 $dbw->rollback( __METHOD__
);
1892 $this->lockedOwnTrx
= false;
1898 protected function readOnlyFatalStatus() {
1899 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1900 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1904 * Clean up any dangling locks
1906 function __destruct() {
1909 } // LocalFile class
1911 # ------------------------------------------------------------------------------
1914 * Helper class for file deletion
1915 * @ingroup FileAbstraction
1917 class LocalFileDeleteBatch
{
1918 /** @var LocalFile */
1925 private $srcRels = array();
1928 private $archiveUrls = array();
1930 /** @var array Items to be processed in the deletion batch */
1931 private $deletionBatch;
1933 /** @var bool Whether to suppress all suppressable fields when deleting */
1936 /** @var FileRepoStatus */
1944 * @param string $reason
1945 * @param bool $suppress
1946 * @param User|null $user
1948 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1949 $this->file
= $file;
1950 $this->reason
= $reason;
1951 $this->suppress
= $suppress;
1953 $this->user
= $user;
1956 $this->user
= $wgUser;
1958 $this->status
= $file->repo
->newGood();
1961 public function addCurrent() {
1962 $this->srcRels
['.'] = $this->file
->getRel();
1966 * @param string $oldName
1968 public function addOld( $oldName ) {
1969 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1970 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1974 * Add the old versions of the image to the batch
1975 * @return array List of archive names from old versions
1977 public function addOlds() {
1978 $archiveNames = array();
1980 $dbw = $this->file
->repo
->getMasterDB();
1981 $result = $dbw->select( 'oldimage',
1982 array( 'oi_archive_name' ),
1983 array( 'oi_name' => $this->file
->getName() ),
1987 foreach ( $result as $row ) {
1988 $this->addOld( $row->oi_archive_name
);
1989 $archiveNames[] = $row->oi_archive_name
;
1992 return $archiveNames;
1998 protected function getOldRels() {
1999 if ( !isset( $this->srcRels
['.'] ) ) {
2000 $oldRels =& $this->srcRels
;
2001 $deleteCurrent = false;
2003 $oldRels = $this->srcRels
;
2004 unset( $oldRels['.'] );
2005 $deleteCurrent = true;
2008 return array( $oldRels, $deleteCurrent );
2014 protected function getHashes() {
2016 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2018 if ( $deleteCurrent ) {
2019 $hashes['.'] = $this->file
->getSha1();
2022 if ( count( $oldRels ) ) {
2023 $dbw = $this->file
->repo
->getMasterDB();
2024 $res = $dbw->select(
2026 array( 'oi_archive_name', 'oi_sha1' ),
2027 array( 'oi_archive_name' => array_keys( $oldRels ),
2028 'oi_name' => $this->file
->getName() ), // performance
2032 foreach ( $res as $row ) {
2033 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2034 // Get the hash from the file
2035 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2036 $props = $this->file
->repo
->getFileProps( $oldUrl );
2038 if ( $props['fileExists'] ) {
2039 // Upgrade the oldimage row
2040 $dbw->update( 'oldimage',
2041 array( 'oi_sha1' => $props['sha1'] ),
2042 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2044 $hashes[$row->oi_archive_name
] = $props['sha1'];
2046 $hashes[$row->oi_archive_name
] = false;
2049 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2054 $missing = array_diff_key( $this->srcRels
, $hashes );
2056 foreach ( $missing as $name => $rel ) {
2057 $this->status
->error( 'filedelete-old-unregistered', $name );
2060 foreach ( $hashes as $name => $hash ) {
2062 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2063 unset( $hashes[$name] );
2070 protected function doDBInserts() {
2071 $dbw = $this->file
->repo
->getMasterDB();
2072 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2073 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2074 $encReason = $dbw->addQuotes( $this->reason
);
2075 $encGroup = $dbw->addQuotes( 'deleted' );
2076 $ext = $this->file
->getExtension();
2077 $dotExt = $ext === '' ?
'' : ".$ext";
2078 $encExt = $dbw->addQuotes( $dotExt );
2079 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2081 // Bitfields to further suppress the content
2082 if ( $this->suppress
) {
2084 // This should be 15...
2085 $bitfield |
= Revision
::DELETED_TEXT
;
2086 $bitfield |
= Revision
::DELETED_COMMENT
;
2087 $bitfield |
= Revision
::DELETED_USER
;
2088 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2090 $bitfield = 'oi_deleted';
2093 if ( $deleteCurrent ) {
2094 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2095 $where = array( 'img_name' => $this->file
->getName() );
2096 $dbw->insertSelect( 'filearchive', 'image',
2098 'fa_storage_group' => $encGroup,
2099 'fa_storage_key' => $dbw->conditional(
2100 array( 'img_sha1' => '' ),
2101 $dbw->addQuotes( '' ),
2104 'fa_deleted_user' => $encUserId,
2105 'fa_deleted_timestamp' => $encTimestamp,
2106 'fa_deleted_reason' => $encReason,
2107 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2109 'fa_name' => 'img_name',
2110 'fa_archive_name' => 'NULL',
2111 'fa_size' => 'img_size',
2112 'fa_width' => 'img_width',
2113 'fa_height' => 'img_height',
2114 'fa_metadata' => 'img_metadata',
2115 'fa_bits' => 'img_bits',
2116 'fa_media_type' => 'img_media_type',
2117 'fa_major_mime' => 'img_major_mime',
2118 'fa_minor_mime' => 'img_minor_mime',
2119 'fa_description' => 'img_description',
2120 'fa_user' => 'img_user',
2121 'fa_user_text' => 'img_user_text',
2122 'fa_timestamp' => 'img_timestamp',
2123 'fa_sha1' => 'img_sha1',
2124 ), $where, __METHOD__
);
2127 if ( count( $oldRels ) ) {
2128 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2130 'oi_name' => $this->file
->getName(),
2131 'oi_archive_name' => array_keys( $oldRels ) );
2132 $dbw->insertSelect( 'filearchive', 'oldimage',
2134 'fa_storage_group' => $encGroup,
2135 'fa_storage_key' => $dbw->conditional(
2136 array( 'oi_sha1' => '' ),
2137 $dbw->addQuotes( '' ),
2140 'fa_deleted_user' => $encUserId,
2141 'fa_deleted_timestamp' => $encTimestamp,
2142 'fa_deleted_reason' => $encReason,
2143 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2145 'fa_name' => 'oi_name',
2146 'fa_archive_name' => 'oi_archive_name',
2147 'fa_size' => 'oi_size',
2148 'fa_width' => 'oi_width',
2149 'fa_height' => 'oi_height',
2150 'fa_metadata' => 'oi_metadata',
2151 'fa_bits' => 'oi_bits',
2152 'fa_media_type' => 'oi_media_type',
2153 'fa_major_mime' => 'oi_major_mime',
2154 'fa_minor_mime' => 'oi_minor_mime',
2155 'fa_description' => 'oi_description',
2156 'fa_user' => 'oi_user',
2157 'fa_user_text' => 'oi_user_text',
2158 'fa_timestamp' => 'oi_timestamp',
2159 'fa_sha1' => 'oi_sha1',
2160 ), $where, __METHOD__
);
2164 function doDBDeletes() {
2165 $dbw = $this->file
->repo
->getMasterDB();
2166 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2168 if ( count( $oldRels ) ) {
2169 $dbw->delete( 'oldimage',
2171 'oi_name' => $this->file
->getName(),
2172 'oi_archive_name' => array_keys( $oldRels )
2176 if ( $deleteCurrent ) {
2177 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2182 * Run the transaction
2183 * @return FileRepoStatus
2185 public function execute() {
2186 $repo = $this->file
->getRepo();
2187 $this->file
->lock();
2189 // Prepare deletion batch
2190 $hashes = $this->getHashes();
2191 $this->deletionBatch
= array();
2192 $ext = $this->file
->getExtension();
2193 $dotExt = $ext === '' ?
'' : ".$ext";
2195 foreach ( $this->srcRels
as $name => $srcRel ) {
2196 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2197 if ( isset( $hashes[$name] ) ) {
2198 $hash = $hashes[$name];
2199 $key = $hash . $dotExt;
2200 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2201 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2205 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2206 // We acquire this lock by running the inserts now, before the file operations.
2208 // This potentially has poor lock contention characteristics -- an alternative
2209 // scheme would be to insert stub filearchive entries with no fa_name and commit
2210 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2211 $this->doDBInserts();
2213 if ( !$repo->hasSha1Storage() ) {
2214 // Removes non-existent file from the batch, so we don't get errors.
2215 // This also handles files in the 'deleted' zone deleted via revision deletion.
2216 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2217 if ( !$checkStatus->isGood() ) {
2218 $this->status
->merge( $checkStatus );
2219 return $this->status
;
2221 $this->deletionBatch
= $checkStatus->value
;
2223 // Execute the file deletion batch
2224 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2226 if ( !$status->isGood() ) {
2227 $this->status
->merge( $status );
2231 if ( !$this->status
->isOK() ) {
2232 // Critical file deletion error
2233 // Roll back inserts, release lock and abort
2234 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2235 $this->file
->unlockAndRollback();
2237 return $this->status
;
2240 // Delete image/oldimage rows
2241 $this->doDBDeletes();
2243 // Commit and return
2244 $this->file
->unlock();
2246 return $this->status
;
2250 * Removes non-existent files from a deletion batch.
2251 * @param array $batch
2254 protected function removeNonexistentFiles( $batch ) {
2255 $files = $newBatch = array();
2257 foreach ( $batch as $batchItem ) {
2258 list( $src, ) = $batchItem;
2259 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2262 $result = $this->file
->repo
->fileExistsBatch( $files );
2263 if ( in_array( null, $result, true ) ) {
2264 return Status
::newFatal( 'backend-fail-internal',
2265 $this->file
->repo
->getBackend()->getName() );
2268 foreach ( $batch as $batchItem ) {
2269 if ( $result[$batchItem[0]] ) {
2270 $newBatch[] = $batchItem;
2274 return Status
::newGood( $newBatch );
2278 # ------------------------------------------------------------------------------
2281 * Helper class for file undeletion
2282 * @ingroup FileAbstraction
2284 class LocalFileRestoreBatch
{
2285 /** @var LocalFile */
2288 /** @var array List of file IDs to restore */
2289 private $cleanupBatch;
2291 /** @var array List of file IDs to restore */
2294 /** @var bool Add all revisions of the file */
2297 /** @var bool Whether to remove all settings for suppressed fields */
2298 private $unsuppress = false;
2302 * @param bool $unsuppress
2304 function __construct( File
$file, $unsuppress = false ) {
2305 $this->file
= $file;
2306 $this->cleanupBatch
= $this->ids
= array();
2307 $this->ids
= array();
2308 $this->unsuppress
= $unsuppress;
2315 public function addId( $fa_id ) {
2316 $this->ids
[] = $fa_id;
2320 * Add a whole lot of files by ID
2323 public function addIds( $ids ) {
2324 $this->ids
= array_merge( $this->ids
, $ids );
2328 * Add all revisions of the file
2330 public function addAll() {
2335 * Run the transaction, except the cleanup batch.
2336 * The cleanup batch should be run in a separate transaction, because it locks different
2337 * rows and there's no need to keep the image row locked while it's acquiring those locks
2338 * The caller may have its own transaction open.
2339 * So we save the batch and let the caller call cleanup()
2340 * @return FileRepoStatus
2342 public function execute() {
2345 $repo = $this->file
->getRepo();
2346 if ( !$this->all
&& !$this->ids
) {
2348 return $repo->newGood();
2351 $lockOwnsTrx = $this->file
->lock();
2353 $dbw = $this->file
->repo
->getMasterDB();
2354 $status = $this->file
->repo
->newGood();
2356 $exists = (bool)$dbw->selectField( 'image', '1',
2357 array( 'img_name' => $this->file
->getName() ),
2359 // The lock() should already prevents changes, but this still may need
2360 // to bypass any transaction snapshot. However, if lock() started the
2361 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2362 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2365 // Fetch all or selected archived revisions for the file,
2366 // sorted from the most recent to the oldest.
2367 $conditions = array( 'fa_name' => $this->file
->getName() );
2369 if ( !$this->all
) {
2370 $conditions['fa_id'] = $this->ids
;
2373 $result = $dbw->select(
2375 ArchivedFile
::selectFields(),
2378 array( 'ORDER BY' => 'fa_timestamp DESC' )
2381 $idsPresent = array();
2382 $storeBatch = array();
2383 $insertBatch = array();
2384 $insertCurrent = false;
2385 $deleteIds = array();
2387 $archiveNames = array();
2389 foreach ( $result as $row ) {
2390 $idsPresent[] = $row->fa_id
;
2392 if ( $row->fa_name
!= $this->file
->getName() ) {
2393 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2394 $status->failCount++
;
2398 if ( $row->fa_storage_key
== '' ) {
2399 // Revision was missing pre-deletion
2400 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2401 $status->failCount++
;
2405 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2406 $row->fa_storage_key
;
2407 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2409 if ( isset( $row->fa_sha1
) ) {
2410 $sha1 = $row->fa_sha1
;
2412 // old row, populate from key
2413 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2417 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2418 $sha1 = substr( $sha1, 1 );
2421 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2422 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2423 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2424 ||
is_null( $row->fa_metadata
)
2426 // Refresh our metadata
2427 // Required for a new current revision; nice for older ones too. :)
2428 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2431 'minor_mime' => $row->fa_minor_mime
,
2432 'major_mime' => $row->fa_major_mime
,
2433 'media_type' => $row->fa_media_type
,
2434 'metadata' => $row->fa_metadata
2438 if ( $first && !$exists ) {
2439 // This revision will be published as the new current version
2440 $destRel = $this->file
->getRel();
2441 $insertCurrent = array(
2442 'img_name' => $row->fa_name
,
2443 'img_size' => $row->fa_size
,
2444 'img_width' => $row->fa_width
,
2445 'img_height' => $row->fa_height
,
2446 'img_metadata' => $props['metadata'],
2447 'img_bits' => $row->fa_bits
,
2448 'img_media_type' => $props['media_type'],
2449 'img_major_mime' => $props['major_mime'],
2450 'img_minor_mime' => $props['minor_mime'],
2451 'img_description' => $row->fa_description
,
2452 'img_user' => $row->fa_user
,
2453 'img_user_text' => $row->fa_user_text
,
2454 'img_timestamp' => $row->fa_timestamp
,
2458 // The live (current) version cannot be hidden!
2459 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2460 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2461 $this->cleanupBatch
[] = $row->fa_storage_key
;
2464 $archiveName = $row->fa_archive_name
;
2466 if ( $archiveName == '' ) {
2467 // This was originally a current version; we
2468 // have to devise a new archive name for it.
2469 // Format is <timestamp of archiving>!<name>
2470 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2473 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2475 } while ( isset( $archiveNames[$archiveName] ) );
2478 $archiveNames[$archiveName] = true;
2479 $destRel = $this->file
->getArchiveRel( $archiveName );
2480 $insertBatch[] = array(
2481 'oi_name' => $row->fa_name
,
2482 'oi_archive_name' => $archiveName,
2483 'oi_size' => $row->fa_size
,
2484 'oi_width' => $row->fa_width
,
2485 'oi_height' => $row->fa_height
,
2486 'oi_bits' => $row->fa_bits
,
2487 'oi_description' => $row->fa_description
,
2488 'oi_user' => $row->fa_user
,
2489 'oi_user_text' => $row->fa_user_text
,
2490 'oi_timestamp' => $row->fa_timestamp
,
2491 'oi_metadata' => $props['metadata'],
2492 'oi_media_type' => $props['media_type'],
2493 'oi_major_mime' => $props['major_mime'],
2494 'oi_minor_mime' => $props['minor_mime'],
2495 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2496 'oi_sha1' => $sha1 );
2499 $deleteIds[] = $row->fa_id
;
2501 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2502 // private files can stay where they are
2503 $status->successCount++
;
2505 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2506 $this->cleanupBatch
[] = $row->fa_storage_key
;
2514 // Add a warning to the status object for missing IDs
2515 $missingIds = array_diff( $this->ids
, $idsPresent );
2517 foreach ( $missingIds as $id ) {
2518 $status->error( 'undelete-missing-filearchive', $id );
2521 if ( !$repo->hasSha1Storage() ) {
2522 // Remove missing files from batch, so we don't get errors when undeleting them
2523 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2524 if ( !$checkStatus->isGood() ) {
2525 $status->merge( $checkStatus );
2528 $storeBatch = $checkStatus->value
;
2530 // Run the store batch
2531 // Use the OVERWRITE_SAME flag to smooth over a common error
2532 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2533 $status->merge( $storeStatus );
2535 if ( !$status->isGood() ) {
2536 // Even if some files could be copied, fail entirely as that is the
2537 // easiest thing to do without data loss
2538 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2539 $status->ok
= false;
2540 $this->file
->unlock();
2546 // Run the DB updates
2547 // Because we have locked the image row, key conflicts should be rare.
2548 // If they do occur, we can roll back the transaction at this time with
2549 // no data loss, but leaving unregistered files scattered throughout the
2551 // This is not ideal, which is why it's important to lock the image row.
2552 if ( $insertCurrent ) {
2553 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2556 if ( $insertBatch ) {
2557 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2561 $dbw->delete( 'filearchive',
2562 array( 'fa_id' => $deleteIds ),
2566 // If store batch is empty (all files are missing), deletion is to be considered successful
2567 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2569 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2571 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2573 $this->file
->purgeEverything();
2575 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2576 $this->file
->purgeDescription();
2580 $this->file
->unlock();
2586 * Removes non-existent files from a store batch.
2587 * @param array $triplets
2590 protected function removeNonexistentFiles( $triplets ) {
2591 $files = $filteredTriplets = array();
2592 foreach ( $triplets as $file ) {
2593 $files[$file[0]] = $file[0];
2596 $result = $this->file
->repo
->fileExistsBatch( $files );
2597 if ( in_array( null, $result, true ) ) {
2598 return Status
::newFatal( 'backend-fail-internal',
2599 $this->file
->repo
->getBackend()->getName() );
2602 foreach ( $triplets as $file ) {
2603 if ( $result[$file[0]] ) {
2604 $filteredTriplets[] = $file;
2608 return Status
::newGood( $filteredTriplets );
2612 * Removes non-existent files from a cleanup batch.
2613 * @param array $batch
2616 protected function removeNonexistentFromCleanup( $batch ) {
2617 $files = $newBatch = array();
2618 $repo = $this->file
->repo
;
2620 foreach ( $batch as $file ) {
2621 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2622 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2625 $result = $repo->fileExistsBatch( $files );
2627 foreach ( $batch as $file ) {
2628 if ( $result[$file] ) {
2629 $newBatch[] = $file;
2637 * Delete unused files in the deleted zone.
2638 * This should be called from outside the transaction in which execute() was called.
2639 * @return FileRepoStatus
2641 public function cleanup() {
2642 if ( !$this->cleanupBatch
) {
2643 return $this->file
->repo
->newGood();
2646 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2648 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2654 * Cleanup a failed batch. The batch was only partially successful, so
2655 * rollback by removing all items that were succesfully copied.
2657 * @param Status $storeStatus
2658 * @param array $storeBatch
2660 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2661 $cleanupBatch = array();
2663 foreach ( $storeStatus->success
as $i => $success ) {
2664 // Check if this item of the batch was successfully copied
2666 // Item was successfully copied and needs to be removed again
2667 // Extract ($dstZone, $dstRel) from the batch
2668 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2671 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2675 # ------------------------------------------------------------------------------
2678 * Helper class for file movement
2679 * @ingroup FileAbstraction
2681 class LocalFileMoveBatch
{
2682 /** @var LocalFile */
2692 protected $oldCount;
2696 /** @var DatabaseBase */
2701 * @param Title $target
2703 function __construct( File
$file, Title
$target ) {
2704 $this->file
= $file;
2705 $this->target
= $target;
2706 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2707 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2708 $this->oldName
= $this->file
->getName();
2709 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2710 $this->oldRel
= $this->oldHash
. $this->oldName
;
2711 $this->newRel
= $this->newHash
. $this->newName
;
2712 $this->db
= $file->getRepo()->getMasterDb();
2716 * Add the current image to the batch
2718 public function addCurrent() {
2719 $this->cur
= array( $this->oldRel
, $this->newRel
);
2723 * Add the old versions of the image to the batch
2724 * @return array List of archive names from old versions
2726 public function addOlds() {
2727 $archiveBase = 'archive';
2728 $this->olds
= array();
2729 $this->oldCount
= 0;
2730 $archiveNames = array();
2732 $result = $this->db
->select( 'oldimage',
2733 array( 'oi_archive_name', 'oi_deleted' ),
2734 array( 'oi_name' => $this->oldName
),
2736 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2739 foreach ( $result as $row ) {
2740 $archiveNames[] = $row->oi_archive_name
;
2741 $oldName = $row->oi_archive_name
;
2742 $bits = explode( '!', $oldName, 2 );
2744 if ( count( $bits ) != 2 ) {
2745 wfDebug( "Old file name missing !: '$oldName' \n" );
2749 list( $timestamp, $filename ) = $bits;
2751 if ( $this->oldName
!= $filename ) {
2752 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2758 // Do we want to add those to oldCount?
2759 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2763 $this->olds
[] = array(
2764 "{$archiveBase}/{$this->oldHash}{$oldName}",
2765 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2769 return $archiveNames;
2774 * @return FileRepoStatus
2776 public function execute() {
2777 $repo = $this->file
->repo
;
2778 $status = $repo->newGood();
2780 $triplets = $this->getMoveTriplets();
2781 $checkStatus = $this->removeNonexistentFiles( $triplets );
2782 if ( !$checkStatus->isGood() ) {
2783 $status->merge( $checkStatus );
2786 $triplets = $checkStatus->value
;
2787 $destFile = wfLocalFile( $this->target
);
2789 $this->file
->lock(); // begin
2790 $destFile->lock(); // quickly fail if destination is not available
2791 // Rename the file versions metadata in the DB.
2792 // This implicitly locks the destination file, which avoids race conditions.
2793 // If we moved the files from A -> C before DB updates, another process could
2794 // move files from B -> C at this point, causing storeBatch() to fail and thus
2795 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2796 $statusDb = $this->doDBUpdates();
2797 if ( !$statusDb->isGood() ) {
2798 $destFile->unlock();
2799 $this->file
->unlockAndRollback();
2800 $statusDb->ok
= false;
2804 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2805 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2807 if ( !$repo->hasSha1Storage() ) {
2808 // Copy the files into their new location.
2809 // If a prior process fataled copying or cleaning up files we tolerate any
2810 // of the existing files if they are identical to the ones being stored.
2811 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2812 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2813 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2814 if ( !$statusMove->isGood() ) {
2815 // Delete any files copied over (while the destination is still locked)
2816 $this->cleanupTarget( $triplets );
2817 $destFile->unlock();
2818 $this->file
->unlockAndRollback(); // unlocks the destination
2819 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2820 $statusMove->ok
= false;
2824 $status->merge( $statusMove );
2827 $destFile->unlock();
2828 $this->file
->unlock(); // done
2830 // Everything went ok, remove the source files
2831 $this->cleanupSource( $triplets );
2833 $status->merge( $statusDb );
2839 * Do the database updates and return a new FileRepoStatus indicating how
2840 * many rows where updated.
2842 * @return FileRepoStatus
2844 protected function doDBUpdates() {
2845 $repo = $this->file
->repo
;
2846 $status = $repo->newGood();
2849 // Update current image
2852 array( 'img_name' => $this->newName
),
2853 array( 'img_name' => $this->oldName
),
2857 if ( $dbw->affectedRows() ) {
2858 $status->successCount++
;
2860 $status->failCount++
;
2861 $status->fatal( 'imageinvalidfilename' );
2866 // Update old images
2870 'oi_name' => $this->newName
,
2871 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2872 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2874 array( 'oi_name' => $this->oldName
),
2878 $affected = $dbw->affectedRows();
2879 $total = $this->oldCount
;
2880 $status->successCount +
= $affected;
2881 // Bug 34934: $total is based on files that actually exist.
2882 // There may be more DB rows than such files, in which case $affected
2883 // can be greater than $total. We use max() to avoid negatives here.
2884 $status->failCount +
= max( 0, $total - $affected );
2885 if ( $status->failCount
) {
2886 $status->error( 'imageinvalidfilename' );
2893 * Generate triplets for FileRepo::storeBatch().
2896 protected function getMoveTriplets() {
2897 $moves = array_merge( array( $this->cur
), $this->olds
);
2898 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2900 foreach ( $moves as $move ) {
2901 // $move: (oldRelativePath, newRelativePath)
2902 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2903 $triplets[] = array( $srcUrl, 'public', $move[1] );
2906 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2914 * Removes non-existent files from move batch.
2915 * @param array $triplets
2918 protected function removeNonexistentFiles( $triplets ) {
2921 foreach ( $triplets as $file ) {
2922 $files[$file[0]] = $file[0];
2925 $result = $this->file
->repo
->fileExistsBatch( $files );
2926 if ( in_array( null, $result, true ) ) {
2927 return Status
::newFatal( 'backend-fail-internal',
2928 $this->file
->repo
->getBackend()->getName() );
2931 $filteredTriplets = array();
2932 foreach ( $triplets as $file ) {
2933 if ( $result[$file[0]] ) {
2934 $filteredTriplets[] = $file;
2936 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2940 return Status
::newGood( $filteredTriplets );
2944 * Cleanup a partially moved array of triplets by deleting the target
2945 * files. Called if something went wrong half way.
2946 * @param array $triplets
2948 protected function cleanupTarget( $triplets ) {
2949 // Create dest pairs from the triplets
2951 foreach ( $triplets as $triplet ) {
2952 // $triplet: (old source virtual URL, dst zone, dest rel)
2953 $pairs[] = array( $triplet[1], $triplet[2] );
2956 $this->file
->repo
->cleanupBatch( $pairs );
2960 * Cleanup a fully moved array of triplets by deleting the source files.
2961 * Called at the end of the move process if everything else went ok.
2962 * @param array $triplets
2964 protected function cleanupSource( $triplets ) {
2965 // Create source file names from the triplets
2967 foreach ( $triplets as $triplet ) {
2968 $files[] = $triplet[0];
2971 $this->file
->repo
->cleanupBatch( $files );