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
383 function loadFromDB( $flags = 0 ) {
384 # Polymorphic function name to distinguish foreign and local fetches
385 $fname = get_class( $this ) . '::' . __FUNCTION__
;
386 wfProfileIn( $fname );
388 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
389 $this->dataLoaded
= true;
390 $this->extraDataLoaded
= true;
392 $dbr = ( $flags & self
::LOAD_VIA_SLAVE
)
393 ?
$this->repo
->getSlaveDB()
394 : $this->repo
->getMasterDB();
396 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
397 array( 'img_name' => $this->getName() ), $fname );
400 $this->loadFromRow( $row );
402 $this->fileExists
= false;
405 wfProfileOut( $fname );
409 * Load lazy file metadata from the DB.
410 * This covers fields that are sometimes not cached.
412 protected function loadExtraFromDB() {
413 # Polymorphic function name to distinguish foreign and local fetches
414 $fname = get_class( $this ) . '::' . __FUNCTION__
;
415 wfProfileIn( $fname );
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 wfProfileOut( $fname );
431 throw new MWException( "Could not find data for image '{$this->getName()}'." );
434 wfProfileOut( $fname );
438 * @param DatabaseBase $dbr
439 * @param string $fname
440 * @return array|false
442 private function loadFieldsWithTimestamp( $dbr, $fname ) {
445 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
446 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
449 $fieldMap = $this->unprefixRow( $row, 'img_' );
451 # File may have been uploaded over in the meantime; check the old versions
452 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
453 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
456 $fieldMap = $this->unprefixRow( $row, 'oi_' );
464 * @param array $row Row
465 * @param string $prefix
466 * @throws MWException
469 protected function unprefixRow( $row, $prefix = 'img_' ) {
470 $array = (array)$row;
471 $prefixLength = strlen( $prefix );
473 // Sanity check prefix once
474 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
475 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
479 foreach ( $array as $name => $value ) {
480 $decoded[substr( $name, $prefixLength )] = $value;
487 * Decode a row from the database (either object or array) to an array
488 * with timestamps and MIME types decoded, and the field prefix removed.
490 * @param string $prefix
491 * @throws MWException
494 function decodeRow( $row, $prefix = 'img_' ) {
495 $decoded = $this->unprefixRow( $row, $prefix );
497 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
499 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
501 if ( empty( $decoded['major_mime'] ) ) {
502 $decoded['mime'] = 'unknown/unknown';
504 if ( !$decoded['minor_mime'] ) {
505 $decoded['minor_mime'] = 'unknown';
507 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
510 # Trim zero padding from char/binary field
511 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
517 * Load file metadata from a DB result row
520 * @param string $prefix
522 function loadFromRow( $row, $prefix = 'img_' ) {
523 $this->dataLoaded
= true;
524 $this->extraDataLoaded
= true;
526 $array = $this->decodeRow( $row, $prefix );
528 foreach ( $array as $name => $value ) {
529 $this->$name = $value;
532 $this->fileExists
= true;
533 $this->maybeUpgradeRow();
537 * Load file metadata from cache or DB, unless already loaded
540 function load( $flags = 0 ) {
541 if ( !$this->dataLoaded
) {
542 if ( !$this->loadFromCache() ) {
543 $this->loadFromDB( $this->isVolatile() ?
0 : self
::LOAD_VIA_SLAVE
);
544 $this->saveToCache();
546 $this->dataLoaded
= true;
548 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
549 $this->loadExtraFromDB();
554 * Upgrade a row if it needs it
556 function maybeUpgradeRow() {
557 global $wgUpdateCompatibleMetadata;
558 if ( wfReadOnly() ) {
562 if ( is_null( $this->media_type
) ||
563 $this->mime
== 'image/svg'
566 $this->upgraded
= true;
568 $handler = $this->getHandler();
570 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
571 if ( $validity === MediaHandler
::METADATA_BAD
572 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
575 $this->upgraded
= true;
581 function getUpgraded() {
582 return $this->upgraded
;
586 * Fix assorted version-related problems with the image row by reloading it from the file
588 function upgradeRow() {
589 wfProfileIn( __METHOD__
);
591 $this->lock(); // begin
593 $this->loadFromFile();
595 # Don't destroy file info of missing files
596 if ( !$this->fileExists
) {
598 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
599 wfProfileOut( __METHOD__
);
604 $dbw = $this->repo
->getMasterDB();
605 list( $major, $minor ) = self
::splitMime( $this->mime
);
607 if ( wfReadOnly() ) {
609 wfProfileOut( __METHOD__
);
613 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
615 $dbw->update( 'image',
617 'img_size' => $this->size
, // sanity
618 'img_width' => $this->width
,
619 'img_height' => $this->height
,
620 'img_bits' => $this->bits
,
621 'img_media_type' => $this->media_type
,
622 'img_major_mime' => $major,
623 'img_minor_mime' => $minor,
624 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
625 'img_sha1' => $this->sha1
,
627 array( 'img_name' => $this->getName() ),
631 $this->saveToCache();
633 $this->unlock(); // done
635 wfProfileOut( __METHOD__
);
639 * Set properties in this object to be equal to those given in the
640 * associative array $info. Only cacheable fields can be set.
641 * All fields *must* be set in $info except for getLazyCacheFields().
643 * If 'mime' is given, it will be split into major_mime/minor_mime.
644 * If major_mime/minor_mime are given, $this->mime will also be set.
648 function setProps( $info ) {
649 $this->dataLoaded
= true;
650 $fields = $this->getCacheFields( '' );
651 $fields[] = 'fileExists';
653 foreach ( $fields as $field ) {
654 if ( isset( $info[$field] ) ) {
655 $this->$field = $info[$field];
659 // Fix up mime fields
660 if ( isset( $info['major_mime'] ) ) {
661 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
662 } elseif ( isset( $info['mime'] ) ) {
663 $this->mime
= $info['mime'];
664 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
668 /** splitMime inherited */
669 /** getName inherited */
670 /** getTitle inherited */
671 /** getURL inherited */
672 /** getViewURL inherited */
673 /** getPath inherited */
674 /** isVisible inhereted */
679 function isMissing() {
680 if ( $this->missing
=== null ) {
681 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
682 $this->missing
= !$fileExists;
685 return $this->missing
;
689 * Return the width of the image
694 public function getWidth( $page = 1 ) {
697 if ( $this->isMultipage() ) {
698 $handler = $this->getHandler();
702 $dim = $handler->getPageDimensions( $this, $page );
704 return $dim['width'];
706 // For non-paged media, the false goes through an
707 // intval, turning failure into 0, so do same here.
716 * Return the height of the image
721 public function getHeight( $page = 1 ) {
724 if ( $this->isMultipage() ) {
725 $handler = $this->getHandler();
729 $dim = $handler->getPageDimensions( $this, $page );
731 return $dim['height'];
733 // For non-paged media, the false goes through an
734 // intval, turning failure into 0, so do same here.
738 return $this->height
;
743 * Returns ID or name of user who uploaded the file
745 * @param string $type 'text' or 'id'
748 function getUser( $type = 'text' ) {
751 if ( $type == 'text' ) {
752 return $this->user_text
;
753 } elseif ( $type == 'id' ) {
759 * Get handler-specific metadata
762 function getMetadata() {
763 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
764 return $this->metadata
;
770 function getBitDepth() {
777 * Returns the size of the image file, in bytes
780 public function getSize() {
787 * Returns the mime type of the file.
790 function getMimeType() {
797 * Returns the type of the media in the file.
798 * Use the value returned by this function with the MEDIATYPE_xxx constants.
801 function getMediaType() {
804 return $this->media_type
;
807 /** canRender inherited */
808 /** mustRender inherited */
809 /** allowInlineDisplay inherited */
810 /** isSafeFile inherited */
811 /** isTrustedFile inherited */
814 * Returns true if the file exists on disk.
815 * @return bool Whether file exist on disk.
817 public function exists() {
820 return $this->fileExists
;
823 /** getTransformScript inherited */
824 /** getUnscaledThumb inherited */
825 /** thumbName inherited */
826 /** createThumb inherited */
827 /** transform inherited */
829 /** getHandler inherited */
830 /** iconThumb inherited */
831 /** getLastError inherited */
834 * Get all thumbnail names previously generated for this file
835 * @param string|bool $archiveName Name of an archive file, default false
836 * @return array first element is the base dir, then files in that base dir.
838 function getThumbnails( $archiveName = false ) {
839 if ( $archiveName ) {
840 $dir = $this->getArchiveThumbPath( $archiveName );
842 $dir = $this->getThumbPath();
845 $backend = $this->repo
->getBackend();
846 $files = array( $dir );
848 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
849 foreach ( $iterator as $file ) {
852 } catch ( FileBackendError
$e ) {
853 } // suppress (bug 54674)
859 * Refresh metadata in memcached, but don't touch thumbnails or squid
861 function purgeMetadataCache() {
863 $this->saveToCache();
864 $this->purgeHistory();
868 * Purge the shared history (OldLocalFile) cache.
870 * @note This used to purge old thumbnails as well.
872 function purgeHistory() {
875 $hashedName = md5( $this->getName() );
876 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
879 $wgMemc->delete( $oldKey );
884 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
886 * @param array $options An array potentially with the key forThumbRefresh.
888 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
890 function purgeCache( $options = array() ) {
891 wfProfileIn( __METHOD__
);
892 // Refresh metadata cache
893 $this->purgeMetadataCache();
896 $this->purgeThumbnails( $options );
898 // Purge squid cache for this file
899 SquidUpdate
::purge( array( $this->getURL() ) );
900 wfProfileOut( __METHOD__
);
904 * Delete cached transformed files for an archived version only.
905 * @param string $archiveName Name of the archived file
907 function purgeOldThumbnails( $archiveName ) {
909 wfProfileIn( __METHOD__
);
911 // Get a list of old thumbnails and URLs
912 $files = $this->getThumbnails( $archiveName );
914 // Purge any custom thumbnail caches
915 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
917 $dir = array_shift( $files );
918 $this->purgeThumbList( $dir, $files );
923 foreach ( $files as $file ) {
924 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
926 SquidUpdate
::purge( $urls );
929 wfProfileOut( __METHOD__
);
933 * Delete cached transformed files for the current version only.
935 function purgeThumbnails( $options = array() ) {
937 wfProfileIn( __METHOD__
);
940 $files = $this->getThumbnails();
941 // Always purge all files from squid regardless of handler filters
944 foreach ( $files as $file ) {
945 $urls[] = $this->getThumbUrl( $file );
947 array_shift( $urls ); // don't purge directory
950 // Give media handler a chance to filter the file purge list
951 if ( !empty( $options['forThumbRefresh'] ) ) {
952 $handler = $this->getHandler();
954 $handler->filterThumbnailPurgeList( $files, $options );
958 // Purge any custom thumbnail caches
959 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
961 $dir = array_shift( $files );
962 $this->purgeThumbList( $dir, $files );
966 SquidUpdate
::purge( $urls );
969 wfProfileOut( __METHOD__
);
973 * Delete a list of thumbnails visible at urls
974 * @param string $dir Base dir of the files.
975 * @param array $files Array of strings: relative filenames (to $dir)
977 protected function purgeThumbList( $dir, $files ) {
978 $fileListDebug = strtr(
979 var_export( $files, true ),
982 wfDebug( __METHOD__
. ": $fileListDebug\n" );
984 $purgeList = array();
985 foreach ( $files as $file ) {
986 # Check that the base file name is part of the thumb name
987 # This is a basic sanity check to avoid erasing unrelated directories
988 if ( strpos( $file, $this->getName() ) !== false
989 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
991 $purgeList[] = "{$dir}/{$file}";
995 # Delete the thumbnails
996 $this->repo
->quickPurgeBatch( $purgeList );
997 # Clear out the thumbnail directory if empty
998 $this->repo
->quickCleanDir( $dir );
1001 /** purgeDescription inherited */
1002 /** purgeEverything inherited */
1005 * @param int $limit Optional: Limit to number of results
1006 * @param int $start Optional: Timestamp, start from
1007 * @param int $end Optional: Timestamp, end at
1011 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1012 $dbr = $this->repo
->getSlaveDB();
1013 $tables = array( 'oldimage' );
1014 $fields = OldLocalFile
::selectFields();
1015 $conds = $opts = $join_conds = array();
1016 $eq = $inc ?
'=' : '';
1017 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1020 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1024 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1028 $opts['LIMIT'] = $limit;
1031 // Search backwards for time > x queries
1032 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1033 $opts['ORDER BY'] = "oi_timestamp $order";
1034 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1036 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1037 &$conds, &$opts, &$join_conds ) );
1039 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1042 foreach ( $res as $row ) {
1043 $r[] = $this->repo
->newFileFromRow( $row );
1046 if ( $order == 'ASC' ) {
1047 $r = array_reverse( $r ); // make sure it ends up descending
1054 * Returns the history of this file, line by line.
1055 * starts with current version, then old versions.
1056 * uses $this->historyLine to check which line to return:
1057 * 0 return line for current version
1058 * 1 query for old versions, return first one
1059 * 2, ... return next old version from above query
1062 public function nextHistoryLine() {
1063 # Polymorphic function name to distinguish foreign and local fetches
1064 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1066 $dbr = $this->repo
->getSlaveDB();
1068 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1069 $this->historyRes
= $dbr->select( 'image',
1072 "'' AS oi_archive_name",
1076 array( 'img_name' => $this->title
->getDBkey() ),
1080 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1081 $this->historyRes
= null;
1085 } elseif ( $this->historyLine
== 1 ) {
1086 $this->historyRes
= $dbr->select( 'oldimage', '*',
1087 array( 'oi_name' => $this->title
->getDBkey() ),
1089 array( 'ORDER BY' => 'oi_timestamp DESC' )
1092 $this->historyLine++
;
1094 return $dbr->fetchObject( $this->historyRes
);
1098 * Reset the history pointer to the first element of the history
1100 public function resetHistory() {
1101 $this->historyLine
= 0;
1103 if ( !is_null( $this->historyRes
) ) {
1104 $this->historyRes
= null;
1108 /** getHashPath inherited */
1109 /** getRel inherited */
1110 /** getUrlRel inherited */
1111 /** getArchiveRel inherited */
1112 /** getArchivePath inherited */
1113 /** getThumbPath inherited */
1114 /** getArchiveUrl inherited */
1115 /** getThumbUrl inherited */
1116 /** getArchiveVirtualUrl inherited */
1117 /** getThumbVirtualUrl inherited */
1118 /** isHashed inherited */
1121 * Upload a file and record it in the DB
1122 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1123 * @param string $comment Upload description
1124 * @param string $pageText Text to use for the new description page,
1125 * if a new description page is created
1126 * @param int|bool $flags Flags for publish()
1127 * @param array|bool $props File properties, if known. This can be used to
1128 * reduce the upload time when uploading virtual URLs for which the file
1129 * info is already known
1130 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1132 * @param User|null $user User object or null to use $wgUser
1134 * @return FileRepoStatus On success, the value member contains the
1135 * archive name, or an empty string if it was a new file.
1137 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1138 $timestamp = false, $user = null
1142 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1143 return $this->readOnlyFatalStatus();
1147 wfProfileIn( __METHOD__
. '-getProps' );
1148 if ( $this->repo
->isVirtualUrl( $srcPath )
1149 || FileBackend
::isStoragePath( $srcPath )
1151 $props = $this->repo
->getFileProps( $srcPath );
1153 $props = FSFile
::getPropsFromPath( $srcPath );
1155 wfProfileOut( __METHOD__
. '-getProps' );
1159 $handler = MediaHandler
::getHandler( $props['mime'] );
1161 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1163 $options['headers'] = array();
1166 // Trim spaces on user supplied text
1167 $comment = trim( $comment );
1169 // Truncate nicely or the DB will do it for us
1170 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1171 $comment = $wgContLang->truncate( $comment, 255 );
1172 $this->lock(); // begin
1173 $status = $this->publish( $srcPath, $flags, $options );
1175 if ( $status->successCount
>= 2 ) {
1176 // There will be a copy+(one of move,copy,store).
1177 // The first succeeding does not commit us to updating the DB
1178 // since it simply copied the current version to a timestamped file name.
1179 // It is only *preferable* to avoid leaving such files orphaned.
1180 // Once the second operation goes through, then the current version was
1181 // updated and we must therefore update the DB too.
1182 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1183 $status->fatal( 'filenotfound', $srcPath );
1187 $this->unlock(); // done
1193 * Record a file upload in the upload log and the image table
1194 * @param string $oldver
1195 * @param string $desc
1196 * @param string $license
1197 * @param string $copyStatus
1198 * @param string $source
1199 * @param bool $watch
1200 * @param string|bool $timestamp
1201 * @param User|null $user User object or null to use $wgUser
1204 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1205 $watch = false, $timestamp = false, User
$user = null ) {
1211 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1213 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1218 $user->addWatch( $this->getTitle() );
1225 * Record a file upload in the upload log and the image table
1226 * @param string $oldver
1227 * @param string $comment
1228 * @param string $pageText
1229 * @param bool|array $props
1230 * @param string|bool $timestamp
1231 * @param null|User $user
1234 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1237 wfProfileIn( __METHOD__
);
1239 if ( is_null( $user ) ) {
1244 $dbw = $this->repo
->getMasterDB();
1245 $dbw->begin( __METHOD__
);
1248 wfProfileIn( __METHOD__
. '-getProps' );
1249 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1250 wfProfileOut( __METHOD__
. '-getProps' );
1253 # Imports or such might force a certain timestamp; otherwise we generate
1254 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1255 if ( $timestamp === false ) {
1256 $timestamp = $dbw->timestamp();
1257 $allowTimeKludge = true;
1259 $allowTimeKludge = false;
1262 $props['description'] = $comment;
1263 $props['user'] = $user->getId();
1264 $props['user_text'] = $user->getName();
1265 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1266 $this->setProps( $props );
1268 # Fail now if the file isn't there
1269 if ( !$this->fileExists
) {
1270 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1271 $dbw->rollback( __METHOD__
);
1272 wfProfileOut( __METHOD__
);
1279 # Test to see if the row exists using INSERT IGNORE
1280 # This avoids race conditions by locking the row until the commit, and also
1281 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1282 $dbw->insert( 'image',
1284 'img_name' => $this->getName(),
1285 'img_size' => $this->size
,
1286 'img_width' => intval( $this->width
),
1287 'img_height' => intval( $this->height
),
1288 'img_bits' => $this->bits
,
1289 'img_media_type' => $this->media_type
,
1290 'img_major_mime' => $this->major_mime
,
1291 'img_minor_mime' => $this->minor_mime
,
1292 'img_timestamp' => $timestamp,
1293 'img_description' => $comment,
1294 'img_user' => $user->getId(),
1295 'img_user_text' => $user->getName(),
1296 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1297 'img_sha1' => $this->sha1
1302 if ( $dbw->affectedRows() == 0 ) {
1303 if ( $allowTimeKludge ) {
1304 # Use FOR UPDATE to ignore any transaction snapshotting
1305 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1306 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1307 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1308 # Avoid a timestamp that is not newer than the last version
1309 # TODO: the image/oldimage tables should be like page/revision with an ID field
1310 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1311 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1312 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1313 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1317 # (bug 34993) Note: $oldver can be empty here, if the previous
1318 # version of the file was broken. Allow registration of the new
1319 # version to continue anyway, because that's better than having
1320 # an image that's not fixable by user operations.
1323 # Collision, this is an update of a file
1324 # Insert previous contents into oldimage
1325 $dbw->insertSelect( 'oldimage', 'image',
1327 'oi_name' => 'img_name',
1328 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1329 'oi_size' => 'img_size',
1330 'oi_width' => 'img_width',
1331 'oi_height' => 'img_height',
1332 'oi_bits' => 'img_bits',
1333 'oi_timestamp' => 'img_timestamp',
1334 'oi_description' => 'img_description',
1335 'oi_user' => 'img_user',
1336 'oi_user_text' => 'img_user_text',
1337 'oi_metadata' => 'img_metadata',
1338 'oi_media_type' => 'img_media_type',
1339 'oi_major_mime' => 'img_major_mime',
1340 'oi_minor_mime' => 'img_minor_mime',
1341 'oi_sha1' => 'img_sha1'
1343 array( 'img_name' => $this->getName() ),
1347 # Update the current image row
1348 $dbw->update( 'image',
1350 'img_size' => $this->size
,
1351 'img_width' => intval( $this->width
),
1352 'img_height' => intval( $this->height
),
1353 'img_bits' => $this->bits
,
1354 'img_media_type' => $this->media_type
,
1355 'img_major_mime' => $this->major_mime
,
1356 'img_minor_mime' => $this->minor_mime
,
1357 'img_timestamp' => $timestamp,
1358 'img_description' => $comment,
1359 'img_user' => $user->getId(),
1360 'img_user_text' => $user->getName(),
1361 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1362 'img_sha1' => $this->sha1
1364 array( 'img_name' => $this->getName() ),
1368 # This is a new file, so update the image count
1369 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1372 $descTitle = $this->getTitle();
1373 $wikiPage = new WikiFilePage( $descTitle );
1374 $wikiPage->setFile( $this );
1377 $action = $reupload ?
'overwrite' : 'upload';
1379 $logEntry = new ManualLogEntry( 'upload', $action );
1380 $logEntry->setPerformer( $user );
1381 $logEntry->setComment( $comment );
1382 $logEntry->setTarget( $descTitle );
1384 // Allow people using the api to associate log entries with the upload.
1385 // Log has a timestamp, but sometimes different from upload timestamp.
1386 $logEntry->setParameters(
1388 'img_sha1' => $this->sha1
,
1389 'img_timestamp' => $timestamp,
1392 // Note we keep $logId around since during new image
1393 // creation, page doesn't exist yet, so log_page = 0
1394 // but we want it to point to the page we're making,
1395 // so we later modify the log entry.
1396 // For a similar reason, we avoid making an RC entry
1397 // now and wait until the page exists.
1398 $logId = $logEntry->insert();
1400 $exists = $descTitle->exists();
1402 // Page exists, do RC entry now (otherwise we wait for later).
1403 $logEntry->publish( $logId );
1405 wfProfileIn( __METHOD__
. '-edit' );
1408 # Create a null revision
1409 $latest = $descTitle->getLatestRevID();
1410 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1412 $nullRevision = Revision
::newNullRevision(
1414 $descTitle->getArticleID(),
1419 if ( !is_null( $nullRevision ) ) {
1420 $nullRevision->insertOn( $dbw );
1422 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1423 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1427 # Commit the transaction now, in case something goes wrong later
1428 # The most important thing is that files don't get lost, especially archives
1429 # NOTE: once we have support for nested transactions, the commit may be moved
1430 # to after $wikiPage->doEdit has been called.
1431 $dbw->commit( __METHOD__
);
1434 # We shall not saveToCache before the commit since otherwise
1435 # in case of a rollback there is an usable file from memcached
1436 # which in fact doesn't really exist (bug 24978)
1437 $this->saveToCache();
1440 # Invalidate the cache for the description page
1441 $descTitle->invalidateCache();
1442 $descTitle->purgeSquid();
1444 # New file; create the description page.
1445 # There's already a log entry, so don't make a second RC entry
1446 # Squid and file cache for the description page are purged by doEditContent.
1447 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1448 $status = $wikiPage->doEditContent(
1451 EDIT_NEW | EDIT_SUPPRESS_RC
,
1456 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1457 // Now that the page exists, make an RC entry.
1458 $logEntry->publish( $logId );
1459 if ( isset( $status->value
['revision'] ) ) {
1460 $dbw->update( 'logging',
1461 array( 'log_page' => $status->value
['revision']->getPage() ),
1462 array( 'log_id' => $logId ),
1466 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1469 wfProfileOut( __METHOD__
. '-edit' );
1472 # Delete old thumbnails
1473 wfProfileIn( __METHOD__
. '-purge' );
1474 $this->purgeThumbnails();
1475 wfProfileOut( __METHOD__
. '-purge' );
1477 # Remove the old file from the squid cache
1478 SquidUpdate
::purge( array( $this->getURL() ) );
1481 # Hooks, hooks, the magic of hooks...
1482 wfProfileIn( __METHOD__
. '-hooks' );
1483 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1484 wfProfileOut( __METHOD__
. '-hooks' );
1486 # Invalidate cache for all pages using this file
1487 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1488 $update->doUpdate();
1490 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1493 wfProfileOut( __METHOD__
);
1499 * Move or copy a file to its public location. If a file exists at the
1500 * destination, move it to an archive. Returns a FileRepoStatus object with
1501 * the archive name in the "value" member on success.
1503 * The archive name should be passed through to recordUpload for database
1506 * @param string $srcPath Local filesystem path to the source image
1507 * @param int $flags A bitwise combination of:
1508 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1509 * @param array $options Optional additional parameters
1510 * @return FileRepoStatus On success, the value member contains the
1511 * archive name, or an empty string if it was a new file.
1513 function publish( $srcPath, $flags = 0, array $options = array() ) {
1514 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1518 * Move or copy a file to a specified location. Returns a FileRepoStatus
1519 * object with the archive name in the "value" member on success.
1521 * The archive name should be passed through to recordUpload for database
1524 * @param string $srcPath Local filesystem path to the source image
1525 * @param string $dstRel Target relative path
1526 * @param int $flags A bitwise combination of:
1527 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1528 * @param array $options Optional additional parameters
1529 * @return FileRepoStatus On success, the value member contains the
1530 * archive name, or an empty string if it was a new file.
1532 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1533 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1534 return $this->readOnlyFatalStatus();
1537 $this->lock(); // begin
1539 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1540 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1541 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1542 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1544 if ( $status->value
== 'new' ) {
1545 $status->value
= '';
1547 $status->value
= $archiveName;
1550 $this->unlock(); // done
1555 /** getLinksTo inherited */
1556 /** getExifData inherited */
1557 /** isLocal inherited */
1558 /** wasDeleted inherited */
1561 * Move file to the new title
1563 * Move current, old version and all thumbnails
1564 * to the new filename. Old file is deleted.
1566 * Cache purging is done; checks for validity
1567 * and logging are caller's responsibility
1569 * @param Title $target New file name
1570 * @return FileRepoStatus
1572 function move( $target ) {
1573 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1574 return $this->readOnlyFatalStatus();
1577 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1578 $batch = new LocalFileMoveBatch( $this, $target );
1580 $this->lock(); // begin
1581 $batch->addCurrent();
1582 $archiveNames = $batch->addOlds();
1583 $status = $batch->execute();
1584 $this->unlock(); // done
1586 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1588 // Purge the source and target files...
1589 $oldTitleFile = wfLocalFile( $this->title
);
1590 $newTitleFile = wfLocalFile( $target );
1591 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1592 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1593 $this->getRepo()->getMasterDB()->onTransactionIdle(
1594 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1595 $oldTitleFile->purgeEverything();
1596 foreach ( $archiveNames as $archiveName ) {
1597 $oldTitleFile->purgeOldThumbnails( $archiveName );
1599 $newTitleFile->purgeEverything();
1603 if ( $status->isOK() ) {
1604 // Now switch the object
1605 $this->title
= $target;
1606 // Force regeneration of the name and hashpath
1607 unset( $this->name
);
1608 unset( $this->hashPath
);
1615 * Delete all versions of the file.
1617 * Moves the files into an archive directory (or deletes them)
1618 * and removes the database rows.
1620 * Cache purging is done; logging is caller's responsibility.
1622 * @param string $reason
1623 * @param bool $suppress
1624 * @param User|null $user
1625 * @return FileRepoStatus
1627 function delete( $reason, $suppress = false, $user = null ) {
1628 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1629 return $this->readOnlyFatalStatus();
1632 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1634 $this->lock(); // begin
1635 $batch->addCurrent();
1636 # Get old version relative paths
1637 $archiveNames = $batch->addOlds();
1638 $status = $batch->execute();
1639 $this->unlock(); // done
1641 if ( $status->isOK() ) {
1642 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1645 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1646 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1648 $this->getRepo()->getMasterDB()->onTransactionIdle(
1649 function () use ( $file, $archiveNames ) {
1652 $file->purgeEverything();
1653 foreach ( $archiveNames as $archiveName ) {
1654 $file->purgeOldThumbnails( $archiveName );
1657 if ( $wgUseSquid ) {
1659 $purgeUrls = array();
1660 foreach ( $archiveNames as $archiveName ) {
1661 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1663 SquidUpdate
::purge( $purgeUrls );
1672 * Delete an old version of the file.
1674 * Moves the file into an archive directory (or deletes it)
1675 * and removes the database row.
1677 * Cache purging is done; logging is caller's responsibility.
1679 * @param string $archiveName
1680 * @param string $reason
1681 * @param bool $suppress
1682 * @param User|null $user
1683 * @throws MWException Exception on database or file store failure
1684 * @return FileRepoStatus
1686 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1688 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1689 return $this->readOnlyFatalStatus();
1692 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1694 $this->lock(); // begin
1695 $batch->addOld( $archiveName );
1696 $status = $batch->execute();
1697 $this->unlock(); // done
1699 $this->purgeOldThumbnails( $archiveName );
1700 if ( $status->isOK() ) {
1701 $this->purgeDescription();
1702 $this->purgeHistory();
1705 if ( $wgUseSquid ) {
1707 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1714 * Restore all or specified deleted revisions to the given file.
1715 * Permissions and logging are left to the caller.
1717 * May throw database exceptions on error.
1719 * @param array $versions Set of record ids of deleted items to restore,
1720 * or empty to restore all revisions.
1721 * @param bool $unsuppress
1722 * @return FileRepoStatus
1724 function restore( $versions = array(), $unsuppress = false ) {
1725 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1726 return $this->readOnlyFatalStatus();
1729 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1731 $this->lock(); // begin
1735 $batch->addIds( $versions );
1737 $status = $batch->execute();
1738 if ( $status->isGood() ) {
1739 $cleanupStatus = $batch->cleanup();
1740 $cleanupStatus->successCount
= 0;
1741 $cleanupStatus->failCount
= 0;
1742 $status->merge( $cleanupStatus );
1744 $this->unlock(); // done
1749 /** isMultipage inherited */
1750 /** pageCount inherited */
1751 /** scaleHeight inherited */
1752 /** getImageSize inherited */
1755 * Get the URL of the file description page.
1758 function getDescriptionUrl() {
1759 return $this->title
->getLocalURL();
1763 * Get the HTML text of the description page
1764 * This is not used by ImagePage for local files, since (among other things)
1765 * it skips the parser cache.
1767 * @param Language $lang What language to get description in (Optional)
1768 * @return bool|mixed
1770 function getDescriptionText( $lang = null ) {
1771 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1775 $content = $revision->getContent();
1779 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1781 return $pout->getText();
1785 * @param int $audience
1789 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1791 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1793 } elseif ( $audience == self
::FOR_THIS_USER
1794 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1798 return $this->description
;
1803 * @return bool|string
1805 function getTimestamp() {
1808 return $this->timestamp
;
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->saveToCache();
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 success
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 $this->markVolatile(); // file may change soon
1882 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1883 * the transaction and thereby releases the image lock.
1886 if ( $this->locked
) {
1888 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1889 $dbw = $this->repo
->getMasterDB();
1890 $dbw->commit( __METHOD__
);
1891 $this->lockedOwnTrx
= false;
1897 * Mark a file as about to be changed
1899 * This sets a cache key that alters master/slave DB loading behavior
1901 * @return bool Success
1903 protected function markVolatile() {
1906 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1908 $this->lastMarkedVolatile
= time();
1909 return $wgMemc->set( $key, $this->lastMarkedVolatile
, self
::VOLATILE_TTL
);
1916 * Check if a file is about to be changed or has been changed recently
1918 * @see LocalFile::isVolatile()
1919 * @return bool Whether the file is volatile
1921 protected function isVolatile() {
1924 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1926 // repo unavailable; bail.
1930 if ( $this->lastMarkedVolatile
=== 0 ) {
1931 $this->lastMarkedVolatile
= $wgMemc->get( $key ) ?
: 0;
1934 $volatileDuration = time() - $this->lastMarkedVolatile
;
1935 return $volatileDuration <= self
::VOLATILE_TTL
;
1939 * Roll back the DB transaction and mark the image unlocked
1941 function unlockAndRollback() {
1942 $this->locked
= false;
1943 $dbw = $this->repo
->getMasterDB();
1944 $dbw->rollback( __METHOD__
);
1945 $this->lockedOwnTrx
= false;
1951 protected function readOnlyFatalStatus() {
1952 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1953 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1957 * Clean up any dangling locks
1959 function __destruct() {
1962 } // LocalFile class
1964 # ------------------------------------------------------------------------------
1967 * Helper class for file deletion
1968 * @ingroup FileAbstraction
1970 class LocalFileDeleteBatch
{
1971 /** @var LocalFile */
1978 private $srcRels = array();
1981 private $archiveUrls = array();
1983 /** @var array Items to be processed in the deletion batch */
1984 private $deletionBatch;
1986 /** @var bool Wether to suppress all suppressable fields when deleting */
1989 /** @var FileRepoStatus */
1997 * @param string $reason
1998 * @param bool $suppress
1999 * @param User|null $user
2001 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2002 $this->file
= $file;
2003 $this->reason
= $reason;
2004 $this->suppress
= $suppress;
2006 $this->user
= $user;
2009 $this->user
= $wgUser;
2011 $this->status
= $file->repo
->newGood();
2014 function addCurrent() {
2015 $this->srcRels
['.'] = $this->file
->getRel();
2019 * @param string $oldName
2021 function addOld( $oldName ) {
2022 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2023 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2027 * Add the old versions of the image to the batch
2028 * @return array List of archive names from old versions
2030 function addOlds() {
2031 $archiveNames = array();
2033 $dbw = $this->file
->repo
->getMasterDB();
2034 $result = $dbw->select( 'oldimage',
2035 array( 'oi_archive_name' ),
2036 array( 'oi_name' => $this->file
->getName() ),
2040 foreach ( $result as $row ) {
2041 $this->addOld( $row->oi_archive_name
);
2042 $archiveNames[] = $row->oi_archive_name
;
2045 return $archiveNames;
2051 function getOldRels() {
2052 if ( !isset( $this->srcRels
['.'] ) ) {
2053 $oldRels =& $this->srcRels
;
2054 $deleteCurrent = false;
2056 $oldRels = $this->srcRels
;
2057 unset( $oldRels['.'] );
2058 $deleteCurrent = true;
2061 return array( $oldRels, $deleteCurrent );
2067 protected function getHashes() {
2069 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2071 if ( $deleteCurrent ) {
2072 $hashes['.'] = $this->file
->getSha1();
2075 if ( count( $oldRels ) ) {
2076 $dbw = $this->file
->repo
->getMasterDB();
2077 $res = $dbw->select(
2079 array( 'oi_archive_name', 'oi_sha1' ),
2080 array( 'oi_archive_name' => array_keys( $oldRels ),
2081 'oi_name' => $this->file
->getName() ), // performance
2085 foreach ( $res as $row ) {
2086 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2087 // Get the hash from the file
2088 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2089 $props = $this->file
->repo
->getFileProps( $oldUrl );
2091 if ( $props['fileExists'] ) {
2092 // Upgrade the oldimage row
2093 $dbw->update( 'oldimage',
2094 array( 'oi_sha1' => $props['sha1'] ),
2095 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2097 $hashes[$row->oi_archive_name
] = $props['sha1'];
2099 $hashes[$row->oi_archive_name
] = false;
2102 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2107 $missing = array_diff_key( $this->srcRels
, $hashes );
2109 foreach ( $missing as $name => $rel ) {
2110 $this->status
->error( 'filedelete-old-unregistered', $name );
2113 foreach ( $hashes as $name => $hash ) {
2115 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2116 unset( $hashes[$name] );
2123 function doDBInserts() {
2124 $dbw = $this->file
->repo
->getMasterDB();
2125 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2126 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2127 $encReason = $dbw->addQuotes( $this->reason
);
2128 $encGroup = $dbw->addQuotes( 'deleted' );
2129 $ext = $this->file
->getExtension();
2130 $dotExt = $ext === '' ?
'' : ".$ext";
2131 $encExt = $dbw->addQuotes( $dotExt );
2132 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2134 // Bitfields to further suppress the content
2135 if ( $this->suppress
) {
2137 // This should be 15...
2138 $bitfield |
= Revision
::DELETED_TEXT
;
2139 $bitfield |
= Revision
::DELETED_COMMENT
;
2140 $bitfield |
= Revision
::DELETED_USER
;
2141 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2143 $bitfield = 'oi_deleted';
2146 if ( $deleteCurrent ) {
2147 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2148 $where = array( 'img_name' => $this->file
->getName() );
2149 $dbw->insertSelect( 'filearchive', 'image',
2151 'fa_storage_group' => $encGroup,
2152 'fa_storage_key' => $dbw->conditional(
2153 array( 'img_sha1' => '' ),
2154 $dbw->addQuotes( '' ),
2157 'fa_deleted_user' => $encUserId,
2158 'fa_deleted_timestamp' => $encTimestamp,
2159 'fa_deleted_reason' => $encReason,
2160 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2162 'fa_name' => 'img_name',
2163 'fa_archive_name' => 'NULL',
2164 'fa_size' => 'img_size',
2165 'fa_width' => 'img_width',
2166 'fa_height' => 'img_height',
2167 'fa_metadata' => 'img_metadata',
2168 'fa_bits' => 'img_bits',
2169 'fa_media_type' => 'img_media_type',
2170 'fa_major_mime' => 'img_major_mime',
2171 'fa_minor_mime' => 'img_minor_mime',
2172 'fa_description' => 'img_description',
2173 'fa_user' => 'img_user',
2174 'fa_user_text' => 'img_user_text',
2175 'fa_timestamp' => 'img_timestamp',
2176 'fa_sha1' => 'img_sha1',
2177 ), $where, __METHOD__
);
2180 if ( count( $oldRels ) ) {
2181 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2183 'oi_name' => $this->file
->getName(),
2184 'oi_archive_name' => array_keys( $oldRels ) );
2185 $dbw->insertSelect( 'filearchive', 'oldimage',
2187 'fa_storage_group' => $encGroup,
2188 'fa_storage_key' => $dbw->conditional(
2189 array( 'oi_sha1' => '' ),
2190 $dbw->addQuotes( '' ),
2193 'fa_deleted_user' => $encUserId,
2194 'fa_deleted_timestamp' => $encTimestamp,
2195 'fa_deleted_reason' => $encReason,
2196 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2198 'fa_name' => 'oi_name',
2199 'fa_archive_name' => 'oi_archive_name',
2200 'fa_size' => 'oi_size',
2201 'fa_width' => 'oi_width',
2202 'fa_height' => 'oi_height',
2203 'fa_metadata' => 'oi_metadata',
2204 'fa_bits' => 'oi_bits',
2205 'fa_media_type' => 'oi_media_type',
2206 'fa_major_mime' => 'oi_major_mime',
2207 'fa_minor_mime' => 'oi_minor_mime',
2208 'fa_description' => 'oi_description',
2209 'fa_user' => 'oi_user',
2210 'fa_user_text' => 'oi_user_text',
2211 'fa_timestamp' => 'oi_timestamp',
2212 'fa_sha1' => 'oi_sha1',
2213 ), $where, __METHOD__
);
2217 function doDBDeletes() {
2218 $dbw = $this->file
->repo
->getMasterDB();
2219 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2221 if ( count( $oldRels ) ) {
2222 $dbw->delete( 'oldimage',
2224 'oi_name' => $this->file
->getName(),
2225 'oi_archive_name' => array_keys( $oldRels )
2229 if ( $deleteCurrent ) {
2230 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2235 * Run the transaction
2236 * @return FileRepoStatus
2238 function execute() {
2239 wfProfileIn( __METHOD__
);
2241 $this->file
->lock();
2242 // Leave private files alone
2243 $privateFiles = array();
2244 list( $oldRels, ) = $this->getOldRels();
2245 $dbw = $this->file
->repo
->getMasterDB();
2247 if ( !empty( $oldRels ) ) {
2248 $res = $dbw->select( 'oldimage',
2249 array( 'oi_archive_name' ),
2250 array( 'oi_name' => $this->file
->getName(),
2251 'oi_archive_name' => array_keys( $oldRels ),
2252 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2255 foreach ( $res as $row ) {
2256 $privateFiles[$row->oi_archive_name
] = 1;
2259 // Prepare deletion batch
2260 $hashes = $this->getHashes();
2261 $this->deletionBatch
= array();
2262 $ext = $this->file
->getExtension();
2263 $dotExt = $ext === '' ?
'' : ".$ext";
2265 foreach ( $this->srcRels
as $name => $srcRel ) {
2266 // Skip files that have no hash (missing source).
2267 // Keep private files where they are.
2268 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2269 $hash = $hashes[$name];
2270 $key = $hash . $dotExt;
2271 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2272 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2276 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2277 // We acquire this lock by running the inserts now, before the file operations.
2279 // This potentially has poor lock contention characteristics -- an alternative
2280 // scheme would be to insert stub filearchive entries with no fa_name and commit
2281 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2282 $this->doDBInserts();
2284 // Removes non-existent file from the batch, so we don't get errors.
2285 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2287 // Execute the file deletion batch
2288 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2290 if ( !$status->isGood() ) {
2291 $this->status
->merge( $status );
2294 if ( !$this->status
->isOK() ) {
2295 // Critical file deletion error
2296 // Roll back inserts, release lock and abort
2297 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2298 $this->file
->unlockAndRollback();
2299 wfProfileOut( __METHOD__
);
2301 return $this->status
;
2304 // Delete image/oldimage rows
2305 $this->doDBDeletes();
2307 // Commit and return
2308 $this->file
->unlock();
2309 wfProfileOut( __METHOD__
);
2311 return $this->status
;
2315 * Removes non-existent files from a deletion batch.
2316 * @param array $batch
2319 function removeNonexistentFiles( $batch ) {
2320 $files = $newBatch = array();
2322 foreach ( $batch as $batchItem ) {
2323 list( $src, ) = $batchItem;
2324 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2327 $result = $this->file
->repo
->fileExistsBatch( $files );
2329 foreach ( $batch as $batchItem ) {
2330 if ( $result[$batchItem[0]] ) {
2331 $newBatch[] = $batchItem;
2339 # ------------------------------------------------------------------------------
2342 * Helper class for file undeletion
2343 * @ingroup FileAbstraction
2345 class LocalFileRestoreBatch
{
2346 /** @var LocalFile */
2349 /** @var array List of file IDs to restore */
2350 private $cleanupBatch;
2352 /** @var array List of file IDs to restore */
2355 /** @var bool Add all revisions of the file */
2358 /** @var bool Wether to remove all settings for suppressed fields */
2359 private $unsuppress = false;
2363 * @param bool $unsuppress
2365 function __construct( File
$file, $unsuppress = false ) {
2366 $this->file
= $file;
2367 $this->cleanupBatch
= $this->ids
= array();
2368 $this->ids
= array();
2369 $this->unsuppress
= $unsuppress;
2375 function addId( $fa_id ) {
2376 $this->ids
[] = $fa_id;
2380 * Add a whole lot of files by ID
2382 function addIds( $ids ) {
2383 $this->ids
= array_merge( $this->ids
, $ids );
2387 * Add all revisions of the file
2394 * Run the transaction, except the cleanup batch.
2395 * The cleanup batch should be run in a separate transaction, because it locks different
2396 * rows and there's no need to keep the image row locked while it's acquiring those locks
2397 * The caller may have its own transaction open.
2398 * So we save the batch and let the caller call cleanup()
2399 * @return FileRepoStatus
2401 function execute() {
2404 if ( !$this->all
&& !$this->ids
) {
2406 return $this->file
->repo
->newGood();
2409 $this->file
->lock();
2411 $dbw = $this->file
->repo
->getMasterDB();
2412 $status = $this->file
->repo
->newGood();
2414 $exists = (bool)$dbw->selectField( 'image', '1',
2415 array( 'img_name' => $this->file
->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
2417 // Fetch all or selected archived revisions for the file,
2418 // sorted from the most recent to the oldest.
2419 $conditions = array( 'fa_name' => $this->file
->getName() );
2421 if ( !$this->all
) {
2422 $conditions['fa_id'] = $this->ids
;
2425 $result = $dbw->select(
2427 ArchivedFile
::selectFields(),
2430 array( 'ORDER BY' => 'fa_timestamp DESC' )
2433 $idsPresent = array();
2434 $storeBatch = array();
2435 $insertBatch = array();
2436 $insertCurrent = false;
2437 $deleteIds = array();
2439 $archiveNames = array();
2441 foreach ( $result as $row ) {
2442 $idsPresent[] = $row->fa_id
;
2444 if ( $row->fa_name
!= $this->file
->getName() ) {
2445 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2446 $status->failCount++
;
2450 if ( $row->fa_storage_key
== '' ) {
2451 // Revision was missing pre-deletion
2452 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2453 $status->failCount++
;
2457 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2458 $row->fa_storage_key
;
2459 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2461 if ( isset( $row->fa_sha1
) ) {
2462 $sha1 = $row->fa_sha1
;
2464 // old row, populate from key
2465 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2469 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2470 $sha1 = substr( $sha1, 1 );
2473 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2474 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2475 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2476 ||
is_null( $row->fa_metadata
)
2478 // Refresh our metadata
2479 // Required for a new current revision; nice for older ones too. :)
2480 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2483 'minor_mime' => $row->fa_minor_mime
,
2484 'major_mime' => $row->fa_major_mime
,
2485 'media_type' => $row->fa_media_type
,
2486 'metadata' => $row->fa_metadata
2490 if ( $first && !$exists ) {
2491 // This revision will be published as the new current version
2492 $destRel = $this->file
->getRel();
2493 $insertCurrent = array(
2494 'img_name' => $row->fa_name
,
2495 'img_size' => $row->fa_size
,
2496 'img_width' => $row->fa_width
,
2497 'img_height' => $row->fa_height
,
2498 'img_metadata' => $props['metadata'],
2499 'img_bits' => $row->fa_bits
,
2500 'img_media_type' => $props['media_type'],
2501 'img_major_mime' => $props['major_mime'],
2502 'img_minor_mime' => $props['minor_mime'],
2503 'img_description' => $row->fa_description
,
2504 'img_user' => $row->fa_user
,
2505 'img_user_text' => $row->fa_user_text
,
2506 'img_timestamp' => $row->fa_timestamp
,
2510 // The live (current) version cannot be hidden!
2511 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2512 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2513 $this->cleanupBatch
[] = $row->fa_storage_key
;
2516 $archiveName = $row->fa_archive_name
;
2518 if ( $archiveName == '' ) {
2519 // This was originally a current version; we
2520 // have to devise a new archive name for it.
2521 // Format is <timestamp of archiving>!<name>
2522 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2525 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2527 } while ( isset( $archiveNames[$archiveName] ) );
2530 $archiveNames[$archiveName] = true;
2531 $destRel = $this->file
->getArchiveRel( $archiveName );
2532 $insertBatch[] = array(
2533 'oi_name' => $row->fa_name
,
2534 'oi_archive_name' => $archiveName,
2535 'oi_size' => $row->fa_size
,
2536 'oi_width' => $row->fa_width
,
2537 'oi_height' => $row->fa_height
,
2538 'oi_bits' => $row->fa_bits
,
2539 'oi_description' => $row->fa_description
,
2540 'oi_user' => $row->fa_user
,
2541 'oi_user_text' => $row->fa_user_text
,
2542 'oi_timestamp' => $row->fa_timestamp
,
2543 'oi_metadata' => $props['metadata'],
2544 'oi_media_type' => $props['media_type'],
2545 'oi_major_mime' => $props['major_mime'],
2546 'oi_minor_mime' => $props['minor_mime'],
2547 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2548 'oi_sha1' => $sha1 );
2551 $deleteIds[] = $row->fa_id
;
2553 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2554 // private files can stay where they are
2555 $status->successCount++
;
2557 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2558 $this->cleanupBatch
[] = $row->fa_storage_key
;
2566 // Add a warning to the status object for missing IDs
2567 $missingIds = array_diff( $this->ids
, $idsPresent );
2569 foreach ( $missingIds as $id ) {
2570 $status->error( 'undelete-missing-filearchive', $id );
2573 // Remove missing files from batch, so we don't get errors when undeleting them
2574 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2576 // Run the store batch
2577 // Use the OVERWRITE_SAME flag to smooth over a common error
2578 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2579 $status->merge( $storeStatus );
2581 if ( !$status->isGood() ) {
2582 // Even if some files could be copied, fail entirely as that is the
2583 // easiest thing to do without data loss
2584 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2585 $status->ok
= false;
2586 $this->file
->unlock();
2591 // Run the DB updates
2592 // Because we have locked the image row, key conflicts should be rare.
2593 // If they do occur, we can roll back the transaction at this time with
2594 // no data loss, but leaving unregistered files scattered throughout the
2596 // This is not ideal, which is why it's important to lock the image row.
2597 if ( $insertCurrent ) {
2598 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2601 if ( $insertBatch ) {
2602 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2606 $dbw->delete( 'filearchive',
2607 array( 'fa_id' => $deleteIds ),
2611 // If store batch is empty (all files are missing), deletion is to be considered successful
2612 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2614 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2616 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2618 $this->file
->purgeEverything();
2620 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2621 $this->file
->purgeDescription();
2622 $this->file
->purgeHistory();
2626 $this->file
->unlock();
2632 * Removes non-existent files from a store batch.
2633 * @param array $triplets
2636 function removeNonexistentFiles( $triplets ) {
2637 $files = $filteredTriplets = array();
2638 foreach ( $triplets as $file ) {
2639 $files[$file[0]] = $file[0];
2642 $result = $this->file
->repo
->fileExistsBatch( $files );
2644 foreach ( $triplets as $file ) {
2645 if ( $result[$file[0]] ) {
2646 $filteredTriplets[] = $file;
2650 return $filteredTriplets;
2654 * Removes non-existent files from a cleanup batch.
2655 * @param array $batch
2658 function removeNonexistentFromCleanup( $batch ) {
2659 $files = $newBatch = array();
2660 $repo = $this->file
->repo
;
2662 foreach ( $batch as $file ) {
2663 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2664 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2667 $result = $repo->fileExistsBatch( $files );
2669 foreach ( $batch as $file ) {
2670 if ( $result[$file] ) {
2671 $newBatch[] = $file;
2679 * Delete unused files in the deleted zone.
2680 * This should be called from outside the transaction in which execute() was called.
2681 * @return FileRepoStatus
2683 function cleanup() {
2684 if ( !$this->cleanupBatch
) {
2685 return $this->file
->repo
->newGood();
2688 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2690 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2696 * Cleanup a failed batch. The batch was only partially successful, so
2697 * rollback by removing all items that were succesfully copied.
2699 * @param Status $storeStatus
2700 * @param array $storeBatch
2702 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2703 $cleanupBatch = array();
2705 foreach ( $storeStatus->success
as $i => $success ) {
2706 // Check if this item of the batch was successfully copied
2708 // Item was successfully copied and needs to be removed again
2709 // Extract ($dstZone, $dstRel) from the batch
2710 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2713 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2717 # ------------------------------------------------------------------------------
2720 * Helper class for file movement
2721 * @ingroup FileAbstraction
2723 class LocalFileMoveBatch
{
2724 /** @var LocalFile */
2734 protected $oldCount;
2738 /** @var DatabaseBase */
2743 * @param Title $target
2745 function __construct( File
$file, Title
$target ) {
2746 $this->file
= $file;
2747 $this->target
= $target;
2748 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2749 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2750 $this->oldName
= $this->file
->getName();
2751 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2752 $this->oldRel
= $this->oldHash
. $this->oldName
;
2753 $this->newRel
= $this->newHash
. $this->newName
;
2754 $this->db
= $file->getRepo()->getMasterDb();
2758 * Add the current image to the batch
2760 function addCurrent() {
2761 $this->cur
= array( $this->oldRel
, $this->newRel
);
2765 * Add the old versions of the image to the batch
2766 * @return array List of archive names from old versions
2768 function addOlds() {
2769 $archiveBase = 'archive';
2770 $this->olds
= array();
2771 $this->oldCount
= 0;
2772 $archiveNames = array();
2774 $result = $this->db
->select( 'oldimage',
2775 array( 'oi_archive_name', 'oi_deleted' ),
2776 array( 'oi_name' => $this->oldName
),
2778 array( 'FOR UPDATE' ) // ignore snapshot
2781 foreach ( $result as $row ) {
2782 $archiveNames[] = $row->oi_archive_name
;
2783 $oldName = $row->oi_archive_name
;
2784 $bits = explode( '!', $oldName, 2 );
2786 if ( count( $bits ) != 2 ) {
2787 wfDebug( "Old file name missing !: '$oldName' \n" );
2791 list( $timestamp, $filename ) = $bits;
2793 if ( $this->oldName
!= $filename ) {
2794 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2800 // Do we want to add those to oldCount?
2801 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2805 $this->olds
[] = array(
2806 "{$archiveBase}/{$this->oldHash}{$oldName}",
2807 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2811 return $archiveNames;
2816 * @return FileRepoStatus
2818 function execute() {
2819 $repo = $this->file
->repo
;
2820 $status = $repo->newGood();
2822 $triplets = $this->getMoveTriplets();
2823 $triplets = $this->removeNonexistentFiles( $triplets );
2824 $destFile = wfLocalFile( $this->target
);
2826 $this->file
->lock(); // begin
2827 $destFile->lock(); // quickly fail if destination is not available
2828 // Rename the file versions metadata in the DB.
2829 // This implicitly locks the destination file, which avoids race conditions.
2830 // If we moved the files from A -> C before DB updates, another process could
2831 // move files from B -> C at this point, causing storeBatch() to fail and thus
2832 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2833 $statusDb = $this->doDBUpdates();
2834 if ( !$statusDb->isGood() ) {
2835 $destFile->unlock();
2836 $this->file
->unlockAndRollback();
2837 $statusDb->ok
= false;
2841 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2842 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2844 // Copy the files into their new location.
2845 // If a prior process fataled copying or cleaning up files we tolerate any
2846 // of the existing files if they are identical to the ones being stored.
2847 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2848 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2849 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2850 if ( !$statusMove->isGood() ) {
2851 // Delete any files copied over (while the destination is still locked)
2852 $this->cleanupTarget( $triplets );
2853 $destFile->unlock();
2854 $this->file
->unlockAndRollback(); // unlocks the destination
2855 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2856 $statusMove->ok
= false;
2860 $destFile->unlock();
2861 $this->file
->unlock(); // done
2863 // Everything went ok, remove the source files
2864 $this->cleanupSource( $triplets );
2866 $status->merge( $statusDb );
2867 $status->merge( $statusMove );
2873 * Do the database updates and return a new FileRepoStatus indicating how
2874 * many rows where updated.
2876 * @return FileRepoStatus
2878 function doDBUpdates() {
2879 $repo = $this->file
->repo
;
2880 $status = $repo->newGood();
2883 // Update current image
2886 array( 'img_name' => $this->newName
),
2887 array( 'img_name' => $this->oldName
),
2891 if ( $dbw->affectedRows() ) {
2892 $status->successCount++
;
2894 $status->failCount++
;
2895 $status->fatal( 'imageinvalidfilename' );
2900 // Update old images
2904 'oi_name' => $this->newName
,
2905 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2906 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2908 array( 'oi_name' => $this->oldName
),
2912 $affected = $dbw->affectedRows();
2913 $total = $this->oldCount
;
2914 $status->successCount +
= $affected;
2915 // Bug 34934: $total is based on files that actually exist.
2916 // There may be more DB rows than such files, in which case $affected
2917 // can be greater than $total. We use max() to avoid negatives here.
2918 $status->failCount +
= max( 0, $total - $affected );
2919 if ( $status->failCount
) {
2920 $status->error( 'imageinvalidfilename' );
2927 * Generate triplets for FileRepo::storeBatch().
2930 function getMoveTriplets() {
2931 $moves = array_merge( array( $this->cur
), $this->olds
);
2932 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2934 foreach ( $moves as $move ) {
2935 // $move: (oldRelativePath, newRelativePath)
2936 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2937 $triplets[] = array( $srcUrl, 'public', $move[1] );
2940 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2948 * Removes non-existent files from move batch.
2949 * @param array $triplets
2952 function removeNonexistentFiles( $triplets ) {
2955 foreach ( $triplets as $file ) {
2956 $files[$file[0]] = $file[0];
2959 $result = $this->file
->repo
->fileExistsBatch( $files );
2960 $filteredTriplets = array();
2962 foreach ( $triplets as $file ) {
2963 if ( $result[$file[0]] ) {
2964 $filteredTriplets[] = $file;
2966 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2970 return $filteredTriplets;
2974 * Cleanup a partially moved array of triplets by deleting the target
2975 * files. Called if something went wrong half way.
2977 function cleanupTarget( $triplets ) {
2978 // Create dest pairs from the triplets
2980 foreach ( $triplets as $triplet ) {
2981 // $triplet: (old source virtual URL, dst zone, dest rel)
2982 $pairs[] = array( $triplet[1], $triplet[2] );
2985 $this->file
->repo
->cleanupBatch( $pairs );
2989 * Cleanup a fully moved array of triplets by deleting the source files.
2990 * Called at the end of the move process if everything else went ok.
2992 function cleanupSource( $triplets ) {
2993 // Create source file names from the triplets
2995 foreach ( $triplets as $triplet ) {
2996 $files[] = $triplet[0];
2999 $this->file
->repo
->cleanupBatch( $files );