3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 9 );
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const CACHE_FIELD_MAX_LEN
= 1000;
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
52 /** @var int Image width */
55 /** @var int Image height */
58 /** @var int Returned by getimagesize (loadFromXxx) */
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
67 /** @var int Size in bytes (loadFromXxx) */
70 /** @var string Handler-specific metadata */
73 /** @var string SHA-1 base 36 content hash */
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
82 /** @var int Bitfield akin to rev_deleted */
86 protected $repoClass = 'LocalRepo';
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
94 /** @var string Major MIME type */
97 /** @var string Minor MIME type */
100 /** @var string Upload timestamp */
103 /** @var int User ID of uploader */
106 /** @var string User name of uploader */
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var bool Whether the row was upgraded on load */
115 /** @var bool True if the image row is locked */
118 /** @var bool True if the image row is locked with a lock initiated transaction */
119 private $lockedOwnTrx;
121 /** @var bool True if file is not present in file system. Not to be cached in memcached */
124 /** @var int UNIX timestamp of last markVolatile() call */
125 private $lastMarkedVolatile = 0;
127 const LOAD_ALL
= 1; // integer; load all the lazy fields too (like metadata)
128 const LOAD_VIA_SLAVE
= 2; // integer; use a slave to load the data
130 const VOLATILE_TTL
= 300; // integer; seconds
133 * Create a LocalFile from a title
134 * Do not call this except from inside a repo class.
136 * Note: $unused param is only here to avoid an E_STRICT
138 * @param Title $title
139 * @param FileRepo $repo
140 * @param null $unused
144 static function newFromTitle( $title, $repo, $unused = null ) {
145 return new self( $title, $repo );
149 * Create a LocalFile from a title
150 * Do not call this except from inside a repo class.
152 * @param stdClass $row
153 * @param FileRepo $repo
157 static function newFromRow( $row, $repo ) {
158 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
159 $file = new self( $title, $repo );
160 $file->loadFromRow( $row );
166 * Create a LocalFile from a SHA-1 key
167 * Do not call this except from inside a repo class.
169 * @param string $sha1 Base-36 SHA-1
170 * @param LocalRepo $repo
171 * @param string|bool $timestamp MW_timestamp (optional)
172 * @return bool|LocalFile
174 static function newFromKey( $sha1, $repo, $timestamp = false ) {
175 $dbr = $repo->getSlaveDB();
177 $conds = array( 'img_sha1' => $sha1 );
179 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
182 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
184 return self
::newFromRow( $row, $repo );
191 * Fields in the image table
194 static function selectFields() {
215 * Do not call this except from inside a repo class.
216 * @param Title $title
217 * @param FileRepo $repo
219 function __construct( $title, $repo ) {
220 parent
::__construct( $title, $repo );
222 $this->metadata
= '';
223 $this->historyLine
= 0;
224 $this->historyRes
= null;
225 $this->dataLoaded
= false;
226 $this->extraDataLoaded
= false;
228 $this->assertRepoDefined();
229 $this->assertTitleDefined();
233 * Get the memcached key for the main data for this file, or false if
234 * there is no access to the shared cache.
235 * @return string|bool
237 function getCacheKey() {
238 $hashedName = md5( $this->getName() );
240 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
244 * Try to load file metadata from memcached. Returns true on success.
247 function loadFromCache() {
250 wfProfileIn( __METHOD__
);
251 $this->dataLoaded
= false;
252 $this->extraDataLoaded
= false;
253 $key = $this->getCacheKey();
256 wfProfileOut( __METHOD__
);
261 $cachedValues = $wgMemc->get( $key );
263 // Check if the key existed and belongs to this version of MediaWiki
264 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
265 wfDebug( "Pulling file metadata from cache key $key\n" );
266 $this->fileExists
= $cachedValues['fileExists'];
267 if ( $this->fileExists
) {
268 $this->setProps( $cachedValues );
270 $this->dataLoaded
= true;
271 $this->extraDataLoaded
= true;
272 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
273 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
277 if ( $this->dataLoaded
) {
278 wfIncrStats( 'image_cache_hit' );
280 wfIncrStats( 'image_cache_miss' );
283 wfProfileOut( __METHOD__
);
285 return $this->dataLoaded
;
289 * Save the file metadata to memcached
291 function saveToCache() {
295 $key = $this->getCacheKey();
301 $fields = $this->getCacheFields( '' );
302 $cache = array( 'version' => MW_FILE_VERSION
);
303 $cache['fileExists'] = $this->fileExists
;
305 if ( $this->fileExists
) {
306 foreach ( $fields as $field ) {
307 $cache[$field] = $this->$field;
311 // Strip off excessive entries from the subset of fields that can become large.
312 // If the cache value gets to large it will not fit in memcached and nothing will
313 // get cached at all, causing master queries for any file access.
314 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
315 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
316 unset( $cache[$field] ); // don't let the value get too big
320 // Cache presence for 1 week and negatives for 1 day
321 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
325 * Load metadata from the file itself
327 function loadFromFile() {
328 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
329 $this->setProps( $props );
333 * @param string $prefix
336 function getCacheFields( $prefix = 'img_' ) {
337 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
338 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
339 'user_text', 'description' );
340 static $results = array();
342 if ( $prefix == '' ) {
346 if ( !isset( $results[$prefix] ) ) {
347 $prefixedFields = array();
348 foreach ( $fields as $field ) {
349 $prefixedFields[] = $prefix . $field;
351 $results[$prefix] = $prefixedFields;
354 return $results[$prefix];
358 * @param string $prefix
361 function getLazyCacheFields( $prefix = 'img_' ) {
362 static $fields = array( 'metadata' );
363 static $results = array();
365 if ( $prefix == '' ) {
369 if ( !isset( $results[$prefix] ) ) {
370 $prefixedFields = array();
371 foreach ( $fields as $field ) {
372 $prefixedFields[] = $prefix . $field;
374 $results[$prefix] = $prefixedFields;
377 return $results[$prefix];
381 * Load file metadata from the DB
384 function loadFromDB( $flags = 0 ) {
385 # Polymorphic function name to distinguish foreign and local fetches
386 $fname = get_class( $this ) . '::' . __FUNCTION__
;
387 wfProfileIn( $fname );
389 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
390 $this->dataLoaded
= true;
391 $this->extraDataLoaded
= true;
393 $dbr = ( $flags & self
::LOAD_VIA_SLAVE
)
394 ?
$this->repo
->getSlaveDB()
395 : $this->repo
->getMasterDB();
397 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
398 array( 'img_name' => $this->getName() ), $fname );
401 $this->loadFromRow( $row );
403 $this->fileExists
= false;
406 wfProfileOut( $fname );
410 * Load lazy file metadata from the DB.
411 * This covers fields that are sometimes not cached.
413 protected function loadExtraFromDB() {
414 # Polymorphic function name to distinguish foreign and local fetches
415 $fname = get_class( $this ) . '::' . __FUNCTION__
;
416 wfProfileIn( $fname );
418 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
419 $this->extraDataLoaded
= true;
421 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
423 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
427 foreach ( $fieldMap as $name => $value ) {
428 $this->$name = $value;
431 wfProfileOut( $fname );
432 throw new MWException( "Could not find data for image '{$this->getName()}'." );
435 wfProfileOut( $fname );
439 * @param DatabaseBase $dbr
440 * @param string $fname
443 private function loadFieldsWithTimestamp( $dbr, $fname ) {
446 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
447 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
450 $fieldMap = $this->unprefixRow( $row, 'img_' );
452 # File may have been uploaded over in the meantime; check the old versions
453 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
454 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
457 $fieldMap = $this->unprefixRow( $row, 'oi_' );
465 * @param array $row Row
466 * @param string $prefix
467 * @throws MWException
470 protected function unprefixRow( $row, $prefix = 'img_' ) {
471 $array = (array)$row;
472 $prefixLength = strlen( $prefix );
474 // Sanity check prefix once
475 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
476 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
480 foreach ( $array as $name => $value ) {
481 $decoded[substr( $name, $prefixLength )] = $value;
488 * Decode a row from the database (either object or array) to an array
489 * with timestamps and MIME types decoded, and the field prefix removed.
491 * @param string $prefix
492 * @throws MWException
495 function decodeRow( $row, $prefix = 'img_' ) {
496 $decoded = $this->unprefixRow( $row, $prefix );
498 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
500 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
502 if ( empty( $decoded['major_mime'] ) ) {
503 $decoded['mime'] = 'unknown/unknown';
505 if ( !$decoded['minor_mime'] ) {
506 $decoded['minor_mime'] = 'unknown';
508 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
511 # Trim zero padding from char/binary field
512 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
518 * Load file metadata from a DB result row
521 * @param string $prefix
523 function loadFromRow( $row, $prefix = 'img_' ) {
524 $this->dataLoaded
= true;
525 $this->extraDataLoaded
= true;
527 $array = $this->decodeRow( $row, $prefix );
529 foreach ( $array as $name => $value ) {
530 $this->$name = $value;
533 $this->fileExists
= true;
534 $this->maybeUpgradeRow();
538 * Load file metadata from cache or DB, unless already loaded
541 function load( $flags = 0 ) {
542 if ( !$this->dataLoaded
) {
543 if ( !$this->loadFromCache() ) {
544 $this->loadFromDB( $this->isVolatile() ?
0 : self
::LOAD_VIA_SLAVE
);
545 $this->saveToCache();
547 $this->dataLoaded
= true;
549 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
550 $this->loadExtraFromDB();
555 * Upgrade a row if it needs it
557 function maybeUpgradeRow() {
558 global $wgUpdateCompatibleMetadata;
559 if ( wfReadOnly() ) {
563 if ( is_null( $this->media_type
) ||
564 $this->mime
== 'image/svg'
567 $this->upgraded
= true;
569 $handler = $this->getHandler();
571 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
572 if ( $validity === MediaHandler
::METADATA_BAD
573 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
576 $this->upgraded
= true;
582 function getUpgraded() {
583 return $this->upgraded
;
587 * Fix assorted version-related problems with the image row by reloading it from the file
589 function upgradeRow() {
590 wfProfileIn( __METHOD__
);
592 $this->lock(); // begin
594 $this->loadFromFile();
596 # Don't destroy file info of missing files
597 if ( !$this->fileExists
) {
599 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
600 wfProfileOut( __METHOD__
);
605 $dbw = $this->repo
->getMasterDB();
606 list( $major, $minor ) = self
::splitMime( $this->mime
);
608 if ( wfReadOnly() ) {
610 wfProfileOut( __METHOD__
);
614 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
616 $dbw->update( 'image',
618 'img_size' => $this->size
, // sanity
619 'img_width' => $this->width
,
620 'img_height' => $this->height
,
621 'img_bits' => $this->bits
,
622 'img_media_type' => $this->media_type
,
623 'img_major_mime' => $major,
624 'img_minor_mime' => $minor,
625 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
626 'img_sha1' => $this->sha1
,
628 array( 'img_name' => $this->getName() ),
632 $this->saveToCache();
634 $this->unlock(); // done
636 wfProfileOut( __METHOD__
);
640 * Set properties in this object to be equal to those given in the
641 * associative array $info. Only cacheable fields can be set.
642 * All fields *must* be set in $info except for getLazyCacheFields().
644 * If 'mime' is given, it will be split into major_mime/minor_mime.
645 * If major_mime/minor_mime are given, $this->mime will also be set.
649 function setProps( $info ) {
650 $this->dataLoaded
= true;
651 $fields = $this->getCacheFields( '' );
652 $fields[] = 'fileExists';
654 foreach ( $fields as $field ) {
655 if ( isset( $info[$field] ) ) {
656 $this->$field = $info[$field];
660 // Fix up mime fields
661 if ( isset( $info['major_mime'] ) ) {
662 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
663 } elseif ( isset( $info['mime'] ) ) {
664 $this->mime
= $info['mime'];
665 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
669 /** splitMime inherited */
670 /** getName inherited */
671 /** getTitle inherited */
672 /** getURL inherited */
673 /** getViewURL inherited */
674 /** getPath inherited */
675 /** isVisible inhereted */
680 function isMissing() {
681 if ( $this->missing
=== null ) {
682 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
683 $this->missing
= !$fileExists;
686 return $this->missing
;
690 * Return the width of the image
695 public function getWidth( $page = 1 ) {
698 if ( $this->isMultipage() ) {
699 $handler = $this->getHandler();
703 $dim = $handler->getPageDimensions( $this, $page );
705 return $dim['width'];
707 // For non-paged media, the false goes through an
708 // intval, turning failure into 0, so do same here.
717 * Return the height of the image
722 public function getHeight( $page = 1 ) {
725 if ( $this->isMultipage() ) {
726 $handler = $this->getHandler();
730 $dim = $handler->getPageDimensions( $this, $page );
732 return $dim['height'];
734 // For non-paged media, the false goes through an
735 // intval, turning failure into 0, so do same here.
739 return $this->height
;
744 * Returns ID or name of user who uploaded the file
746 * @param string $type 'text' or 'id'
749 function getUser( $type = 'text' ) {
752 if ( $type == 'text' ) {
753 return $this->user_text
;
754 } elseif ( $type == 'id' ) {
760 * Get handler-specific metadata
763 function getMetadata() {
764 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
765 return $this->metadata
;
771 function getBitDepth() {
778 * Returns the size of the image file, in bytes
781 public function getSize() {
788 * Returns the MIME type of the file.
791 function getMimeType() {
798 * Returns the type of the media in the file.
799 * Use the value returned by this function with the MEDIATYPE_xxx constants.
802 function getMediaType() {
805 return $this->media_type
;
808 /** canRender inherited */
809 /** mustRender inherited */
810 /** allowInlineDisplay inherited */
811 /** isSafeFile inherited */
812 /** isTrustedFile inherited */
815 * Returns true if the file exists on disk.
816 * @return bool Whether file exist on disk.
818 public function exists() {
821 return $this->fileExists
;
824 /** getTransformScript inherited */
825 /** getUnscaledThumb inherited */
826 /** thumbName inherited */
827 /** createThumb inherited */
828 /** transform inherited */
830 /** getHandler inherited */
831 /** iconThumb inherited */
832 /** getLastError inherited */
835 * Get all thumbnail names previously generated for this file
836 * @param string|bool $archiveName Name of an archive file, default false
837 * @return array First element is the base dir, then files in that base dir.
839 function getThumbnails( $archiveName = false ) {
840 if ( $archiveName ) {
841 $dir = $this->getArchiveThumbPath( $archiveName );
843 $dir = $this->getThumbPath();
846 $backend = $this->repo
->getBackend();
847 $files = array( $dir );
849 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
850 foreach ( $iterator as $file ) {
853 } catch ( FileBackendError
$e ) {
854 } // suppress (bug 54674)
860 * Refresh metadata in memcached, but don't touch thumbnails or squid
862 function purgeMetadataCache() {
864 $this->saveToCache();
865 $this->purgeHistory();
869 * Purge the shared history (OldLocalFile) cache.
871 * @note This used to purge old thumbnails as well.
873 function purgeHistory() {
876 $hashedName = md5( $this->getName() );
877 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
880 $wgMemc->delete( $oldKey );
885 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
887 * @param array $options An array potentially with the key forThumbRefresh.
889 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
891 function purgeCache( $options = array() ) {
892 wfProfileIn( __METHOD__
);
893 // Refresh metadata cache
894 $this->purgeMetadataCache();
897 $this->purgeThumbnails( $options );
899 // Purge squid cache for this file
900 SquidUpdate
::purge( array( $this->getURL() ) );
901 wfProfileOut( __METHOD__
);
905 * Delete cached transformed files for an archived version only.
906 * @param string $archiveName Name of the archived file
908 function purgeOldThumbnails( $archiveName ) {
910 wfProfileIn( __METHOD__
);
912 // Get a list of old thumbnails and URLs
913 $files = $this->getThumbnails( $archiveName );
915 // Purge any custom thumbnail caches
916 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
918 $dir = array_shift( $files );
919 $this->purgeThumbList( $dir, $files );
924 foreach ( $files as $file ) {
925 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
927 SquidUpdate
::purge( $urls );
930 wfProfileOut( __METHOD__
);
934 * Delete cached transformed files for the current version only.
935 * @param array $options
937 function purgeThumbnails( $options = array() ) {
939 wfProfileIn( __METHOD__
);
942 $files = $this->getThumbnails();
943 // Always purge all files from squid regardless of handler filters
946 foreach ( $files as $file ) {
947 $urls[] = $this->getThumbUrl( $file );
949 array_shift( $urls ); // don't purge directory
952 // Give media handler a chance to filter the file purge list
953 if ( !empty( $options['forThumbRefresh'] ) ) {
954 $handler = $this->getHandler();
956 $handler->filterThumbnailPurgeList( $files, $options );
960 // Purge any custom thumbnail caches
961 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
963 $dir = array_shift( $files );
964 $this->purgeThumbList( $dir, $files );
968 SquidUpdate
::purge( $urls );
971 wfProfileOut( __METHOD__
);
975 * Delete a list of thumbnails visible at urls
976 * @param string $dir Base dir of the files.
977 * @param array $files Array of strings: relative filenames (to $dir)
979 protected function purgeThumbList( $dir, $files ) {
980 $fileListDebug = strtr(
981 var_export( $files, true ),
984 wfDebug( __METHOD__
. ": $fileListDebug\n" );
986 $purgeList = array();
987 foreach ( $files as $file ) {
988 # Check that the base file name is part of the thumb name
989 # This is a basic sanity check to avoid erasing unrelated directories
990 if ( strpos( $file, $this->getName() ) !== false
991 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
993 $purgeList[] = "{$dir}/{$file}";
997 # Delete the thumbnails
998 $this->repo
->quickPurgeBatch( $purgeList );
999 # Clear out the thumbnail directory if empty
1000 $this->repo
->quickCleanDir( $dir );
1003 /** purgeDescription inherited */
1004 /** purgeEverything inherited */
1007 * @param int $limit Optional: Limit to number of results
1008 * @param int $start Optional: Timestamp, start from
1009 * @param int $end Optional: Timestamp, end at
1013 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1014 $dbr = $this->repo
->getSlaveDB();
1015 $tables = array( 'oldimage' );
1016 $fields = OldLocalFile
::selectFields();
1017 $conds = $opts = $join_conds = array();
1018 $eq = $inc ?
'=' : '';
1019 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1022 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1026 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1030 $opts['LIMIT'] = $limit;
1033 // Search backwards for time > x queries
1034 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1035 $opts['ORDER BY'] = "oi_timestamp $order";
1036 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1038 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1039 &$conds, &$opts, &$join_conds ) );
1041 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1044 foreach ( $res as $row ) {
1045 $r[] = $this->repo
->newFileFromRow( $row );
1048 if ( $order == 'ASC' ) {
1049 $r = array_reverse( $r ); // make sure it ends up descending
1056 * Returns the history of this file, line by line.
1057 * starts with current version, then old versions.
1058 * uses $this->historyLine to check which line to return:
1059 * 0 return line for current version
1060 * 1 query for old versions, return first one
1061 * 2, ... return next old version from above query
1064 public function nextHistoryLine() {
1065 # Polymorphic function name to distinguish foreign and local fetches
1066 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1068 $dbr = $this->repo
->getSlaveDB();
1070 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1071 $this->historyRes
= $dbr->select( 'image',
1074 "'' AS oi_archive_name",
1078 array( 'img_name' => $this->title
->getDBkey() ),
1082 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1083 $this->historyRes
= null;
1087 } elseif ( $this->historyLine
== 1 ) {
1088 $this->historyRes
= $dbr->select( 'oldimage', '*',
1089 array( 'oi_name' => $this->title
->getDBkey() ),
1091 array( 'ORDER BY' => 'oi_timestamp DESC' )
1094 $this->historyLine++
;
1096 return $dbr->fetchObject( $this->historyRes
);
1100 * Reset the history pointer to the first element of the history
1102 public function resetHistory() {
1103 $this->historyLine
= 0;
1105 if ( !is_null( $this->historyRes
) ) {
1106 $this->historyRes
= null;
1110 /** getHashPath inherited */
1111 /** getRel inherited */
1112 /** getUrlRel inherited */
1113 /** getArchiveRel inherited */
1114 /** getArchivePath inherited */
1115 /** getThumbPath inherited */
1116 /** getArchiveUrl inherited */
1117 /** getThumbUrl inherited */
1118 /** getArchiveVirtualUrl inherited */
1119 /** getThumbVirtualUrl inherited */
1120 /** isHashed inherited */
1123 * Upload a file and record it in the DB
1124 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1125 * @param string $comment Upload description
1126 * @param string $pageText Text to use for the new description page,
1127 * if a new description page is created
1128 * @param int|bool $flags Flags for publish()
1129 * @param array|bool $props File properties, if known. This can be used to
1130 * reduce the upload time when uploading virtual URLs for which the file
1131 * info is already known
1132 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1134 * @param User|null $user User object or null to use $wgUser
1136 * @return FileRepoStatus On success, the value member contains the
1137 * archive name, or an empty string if it was a new file.
1139 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1140 $timestamp = false, $user = null
1144 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1145 return $this->readOnlyFatalStatus();
1149 wfProfileIn( __METHOD__
. '-getProps' );
1150 if ( $this->repo
->isVirtualUrl( $srcPath )
1151 || FileBackend
::isStoragePath( $srcPath )
1153 $props = $this->repo
->getFileProps( $srcPath );
1155 $props = FSFile
::getPropsFromPath( $srcPath );
1157 wfProfileOut( __METHOD__
. '-getProps' );
1161 $handler = MediaHandler
::getHandler( $props['mime'] );
1163 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1165 $options['headers'] = array();
1168 // Trim spaces on user supplied text
1169 $comment = trim( $comment );
1171 // Truncate nicely or the DB will do it for us
1172 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1173 $comment = $wgContLang->truncate( $comment, 255 );
1174 $this->lock(); // begin
1175 $status = $this->publish( $srcPath, $flags, $options );
1177 if ( $status->successCount
>= 2 ) {
1178 // There will be a copy+(one of move,copy,store).
1179 // The first succeeding does not commit us to updating the DB
1180 // since it simply copied the current version to a timestamped file name.
1181 // It is only *preferable* to avoid leaving such files orphaned.
1182 // Once the second operation goes through, then the current version was
1183 // updated and we must therefore update the DB too.
1184 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1185 $status->fatal( 'filenotfound', $srcPath );
1189 $this->unlock(); // done
1195 * Record a file upload in the upload log and the image table
1196 * @param string $oldver
1197 * @param string $desc
1198 * @param string $license
1199 * @param string $copyStatus
1200 * @param string $source
1201 * @param bool $watch
1202 * @param string|bool $timestamp
1203 * @param User|null $user User object or null to use $wgUser
1206 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1207 $watch = false, $timestamp = false, User
$user = null ) {
1213 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1215 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1220 $user->addWatch( $this->getTitle() );
1227 * Record a file upload in the upload log and the image table
1228 * @param string $oldver
1229 * @param string $comment
1230 * @param string $pageText
1231 * @param bool|array $props
1232 * @param string|bool $timestamp
1233 * @param null|User $user
1236 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1239 wfProfileIn( __METHOD__
);
1241 if ( is_null( $user ) ) {
1246 $dbw = $this->repo
->getMasterDB();
1247 $dbw->begin( __METHOD__
);
1250 wfProfileIn( __METHOD__
. '-getProps' );
1251 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1252 wfProfileOut( __METHOD__
. '-getProps' );
1255 # Imports or such might force a certain timestamp; otherwise we generate
1256 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1257 if ( $timestamp === false ) {
1258 $timestamp = $dbw->timestamp();
1259 $allowTimeKludge = true;
1261 $allowTimeKludge = false;
1264 $props['description'] = $comment;
1265 $props['user'] = $user->getId();
1266 $props['user_text'] = $user->getName();
1267 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1268 $this->setProps( $props );
1270 # Fail now if the file isn't there
1271 if ( !$this->fileExists
) {
1272 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1273 $dbw->rollback( __METHOD__
);
1274 wfProfileOut( __METHOD__
);
1281 # Test to see if the row exists using INSERT IGNORE
1282 # This avoids race conditions by locking the row until the commit, and also
1283 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1284 $dbw->insert( 'image',
1286 'img_name' => $this->getName(),
1287 'img_size' => $this->size
,
1288 'img_width' => intval( $this->width
),
1289 'img_height' => intval( $this->height
),
1290 'img_bits' => $this->bits
,
1291 'img_media_type' => $this->media_type
,
1292 'img_major_mime' => $this->major_mime
,
1293 'img_minor_mime' => $this->minor_mime
,
1294 'img_timestamp' => $timestamp,
1295 'img_description' => $comment,
1296 'img_user' => $user->getId(),
1297 'img_user_text' => $user->getName(),
1298 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1299 'img_sha1' => $this->sha1
1304 if ( $dbw->affectedRows() == 0 ) {
1305 if ( $allowTimeKludge ) {
1306 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1307 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1308 array( 'img_name' => $this->getName() ),
1310 array( 'LOCK IN SHARE MODE' ) );
1311 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1312 # Avoid a timestamp that is not newer than the last version
1313 # TODO: the image/oldimage tables should be like page/revision with an ID field
1314 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1315 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1316 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1317 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1321 # (bug 34993) Note: $oldver can be empty here, if the previous
1322 # version of the file was broken. Allow registration of the new
1323 # version to continue anyway, because that's better than having
1324 # an image that's not fixable by user operations.
1327 # Collision, this is an update of a file
1328 # Insert previous contents into oldimage
1329 $dbw->insertSelect( 'oldimage', 'image',
1331 'oi_name' => 'img_name',
1332 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1333 'oi_size' => 'img_size',
1334 'oi_width' => 'img_width',
1335 'oi_height' => 'img_height',
1336 'oi_bits' => 'img_bits',
1337 'oi_timestamp' => 'img_timestamp',
1338 'oi_description' => 'img_description',
1339 'oi_user' => 'img_user',
1340 'oi_user_text' => 'img_user_text',
1341 'oi_metadata' => 'img_metadata',
1342 'oi_media_type' => 'img_media_type',
1343 'oi_major_mime' => 'img_major_mime',
1344 'oi_minor_mime' => 'img_minor_mime',
1345 'oi_sha1' => 'img_sha1'
1347 array( 'img_name' => $this->getName() ),
1351 # Update the current image row
1352 $dbw->update( 'image',
1354 'img_size' => $this->size
,
1355 'img_width' => intval( $this->width
),
1356 'img_height' => intval( $this->height
),
1357 'img_bits' => $this->bits
,
1358 'img_media_type' => $this->media_type
,
1359 'img_major_mime' => $this->major_mime
,
1360 'img_minor_mime' => $this->minor_mime
,
1361 'img_timestamp' => $timestamp,
1362 'img_description' => $comment,
1363 'img_user' => $user->getId(),
1364 'img_user_text' => $user->getName(),
1365 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1366 'img_sha1' => $this->sha1
1368 array( 'img_name' => $this->getName() ),
1372 # This is a new file, so update the image count
1373 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1376 $descTitle = $this->getTitle();
1377 $wikiPage = new WikiFilePage( $descTitle );
1378 $wikiPage->setFile( $this );
1381 $action = $reupload ?
'overwrite' : 'upload';
1383 $logEntry = new ManualLogEntry( 'upload', $action );
1384 $logEntry->setPerformer( $user );
1385 $logEntry->setComment( $comment );
1386 $logEntry->setTarget( $descTitle );
1388 // Allow people using the api to associate log entries with the upload.
1389 // Log has a timestamp, but sometimes different from upload timestamp.
1390 $logEntry->setParameters(
1392 'img_sha1' => $this->sha1
,
1393 'img_timestamp' => $timestamp,
1396 // Note we keep $logId around since during new image
1397 // creation, page doesn't exist yet, so log_page = 0
1398 // but we want it to point to the page we're making,
1399 // so we later modify the log entry.
1400 // For a similar reason, we avoid making an RC entry
1401 // now and wait until the page exists.
1402 $logId = $logEntry->insert();
1404 $exists = $descTitle->exists();
1406 // Page exists, do RC entry now (otherwise we wait for later).
1407 $logEntry->publish( $logId );
1409 wfProfileIn( __METHOD__
. '-edit' );
1412 # Create a null revision
1413 $latest = $descTitle->getLatestRevID();
1414 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1416 $nullRevision = Revision
::newNullRevision(
1418 $descTitle->getArticleID(),
1423 if ( !is_null( $nullRevision ) ) {
1424 $nullRevision->insertOn( $dbw );
1426 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1427 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1431 # Commit the transaction now, in case something goes wrong later
1432 # The most important thing is that files don't get lost, especially archives
1433 # NOTE: once we have support for nested transactions, the commit may be moved
1434 # to after $wikiPage->doEdit has been called.
1435 $dbw->commit( __METHOD__
);
1438 # We shall not saveToCache before the commit since otherwise
1439 # in case of a rollback there is an usable file from memcached
1440 # which in fact doesn't really exist (bug 24978)
1441 $this->saveToCache();
1444 # Invalidate the cache for the description page
1445 $descTitle->invalidateCache();
1446 $descTitle->purgeSquid();
1448 # New file; create the description page.
1449 # There's already a log entry, so don't make a second RC entry
1450 # Squid and file cache for the description page are purged by doEditContent.
1451 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1452 $status = $wikiPage->doEditContent(
1455 EDIT_NEW | EDIT_SUPPRESS_RC
,
1460 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1461 // Now that the page exists, make an RC entry.
1462 $logEntry->publish( $logId );
1463 if ( isset( $status->value
['revision'] ) ) {
1464 $dbw->update( 'logging',
1465 array( 'log_page' => $status->value
['revision']->getPage() ),
1466 array( 'log_id' => $logId ),
1470 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1473 wfProfileOut( __METHOD__
. '-edit' );
1476 # Delete old thumbnails
1477 wfProfileIn( __METHOD__
. '-purge' );
1478 $this->purgeThumbnails();
1479 wfProfileOut( __METHOD__
. '-purge' );
1481 # Remove the old file from the squid cache
1482 SquidUpdate
::purge( array( $this->getURL() ) );
1485 # Hooks, hooks, the magic of hooks...
1486 wfProfileIn( __METHOD__
. '-hooks' );
1487 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1488 wfProfileOut( __METHOD__
. '-hooks' );
1490 # Invalidate cache for all pages using this file
1491 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1492 $update->doUpdate();
1494 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1497 wfProfileOut( __METHOD__
);
1503 * Move or copy a file to its public location. If a file exists at the
1504 * destination, move it to an archive. Returns a FileRepoStatus object with
1505 * the archive name in the "value" member on success.
1507 * The archive name should be passed through to recordUpload for database
1510 * @param string $srcPath Local filesystem path to the source image
1511 * @param int $flags A bitwise combination of:
1512 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1513 * @param array $options Optional additional parameters
1514 * @return FileRepoStatus On success, the value member contains the
1515 * archive name, or an empty string if it was a new file.
1517 function publish( $srcPath, $flags = 0, array $options = array() ) {
1518 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1522 * Move or copy a file to a specified location. Returns a FileRepoStatus
1523 * object with the archive name in the "value" member on success.
1525 * The archive name should be passed through to recordUpload for database
1528 * @param string $srcPath Local filesystem path to the source image
1529 * @param string $dstRel Target relative path
1530 * @param int $flags A bitwise combination of:
1531 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1532 * @param array $options Optional additional parameters
1533 * @return FileRepoStatus On success, the value member contains the
1534 * archive name, or an empty string if it was a new file.
1536 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1537 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1538 return $this->readOnlyFatalStatus();
1541 $this->lock(); // begin
1543 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1544 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1545 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1546 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1548 if ( $status->value
== 'new' ) {
1549 $status->value
= '';
1551 $status->value
= $archiveName;
1554 $this->unlock(); // done
1559 /** getLinksTo inherited */
1560 /** getExifData inherited */
1561 /** isLocal inherited */
1562 /** wasDeleted inherited */
1565 * Move file to the new title
1567 * Move current, old version and all thumbnails
1568 * to the new filename. Old file is deleted.
1570 * Cache purging is done; checks for validity
1571 * and logging are caller's responsibility
1573 * @param Title $target New file name
1574 * @return FileRepoStatus
1576 function move( $target ) {
1577 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1578 return $this->readOnlyFatalStatus();
1581 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1582 $batch = new LocalFileMoveBatch( $this, $target );
1584 $this->lock(); // begin
1585 $batch->addCurrent();
1586 $archiveNames = $batch->addOlds();
1587 $status = $batch->execute();
1588 $this->unlock(); // done
1590 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1592 // Purge the source and target files...
1593 $oldTitleFile = wfLocalFile( $this->title
);
1594 $newTitleFile = wfLocalFile( $target );
1595 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1596 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1597 $this->getRepo()->getMasterDB()->onTransactionIdle(
1598 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1599 $oldTitleFile->purgeEverything();
1600 foreach ( $archiveNames as $archiveName ) {
1601 $oldTitleFile->purgeOldThumbnails( $archiveName );
1603 $newTitleFile->purgeEverything();
1607 if ( $status->isOK() ) {
1608 // Now switch the object
1609 $this->title
= $target;
1610 // Force regeneration of the name and hashpath
1611 unset( $this->name
);
1612 unset( $this->hashPath
);
1619 * Delete all versions of the file.
1621 * Moves the files into an archive directory (or deletes them)
1622 * and removes the database rows.
1624 * Cache purging is done; logging is caller's responsibility.
1626 * @param string $reason
1627 * @param bool $suppress
1628 * @param User|null $user
1629 * @return FileRepoStatus
1631 function delete( $reason, $suppress = false, $user = null ) {
1632 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1633 return $this->readOnlyFatalStatus();
1636 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1638 $this->lock(); // begin
1639 $batch->addCurrent();
1640 # Get old version relative paths
1641 $archiveNames = $batch->addOlds();
1642 $status = $batch->execute();
1643 $this->unlock(); // done
1645 if ( $status->isOK() ) {
1646 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1649 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1650 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1652 $this->getRepo()->getMasterDB()->onTransactionIdle(
1653 function () use ( $file, $archiveNames ) {
1656 $file->purgeEverything();
1657 foreach ( $archiveNames as $archiveName ) {
1658 $file->purgeOldThumbnails( $archiveName );
1661 if ( $wgUseSquid ) {
1663 $purgeUrls = array();
1664 foreach ( $archiveNames as $archiveName ) {
1665 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1667 SquidUpdate
::purge( $purgeUrls );
1676 * Delete an old version of the file.
1678 * Moves the file into an archive directory (or deletes it)
1679 * and removes the database row.
1681 * Cache purging is done; logging is caller's responsibility.
1683 * @param string $archiveName
1684 * @param string $reason
1685 * @param bool $suppress
1686 * @param User|null $user
1687 * @throws MWException Exception on database or file store failure
1688 * @return FileRepoStatus
1690 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1692 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1693 return $this->readOnlyFatalStatus();
1696 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1698 $this->lock(); // begin
1699 $batch->addOld( $archiveName );
1700 $status = $batch->execute();
1701 $this->unlock(); // done
1703 $this->purgeOldThumbnails( $archiveName );
1704 if ( $status->isOK() ) {
1705 $this->purgeDescription();
1706 $this->purgeHistory();
1709 if ( $wgUseSquid ) {
1711 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1718 * Restore all or specified deleted revisions to the given file.
1719 * Permissions and logging are left to the caller.
1721 * May throw database exceptions on error.
1723 * @param array $versions Set of record ids of deleted items to restore,
1724 * or empty to restore all revisions.
1725 * @param bool $unsuppress
1726 * @return FileRepoStatus
1728 function restore( $versions = array(), $unsuppress = false ) {
1729 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1730 return $this->readOnlyFatalStatus();
1733 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1735 $this->lock(); // begin
1739 $batch->addIds( $versions );
1741 $status = $batch->execute();
1742 if ( $status->isGood() ) {
1743 $cleanupStatus = $batch->cleanup();
1744 $cleanupStatus->successCount
= 0;
1745 $cleanupStatus->failCount
= 0;
1746 $status->merge( $cleanupStatus );
1748 $this->unlock(); // done
1753 /** isMultipage inherited */
1754 /** pageCount inherited */
1755 /** scaleHeight inherited */
1756 /** getImageSize inherited */
1759 * Get the URL of the file description page.
1762 function getDescriptionUrl() {
1763 return $this->title
->getLocalURL();
1767 * Get the HTML text of the description page
1768 * This is not used by ImagePage for local files, since (among other things)
1769 * it skips the parser cache.
1771 * @param Language $lang What language to get description in (Optional)
1772 * @return bool|mixed
1774 function getDescriptionText( $lang = null ) {
1775 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1779 $content = $revision->getContent();
1783 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1785 return $pout->getText();
1789 * @param int $audience
1793 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1795 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1797 } elseif ( $audience == self
::FOR_THIS_USER
1798 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1802 return $this->description
;
1807 * @return bool|string
1809 function getTimestamp() {
1812 return $this->timestamp
;
1818 function getSha1() {
1820 // Initialise now if necessary
1821 if ( $this->sha1
== '' && $this->fileExists
) {
1822 $this->lock(); // begin
1824 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1825 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1826 $dbw = $this->repo
->getMasterDB();
1827 $dbw->update( 'image',
1828 array( 'img_sha1' => $this->sha1
),
1829 array( 'img_name' => $this->getName() ),
1831 $this->saveToCache();
1834 $this->unlock(); // done
1841 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1843 function isCacheable() {
1846 // If extra data (metadata) was not loaded then it must have been large
1847 return $this->extraDataLoaded
1848 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1852 * Start a transaction and lock the image for update
1853 * Increments a reference counter if the lock is already held
1854 * @throws MWException Throws an error if the lock was not acquired
1855 * @return bool Whether the file lock owns/spawned the DB transaction
1858 $dbw = $this->repo
->getMasterDB();
1860 if ( !$this->locked
) {
1861 if ( !$dbw->trxLevel() ) {
1862 $dbw->begin( __METHOD__
);
1863 $this->lockedOwnTrx
= true;
1866 // Bug 54736: use simple lock to handle when the file does not exist.
1867 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1868 // Also, that would cause contention on INSERT of similarly named rows.
1869 $backend = $this->getRepo()->getBackend();
1870 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1871 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1872 if ( !$status->isGood() ) {
1873 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1875 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1876 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1880 $this->markVolatile(); // file may change soon
1882 return $this->lockedOwnTrx
;
1886 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1887 * the transaction and thereby releases the image lock.
1890 if ( $this->locked
) {
1892 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1893 $dbw = $this->repo
->getMasterDB();
1894 $dbw->commit( __METHOD__
);
1895 $this->lockedOwnTrx
= false;
1901 * Mark a file as about to be changed
1903 * This sets a cache key that alters master/slave DB loading behavior
1905 * @return bool Success
1907 protected function markVolatile() {
1910 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1912 $this->lastMarkedVolatile
= time();
1913 return $wgMemc->set( $key, $this->lastMarkedVolatile
, self
::VOLATILE_TTL
);
1920 * Check if a file is about to be changed or has been changed recently
1922 * @see LocalFile::isVolatile()
1923 * @return bool Whether the file is volatile
1925 protected function isVolatile() {
1928 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1930 // repo unavailable; bail.
1934 if ( $this->lastMarkedVolatile
=== 0 ) {
1935 $this->lastMarkedVolatile
= $wgMemc->get( $key ) ?
: 0;
1938 $volatileDuration = time() - $this->lastMarkedVolatile
;
1939 return $volatileDuration <= self
::VOLATILE_TTL
;
1943 * Roll back the DB transaction and mark the image unlocked
1945 function unlockAndRollback() {
1946 $this->locked
= false;
1947 $dbw = $this->repo
->getMasterDB();
1948 $dbw->rollback( __METHOD__
);
1949 $this->lockedOwnTrx
= false;
1955 protected function readOnlyFatalStatus() {
1956 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1957 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1961 * Clean up any dangling locks
1963 function __destruct() {
1966 } // LocalFile class
1968 # ------------------------------------------------------------------------------
1971 * Helper class for file deletion
1972 * @ingroup FileAbstraction
1974 class LocalFileDeleteBatch
{
1975 /** @var LocalFile */
1982 private $srcRels = array();
1985 private $archiveUrls = array();
1987 /** @var array Items to be processed in the deletion batch */
1988 private $deletionBatch;
1990 /** @var bool Wether to suppress all suppressable fields when deleting */
1993 /** @var FileRepoStatus */
2001 * @param string $reason
2002 * @param bool $suppress
2003 * @param User|null $user
2005 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2006 $this->file
= $file;
2007 $this->reason
= $reason;
2008 $this->suppress
= $suppress;
2010 $this->user
= $user;
2013 $this->user
= $wgUser;
2015 $this->status
= $file->repo
->newGood();
2018 function addCurrent() {
2019 $this->srcRels
['.'] = $this->file
->getRel();
2023 * @param string $oldName
2025 function addOld( $oldName ) {
2026 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2027 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2031 * Add the old versions of the image to the batch
2032 * @return array List of archive names from old versions
2034 function addOlds() {
2035 $archiveNames = array();
2037 $dbw = $this->file
->repo
->getMasterDB();
2038 $result = $dbw->select( 'oldimage',
2039 array( 'oi_archive_name' ),
2040 array( 'oi_name' => $this->file
->getName() ),
2044 foreach ( $result as $row ) {
2045 $this->addOld( $row->oi_archive_name
);
2046 $archiveNames[] = $row->oi_archive_name
;
2049 return $archiveNames;
2055 function getOldRels() {
2056 if ( !isset( $this->srcRels
['.'] ) ) {
2057 $oldRels =& $this->srcRels
;
2058 $deleteCurrent = false;
2060 $oldRels = $this->srcRels
;
2061 unset( $oldRels['.'] );
2062 $deleteCurrent = true;
2065 return array( $oldRels, $deleteCurrent );
2071 protected function getHashes() {
2073 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2075 if ( $deleteCurrent ) {
2076 $hashes['.'] = $this->file
->getSha1();
2079 if ( count( $oldRels ) ) {
2080 $dbw = $this->file
->repo
->getMasterDB();
2081 $res = $dbw->select(
2083 array( 'oi_archive_name', 'oi_sha1' ),
2084 array( 'oi_archive_name' => array_keys( $oldRels ),
2085 'oi_name' => $this->file
->getName() ), // performance
2089 foreach ( $res as $row ) {
2090 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2091 // Get the hash from the file
2092 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2093 $props = $this->file
->repo
->getFileProps( $oldUrl );
2095 if ( $props['fileExists'] ) {
2096 // Upgrade the oldimage row
2097 $dbw->update( 'oldimage',
2098 array( 'oi_sha1' => $props['sha1'] ),
2099 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2101 $hashes[$row->oi_archive_name
] = $props['sha1'];
2103 $hashes[$row->oi_archive_name
] = false;
2106 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2111 $missing = array_diff_key( $this->srcRels
, $hashes );
2113 foreach ( $missing as $name => $rel ) {
2114 $this->status
->error( 'filedelete-old-unregistered', $name );
2117 foreach ( $hashes as $name => $hash ) {
2119 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2120 unset( $hashes[$name] );
2127 function doDBInserts() {
2128 $dbw = $this->file
->repo
->getMasterDB();
2129 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2130 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2131 $encReason = $dbw->addQuotes( $this->reason
);
2132 $encGroup = $dbw->addQuotes( 'deleted' );
2133 $ext = $this->file
->getExtension();
2134 $dotExt = $ext === '' ?
'' : ".$ext";
2135 $encExt = $dbw->addQuotes( $dotExt );
2136 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2138 // Bitfields to further suppress the content
2139 if ( $this->suppress
) {
2141 // This should be 15...
2142 $bitfield |
= Revision
::DELETED_TEXT
;
2143 $bitfield |
= Revision
::DELETED_COMMENT
;
2144 $bitfield |
= Revision
::DELETED_USER
;
2145 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2147 $bitfield = 'oi_deleted';
2150 if ( $deleteCurrent ) {
2151 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2152 $where = array( 'img_name' => $this->file
->getName() );
2153 $dbw->insertSelect( 'filearchive', 'image',
2155 'fa_storage_group' => $encGroup,
2156 'fa_storage_key' => $dbw->conditional(
2157 array( 'img_sha1' => '' ),
2158 $dbw->addQuotes( '' ),
2161 'fa_deleted_user' => $encUserId,
2162 'fa_deleted_timestamp' => $encTimestamp,
2163 'fa_deleted_reason' => $encReason,
2164 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2166 'fa_name' => 'img_name',
2167 'fa_archive_name' => 'NULL',
2168 'fa_size' => 'img_size',
2169 'fa_width' => 'img_width',
2170 'fa_height' => 'img_height',
2171 'fa_metadata' => 'img_metadata',
2172 'fa_bits' => 'img_bits',
2173 'fa_media_type' => 'img_media_type',
2174 'fa_major_mime' => 'img_major_mime',
2175 'fa_minor_mime' => 'img_minor_mime',
2176 'fa_description' => 'img_description',
2177 'fa_user' => 'img_user',
2178 'fa_user_text' => 'img_user_text',
2179 'fa_timestamp' => 'img_timestamp',
2180 'fa_sha1' => 'img_sha1',
2181 ), $where, __METHOD__
);
2184 if ( count( $oldRels ) ) {
2185 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2187 'oi_name' => $this->file
->getName(),
2188 'oi_archive_name' => array_keys( $oldRels ) );
2189 $dbw->insertSelect( 'filearchive', 'oldimage',
2191 'fa_storage_group' => $encGroup,
2192 'fa_storage_key' => $dbw->conditional(
2193 array( 'oi_sha1' => '' ),
2194 $dbw->addQuotes( '' ),
2197 'fa_deleted_user' => $encUserId,
2198 'fa_deleted_timestamp' => $encTimestamp,
2199 'fa_deleted_reason' => $encReason,
2200 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2202 'fa_name' => 'oi_name',
2203 'fa_archive_name' => 'oi_archive_name',
2204 'fa_size' => 'oi_size',
2205 'fa_width' => 'oi_width',
2206 'fa_height' => 'oi_height',
2207 'fa_metadata' => 'oi_metadata',
2208 'fa_bits' => 'oi_bits',
2209 'fa_media_type' => 'oi_media_type',
2210 'fa_major_mime' => 'oi_major_mime',
2211 'fa_minor_mime' => 'oi_minor_mime',
2212 'fa_description' => 'oi_description',
2213 'fa_user' => 'oi_user',
2214 'fa_user_text' => 'oi_user_text',
2215 'fa_timestamp' => 'oi_timestamp',
2216 'fa_sha1' => 'oi_sha1',
2217 ), $where, __METHOD__
);
2221 function doDBDeletes() {
2222 $dbw = $this->file
->repo
->getMasterDB();
2223 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2225 if ( count( $oldRels ) ) {
2226 $dbw->delete( 'oldimage',
2228 'oi_name' => $this->file
->getName(),
2229 'oi_archive_name' => array_keys( $oldRels )
2233 if ( $deleteCurrent ) {
2234 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2239 * Run the transaction
2240 * @return FileRepoStatus
2242 function execute() {
2243 wfProfileIn( __METHOD__
);
2245 $this->file
->lock();
2246 // Leave private files alone
2247 $privateFiles = array();
2248 list( $oldRels, ) = $this->getOldRels();
2249 $dbw = $this->file
->repo
->getMasterDB();
2251 if ( !empty( $oldRels ) ) {
2252 $res = $dbw->select( 'oldimage',
2253 array( 'oi_archive_name' ),
2254 array( 'oi_name' => $this->file
->getName(),
2255 'oi_archive_name' => array_keys( $oldRels ),
2256 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2259 foreach ( $res as $row ) {
2260 $privateFiles[$row->oi_archive_name
] = 1;
2263 // Prepare deletion batch
2264 $hashes = $this->getHashes();
2265 $this->deletionBatch
= array();
2266 $ext = $this->file
->getExtension();
2267 $dotExt = $ext === '' ?
'' : ".$ext";
2269 foreach ( $this->srcRels
as $name => $srcRel ) {
2270 // Skip files that have no hash (missing source).
2271 // Keep private files where they are.
2272 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2273 $hash = $hashes[$name];
2274 $key = $hash . $dotExt;
2275 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2276 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2280 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2281 // We acquire this lock by running the inserts now, before the file operations.
2283 // This potentially has poor lock contention characteristics -- an alternative
2284 // scheme would be to insert stub filearchive entries with no fa_name and commit
2285 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2286 $this->doDBInserts();
2288 // Removes non-existent file from the batch, so we don't get errors.
2289 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2290 if ( !$checkStatus->isGood() ) {
2291 $this->status
->merge( $checkStatus );
2292 return $this->status
;
2294 $this->deletionBatch
= $checkStatus->value
;
2296 // Execute the file deletion batch
2297 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2299 if ( !$status->isGood() ) {
2300 $this->status
->merge( $status );
2303 if ( !$this->status
->isOK() ) {
2304 // Critical file deletion error
2305 // Roll back inserts, release lock and abort
2306 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2307 $this->file
->unlockAndRollback();
2308 wfProfileOut( __METHOD__
);
2310 return $this->status
;
2313 // Delete image/oldimage rows
2314 $this->doDBDeletes();
2316 // Commit and return
2317 $this->file
->unlock();
2318 wfProfileOut( __METHOD__
);
2320 return $this->status
;
2324 * Removes non-existent files from a deletion batch.
2325 * @param array $batch
2328 function removeNonexistentFiles( $batch ) {
2329 $files = $newBatch = array();
2331 foreach ( $batch as $batchItem ) {
2332 list( $src, ) = $batchItem;
2333 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2336 $result = $this->file
->repo
->fileExistsBatch( $files );
2337 if ( in_array( null, $result, true ) ) {
2338 return Status
::newFatal( 'backend-fail-internal',
2339 $this->file
->repo
->getBackend()->getName() );
2342 foreach ( $batch as $batchItem ) {
2343 if ( $result[$batchItem[0]] ) {
2344 $newBatch[] = $batchItem;
2348 return Status
::newGood( $newBatch );
2352 # ------------------------------------------------------------------------------
2355 * Helper class for file undeletion
2356 * @ingroup FileAbstraction
2358 class LocalFileRestoreBatch
{
2359 /** @var LocalFile */
2362 /** @var array List of file IDs to restore */
2363 private $cleanupBatch;
2365 /** @var array List of file IDs to restore */
2368 /** @var bool Add all revisions of the file */
2371 /** @var bool Wether to remove all settings for suppressed fields */
2372 private $unsuppress = false;
2376 * @param bool $unsuppress
2378 function __construct( File
$file, $unsuppress = false ) {
2379 $this->file
= $file;
2380 $this->cleanupBatch
= $this->ids
= array();
2381 $this->ids
= array();
2382 $this->unsuppress
= $unsuppress;
2389 function addId( $fa_id ) {
2390 $this->ids
[] = $fa_id;
2394 * Add a whole lot of files by ID
2397 function addIds( $ids ) {
2398 $this->ids
= array_merge( $this->ids
, $ids );
2402 * Add all revisions of the file
2409 * Run the transaction, except the cleanup batch.
2410 * The cleanup batch should be run in a separate transaction, because it locks different
2411 * rows and there's no need to keep the image row locked while it's acquiring those locks
2412 * The caller may have its own transaction open.
2413 * So we save the batch and let the caller call cleanup()
2414 * @return FileRepoStatus
2416 function execute() {
2419 if ( !$this->all
&& !$this->ids
) {
2421 return $this->file
->repo
->newGood();
2424 $lockOwnsTrx = $this->file
->lock();
2426 $dbw = $this->file
->repo
->getMasterDB();
2427 $status = $this->file
->repo
->newGood();
2429 $exists = (bool)$dbw->selectField( 'image', '1',
2430 array( 'img_name' => $this->file
->getName() ),
2432 // The lock() should already prevents changes, but this still may need
2433 // to bypass any transaction snapshot. However, if lock() started the
2434 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2435 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2438 // Fetch all or selected archived revisions for the file,
2439 // sorted from the most recent to the oldest.
2440 $conditions = array( 'fa_name' => $this->file
->getName() );
2442 if ( !$this->all
) {
2443 $conditions['fa_id'] = $this->ids
;
2446 $result = $dbw->select(
2448 ArchivedFile
::selectFields(),
2451 array( 'ORDER BY' => 'fa_timestamp DESC' )
2454 $idsPresent = array();
2455 $storeBatch = array();
2456 $insertBatch = array();
2457 $insertCurrent = false;
2458 $deleteIds = array();
2460 $archiveNames = array();
2462 foreach ( $result as $row ) {
2463 $idsPresent[] = $row->fa_id
;
2465 if ( $row->fa_name
!= $this->file
->getName() ) {
2466 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2467 $status->failCount++
;
2471 if ( $row->fa_storage_key
== '' ) {
2472 // Revision was missing pre-deletion
2473 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2474 $status->failCount++
;
2478 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2479 $row->fa_storage_key
;
2480 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2482 if ( isset( $row->fa_sha1
) ) {
2483 $sha1 = $row->fa_sha1
;
2485 // old row, populate from key
2486 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2490 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2491 $sha1 = substr( $sha1, 1 );
2494 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2495 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2496 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2497 ||
is_null( $row->fa_metadata
)
2499 // Refresh our metadata
2500 // Required for a new current revision; nice for older ones too. :)
2501 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2504 'minor_mime' => $row->fa_minor_mime
,
2505 'major_mime' => $row->fa_major_mime
,
2506 'media_type' => $row->fa_media_type
,
2507 'metadata' => $row->fa_metadata
2511 if ( $first && !$exists ) {
2512 // This revision will be published as the new current version
2513 $destRel = $this->file
->getRel();
2514 $insertCurrent = array(
2515 'img_name' => $row->fa_name
,
2516 'img_size' => $row->fa_size
,
2517 'img_width' => $row->fa_width
,
2518 'img_height' => $row->fa_height
,
2519 'img_metadata' => $props['metadata'],
2520 'img_bits' => $row->fa_bits
,
2521 'img_media_type' => $props['media_type'],
2522 'img_major_mime' => $props['major_mime'],
2523 'img_minor_mime' => $props['minor_mime'],
2524 'img_description' => $row->fa_description
,
2525 'img_user' => $row->fa_user
,
2526 'img_user_text' => $row->fa_user_text
,
2527 'img_timestamp' => $row->fa_timestamp
,
2531 // The live (current) version cannot be hidden!
2532 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2533 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2534 $this->cleanupBatch
[] = $row->fa_storage_key
;
2537 $archiveName = $row->fa_archive_name
;
2539 if ( $archiveName == '' ) {
2540 // This was originally a current version; we
2541 // have to devise a new archive name for it.
2542 // Format is <timestamp of archiving>!<name>
2543 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2546 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2548 } while ( isset( $archiveNames[$archiveName] ) );
2551 $archiveNames[$archiveName] = true;
2552 $destRel = $this->file
->getArchiveRel( $archiveName );
2553 $insertBatch[] = array(
2554 'oi_name' => $row->fa_name
,
2555 'oi_archive_name' => $archiveName,
2556 'oi_size' => $row->fa_size
,
2557 'oi_width' => $row->fa_width
,
2558 'oi_height' => $row->fa_height
,
2559 'oi_bits' => $row->fa_bits
,
2560 'oi_description' => $row->fa_description
,
2561 'oi_user' => $row->fa_user
,
2562 'oi_user_text' => $row->fa_user_text
,
2563 'oi_timestamp' => $row->fa_timestamp
,
2564 'oi_metadata' => $props['metadata'],
2565 'oi_media_type' => $props['media_type'],
2566 'oi_major_mime' => $props['major_mime'],
2567 'oi_minor_mime' => $props['minor_mime'],
2568 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2569 'oi_sha1' => $sha1 );
2572 $deleteIds[] = $row->fa_id
;
2574 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2575 // private files can stay where they are
2576 $status->successCount++
;
2578 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2579 $this->cleanupBatch
[] = $row->fa_storage_key
;
2587 // Add a warning to the status object for missing IDs
2588 $missingIds = array_diff( $this->ids
, $idsPresent );
2590 foreach ( $missingIds as $id ) {
2591 $status->error( 'undelete-missing-filearchive', $id );
2594 // Remove missing files from batch, so we don't get errors when undeleting them
2595 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2596 if ( !$checkStatus->isGood() ) {
2597 $status->merge( $checkStatus );
2600 $storeBatch = $checkStatus->value
;
2602 // Run the store batch
2603 // Use the OVERWRITE_SAME flag to smooth over a common error
2604 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2605 $status->merge( $storeStatus );
2607 if ( !$status->isGood() ) {
2608 // Even if some files could be copied, fail entirely as that is the
2609 // easiest thing to do without data loss
2610 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2611 $status->ok
= false;
2612 $this->file
->unlock();
2617 // Run the DB updates
2618 // Because we have locked the image row, key conflicts should be rare.
2619 // If they do occur, we can roll back the transaction at this time with
2620 // no data loss, but leaving unregistered files scattered throughout the
2622 // This is not ideal, which is why it's important to lock the image row.
2623 if ( $insertCurrent ) {
2624 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2627 if ( $insertBatch ) {
2628 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2632 $dbw->delete( 'filearchive',
2633 array( 'fa_id' => $deleteIds ),
2637 // If store batch is empty (all files are missing), deletion is to be considered successful
2638 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2640 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2642 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2644 $this->file
->purgeEverything();
2646 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2647 $this->file
->purgeDescription();
2648 $this->file
->purgeHistory();
2652 $this->file
->unlock();
2658 * Removes non-existent files from a store batch.
2659 * @param array $triplets
2662 function removeNonexistentFiles( $triplets ) {
2663 $files = $filteredTriplets = array();
2664 foreach ( $triplets as $file ) {
2665 $files[$file[0]] = $file[0];
2668 $result = $this->file
->repo
->fileExistsBatch( $files );
2669 if ( in_array( null, $result, true ) ) {
2670 return Status
::newFatal( 'backend-fail-internal',
2671 $this->file
->repo
->getBackend()->getName() );
2674 foreach ( $triplets as $file ) {
2675 if ( $result[$file[0]] ) {
2676 $filteredTriplets[] = $file;
2680 return Status
::newGood( $filteredTriplets );
2684 * Removes non-existent files from a cleanup batch.
2685 * @param array $batch
2688 function removeNonexistentFromCleanup( $batch ) {
2689 $files = $newBatch = array();
2690 $repo = $this->file
->repo
;
2692 foreach ( $batch as $file ) {
2693 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2694 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2697 $result = $repo->fileExistsBatch( $files );
2699 foreach ( $batch as $file ) {
2700 if ( $result[$file] ) {
2701 $newBatch[] = $file;
2709 * Delete unused files in the deleted zone.
2710 * This should be called from outside the transaction in which execute() was called.
2711 * @return FileRepoStatus
2713 function cleanup() {
2714 if ( !$this->cleanupBatch
) {
2715 return $this->file
->repo
->newGood();
2718 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2720 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2726 * Cleanup a failed batch. The batch was only partially successful, so
2727 * rollback by removing all items that were succesfully copied.
2729 * @param Status $storeStatus
2730 * @param array $storeBatch
2732 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2733 $cleanupBatch = array();
2735 foreach ( $storeStatus->success
as $i => $success ) {
2736 // Check if this item of the batch was successfully copied
2738 // Item was successfully copied and needs to be removed again
2739 // Extract ($dstZone, $dstRel) from the batch
2740 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2743 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2747 # ------------------------------------------------------------------------------
2750 * Helper class for file movement
2751 * @ingroup FileAbstraction
2753 class LocalFileMoveBatch
{
2754 /** @var LocalFile */
2764 protected $oldCount;
2768 /** @var DatabaseBase */
2773 * @param Title $target
2775 function __construct( File
$file, Title
$target ) {
2776 $this->file
= $file;
2777 $this->target
= $target;
2778 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2779 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2780 $this->oldName
= $this->file
->getName();
2781 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2782 $this->oldRel
= $this->oldHash
. $this->oldName
;
2783 $this->newRel
= $this->newHash
. $this->newName
;
2784 $this->db
= $file->getRepo()->getMasterDb();
2788 * Add the current image to the batch
2790 function addCurrent() {
2791 $this->cur
= array( $this->oldRel
, $this->newRel
);
2795 * Add the old versions of the image to the batch
2796 * @return array List of archive names from old versions
2798 function addOlds() {
2799 $archiveBase = 'archive';
2800 $this->olds
= array();
2801 $this->oldCount
= 0;
2802 $archiveNames = array();
2804 $result = $this->db
->select( 'oldimage',
2805 array( 'oi_archive_name', 'oi_deleted' ),
2806 array( 'oi_name' => $this->oldName
),
2808 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2811 foreach ( $result as $row ) {
2812 $archiveNames[] = $row->oi_archive_name
;
2813 $oldName = $row->oi_archive_name
;
2814 $bits = explode( '!', $oldName, 2 );
2816 if ( count( $bits ) != 2 ) {
2817 wfDebug( "Old file name missing !: '$oldName' \n" );
2821 list( $timestamp, $filename ) = $bits;
2823 if ( $this->oldName
!= $filename ) {
2824 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2830 // Do we want to add those to oldCount?
2831 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2835 $this->olds
[] = array(
2836 "{$archiveBase}/{$this->oldHash}{$oldName}",
2837 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2841 return $archiveNames;
2846 * @return FileRepoStatus
2848 function execute() {
2849 $repo = $this->file
->repo
;
2850 $status = $repo->newGood();
2852 $triplets = $this->getMoveTriplets();
2853 $checkStatus = $this->removeNonexistentFiles( $triplets );
2854 if ( !$checkStatus->isGood() ) {
2855 $status->merge( $checkStatus );
2858 $triplets = $checkStatus->value
;
2859 $destFile = wfLocalFile( $this->target
);
2861 $this->file
->lock(); // begin
2862 $destFile->lock(); // quickly fail if destination is not available
2863 // Rename the file versions metadata in the DB.
2864 // This implicitly locks the destination file, which avoids race conditions.
2865 // If we moved the files from A -> C before DB updates, another process could
2866 // move files from B -> C at this point, causing storeBatch() to fail and thus
2867 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2868 $statusDb = $this->doDBUpdates();
2869 if ( !$statusDb->isGood() ) {
2870 $destFile->unlock();
2871 $this->file
->unlockAndRollback();
2872 $statusDb->ok
= false;
2876 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2877 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2879 // Copy the files into their new location.
2880 // If a prior process fataled copying or cleaning up files we tolerate any
2881 // of the existing files if they are identical to the ones being stored.
2882 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2883 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2884 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2885 if ( !$statusMove->isGood() ) {
2886 // Delete any files copied over (while the destination is still locked)
2887 $this->cleanupTarget( $triplets );
2888 $destFile->unlock();
2889 $this->file
->unlockAndRollback(); // unlocks the destination
2890 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2891 $statusMove->ok
= false;
2895 $destFile->unlock();
2896 $this->file
->unlock(); // done
2898 // Everything went ok, remove the source files
2899 $this->cleanupSource( $triplets );
2901 $status->merge( $statusDb );
2902 $status->merge( $statusMove );
2908 * Do the database updates and return a new FileRepoStatus indicating how
2909 * many rows where updated.
2911 * @return FileRepoStatus
2913 function doDBUpdates() {
2914 $repo = $this->file
->repo
;
2915 $status = $repo->newGood();
2918 // Update current image
2921 array( 'img_name' => $this->newName
),
2922 array( 'img_name' => $this->oldName
),
2926 if ( $dbw->affectedRows() ) {
2927 $status->successCount++
;
2929 $status->failCount++
;
2930 $status->fatal( 'imageinvalidfilename' );
2935 // Update old images
2939 'oi_name' => $this->newName
,
2940 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2941 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2943 array( 'oi_name' => $this->oldName
),
2947 $affected = $dbw->affectedRows();
2948 $total = $this->oldCount
;
2949 $status->successCount +
= $affected;
2950 // Bug 34934: $total is based on files that actually exist.
2951 // There may be more DB rows than such files, in which case $affected
2952 // can be greater than $total. We use max() to avoid negatives here.
2953 $status->failCount +
= max( 0, $total - $affected );
2954 if ( $status->failCount
) {
2955 $status->error( 'imageinvalidfilename' );
2962 * Generate triplets for FileRepo::storeBatch().
2965 function getMoveTriplets() {
2966 $moves = array_merge( array( $this->cur
), $this->olds
);
2967 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2969 foreach ( $moves as $move ) {
2970 // $move: (oldRelativePath, newRelativePath)
2971 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2972 $triplets[] = array( $srcUrl, 'public', $move[1] );
2975 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2983 * Removes non-existent files from move batch.
2984 * @param array $triplets
2987 function removeNonexistentFiles( $triplets ) {
2990 foreach ( $triplets as $file ) {
2991 $files[$file[0]] = $file[0];
2994 $result = $this->file
->repo
->fileExistsBatch( $files );
2995 if ( in_array( null, $result, true ) ) {
2996 return Status
::newFatal( 'backend-fail-internal',
2997 $this->file
->repo
->getBackend()->getName() );
3000 $filteredTriplets = array();
3001 foreach ( $triplets as $file ) {
3002 if ( $result[$file[0]] ) {
3003 $filteredTriplets[] = $file;
3005 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3009 return Status
::newGood( $filteredTriplets );
3013 * Cleanup a partially moved array of triplets by deleting the target
3014 * files. Called if something went wrong half way.
3015 * @param array $triplets
3017 function cleanupTarget( $triplets ) {
3018 // Create dest pairs from the triplets
3020 foreach ( $triplets as $triplet ) {
3021 // $triplet: (old source virtual URL, dst zone, dest rel)
3022 $pairs[] = array( $triplet[1], $triplet[2] );
3025 $this->file
->repo
->cleanupBatch( $pairs );
3029 * Cleanup a fully moved array of triplets by deleting the source files.
3030 * Called at the end of the move process if everything else went ok.
3031 * @param array $triplets
3033 function cleanupSource( $triplets ) {
3034 // Create source file names from the triplets
3036 foreach ( $triplets as $triplet ) {
3037 $files[] = $triplet[0];
3040 $this->file
->repo
->cleanupBatch( $files );