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 $this->fileExists
= $cachedValues['fileExists'];
260 if ( $this->fileExists
) {
261 $this->setProps( $cachedValues );
263 $this->dataLoaded
= true;
264 $this->extraDataLoaded
= true;
265 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
266 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
270 if ( $this->dataLoaded
) {
271 wfIncrStats( 'image_cache.hit' );
273 wfIncrStats( 'image_cache.miss' );
276 return $this->dataLoaded
;
280 * Save the file metadata to memcached
282 function saveToCache() {
285 $key = $this->getCacheKey();
290 $fields = $this->getCacheFields( '' );
291 $cacheVal = array( 'version' => MW_FILE_VERSION
);
292 $cacheVal['fileExists'] = $this->fileExists
;
294 if ( $this->fileExists
) {
295 foreach ( $fields as $field ) {
296 $cacheVal[$field] = $this->$field;
300 // Strip off excessive entries from the subset of fields that can become large.
301 // If the cache value gets to large it will not fit in memcached and nothing will
302 // get cached at all, causing master queries for any file access.
303 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
304 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
305 unset( $cacheVal[$field] ); // don't let the value get too big
309 // Cache presence for 1 week and negatives for 1 day
310 $ttl = $this->fileExists ?
86400 * 7 : 86400;
311 $opts = Database
::getCacheSetOptions( $this->repo
->getSlaveDB() );
312 ObjectCache
::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
316 * Purge the file object/metadata cache
318 public function invalidateCache() {
319 $key = $this->getCacheKey();
324 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
325 ObjectCache
::getMainWANInstance()->delete( $key );
330 * Load metadata from the file itself
332 function loadFromFile() {
333 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
334 $this->setProps( $props );
338 * @param string $prefix
341 function getCacheFields( $prefix = 'img_' ) {
342 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
343 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
344 'user_text', 'description' );
345 static $results = array();
347 if ( $prefix == '' ) {
351 if ( !isset( $results[$prefix] ) ) {
352 $prefixedFields = array();
353 foreach ( $fields as $field ) {
354 $prefixedFields[] = $prefix . $field;
356 $results[$prefix] = $prefixedFields;
359 return $results[$prefix];
363 * @param string $prefix
366 function getLazyCacheFields( $prefix = 'img_' ) {
367 static $fields = array( 'metadata' );
368 static $results = array();
370 if ( $prefix == '' ) {
374 if ( !isset( $results[$prefix] ) ) {
375 $prefixedFields = array();
376 foreach ( $fields as $field ) {
377 $prefixedFields[] = $prefix . $field;
379 $results[$prefix] = $prefixedFields;
382 return $results[$prefix];
386 * Load file metadata from the DB
389 function loadFromDB( $flags = 0 ) {
390 $fname = get_class( $this ) . '::' . __FUNCTION__
;
392 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
393 $this->dataLoaded
= true;
394 $this->extraDataLoaded
= true;
396 $dbr = ( $flags & self
::READ_LATEST
)
397 ?
$this->repo
->getMasterDB()
398 : $this->repo
->getSlaveDB();
400 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
401 array( 'img_name' => $this->getName() ), $fname );
404 $this->loadFromRow( $row );
406 $this->fileExists
= false;
411 * Load lazy file metadata from the DB.
412 * This covers fields that are sometimes not cached.
414 protected function loadExtraFromDB() {
415 $fname = get_class( $this ) . '::' . __FUNCTION__
;
417 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
418 $this->extraDataLoaded
= true;
420 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
422 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
426 foreach ( $fieldMap as $name => $value ) {
427 $this->$name = $value;
430 throw new MWException( "Could not find data for image '{$this->getName()}'." );
435 * @param IDatabase $dbr
436 * @param string $fname
439 private function loadFieldsWithTimestamp( $dbr, $fname ) {
442 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
443 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
446 $fieldMap = $this->unprefixRow( $row, 'img_' );
448 # File may have been uploaded over in the meantime; check the old versions
449 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
450 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
453 $fieldMap = $this->unprefixRow( $row, 'oi_' );
461 * @param array|object $row
462 * @param string $prefix
463 * @throws MWException
466 protected function unprefixRow( $row, $prefix = 'img_' ) {
467 $array = (array)$row;
468 $prefixLength = strlen( $prefix );
470 // Sanity check prefix once
471 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
472 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
476 foreach ( $array as $name => $value ) {
477 $decoded[substr( $name, $prefixLength )] = $value;
484 * Decode a row from the database (either object or array) to an array
485 * with timestamps and MIME types decoded, and the field prefix removed.
487 * @param string $prefix
488 * @throws MWException
491 function decodeRow( $row, $prefix = 'img_' ) {
492 $decoded = $this->unprefixRow( $row, $prefix );
494 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
496 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
498 if ( empty( $decoded['major_mime'] ) ) {
499 $decoded['mime'] = 'unknown/unknown';
501 if ( !$decoded['minor_mime'] ) {
502 $decoded['minor_mime'] = 'unknown';
504 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
507 // Trim zero padding from char/binary field
508 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
510 // Normalize some fields to integer type, per their database definition.
511 // Use unary + so that overflows will be upgraded to double instead of
512 // being trucated as with intval(). This is important to allow >2GB
513 // files on 32-bit systems.
514 foreach ( array( 'size', 'width', 'height', 'bits' ) as $field ) {
515 $decoded[$field] = +
$decoded[$field];
522 * Load file metadata from a DB result row
525 * @param string $prefix
527 function loadFromRow( $row, $prefix = 'img_' ) {
528 $this->dataLoaded
= true;
529 $this->extraDataLoaded
= true;
531 $array = $this->decodeRow( $row, $prefix );
533 foreach ( $array as $name => $value ) {
534 $this->$name = $value;
537 $this->fileExists
= true;
538 $this->maybeUpgradeRow();
542 * Load file metadata from cache or DB, unless already loaded
545 function load( $flags = 0 ) {
546 if ( !$this->dataLoaded
) {
547 if ( ( $flags & self
::READ_LATEST
) ||
!$this->loadFromCache() ) {
548 $this->loadFromDB( $flags );
549 $this->saveToCache();
551 $this->dataLoaded
= true;
553 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
554 // @note: loads on name/timestamp to reduce race condition problems
555 $this->loadExtraFromDB();
560 * Upgrade a row if it needs it
562 function maybeUpgradeRow() {
563 global $wgUpdateCompatibleMetadata;
564 if ( wfReadOnly() ) {
568 if ( is_null( $this->media_type
) ||
569 $this->mime
== 'image/svg'
572 $this->upgraded
= true;
574 $handler = $this->getHandler();
576 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
577 if ( $validity === MediaHandler
::METADATA_BAD
578 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
581 $this->upgraded
= true;
587 function getUpgraded() {
588 return $this->upgraded
;
592 * Fix assorted version-related problems with the image row by reloading it from the file
594 function upgradeRow() {
596 $this->lock(); // begin
598 $this->loadFromFile();
600 # Don't destroy file info of missing files
601 if ( !$this->fileExists
) {
603 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
608 $dbw = $this->repo
->getMasterDB();
609 list( $major, $minor ) = self
::splitMime( $this->mime
);
611 if ( wfReadOnly() ) {
616 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
618 $dbw->update( 'image',
620 'img_size' => $this->size
, // sanity
621 'img_width' => $this->width
,
622 'img_height' => $this->height
,
623 'img_bits' => $this->bits
,
624 'img_media_type' => $this->media_type
,
625 'img_major_mime' => $major,
626 'img_minor_mime' => $minor,
627 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
628 'img_sha1' => $this->sha1
,
630 array( 'img_name' => $this->getName() ),
634 $this->invalidateCache();
636 $this->unlock(); // done
641 * Set properties in this object to be equal to those given in the
642 * associative array $info. Only cacheable fields can be set.
643 * All fields *must* be set in $info except for getLazyCacheFields().
645 * If 'mime' is given, it will be split into major_mime/minor_mime.
646 * If major_mime/minor_mime are given, $this->mime will also be set.
650 function setProps( $info ) {
651 $this->dataLoaded
= true;
652 $fields = $this->getCacheFields( '' );
653 $fields[] = 'fileExists';
655 foreach ( $fields as $field ) {
656 if ( isset( $info[$field] ) ) {
657 $this->$field = $info[$field];
661 // Fix up mime fields
662 if ( isset( $info['major_mime'] ) ) {
663 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
664 } elseif ( isset( $info['mime'] ) ) {
665 $this->mime
= $info['mime'];
666 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
670 /** splitMime inherited */
671 /** getName inherited */
672 /** getTitle inherited */
673 /** getURL inherited */
674 /** getViewURL inherited */
675 /** getPath inherited */
676 /** isVisible inherited */
681 function isMissing() {
682 if ( $this->missing
=== null ) {
683 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
684 $this->missing
= !$fileExists;
687 return $this->missing
;
691 * Return the width of the image
696 public function getWidth( $page = 1 ) {
699 if ( $this->isMultipage() ) {
700 $handler = $this->getHandler();
704 $dim = $handler->getPageDimensions( $this, $page );
706 return $dim['width'];
708 // For non-paged media, the false goes through an
709 // intval, turning failure into 0, so do same here.
718 * Return the height of the image
723 public function getHeight( $page = 1 ) {
726 if ( $this->isMultipage() ) {
727 $handler = $this->getHandler();
731 $dim = $handler->getPageDimensions( $this, $page );
733 return $dim['height'];
735 // For non-paged media, the false goes through an
736 // intval, turning failure into 0, so do same here.
740 return $this->height
;
745 * Returns ID or name of user who uploaded the file
747 * @param string $type 'text' or 'id'
750 function getUser( $type = 'text' ) {
753 if ( $type == 'text' ) {
754 return $this->user_text
;
755 } elseif ( $type == 'id' ) {
756 return (int)$this->user
;
761 * Get handler-specific metadata
764 function getMetadata() {
765 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
766 return $this->metadata
;
772 function getBitDepth() {
775 return (int)$this->bits
;
779 * Returns the size of the image file, in bytes
782 public function getSize() {
789 * Returns the MIME type of the file.
792 function getMimeType() {
799 * Returns the type of the media in the file.
800 * Use the value returned by this function with the MEDIATYPE_xxx constants.
803 function getMediaType() {
806 return $this->media_type
;
809 /** canRender inherited */
810 /** mustRender inherited */
811 /** allowInlineDisplay inherited */
812 /** isSafeFile inherited */
813 /** isTrustedFile inherited */
816 * Returns true if the file exists on disk.
817 * @return bool Whether file exist on disk.
819 public function exists() {
822 return $this->fileExists
;
825 /** getTransformScript inherited */
826 /** getUnscaledThumb inherited */
827 /** thumbName inherited */
828 /** createThumb inherited */
829 /** transform inherited */
831 /** getHandler inherited */
832 /** iconThumb inherited */
833 /** getLastError inherited */
836 * Get all thumbnail names previously generated for this file
837 * @param string|bool $archiveName Name of an archive file, default false
838 * @return array First element is the base dir, then files in that base dir.
840 function getThumbnails( $archiveName = false ) {
841 if ( $archiveName ) {
842 $dir = $this->getArchiveThumbPath( $archiveName );
844 $dir = $this->getThumbPath();
847 $backend = $this->repo
->getBackend();
848 $files = array( $dir );
850 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
851 foreach ( $iterator as $file ) {
854 } catch ( FileBackendError
$e ) {
855 } // suppress (bug 54674)
861 * Refresh metadata in memcached, but don't touch thumbnails or CDN
863 function purgeMetadataCache() {
864 $this->invalidateCache();
868 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
870 * @param array $options An array potentially with the key forThumbRefresh.
872 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
874 function purgeCache( $options = array() ) {
875 // Refresh metadata cache
876 $this->purgeMetadataCache();
879 $this->purgeThumbnails( $options );
881 // Purge CDN cache for this file
882 DeferredUpdates
::addUpdate(
883 new CdnCacheUpdate( array( $this->getUrl() ) ),
884 DeferredUpdates
::PRESEND
889 * Delete cached transformed files for an archived version only.
890 * @param string $archiveName Name of the archived file
892 function purgeOldThumbnails( $archiveName ) {
893 // Get a list of old thumbnails and URLs
894 $files = $this->getThumbnails( $archiveName );
896 // Purge any custom thumbnail caches
897 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
899 $dir = array_shift( $files );
900 $this->purgeThumbList( $dir, $files );
904 foreach ( $files as $file ) {
905 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
907 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
911 * Delete cached transformed files for the current version only.
912 * @param array $options
914 public function purgeThumbnails( $options = array() ) {
916 $files = $this->getThumbnails();
917 // Always purge all files from CDN regardless of handler filters
919 foreach ( $files as $file ) {
920 $urls[] = $this->getThumbUrl( $file );
922 array_shift( $urls ); // don't purge directory
924 // Give media handler a chance to filter the file purge list
925 if ( !empty( $options['forThumbRefresh'] ) ) {
926 $handler = $this->getHandler();
928 $handler->filterThumbnailPurgeList( $files, $options );
932 // Purge any custom thumbnail caches
933 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
935 $dir = array_shift( $files );
936 $this->purgeThumbList( $dir, $files );
939 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
943 * Delete a list of thumbnails visible at urls
944 * @param string $dir Base dir of the files.
945 * @param array $files Array of strings: relative filenames (to $dir)
947 protected function purgeThumbList( $dir, $files ) {
948 $fileListDebug = strtr(
949 var_export( $files, true ),
952 wfDebug( __METHOD__
. ": $fileListDebug\n" );
954 $purgeList = array();
955 foreach ( $files as $file ) {
956 # Check that the base file name is part of the thumb name
957 # This is a basic sanity check to avoid erasing unrelated directories
958 if ( strpos( $file, $this->getName() ) !== false
959 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
961 $purgeList[] = "{$dir}/{$file}";
965 # Delete the thumbnails
966 $this->repo
->quickPurgeBatch( $purgeList );
967 # Clear out the thumbnail directory if empty
968 $this->repo
->quickCleanDir( $dir );
971 /** purgeDescription inherited */
972 /** purgeEverything inherited */
975 * @param int $limit Optional: Limit to number of results
976 * @param int $start Optional: Timestamp, start from
977 * @param int $end Optional: Timestamp, end at
979 * @return OldLocalFile[]
981 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
982 $dbr = $this->repo
->getSlaveDB();
983 $tables = array( 'oldimage' );
984 $fields = OldLocalFile
::selectFields();
985 $conds = $opts = $join_conds = array();
986 $eq = $inc ?
'=' : '';
987 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
990 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
994 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
998 $opts['LIMIT'] = $limit;
1001 // Search backwards for time > x queries
1002 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1003 $opts['ORDER BY'] = "oi_timestamp $order";
1004 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1006 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1007 &$conds, &$opts, &$join_conds ) );
1009 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1012 foreach ( $res as $row ) {
1013 $r[] = $this->repo
->newFileFromRow( $row );
1016 if ( $order == 'ASC' ) {
1017 $r = array_reverse( $r ); // make sure it ends up descending
1024 * Returns the history of this file, line by line.
1025 * starts with current version, then old versions.
1026 * uses $this->historyLine to check which line to return:
1027 * 0 return line for current version
1028 * 1 query for old versions, return first one
1029 * 2, ... return next old version from above query
1032 public function nextHistoryLine() {
1033 # Polymorphic function name to distinguish foreign and local fetches
1034 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1036 $dbr = $this->repo
->getSlaveDB();
1038 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1039 $this->historyRes
= $dbr->select( 'image',
1042 "'' AS oi_archive_name",
1046 array( 'img_name' => $this->title
->getDBkey() ),
1050 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1051 $this->historyRes
= null;
1055 } elseif ( $this->historyLine
== 1 ) {
1056 $this->historyRes
= $dbr->select( 'oldimage', '*',
1057 array( 'oi_name' => $this->title
->getDBkey() ),
1059 array( 'ORDER BY' => 'oi_timestamp DESC' )
1062 $this->historyLine++
;
1064 return $dbr->fetchObject( $this->historyRes
);
1068 * Reset the history pointer to the first element of the history
1070 public function resetHistory() {
1071 $this->historyLine
= 0;
1073 if ( !is_null( $this->historyRes
) ) {
1074 $this->historyRes
= null;
1078 /** getHashPath inherited */
1079 /** getRel inherited */
1080 /** getUrlRel inherited */
1081 /** getArchiveRel inherited */
1082 /** getArchivePath inherited */
1083 /** getThumbPath inherited */
1084 /** getArchiveUrl inherited */
1085 /** getThumbUrl inherited */
1086 /** getArchiveVirtualUrl inherited */
1087 /** getThumbVirtualUrl inherited */
1088 /** isHashed inherited */
1091 * Upload a file and record it in the DB
1092 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1093 * @param string $comment Upload description
1094 * @param string $pageText Text to use for the new description page,
1095 * if a new description page is created
1096 * @param int|bool $flags Flags for publish()
1097 * @param array|bool $props File properties, if known. This can be used to
1098 * reduce the upload time when uploading virtual URLs for which the file
1099 * info is already known
1100 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1102 * @param User|null $user User object or null to use $wgUser
1104 * @return FileRepoStatus On success, the value member contains the
1105 * archive name, or an empty string if it was a new file.
1107 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1108 $timestamp = false, $user = null
1112 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1113 return $this->readOnlyFatalStatus();
1117 if ( $this->repo
->isVirtualUrl( $srcPath )
1118 || FileBackend
::isStoragePath( $srcPath )
1120 $props = $this->repo
->getFileProps( $srcPath );
1122 $props = FSFile
::getPropsFromPath( $srcPath );
1127 $handler = MediaHandler
::getHandler( $props['mime'] );
1129 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1131 $options['headers'] = array();
1134 // Trim spaces on user supplied text
1135 $comment = trim( $comment );
1137 // Truncate nicely or the DB will do it for us
1138 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1139 $comment = $wgContLang->truncate( $comment, 255 );
1140 $this->lock(); // begin
1141 $status = $this->publish( $srcPath, $flags, $options );
1143 if ( $status->successCount
>= 2 ) {
1144 // There will be a copy+(one of move,copy,store).
1145 // The first succeeding does not commit us to updating the DB
1146 // since it simply copied the current version to a timestamped file name.
1147 // It is only *preferable* to avoid leaving such files orphaned.
1148 // Once the second operation goes through, then the current version was
1149 // updated and we must therefore update the DB too.
1150 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1151 $status->fatal( 'filenotfound', $srcPath );
1155 $this->unlock(); // done
1161 * Record a file upload in the upload log and the image table
1162 * @param string $oldver
1163 * @param string $desc
1164 * @param string $license
1165 * @param string $copyStatus
1166 * @param string $source
1167 * @param bool $watch
1168 * @param string|bool $timestamp
1169 * @param User|null $user User object or null to use $wgUser
1172 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1173 $watch = false, $timestamp = false, User
$user = null ) {
1179 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1181 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1186 $user->addWatch( $this->getTitle() );
1193 * Record a file upload in the upload log and the image table
1194 * @param string $oldver
1195 * @param string $comment
1196 * @param string $pageText
1197 * @param bool|array $props
1198 * @param string|bool $timestamp
1199 * @param null|User $user
1202 function recordUpload2(
1203 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1205 if ( is_null( $user ) ) {
1210 $dbw = $this->repo
->getMasterDB();
1212 # Imports or such might force a certain timestamp; otherwise we generate
1213 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1214 if ( $timestamp === false ) {
1215 $timestamp = $dbw->timestamp();
1216 $allowTimeKludge = true;
1218 $allowTimeKludge = false;
1221 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1222 $props['description'] = $comment;
1223 $props['user'] = $user->getId();
1224 $props['user_text'] = $user->getName();
1225 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1226 $this->setProps( $props );
1228 # Fail now if the file isn't there
1229 if ( !$this->fileExists
) {
1230 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1235 $dbw->startAtomic( __METHOD__
);
1237 # Test to see if the row exists using INSERT IGNORE
1238 # This avoids race conditions by locking the row until the commit, and also
1239 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1240 $dbw->insert( 'image',
1242 'img_name' => $this->getName(),
1243 'img_size' => $this->size
,
1244 'img_width' => intval( $this->width
),
1245 'img_height' => intval( $this->height
),
1246 'img_bits' => $this->bits
,
1247 'img_media_type' => $this->media_type
,
1248 'img_major_mime' => $this->major_mime
,
1249 'img_minor_mime' => $this->minor_mime
,
1250 'img_timestamp' => $timestamp,
1251 'img_description' => $comment,
1252 'img_user' => $user->getId(),
1253 'img_user_text' => $user->getName(),
1254 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1255 'img_sha1' => $this->sha1
1261 $reupload = ( $dbw->affectedRows() == 0 );
1263 if ( $allowTimeKludge ) {
1264 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1265 $ltimestamp = $dbw->selectField(
1268 array( 'img_name' => $this->getName() ),
1270 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.
1286 # Collision, this is an update of a file
1287 # Insert previous contents into oldimage
1288 $dbw->insertSelect( 'oldimage', 'image',
1290 'oi_name' => 'img_name',
1291 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1292 'oi_size' => 'img_size',
1293 'oi_width' => 'img_width',
1294 'oi_height' => 'img_height',
1295 'oi_bits' => 'img_bits',
1296 'oi_timestamp' => 'img_timestamp',
1297 'oi_description' => 'img_description',
1298 'oi_user' => 'img_user',
1299 'oi_user_text' => 'img_user_text',
1300 'oi_metadata' => 'img_metadata',
1301 'oi_media_type' => 'img_media_type',
1302 'oi_major_mime' => 'img_major_mime',
1303 'oi_minor_mime' => 'img_minor_mime',
1304 'oi_sha1' => 'img_sha1'
1306 array( 'img_name' => $this->getName() ),
1310 # Update the current image row
1311 $dbw->update( 'image',
1313 'img_size' => $this->size
,
1314 'img_width' => intval( $this->width
),
1315 'img_height' => intval( $this->height
),
1316 'img_bits' => $this->bits
,
1317 'img_media_type' => $this->media_type
,
1318 'img_major_mime' => $this->major_mime
,
1319 'img_minor_mime' => $this->minor_mime
,
1320 'img_timestamp' => $timestamp,
1321 'img_description' => $comment,
1322 'img_user' => $user->getId(),
1323 'img_user_text' => $user->getName(),
1324 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1325 'img_sha1' => $this->sha1
1327 array( 'img_name' => $this->getName() ),
1332 $descTitle = $this->getTitle();
1333 $descId = $descTitle->getArticleID();
1334 $wikiPage = new WikiFilePage( $descTitle );
1335 $wikiPage->setFile( $this );
1337 // Add the log entry...
1338 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1339 $logEntry->setPerformer( $user );
1340 $logEntry->setComment( $comment );
1341 $logEntry->setTarget( $descTitle );
1342 // Allow people using the api to associate log entries with the upload.
1343 // Log has a timestamp, but sometimes different from upload timestamp.
1344 $logEntry->setParameters(
1346 'img_sha1' => $this->sha1
,
1347 'img_timestamp' => $timestamp,
1350 // Note we keep $logId around since during new image
1351 // creation, page doesn't exist yet, so log_page = 0
1352 // but we want it to point to the page we're making,
1353 // so we later modify the log entry.
1354 // For a similar reason, we avoid making an RC entry
1355 // now and wait until the page exists.
1356 $logId = $logEntry->insert();
1358 if ( $descTitle->exists() ) {
1359 // Use own context to get the action text in content language
1360 $formatter = LogFormatter
::newFromEntry( $logEntry );
1361 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1362 $editSummary = $formatter->getPlainActionText();
1364 $nullRevision = Revision
::newNullRevision(
1371 if ( $nullRevision ) {
1372 $nullRevision->insertOn( $dbw );
1374 'NewRevisionFromEditComplete',
1375 array( $wikiPage, $nullRevision, $nullRevision->getParentId(), $user )
1377 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1378 // Associate null revision id
1379 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1382 $newPageContent = null;
1384 // Make the description page and RC log entry post-commit
1385 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1388 # Defer purges, page creation, and link updates in case they error out.
1389 # The most important thing is that files and the DB registry stay synced.
1390 $dbw->endAtomic( __METHOD__
);
1392 # Do some cache purges after final commit so that:
1393 # a) Changes are more likely to be seen post-purge
1394 # b) They won't cause rollback of the log publish/update above
1396 $dbw->onTransactionIdle( function () use (
1397 $that, $reupload, $wikiPage, $newPageContent, $comment, $user, $logEntry, $logId, $descId
1399 # Update memcache after the commit
1400 $that->invalidateCache();
1402 if ( $newPageContent ) {
1403 # New file page; create the description page.
1404 # There's already a log entry, so don't make a second RC entry
1405 # CDN and file cache for the description page are purged by doEditContent.
1406 $status = $wikiPage->doEditContent(
1409 EDIT_NEW | EDIT_SUPPRESS_RC
,
1414 if ( isset( $status->value
['revision'] ) ) {
1415 // Associate new page revision id
1416 $logEntry->setAssociatedRevId( $status->value
['revision']->getId() );
1418 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1419 // which is triggered on $descTitle by doEditContent() above.
1420 if ( isset( $status->value
['revision'] ) ) {
1421 /** @var $rev Revision */
1422 $rev = $status->value
['revision'];
1423 $that->getRepo()->getMasterDB()->update(
1425 array( 'log_page' => $rev->getPage() ),
1426 array( 'log_id' => $logId ),
1431 # Existing file page: invalidate description page cache
1432 $wikiPage->getTitle()->invalidateCache();
1433 $wikiPage->getTitle()->purgeSquid();
1434 # Allow the new file version to be patrolled from the page footer
1435 Article
::purgePatrolFooterCache( $descId );
1438 # Now that the page exists, make an RC entry.
1439 $logEntry->publish( $logId );
1440 # Run hook for other updates (typically more cache purging)
1441 Hooks
::run( 'FileUpload', array( $that, $reupload, !$newPageContent ) );
1444 # Delete old thumbnails
1445 $that->purgeThumbnails();
1446 # Remove the old file from the CDN cache
1447 DeferredUpdates
::addUpdate(
1448 new CdnCacheUpdate( array( $that->getUrl() ) ),
1449 DeferredUpdates
::PRESEND
1452 # Update backlink pages pointing to this title if created
1453 LinksUpdate
::queueRecursiveJobsForTable( $that->getTitle(), 'imagelinks' );
1458 # This is a new file, so update the image count
1459 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1462 # Invalidate cache for all pages using this file
1463 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1469 * Move or copy a file to its public location. If a file exists at the
1470 * destination, move it to an archive. Returns a FileRepoStatus object with
1471 * the archive name in the "value" member on success.
1473 * The archive name should be passed through to recordUpload for database
1476 * @param string $srcPath Local filesystem path or virtual URL to the source image
1477 * @param int $flags A bitwise combination of:
1478 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1479 * @param array $options Optional additional parameters
1480 * @return FileRepoStatus On success, the value member contains the
1481 * archive name, or an empty string if it was a new file.
1483 function publish( $srcPath, $flags = 0, array $options = array() ) {
1484 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1488 * Move or copy a file to a specified location. Returns a FileRepoStatus
1489 * object with the archive name in the "value" member on success.
1491 * The archive name should be passed through to recordUpload for database
1494 * @param string $srcPath Local filesystem path or virtual URL to the source image
1495 * @param string $dstRel Target relative path
1496 * @param int $flags A bitwise combination of:
1497 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1498 * @param array $options Optional additional parameters
1499 * @return FileRepoStatus On success, the value member contains the
1500 * archive name, or an empty string if it was a new file.
1502 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1503 $repo = $this->getRepo();
1504 if ( $repo->getReadOnlyReason() !== false ) {
1505 return $this->readOnlyFatalStatus();
1508 $this->lock(); // begin
1510 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1511 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1513 if ( $repo->hasSha1Storage() ) {
1514 $sha1 = $repo->isVirtualUrl( $srcPath )
1515 ?
$repo->getFileSha1( $srcPath )
1516 : File
::sha1Base36( $srcPath );
1517 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1518 $status = $repo->quickImport( $srcPath, $dst );
1519 if ( $flags & File
::DELETE_SOURCE
) {
1523 if ( $this->exists() ) {
1524 $status->value
= $archiveName;
1527 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1528 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1530 if ( $status->value
== 'new' ) {
1531 $status->value
= '';
1533 $status->value
= $archiveName;
1537 $this->unlock(); // done
1542 /** getLinksTo inherited */
1543 /** getExifData inherited */
1544 /** isLocal inherited */
1545 /** wasDeleted inherited */
1548 * Move file to the new title
1550 * Move current, old version and all thumbnails
1551 * to the new filename. Old file is deleted.
1553 * Cache purging is done; checks for validity
1554 * and logging are caller's responsibility
1556 * @param Title $target New file name
1557 * @return FileRepoStatus
1559 function move( $target ) {
1560 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1561 return $this->readOnlyFatalStatus();
1564 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1565 $batch = new LocalFileMoveBatch( $this, $target );
1567 $this->lock(); // begin
1568 $batch->addCurrent();
1569 $archiveNames = $batch->addOlds();
1570 $status = $batch->execute();
1571 $this->unlock(); // done
1573 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1575 // Purge the source and target files...
1576 $oldTitleFile = wfLocalFile( $this->title
);
1577 $newTitleFile = wfLocalFile( $target );
1578 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1579 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1580 $this->getRepo()->getMasterDB()->onTransactionIdle(
1581 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1582 $oldTitleFile->purgeEverything();
1583 foreach ( $archiveNames as $archiveName ) {
1584 $oldTitleFile->purgeOldThumbnails( $archiveName );
1586 $newTitleFile->purgeEverything();
1590 if ( $status->isOK() ) {
1591 // Now switch the object
1592 $this->title
= $target;
1593 // Force regeneration of the name and hashpath
1594 unset( $this->name
);
1595 unset( $this->hashPath
);
1602 * Delete all versions of the file.
1604 * Moves the files into an archive directory (or deletes them)
1605 * and removes the database rows.
1607 * Cache purging is done; logging is caller's responsibility.
1609 * @param string $reason
1610 * @param bool $suppress
1611 * @param User|null $user
1612 * @return FileRepoStatus
1614 function delete( $reason, $suppress = false, $user = null ) {
1615 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1616 return $this->readOnlyFatalStatus();
1619 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1621 $this->lock(); // begin
1622 $batch->addCurrent();
1623 # Get old version relative paths
1624 $archiveNames = $batch->addOlds();
1625 $status = $batch->execute();
1626 $this->unlock(); // done
1628 if ( $status->isOK() ) {
1629 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1632 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1633 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1635 $this->getRepo()->getMasterDB()->onTransactionIdle(
1636 function () use ( $that, $archiveNames ) {
1637 $that->purgeEverything();
1638 foreach ( $archiveNames as $archiveName ) {
1639 $that->purgeOldThumbnails( $archiveName );
1645 $purgeUrls = array();
1646 foreach ( $archiveNames as $archiveName ) {
1647 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1649 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1655 * Delete an old version of the file.
1657 * Moves the file into an archive directory (or deletes it)
1658 * and removes the database row.
1660 * Cache purging is done; logging is caller's responsibility.
1662 * @param string $archiveName
1663 * @param string $reason
1664 * @param bool $suppress
1665 * @param User|null $user
1666 * @throws MWException Exception on database or file store failure
1667 * @return FileRepoStatus
1669 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1670 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1671 return $this->readOnlyFatalStatus();
1674 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1676 $this->lock(); // begin
1677 $batch->addOld( $archiveName );
1678 $status = $batch->execute();
1679 $this->unlock(); // done
1681 $this->purgeOldThumbnails( $archiveName );
1682 if ( $status->isOK() ) {
1683 $this->purgeDescription();
1686 DeferredUpdates
::addUpdate(
1687 new CdnCacheUpdate( array( $this->getArchiveUrl( $archiveName ) ) ),
1688 DeferredUpdates
::PRESEND
1695 * Restore all or specified deleted revisions to the given file.
1696 * Permissions and logging are left to the caller.
1698 * May throw database exceptions on error.
1700 * @param array $versions Set of record ids of deleted items to restore,
1701 * or empty to restore all revisions.
1702 * @param bool $unsuppress
1703 * @return FileRepoStatus
1705 function restore( $versions = array(), $unsuppress = false ) {
1706 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1707 return $this->readOnlyFatalStatus();
1710 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1712 $this->lock(); // begin
1716 $batch->addIds( $versions );
1718 $status = $batch->execute();
1719 if ( $status->isGood() ) {
1720 $cleanupStatus = $batch->cleanup();
1721 $cleanupStatus->successCount
= 0;
1722 $cleanupStatus->failCount
= 0;
1723 $status->merge( $cleanupStatus );
1725 $this->unlock(); // done
1730 /** isMultipage inherited */
1731 /** pageCount inherited */
1732 /** scaleHeight inherited */
1733 /** getImageSize inherited */
1736 * Get the URL of the file description page.
1739 function getDescriptionUrl() {
1740 return $this->title
->getLocalURL();
1744 * Get the HTML text of the description page
1745 * This is not used by ImagePage for local files, since (among other things)
1746 * it skips the parser cache.
1748 * @param Language $lang What language to get description in (Optional)
1749 * @return bool|mixed
1751 function getDescriptionText( $lang = null ) {
1752 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1756 $content = $revision->getContent();
1760 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1762 return $pout->getText();
1766 * @param int $audience
1770 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1772 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1774 } elseif ( $audience == self
::FOR_THIS_USER
1775 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1779 return $this->description
;
1784 * @return bool|string
1786 function getTimestamp() {
1789 return $this->timestamp
;
1793 * @return bool|string
1795 public function getDescriptionTouched() {
1796 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1797 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1798 // need to differentiate between null (uninitialized) and false (failed to load).
1799 if ( $this->descriptionTouched
=== null ) {
1801 'page_namespace' => $this->title
->getNamespace(),
1802 'page_title' => $this->title
->getDBkey()
1804 $touched = $this->repo
->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1805 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1808 return $this->descriptionTouched
;
1814 function getSha1() {
1816 // Initialise now if necessary
1817 if ( $this->sha1
== '' && $this->fileExists
) {
1818 $this->lock(); // begin
1820 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1821 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1822 $dbw = $this->repo
->getMasterDB();
1823 $dbw->update( 'image',
1824 array( 'img_sha1' => $this->sha1
),
1825 array( 'img_name' => $this->getName() ),
1827 $this->invalidateCache();
1830 $this->unlock(); // done
1837 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1839 function isCacheable() {
1842 // If extra data (metadata) was not loaded then it must have been large
1843 return $this->extraDataLoaded
1844 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1848 * Start a transaction and lock the image for update
1849 * Increments a reference counter if the lock is already held
1850 * @throws MWException Throws an error if the lock was not acquired
1851 * @return bool Whether the file lock owns/spawned the DB transaction
1854 $dbw = $this->repo
->getMasterDB();
1856 if ( !$this->locked
) {
1857 if ( !$dbw->trxLevel() ) {
1858 $dbw->begin( __METHOD__
);
1859 $this->lockedOwnTrx
= true;
1862 // Bug 54736: use simple lock to handle when the file does not exist.
1863 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1864 // Also, that would cause contention on INSERT of similarly named rows.
1865 $backend = $this->getRepo()->getBackend();
1866 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1867 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1868 if ( !$status->isGood() ) {
1869 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1871 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1872 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1876 return $this->lockedOwnTrx
;
1880 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1881 * the transaction and thereby releases the image lock.
1884 if ( $this->locked
) {
1886 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1887 $dbw = $this->repo
->getMasterDB();
1888 $dbw->commit( __METHOD__
);
1889 $this->lockedOwnTrx
= false;
1895 * Roll back the DB transaction and mark the image unlocked
1897 function unlockAndRollback() {
1898 $this->locked
= false;
1899 $dbw = $this->repo
->getMasterDB();
1900 $dbw->rollback( __METHOD__
);
1901 $this->lockedOwnTrx
= false;
1907 protected function readOnlyFatalStatus() {
1908 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1909 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1913 * Clean up any dangling locks
1915 function __destruct() {
1918 } // LocalFile class
1920 # ------------------------------------------------------------------------------
1923 * Helper class for file deletion
1924 * @ingroup FileAbstraction
1926 class LocalFileDeleteBatch
{
1927 /** @var LocalFile */
1934 private $srcRels = array();
1937 private $archiveUrls = array();
1939 /** @var array Items to be processed in the deletion batch */
1940 private $deletionBatch;
1942 /** @var bool Whether to suppress all suppressable fields when deleting */
1945 /** @var FileRepoStatus */
1953 * @param string $reason
1954 * @param bool $suppress
1955 * @param User|null $user
1957 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1958 $this->file
= $file;
1959 $this->reason
= $reason;
1960 $this->suppress
= $suppress;
1962 $this->user
= $user;
1965 $this->user
= $wgUser;
1967 $this->status
= $file->repo
->newGood();
1970 public function addCurrent() {
1971 $this->srcRels
['.'] = $this->file
->getRel();
1975 * @param string $oldName
1977 public function addOld( $oldName ) {
1978 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1979 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1983 * Add the old versions of the image to the batch
1984 * @return array List of archive names from old versions
1986 public function addOlds() {
1987 $archiveNames = array();
1989 $dbw = $this->file
->repo
->getMasterDB();
1990 $result = $dbw->select( 'oldimage',
1991 array( 'oi_archive_name' ),
1992 array( 'oi_name' => $this->file
->getName() ),
1996 foreach ( $result as $row ) {
1997 $this->addOld( $row->oi_archive_name
);
1998 $archiveNames[] = $row->oi_archive_name
;
2001 return $archiveNames;
2007 protected function getOldRels() {
2008 if ( !isset( $this->srcRels
['.'] ) ) {
2009 $oldRels =& $this->srcRels
;
2010 $deleteCurrent = false;
2012 $oldRels = $this->srcRels
;
2013 unset( $oldRels['.'] );
2014 $deleteCurrent = true;
2017 return array( $oldRels, $deleteCurrent );
2023 protected function getHashes() {
2025 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2027 if ( $deleteCurrent ) {
2028 $hashes['.'] = $this->file
->getSha1();
2031 if ( count( $oldRels ) ) {
2032 $dbw = $this->file
->repo
->getMasterDB();
2033 $res = $dbw->select(
2035 array( 'oi_archive_name', 'oi_sha1' ),
2036 array( 'oi_archive_name' => array_keys( $oldRels ),
2037 'oi_name' => $this->file
->getName() ), // performance
2041 foreach ( $res as $row ) {
2042 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2043 // Get the hash from the file
2044 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2045 $props = $this->file
->repo
->getFileProps( $oldUrl );
2047 if ( $props['fileExists'] ) {
2048 // Upgrade the oldimage row
2049 $dbw->update( 'oldimage',
2050 array( 'oi_sha1' => $props['sha1'] ),
2051 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2053 $hashes[$row->oi_archive_name
] = $props['sha1'];
2055 $hashes[$row->oi_archive_name
] = false;
2058 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2063 $missing = array_diff_key( $this->srcRels
, $hashes );
2065 foreach ( $missing as $name => $rel ) {
2066 $this->status
->error( 'filedelete-old-unregistered', $name );
2069 foreach ( $hashes as $name => $hash ) {
2071 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2072 unset( $hashes[$name] );
2079 protected function doDBInserts() {
2080 $dbw = $this->file
->repo
->getMasterDB();
2081 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2082 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2083 $encReason = $dbw->addQuotes( $this->reason
);
2084 $encGroup = $dbw->addQuotes( 'deleted' );
2085 $ext = $this->file
->getExtension();
2086 $dotExt = $ext === '' ?
'' : ".$ext";
2087 $encExt = $dbw->addQuotes( $dotExt );
2088 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2090 // Bitfields to further suppress the content
2091 if ( $this->suppress
) {
2093 // This should be 15...
2094 $bitfield |
= Revision
::DELETED_TEXT
;
2095 $bitfield |
= Revision
::DELETED_COMMENT
;
2096 $bitfield |
= Revision
::DELETED_USER
;
2097 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2099 $bitfield = 'oi_deleted';
2102 if ( $deleteCurrent ) {
2103 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2104 $where = array( 'img_name' => $this->file
->getName() );
2105 $dbw->insertSelect( 'filearchive', 'image',
2107 'fa_storage_group' => $encGroup,
2108 'fa_storage_key' => $dbw->conditional(
2109 array( 'img_sha1' => '' ),
2110 $dbw->addQuotes( '' ),
2113 'fa_deleted_user' => $encUserId,
2114 'fa_deleted_timestamp' => $encTimestamp,
2115 'fa_deleted_reason' => $encReason,
2116 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2118 'fa_name' => 'img_name',
2119 'fa_archive_name' => 'NULL',
2120 'fa_size' => 'img_size',
2121 'fa_width' => 'img_width',
2122 'fa_height' => 'img_height',
2123 'fa_metadata' => 'img_metadata',
2124 'fa_bits' => 'img_bits',
2125 'fa_media_type' => 'img_media_type',
2126 'fa_major_mime' => 'img_major_mime',
2127 'fa_minor_mime' => 'img_minor_mime',
2128 'fa_description' => 'img_description',
2129 'fa_user' => 'img_user',
2130 'fa_user_text' => 'img_user_text',
2131 'fa_timestamp' => 'img_timestamp',
2132 'fa_sha1' => 'img_sha1',
2133 ), $where, __METHOD__
);
2136 if ( count( $oldRels ) ) {
2137 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2139 'oi_name' => $this->file
->getName(),
2140 'oi_archive_name' => array_keys( $oldRels ) );
2141 $dbw->insertSelect( 'filearchive', 'oldimage',
2143 'fa_storage_group' => $encGroup,
2144 'fa_storage_key' => $dbw->conditional(
2145 array( 'oi_sha1' => '' ),
2146 $dbw->addQuotes( '' ),
2149 'fa_deleted_user' => $encUserId,
2150 'fa_deleted_timestamp' => $encTimestamp,
2151 'fa_deleted_reason' => $encReason,
2152 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2154 'fa_name' => 'oi_name',
2155 'fa_archive_name' => 'oi_archive_name',
2156 'fa_size' => 'oi_size',
2157 'fa_width' => 'oi_width',
2158 'fa_height' => 'oi_height',
2159 'fa_metadata' => 'oi_metadata',
2160 'fa_bits' => 'oi_bits',
2161 'fa_media_type' => 'oi_media_type',
2162 'fa_major_mime' => 'oi_major_mime',
2163 'fa_minor_mime' => 'oi_minor_mime',
2164 'fa_description' => 'oi_description',
2165 'fa_user' => 'oi_user',
2166 'fa_user_text' => 'oi_user_text',
2167 'fa_timestamp' => 'oi_timestamp',
2168 'fa_sha1' => 'oi_sha1',
2169 ), $where, __METHOD__
);
2173 function doDBDeletes() {
2174 $dbw = $this->file
->repo
->getMasterDB();
2175 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2177 if ( count( $oldRels ) ) {
2178 $dbw->delete( 'oldimage',
2180 'oi_name' => $this->file
->getName(),
2181 'oi_archive_name' => array_keys( $oldRels )
2185 if ( $deleteCurrent ) {
2186 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2191 * Run the transaction
2192 * @return FileRepoStatus
2194 public function execute() {
2195 $repo = $this->file
->getRepo();
2196 $this->file
->lock();
2198 // Prepare deletion batch
2199 $hashes = $this->getHashes();
2200 $this->deletionBatch
= array();
2201 $ext = $this->file
->getExtension();
2202 $dotExt = $ext === '' ?
'' : ".$ext";
2204 foreach ( $this->srcRels
as $name => $srcRel ) {
2205 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2206 if ( isset( $hashes[$name] ) ) {
2207 $hash = $hashes[$name];
2208 $key = $hash . $dotExt;
2209 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2210 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2214 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2215 // We acquire this lock by running the inserts now, before the file operations.
2216 // This potentially has poor lock contention characteristics -- an alternative
2217 // scheme would be to insert stub filearchive entries with no fa_name and commit
2218 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2219 $this->doDBInserts();
2221 if ( !$repo->hasSha1Storage() ) {
2222 // Removes non-existent file from the batch, so we don't get errors.
2223 // This also handles files in the 'deleted' zone deleted via revision deletion.
2224 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2225 if ( !$checkStatus->isGood() ) {
2226 $this->status
->merge( $checkStatus );
2227 return $this->status
;
2229 $this->deletionBatch
= $checkStatus->value
;
2231 // Execute the file deletion batch
2232 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2234 if ( !$status->isGood() ) {
2235 $this->status
->merge( $status );
2239 if ( !$this->status
->isOK() ) {
2240 // Critical file deletion error
2241 // Roll back inserts, release lock and abort
2242 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2243 $this->file
->unlockAndRollback();
2245 return $this->status
;
2248 // Delete image/oldimage rows
2249 $this->doDBDeletes();
2251 // Commit and return
2252 $this->file
->unlock();
2254 return $this->status
;
2258 * Removes non-existent files from a deletion batch.
2259 * @param array $batch
2262 protected function removeNonexistentFiles( $batch ) {
2263 $files = $newBatch = array();
2265 foreach ( $batch as $batchItem ) {
2266 list( $src, ) = $batchItem;
2267 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2270 $result = $this->file
->repo
->fileExistsBatch( $files );
2271 if ( in_array( null, $result, true ) ) {
2272 return Status
::newFatal( 'backend-fail-internal',
2273 $this->file
->repo
->getBackend()->getName() );
2276 foreach ( $batch as $batchItem ) {
2277 if ( $result[$batchItem[0]] ) {
2278 $newBatch[] = $batchItem;
2282 return Status
::newGood( $newBatch );
2286 # ------------------------------------------------------------------------------
2289 * Helper class for file undeletion
2290 * @ingroup FileAbstraction
2292 class LocalFileRestoreBatch
{
2293 /** @var LocalFile */
2296 /** @var array List of file IDs to restore */
2297 private $cleanupBatch;
2299 /** @var array List of file IDs to restore */
2302 /** @var bool Add all revisions of the file */
2305 /** @var bool Whether to remove all settings for suppressed fields */
2306 private $unsuppress = false;
2310 * @param bool $unsuppress
2312 function __construct( File
$file, $unsuppress = false ) {
2313 $this->file
= $file;
2314 $this->cleanupBatch
= $this->ids
= array();
2315 $this->ids
= array();
2316 $this->unsuppress
= $unsuppress;
2323 public function addId( $fa_id ) {
2324 $this->ids
[] = $fa_id;
2328 * Add a whole lot of files by ID
2331 public function addIds( $ids ) {
2332 $this->ids
= array_merge( $this->ids
, $ids );
2336 * Add all revisions of the file
2338 public function addAll() {
2343 * Run the transaction, except the cleanup batch.
2344 * The cleanup batch should be run in a separate transaction, because it locks different
2345 * rows and there's no need to keep the image row locked while it's acquiring those locks
2346 * The caller may have its own transaction open.
2347 * So we save the batch and let the caller call cleanup()
2348 * @return FileRepoStatus
2350 public function execute() {
2353 $repo = $this->file
->getRepo();
2354 if ( !$this->all
&& !$this->ids
) {
2356 return $repo->newGood();
2359 $lockOwnsTrx = $this->file
->lock();
2361 $dbw = $this->file
->repo
->getMasterDB();
2362 $status = $this->file
->repo
->newGood();
2364 $exists = (bool)$dbw->selectField( 'image', '1',
2365 array( 'img_name' => $this->file
->getName() ),
2367 // The lock() should already prevents changes, but this still may need
2368 // to bypass any transaction snapshot. However, if lock() started the
2369 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2370 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2373 // Fetch all or selected archived revisions for the file,
2374 // sorted from the most recent to the oldest.
2375 $conditions = array( 'fa_name' => $this->file
->getName() );
2377 if ( !$this->all
) {
2378 $conditions['fa_id'] = $this->ids
;
2381 $result = $dbw->select(
2383 ArchivedFile
::selectFields(),
2386 array( 'ORDER BY' => 'fa_timestamp DESC' )
2389 $idsPresent = array();
2390 $storeBatch = array();
2391 $insertBatch = array();
2392 $insertCurrent = false;
2393 $deleteIds = array();
2395 $archiveNames = array();
2397 foreach ( $result as $row ) {
2398 $idsPresent[] = $row->fa_id
;
2400 if ( $row->fa_name
!= $this->file
->getName() ) {
2401 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2402 $status->failCount++
;
2406 if ( $row->fa_storage_key
== '' ) {
2407 // Revision was missing pre-deletion
2408 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2409 $status->failCount++
;
2413 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2414 $row->fa_storage_key
;
2415 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2417 if ( isset( $row->fa_sha1
) ) {
2418 $sha1 = $row->fa_sha1
;
2420 // old row, populate from key
2421 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2425 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2426 $sha1 = substr( $sha1, 1 );
2429 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2430 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2431 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2432 ||
is_null( $row->fa_metadata
)
2434 // Refresh our metadata
2435 // Required for a new current revision; nice for older ones too. :)
2436 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2439 'minor_mime' => $row->fa_minor_mime
,
2440 'major_mime' => $row->fa_major_mime
,
2441 'media_type' => $row->fa_media_type
,
2442 'metadata' => $row->fa_metadata
2446 if ( $first && !$exists ) {
2447 // This revision will be published as the new current version
2448 $destRel = $this->file
->getRel();
2449 $insertCurrent = array(
2450 'img_name' => $row->fa_name
,
2451 'img_size' => $row->fa_size
,
2452 'img_width' => $row->fa_width
,
2453 'img_height' => $row->fa_height
,
2454 'img_metadata' => $props['metadata'],
2455 'img_bits' => $row->fa_bits
,
2456 'img_media_type' => $props['media_type'],
2457 'img_major_mime' => $props['major_mime'],
2458 'img_minor_mime' => $props['minor_mime'],
2459 'img_description' => $row->fa_description
,
2460 'img_user' => $row->fa_user
,
2461 'img_user_text' => $row->fa_user_text
,
2462 'img_timestamp' => $row->fa_timestamp
,
2466 // The live (current) version cannot be hidden!
2467 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2468 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2469 $this->cleanupBatch
[] = $row->fa_storage_key
;
2472 $archiveName = $row->fa_archive_name
;
2474 if ( $archiveName == '' ) {
2475 // This was originally a current version; we
2476 // have to devise a new archive name for it.
2477 // Format is <timestamp of archiving>!<name>
2478 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2481 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2483 } while ( isset( $archiveNames[$archiveName] ) );
2486 $archiveNames[$archiveName] = true;
2487 $destRel = $this->file
->getArchiveRel( $archiveName );
2488 $insertBatch[] = array(
2489 'oi_name' => $row->fa_name
,
2490 'oi_archive_name' => $archiveName,
2491 'oi_size' => $row->fa_size
,
2492 'oi_width' => $row->fa_width
,
2493 'oi_height' => $row->fa_height
,
2494 'oi_bits' => $row->fa_bits
,
2495 'oi_description' => $row->fa_description
,
2496 'oi_user' => $row->fa_user
,
2497 'oi_user_text' => $row->fa_user_text
,
2498 'oi_timestamp' => $row->fa_timestamp
,
2499 'oi_metadata' => $props['metadata'],
2500 'oi_media_type' => $props['media_type'],
2501 'oi_major_mime' => $props['major_mime'],
2502 'oi_minor_mime' => $props['minor_mime'],
2503 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2504 'oi_sha1' => $sha1 );
2507 $deleteIds[] = $row->fa_id
;
2509 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2510 // private files can stay where they are
2511 $status->successCount++
;
2513 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2514 $this->cleanupBatch
[] = $row->fa_storage_key
;
2522 // Add a warning to the status object for missing IDs
2523 $missingIds = array_diff( $this->ids
, $idsPresent );
2525 foreach ( $missingIds as $id ) {
2526 $status->error( 'undelete-missing-filearchive', $id );
2529 if ( !$repo->hasSha1Storage() ) {
2530 // Remove missing files from batch, so we don't get errors when undeleting them
2531 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2532 if ( !$checkStatus->isGood() ) {
2533 $status->merge( $checkStatus );
2536 $storeBatch = $checkStatus->value
;
2538 // Run the store batch
2539 // Use the OVERWRITE_SAME flag to smooth over a common error
2540 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2541 $status->merge( $storeStatus );
2543 if ( !$status->isGood() ) {
2544 // Even if some files could be copied, fail entirely as that is the
2545 // easiest thing to do without data loss
2546 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2547 $status->ok
= false;
2548 $this->file
->unlock();
2554 // Run the DB updates
2555 // Because we have locked the image row, key conflicts should be rare.
2556 // If they do occur, we can roll back the transaction at this time with
2557 // no data loss, but leaving unregistered files scattered throughout the
2559 // This is not ideal, which is why it's important to lock the image row.
2560 if ( $insertCurrent ) {
2561 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2564 if ( $insertBatch ) {
2565 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2569 $dbw->delete( 'filearchive',
2570 array( 'fa_id' => $deleteIds ),
2574 // If store batch is empty (all files are missing), deletion is to be considered successful
2575 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2577 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2579 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2581 $this->file
->purgeEverything();
2583 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2584 $this->file
->purgeDescription();
2588 $this->file
->unlock();
2594 * Removes non-existent files from a store batch.
2595 * @param array $triplets
2598 protected function removeNonexistentFiles( $triplets ) {
2599 $files = $filteredTriplets = array();
2600 foreach ( $triplets as $file ) {
2601 $files[$file[0]] = $file[0];
2604 $result = $this->file
->repo
->fileExistsBatch( $files );
2605 if ( in_array( null, $result, true ) ) {
2606 return Status
::newFatal( 'backend-fail-internal',
2607 $this->file
->repo
->getBackend()->getName() );
2610 foreach ( $triplets as $file ) {
2611 if ( $result[$file[0]] ) {
2612 $filteredTriplets[] = $file;
2616 return Status
::newGood( $filteredTriplets );
2620 * Removes non-existent files from a cleanup batch.
2621 * @param array $batch
2624 protected function removeNonexistentFromCleanup( $batch ) {
2625 $files = $newBatch = array();
2626 $repo = $this->file
->repo
;
2628 foreach ( $batch as $file ) {
2629 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2630 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2633 $result = $repo->fileExistsBatch( $files );
2635 foreach ( $batch as $file ) {
2636 if ( $result[$file] ) {
2637 $newBatch[] = $file;
2645 * Delete unused files in the deleted zone.
2646 * This should be called from outside the transaction in which execute() was called.
2647 * @return FileRepoStatus
2649 public function cleanup() {
2650 if ( !$this->cleanupBatch
) {
2651 return $this->file
->repo
->newGood();
2654 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2656 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2662 * Cleanup a failed batch. The batch was only partially successful, so
2663 * rollback by removing all items that were succesfully copied.
2665 * @param Status $storeStatus
2666 * @param array $storeBatch
2668 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2669 $cleanupBatch = array();
2671 foreach ( $storeStatus->success
as $i => $success ) {
2672 // Check if this item of the batch was successfully copied
2674 // Item was successfully copied and needs to be removed again
2675 // Extract ($dstZone, $dstRel) from the batch
2676 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2679 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2683 # ------------------------------------------------------------------------------
2686 * Helper class for file movement
2687 * @ingroup FileAbstraction
2689 class LocalFileMoveBatch
{
2690 /** @var LocalFile */
2700 protected $oldCount;
2704 /** @var DatabaseBase */
2709 * @param Title $target
2711 function __construct( File
$file, Title
$target ) {
2712 $this->file
= $file;
2713 $this->target
= $target;
2714 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2715 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2716 $this->oldName
= $this->file
->getName();
2717 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2718 $this->oldRel
= $this->oldHash
. $this->oldName
;
2719 $this->newRel
= $this->newHash
. $this->newName
;
2720 $this->db
= $file->getRepo()->getMasterDb();
2724 * Add the current image to the batch
2726 public function addCurrent() {
2727 $this->cur
= array( $this->oldRel
, $this->newRel
);
2731 * Add the old versions of the image to the batch
2732 * @return array List of archive names from old versions
2734 public function addOlds() {
2735 $archiveBase = 'archive';
2736 $this->olds
= array();
2737 $this->oldCount
= 0;
2738 $archiveNames = array();
2740 $result = $this->db
->select( 'oldimage',
2741 array( 'oi_archive_name', 'oi_deleted' ),
2742 array( 'oi_name' => $this->oldName
),
2744 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2747 foreach ( $result as $row ) {
2748 $archiveNames[] = $row->oi_archive_name
;
2749 $oldName = $row->oi_archive_name
;
2750 $bits = explode( '!', $oldName, 2 );
2752 if ( count( $bits ) != 2 ) {
2753 wfDebug( "Old file name missing !: '$oldName' \n" );
2757 list( $timestamp, $filename ) = $bits;
2759 if ( $this->oldName
!= $filename ) {
2760 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2766 // Do we want to add those to oldCount?
2767 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2771 $this->olds
[] = array(
2772 "{$archiveBase}/{$this->oldHash}{$oldName}",
2773 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2777 return $archiveNames;
2782 * @return FileRepoStatus
2784 public function execute() {
2785 $repo = $this->file
->repo
;
2786 $status = $repo->newGood();
2788 $triplets = $this->getMoveTriplets();
2789 $checkStatus = $this->removeNonexistentFiles( $triplets );
2790 if ( !$checkStatus->isGood() ) {
2791 $status->merge( $checkStatus );
2794 $triplets = $checkStatus->value
;
2795 $destFile = wfLocalFile( $this->target
);
2797 $this->file
->lock(); // begin
2798 $destFile->lock(); // quickly fail if destination is not available
2799 // Rename the file versions metadata in the DB.
2800 // This implicitly locks the destination file, which avoids race conditions.
2801 // If we moved the files from A -> C before DB updates, another process could
2802 // move files from B -> C at this point, causing storeBatch() to fail and thus
2803 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2804 $statusDb = $this->doDBUpdates();
2805 if ( !$statusDb->isGood() ) {
2806 $destFile->unlock();
2807 $this->file
->unlockAndRollback();
2808 $statusDb->ok
= false;
2812 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2813 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2815 if ( !$repo->hasSha1Storage() ) {
2816 // Copy the files into their new location.
2817 // If a prior process fataled copying or cleaning up files we tolerate any
2818 // of the existing files if they are identical to the ones being stored.
2819 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2820 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2821 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2822 if ( !$statusMove->isGood() ) {
2823 // Delete any files copied over (while the destination is still locked)
2824 $this->cleanupTarget( $triplets );
2825 $destFile->unlock();
2826 $this->file
->unlockAndRollback(); // unlocks the destination
2827 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2828 $statusMove->ok
= false;
2832 $status->merge( $statusMove );
2835 $destFile->unlock();
2836 $this->file
->unlock(); // done
2838 // Everything went ok, remove the source files
2839 $this->cleanupSource( $triplets );
2841 $status->merge( $statusDb );
2847 * Do the database updates and return a new FileRepoStatus indicating how
2848 * many rows where updated.
2850 * @return FileRepoStatus
2852 protected function doDBUpdates() {
2853 $repo = $this->file
->repo
;
2854 $status = $repo->newGood();
2857 // Update current image
2860 array( 'img_name' => $this->newName
),
2861 array( 'img_name' => $this->oldName
),
2865 if ( $dbw->affectedRows() ) {
2866 $status->successCount++
;
2868 $status->failCount++
;
2869 $status->fatal( 'imageinvalidfilename' );
2874 // Update old images
2878 'oi_name' => $this->newName
,
2879 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2880 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2882 array( 'oi_name' => $this->oldName
),
2886 $affected = $dbw->affectedRows();
2887 $total = $this->oldCount
;
2888 $status->successCount +
= $affected;
2889 // Bug 34934: $total is based on files that actually exist.
2890 // There may be more DB rows than such files, in which case $affected
2891 // can be greater than $total. We use max() to avoid negatives here.
2892 $status->failCount +
= max( 0, $total - $affected );
2893 if ( $status->failCount
) {
2894 $status->error( 'imageinvalidfilename' );
2901 * Generate triplets for FileRepo::storeBatch().
2904 protected function getMoveTriplets() {
2905 $moves = array_merge( array( $this->cur
), $this->olds
);
2906 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2908 foreach ( $moves as $move ) {
2909 // $move: (oldRelativePath, newRelativePath)
2910 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2911 $triplets[] = array( $srcUrl, 'public', $move[1] );
2914 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2922 * Removes non-existent files from move batch.
2923 * @param array $triplets
2926 protected function removeNonexistentFiles( $triplets ) {
2929 foreach ( $triplets as $file ) {
2930 $files[$file[0]] = $file[0];
2933 $result = $this->file
->repo
->fileExistsBatch( $files );
2934 if ( in_array( null, $result, true ) ) {
2935 return Status
::newFatal( 'backend-fail-internal',
2936 $this->file
->repo
->getBackend()->getName() );
2939 $filteredTriplets = array();
2940 foreach ( $triplets as $file ) {
2941 if ( $result[$file[0]] ) {
2942 $filteredTriplets[] = $file;
2944 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2948 return Status
::newGood( $filteredTriplets );
2952 * Cleanup a partially moved array of triplets by deleting the target
2953 * files. Called if something went wrong half way.
2954 * @param array $triplets
2956 protected function cleanupTarget( $triplets ) {
2957 // Create dest pairs from the triplets
2959 foreach ( $triplets as $triplet ) {
2960 // $triplet: (old source virtual URL, dst zone, dest rel)
2961 $pairs[] = array( $triplet[1], $triplet[2] );
2964 $this->file
->repo
->cleanupBatch( $pairs );
2968 * Cleanup a fully moved array of triplets by deleting the source files.
2969 * Called at the end of the move process if everything else went ok.
2970 * @param array $triplets
2972 protected function cleanupSource( $triplets ) {
2973 // Create source file names from the triplets
2975 foreach ( $triplets as $triplet ) {
2976 $files[] = $triplet[0];
2979 $this->file
->repo
->cleanupBatch( $files );