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 wfProfileOut( __METHOD__
);
1278 # Test to see if the row exists using INSERT IGNORE
1279 # This avoids race conditions by locking the row until the commit, and also
1280 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1281 $dbw->insert( 'image',
1283 'img_name' => $this->getName(),
1284 'img_size' => $this->size
,
1285 'img_width' => intval( $this->width
),
1286 'img_height' => intval( $this->height
),
1287 'img_bits' => $this->bits
,
1288 'img_media_type' => $this->media_type
,
1289 'img_major_mime' => $this->major_mime
,
1290 'img_minor_mime' => $this->minor_mime
,
1291 'img_timestamp' => $timestamp,
1292 'img_description' => $comment,
1293 'img_user' => $user->getId(),
1294 'img_user_text' => $user->getName(),
1295 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1296 'img_sha1' => $this->sha1
1301 if ( $dbw->affectedRows() == 0 ) {
1302 if ( $allowTimeKludge ) {
1303 # Use FOR UPDATE to ignore any transaction snapshotting
1304 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1305 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1306 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1307 # Avoid a timestamp that is not newer than the last version
1308 # TODO: the image/oldimage tables should be like page/revision with an ID field
1309 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1310 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1311 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1312 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1316 # (bug 34993) Note: $oldver can be empty here, if the previous
1317 # version of the file was broken. Allow registration of the new
1318 # version to continue anyway, because that's better than having
1319 # an image that's not fixable by user operations.
1322 # Collision, this is an update of a file
1323 # Insert previous contents into oldimage
1324 $dbw->insertSelect( 'oldimage', 'image',
1326 'oi_name' => 'img_name',
1327 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1328 'oi_size' => 'img_size',
1329 'oi_width' => 'img_width',
1330 'oi_height' => 'img_height',
1331 'oi_bits' => 'img_bits',
1332 'oi_timestamp' => 'img_timestamp',
1333 'oi_description' => 'img_description',
1334 'oi_user' => 'img_user',
1335 'oi_user_text' => 'img_user_text',
1336 'oi_metadata' => 'img_metadata',
1337 'oi_media_type' => 'img_media_type',
1338 'oi_major_mime' => 'img_major_mime',
1339 'oi_minor_mime' => 'img_minor_mime',
1340 'oi_sha1' => 'img_sha1'
1342 array( 'img_name' => $this->getName() ),
1346 # Update the current image row
1347 $dbw->update( 'image',
1349 'img_size' => $this->size
,
1350 'img_width' => intval( $this->width
),
1351 'img_height' => intval( $this->height
),
1352 'img_bits' => $this->bits
,
1353 'img_media_type' => $this->media_type
,
1354 'img_major_mime' => $this->major_mime
,
1355 'img_minor_mime' => $this->minor_mime
,
1356 'img_timestamp' => $timestamp,
1357 'img_description' => $comment,
1358 'img_user' => $user->getId(),
1359 'img_user_text' => $user->getName(),
1360 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1361 'img_sha1' => $this->sha1
1363 array( 'img_name' => $this->getName() ),
1367 # This is a new file, so update the image count
1368 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1371 $descTitle = $this->getTitle();
1372 $wikiPage = new WikiFilePage( $descTitle );
1373 $wikiPage->setFile( $this );
1376 $action = $reupload ?
'overwrite' : 'upload';
1378 $logEntry = new ManualLogEntry( 'upload', $action );
1379 $logEntry->setPerformer( $user );
1380 $logEntry->setComment( $comment );
1381 $logEntry->setTarget( $descTitle );
1383 // Allow people using the api to associate log entries with the upload.
1384 // Log has a timestamp, but sometimes different from upload timestamp.
1385 $logEntry->setParameters(
1387 'img_sha1' => $this->sha1
,
1388 'img_timestamp' => $timestamp,
1391 // Note we keep $logId around since during new image
1392 // creation, page doesn't exist yet, so log_page = 0
1393 // but we want it to point to the page we're making,
1394 // so we later modify the log entry.
1395 // For a similar reason, we avoid making an RC entry
1396 // now and wait until the page exists.
1397 $logId = $logEntry->insert();
1399 $exists = $descTitle->exists();
1401 // Page exists, do RC entry now (otherwise we wait for later).
1402 $logEntry->publish( $logId );
1404 wfProfileIn( __METHOD__
. '-edit' );
1407 # Create a null revision
1408 $latest = $descTitle->getLatestRevID();
1409 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1411 $nullRevision = Revision
::newNullRevision(
1413 $descTitle->getArticleID(),
1418 if ( !is_null( $nullRevision ) ) {
1419 $nullRevision->insertOn( $dbw );
1421 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1422 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1426 # Commit the transaction now, in case something goes wrong later
1427 # The most important thing is that files don't get lost, especially archives
1428 # NOTE: once we have support for nested transactions, the commit may be moved
1429 # to after $wikiPage->doEdit has been called.
1430 $dbw->commit( __METHOD__
);
1433 # We shall not saveToCache before the commit since otherwise
1434 # in case of a rollback there is an usable file from memcached
1435 # which in fact doesn't really exist (bug 24978)
1436 $this->saveToCache();
1439 # Invalidate the cache for the description page
1440 $descTitle->invalidateCache();
1441 $descTitle->purgeSquid();
1443 # New file; create the description page.
1444 # There's already a log entry, so don't make a second RC entry
1445 # Squid and file cache for the description page are purged by doEditContent.
1446 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1447 $status = $wikiPage->doEditContent(
1450 EDIT_NEW | EDIT_SUPPRESS_RC
,
1455 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1456 // Now that the page exists, make an RC entry.
1457 $logEntry->publish( $logId );
1458 if ( isset( $status->value
['revision'] ) ) {
1459 $dbw->update( 'logging',
1460 array( 'log_page' => $status->value
['revision']->getPage() ),
1461 array( 'log_id' => $logId ),
1465 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1468 wfProfileOut( __METHOD__
. '-edit' );
1471 # Delete old thumbnails
1472 wfProfileIn( __METHOD__
. '-purge' );
1473 $this->purgeThumbnails();
1474 wfProfileOut( __METHOD__
. '-purge' );
1476 # Remove the old file from the squid cache
1477 SquidUpdate
::purge( array( $this->getURL() ) );
1480 # Hooks, hooks, the magic of hooks...
1481 wfProfileIn( __METHOD__
. '-hooks' );
1482 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1483 wfProfileOut( __METHOD__
. '-hooks' );
1485 # Invalidate cache for all pages using this file
1486 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1487 $update->doUpdate();
1489 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1492 wfProfileOut( __METHOD__
);
1498 * Move or copy a file to its public location. If a file exists at the
1499 * destination, move it to an archive. Returns a FileRepoStatus object with
1500 * the archive name in the "value" member on success.
1502 * The archive name should be passed through to recordUpload for database
1505 * @param string $srcPath Local filesystem path to the source image
1506 * @param int $flags A bitwise combination of:
1507 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1508 * @param array $options Optional additional parameters
1509 * @return FileRepoStatus On success, the value member contains the
1510 * archive name, or an empty string if it was a new file.
1512 function publish( $srcPath, $flags = 0, array $options = array() ) {
1513 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1517 * Move or copy a file to a specified location. Returns a FileRepoStatus
1518 * object with the archive name in the "value" member on success.
1520 * The archive name should be passed through to recordUpload for database
1523 * @param string $srcPath Local filesystem path to the source image
1524 * @param string $dstRel Target relative path
1525 * @param int $flags A bitwise combination of:
1526 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1527 * @param array $options Optional additional parameters
1528 * @return FileRepoStatus On success, the value member contains the
1529 * archive name, or an empty string if it was a new file.
1531 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1532 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1533 return $this->readOnlyFatalStatus();
1536 $this->lock(); // begin
1538 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1539 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1540 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1541 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1543 if ( $status->value
== 'new' ) {
1544 $status->value
= '';
1546 $status->value
= $archiveName;
1549 $this->unlock(); // done
1554 /** getLinksTo inherited */
1555 /** getExifData inherited */
1556 /** isLocal inherited */
1557 /** wasDeleted inherited */
1560 * Move file to the new title
1562 * Move current, old version and all thumbnails
1563 * to the new filename. Old file is deleted.
1565 * Cache purging is done; checks for validity
1566 * and logging are caller's responsibility
1568 * @param Title $target New file name
1569 * @return FileRepoStatus
1571 function move( $target ) {
1572 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1573 return $this->readOnlyFatalStatus();
1576 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1577 $batch = new LocalFileMoveBatch( $this, $target );
1579 $this->lock(); // begin
1580 $batch->addCurrent();
1581 $archiveNames = $batch->addOlds();
1582 $status = $batch->execute();
1583 $this->unlock(); // done
1585 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1587 // Purge the source and target files...
1588 $oldTitleFile = wfLocalFile( $this->title
);
1589 $newTitleFile = wfLocalFile( $target );
1590 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1591 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1592 $this->getRepo()->getMasterDB()->onTransactionIdle(
1593 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1594 $oldTitleFile->purgeEverything();
1595 foreach ( $archiveNames as $archiveName ) {
1596 $oldTitleFile->purgeOldThumbnails( $archiveName );
1598 $newTitleFile->purgeEverything();
1602 if ( $status->isOK() ) {
1603 // Now switch the object
1604 $this->title
= $target;
1605 // Force regeneration of the name and hashpath
1606 unset( $this->name
);
1607 unset( $this->hashPath
);
1614 * Delete all versions of the file.
1616 * Moves the files into an archive directory (or deletes them)
1617 * and removes the database rows.
1619 * Cache purging is done; logging is caller's responsibility.
1621 * @param string $reason
1622 * @param bool $suppress
1623 * @param User|null $user
1624 * @return FileRepoStatus
1626 function delete( $reason, $suppress = false, $user = null ) {
1627 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1628 return $this->readOnlyFatalStatus();
1631 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1633 $this->lock(); // begin
1634 $batch->addCurrent();
1635 # Get old version relative paths
1636 $archiveNames = $batch->addOlds();
1637 $status = $batch->execute();
1638 $this->unlock(); // done
1640 if ( $status->isOK() ) {
1641 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1644 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1645 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1647 $this->getRepo()->getMasterDB()->onTransactionIdle(
1648 function () use ( $file, $archiveNames ) {
1651 $file->purgeEverything();
1652 foreach ( $archiveNames as $archiveName ) {
1653 $file->purgeOldThumbnails( $archiveName );
1656 if ( $wgUseSquid ) {
1658 $purgeUrls = array();
1659 foreach ( $archiveNames as $archiveName ) {
1660 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1662 SquidUpdate
::purge( $purgeUrls );
1671 * Delete an old version of the file.
1673 * Moves the file into an archive directory (or deletes it)
1674 * and removes the database row.
1676 * Cache purging is done; logging is caller's responsibility.
1678 * @param string $archiveName
1679 * @param string $reason
1680 * @param bool $suppress
1681 * @param User|null $user
1682 * @throws MWException Exception on database or file store failure
1683 * @return FileRepoStatus
1685 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1687 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1688 return $this->readOnlyFatalStatus();
1691 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1693 $this->lock(); // begin
1694 $batch->addOld( $archiveName );
1695 $status = $batch->execute();
1696 $this->unlock(); // done
1698 $this->purgeOldThumbnails( $archiveName );
1699 if ( $status->isOK() ) {
1700 $this->purgeDescription();
1701 $this->purgeHistory();
1704 if ( $wgUseSquid ) {
1706 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1713 * Restore all or specified deleted revisions to the given file.
1714 * Permissions and logging are left to the caller.
1716 * May throw database exceptions on error.
1718 * @param array $versions Set of record ids of deleted items to restore,
1719 * or empty to restore all revisions.
1720 * @param bool $unsuppress
1721 * @return FileRepoStatus
1723 function restore( $versions = array(), $unsuppress = false ) {
1724 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1725 return $this->readOnlyFatalStatus();
1728 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1730 $this->lock(); // begin
1734 $batch->addIds( $versions );
1736 $status = $batch->execute();
1737 if ( $status->isGood() ) {
1738 $cleanupStatus = $batch->cleanup();
1739 $cleanupStatus->successCount
= 0;
1740 $cleanupStatus->failCount
= 0;
1741 $status->merge( $cleanupStatus );
1743 $this->unlock(); // done
1748 /** isMultipage inherited */
1749 /** pageCount inherited */
1750 /** scaleHeight inherited */
1751 /** getImageSize inherited */
1754 * Get the URL of the file description page.
1757 function getDescriptionUrl() {
1758 return $this->title
->getLocalURL();
1762 * Get the HTML text of the description page
1763 * This is not used by ImagePage for local files, since (among other things)
1764 * it skips the parser cache.
1766 * @param Language $lang What language to get description in (Optional)
1767 * @return bool|mixed
1769 function getDescriptionText( $lang = null ) {
1770 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1774 $content = $revision->getContent();
1778 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1780 return $pout->getText();
1784 * @param int $audience
1788 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1790 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1792 } elseif ( $audience == self
::FOR_THIS_USER
1793 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1797 return $this->description
;
1802 * @return bool|string
1804 function getTimestamp() {
1807 return $this->timestamp
;
1813 function getSha1() {
1815 // Initialise now if necessary
1816 if ( $this->sha1
== '' && $this->fileExists
) {
1817 $this->lock(); // begin
1819 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1820 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1821 $dbw = $this->repo
->getMasterDB();
1822 $dbw->update( 'image',
1823 array( 'img_sha1' => $this->sha1
),
1824 array( 'img_name' => $this->getName() ),
1826 $this->saveToCache();
1829 $this->unlock(); // done
1836 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1838 function isCacheable() {
1841 // If extra data (metadata) was not loaded then it must have been large
1842 return $this->extraDataLoaded
1843 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1847 * Start a transaction and lock the image for update
1848 * Increments a reference counter if the lock is already held
1849 * @throws MWException Throws an error if the lock was not acquired
1850 * @return bool success
1853 $dbw = $this->repo
->getMasterDB();
1855 if ( !$this->locked
) {
1856 if ( !$dbw->trxLevel() ) {
1857 $dbw->begin( __METHOD__
);
1858 $this->lockedOwnTrx
= true;
1861 // Bug 54736: use simple lock to handle when the file does not exist.
1862 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1863 // Also, that would cause contention on INSERT of similarly named rows.
1864 $backend = $this->getRepo()->getBackend();
1865 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1866 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1867 if ( !$status->isGood() ) {
1868 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1870 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1871 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1875 $this->markVolatile(); // file may change soon
1881 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1882 * the transaction and thereby releases the image lock.
1885 if ( $this->locked
) {
1887 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1888 $dbw = $this->repo
->getMasterDB();
1889 $dbw->commit( __METHOD__
);
1890 $this->lockedOwnTrx
= false;
1896 * Mark a file as about to be changed
1898 * This sets a cache key that alters master/slave DB loading behavior
1900 * @return bool Success
1902 protected function markVolatile() {
1905 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1907 $this->lastMarkedVolatile
= time();
1908 return $wgMemc->set( $key, $this->lastMarkedVolatile
, self
::VOLATILE_TTL
);
1915 * Check if a file is about to be changed or has been changed recently
1917 * @see LocalFile::isVolatile()
1918 * @return bool Whether the file is volatile
1920 protected function isVolatile() {
1923 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1925 // repo unavailable; bail.
1929 if ( $this->lastMarkedVolatile
=== 0 ) {
1930 $this->lastMarkedVolatile
= $wgMemc->get( $key ) ?
: 0;
1933 $volatileDuration = time() - $this->lastMarkedVolatile
;
1934 return $volatileDuration <= self
::VOLATILE_TTL
;
1938 * Roll back the DB transaction and mark the image unlocked
1940 function unlockAndRollback() {
1941 $this->locked
= false;
1942 $dbw = $this->repo
->getMasterDB();
1943 $dbw->rollback( __METHOD__
);
1944 $this->lockedOwnTrx
= false;
1950 protected function readOnlyFatalStatus() {
1951 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1952 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1956 * Clean up any dangling locks
1958 function __destruct() {
1961 } // LocalFile class
1963 # ------------------------------------------------------------------------------
1966 * Helper class for file deletion
1967 * @ingroup FileAbstraction
1969 class LocalFileDeleteBatch
{
1970 /** @var LocalFile */
1977 private $srcRels = array();
1980 private $archiveUrls = array();
1982 /** @var array Items to be processed in the deletion batch */
1983 private $deletionBatch;
1985 /** @var bool Wether to suppress all suppressable fields when deleting */
1988 /** @var FileRepoStatus */
1996 * @param string $reason
1997 * @param bool $suppress
1998 * @param User|null $user
2000 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2001 $this->file
= $file;
2002 $this->reason
= $reason;
2003 $this->suppress
= $suppress;
2005 $this->user
= $user;
2008 $this->user
= $wgUser;
2010 $this->status
= $file->repo
->newGood();
2013 function addCurrent() {
2014 $this->srcRels
['.'] = $this->file
->getRel();
2018 * @param string $oldName
2020 function addOld( $oldName ) {
2021 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2022 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2026 * Add the old versions of the image to the batch
2027 * @return array List of archive names from old versions
2029 function addOlds() {
2030 $archiveNames = array();
2032 $dbw = $this->file
->repo
->getMasterDB();
2033 $result = $dbw->select( 'oldimage',
2034 array( 'oi_archive_name' ),
2035 array( 'oi_name' => $this->file
->getName() ),
2039 foreach ( $result as $row ) {
2040 $this->addOld( $row->oi_archive_name
);
2041 $archiveNames[] = $row->oi_archive_name
;
2044 return $archiveNames;
2050 function getOldRels() {
2051 if ( !isset( $this->srcRels
['.'] ) ) {
2052 $oldRels =& $this->srcRels
;
2053 $deleteCurrent = false;
2055 $oldRels = $this->srcRels
;
2056 unset( $oldRels['.'] );
2057 $deleteCurrent = true;
2060 return array( $oldRels, $deleteCurrent );
2066 protected function getHashes() {
2068 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2070 if ( $deleteCurrent ) {
2071 $hashes['.'] = $this->file
->getSha1();
2074 if ( count( $oldRels ) ) {
2075 $dbw = $this->file
->repo
->getMasterDB();
2076 $res = $dbw->select(
2078 array( 'oi_archive_name', 'oi_sha1' ),
2079 array( 'oi_archive_name' => array_keys( $oldRels ),
2080 'oi_name' => $this->file
->getName() ), // performance
2084 foreach ( $res as $row ) {
2085 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2086 // Get the hash from the file
2087 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2088 $props = $this->file
->repo
->getFileProps( $oldUrl );
2090 if ( $props['fileExists'] ) {
2091 // Upgrade the oldimage row
2092 $dbw->update( 'oldimage',
2093 array( 'oi_sha1' => $props['sha1'] ),
2094 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2096 $hashes[$row->oi_archive_name
] = $props['sha1'];
2098 $hashes[$row->oi_archive_name
] = false;
2101 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2106 $missing = array_diff_key( $this->srcRels
, $hashes );
2108 foreach ( $missing as $name => $rel ) {
2109 $this->status
->error( 'filedelete-old-unregistered', $name );
2112 foreach ( $hashes as $name => $hash ) {
2114 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2115 unset( $hashes[$name] );
2122 function doDBInserts() {
2123 $dbw = $this->file
->repo
->getMasterDB();
2124 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2125 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2126 $encReason = $dbw->addQuotes( $this->reason
);
2127 $encGroup = $dbw->addQuotes( 'deleted' );
2128 $ext = $this->file
->getExtension();
2129 $dotExt = $ext === '' ?
'' : ".$ext";
2130 $encExt = $dbw->addQuotes( $dotExt );
2131 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2133 // Bitfields to further suppress the content
2134 if ( $this->suppress
) {
2136 // This should be 15...
2137 $bitfield |
= Revision
::DELETED_TEXT
;
2138 $bitfield |
= Revision
::DELETED_COMMENT
;
2139 $bitfield |
= Revision
::DELETED_USER
;
2140 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2142 $bitfield = 'oi_deleted';
2145 if ( $deleteCurrent ) {
2146 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2147 $where = array( 'img_name' => $this->file
->getName() );
2148 $dbw->insertSelect( 'filearchive', 'image',
2150 'fa_storage_group' => $encGroup,
2151 'fa_storage_key' => $dbw->conditional(
2152 array( 'img_sha1' => '' ),
2153 $dbw->addQuotes( '' ),
2156 'fa_deleted_user' => $encUserId,
2157 'fa_deleted_timestamp' => $encTimestamp,
2158 'fa_deleted_reason' => $encReason,
2159 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2161 'fa_name' => 'img_name',
2162 'fa_archive_name' => 'NULL',
2163 'fa_size' => 'img_size',
2164 'fa_width' => 'img_width',
2165 'fa_height' => 'img_height',
2166 'fa_metadata' => 'img_metadata',
2167 'fa_bits' => 'img_bits',
2168 'fa_media_type' => 'img_media_type',
2169 'fa_major_mime' => 'img_major_mime',
2170 'fa_minor_mime' => 'img_minor_mime',
2171 'fa_description' => 'img_description',
2172 'fa_user' => 'img_user',
2173 'fa_user_text' => 'img_user_text',
2174 'fa_timestamp' => 'img_timestamp',
2175 'fa_sha1' => 'img_sha1',
2176 ), $where, __METHOD__
);
2179 if ( count( $oldRels ) ) {
2180 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2182 'oi_name' => $this->file
->getName(),
2183 'oi_archive_name' => array_keys( $oldRels ) );
2184 $dbw->insertSelect( 'filearchive', 'oldimage',
2186 'fa_storage_group' => $encGroup,
2187 'fa_storage_key' => $dbw->conditional(
2188 array( 'oi_sha1' => '' ),
2189 $dbw->addQuotes( '' ),
2192 'fa_deleted_user' => $encUserId,
2193 'fa_deleted_timestamp' => $encTimestamp,
2194 'fa_deleted_reason' => $encReason,
2195 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2197 'fa_name' => 'oi_name',
2198 'fa_archive_name' => 'oi_archive_name',
2199 'fa_size' => 'oi_size',
2200 'fa_width' => 'oi_width',
2201 'fa_height' => 'oi_height',
2202 'fa_metadata' => 'oi_metadata',
2203 'fa_bits' => 'oi_bits',
2204 'fa_media_type' => 'oi_media_type',
2205 'fa_major_mime' => 'oi_major_mime',
2206 'fa_minor_mime' => 'oi_minor_mime',
2207 'fa_description' => 'oi_description',
2208 'fa_user' => 'oi_user',
2209 'fa_user_text' => 'oi_user_text',
2210 'fa_timestamp' => 'oi_timestamp',
2211 'fa_sha1' => 'oi_sha1',
2212 ), $where, __METHOD__
);
2216 function doDBDeletes() {
2217 $dbw = $this->file
->repo
->getMasterDB();
2218 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2220 if ( count( $oldRels ) ) {
2221 $dbw->delete( 'oldimage',
2223 'oi_name' => $this->file
->getName(),
2224 'oi_archive_name' => array_keys( $oldRels )
2228 if ( $deleteCurrent ) {
2229 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2234 * Run the transaction
2235 * @return FileRepoStatus
2237 function execute() {
2238 wfProfileIn( __METHOD__
);
2240 $this->file
->lock();
2241 // Leave private files alone
2242 $privateFiles = array();
2243 list( $oldRels, ) = $this->getOldRels();
2244 $dbw = $this->file
->repo
->getMasterDB();
2246 if ( !empty( $oldRels ) ) {
2247 $res = $dbw->select( 'oldimage',
2248 array( 'oi_archive_name' ),
2249 array( 'oi_name' => $this->file
->getName(),
2250 'oi_archive_name' => array_keys( $oldRels ),
2251 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2254 foreach ( $res as $row ) {
2255 $privateFiles[$row->oi_archive_name
] = 1;
2258 // Prepare deletion batch
2259 $hashes = $this->getHashes();
2260 $this->deletionBatch
= array();
2261 $ext = $this->file
->getExtension();
2262 $dotExt = $ext === '' ?
'' : ".$ext";
2264 foreach ( $this->srcRels
as $name => $srcRel ) {
2265 // Skip files that have no hash (missing source).
2266 // Keep private files where they are.
2267 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2268 $hash = $hashes[$name];
2269 $key = $hash . $dotExt;
2270 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2271 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2275 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2276 // We acquire this lock by running the inserts now, before the file operations.
2278 // This potentially has poor lock contention characteristics -- an alternative
2279 // scheme would be to insert stub filearchive entries with no fa_name and commit
2280 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2281 $this->doDBInserts();
2283 // Removes non-existent file from the batch, so we don't get errors.
2284 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2286 // Execute the file deletion batch
2287 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2289 if ( !$status->isGood() ) {
2290 $this->status
->merge( $status );
2293 if ( !$this->status
->isOK() ) {
2294 // Critical file deletion error
2295 // Roll back inserts, release lock and abort
2296 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2297 $this->file
->unlockAndRollback();
2298 wfProfileOut( __METHOD__
);
2300 return $this->status
;
2303 // Delete image/oldimage rows
2304 $this->doDBDeletes();
2306 // Commit and return
2307 $this->file
->unlock();
2308 wfProfileOut( __METHOD__
);
2310 return $this->status
;
2314 * Removes non-existent files from a deletion batch.
2315 * @param array $batch
2318 function removeNonexistentFiles( $batch ) {
2319 $files = $newBatch = array();
2321 foreach ( $batch as $batchItem ) {
2322 list( $src, ) = $batchItem;
2323 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2326 $result = $this->file
->repo
->fileExistsBatch( $files );
2328 foreach ( $batch as $batchItem ) {
2329 if ( $result[$batchItem[0]] ) {
2330 $newBatch[] = $batchItem;
2338 # ------------------------------------------------------------------------------
2341 * Helper class for file undeletion
2342 * @ingroup FileAbstraction
2344 class LocalFileRestoreBatch
{
2345 /** @var LocalFile */
2348 /** @var array List of file IDs to restore */
2349 private $cleanupBatch;
2351 /** @var array List of file IDs to restore */
2354 /** @var bool Add all revisions of the file */
2357 /** @var bool Wether to remove all settings for suppressed fields */
2358 private $unsuppress = false;
2362 * @param bool $unsuppress
2364 function __construct( File
$file, $unsuppress = false ) {
2365 $this->file
= $file;
2366 $this->cleanupBatch
= $this->ids
= array();
2367 $this->ids
= array();
2368 $this->unsuppress
= $unsuppress;
2374 function addId( $fa_id ) {
2375 $this->ids
[] = $fa_id;
2379 * Add a whole lot of files by ID
2381 function addIds( $ids ) {
2382 $this->ids
= array_merge( $this->ids
, $ids );
2386 * Add all revisions of the file
2393 * Run the transaction, except the cleanup batch.
2394 * The cleanup batch should be run in a separate transaction, because it locks different
2395 * rows and there's no need to keep the image row locked while it's acquiring those locks
2396 * The caller may have its own transaction open.
2397 * So we save the batch and let the caller call cleanup()
2398 * @return FileRepoStatus
2400 function execute() {
2403 if ( !$this->all
&& !$this->ids
) {
2405 return $this->file
->repo
->newGood();
2408 $this->file
->lock();
2410 $dbw = $this->file
->repo
->getMasterDB();
2411 $status = $this->file
->repo
->newGood();
2413 $exists = (bool)$dbw->selectField( 'image', '1',
2414 array( 'img_name' => $this->file
->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
2416 // Fetch all or selected archived revisions for the file,
2417 // sorted from the most recent to the oldest.
2418 $conditions = array( 'fa_name' => $this->file
->getName() );
2420 if ( !$this->all
) {
2421 $conditions['fa_id'] = $this->ids
;
2424 $result = $dbw->select(
2426 ArchivedFile
::selectFields(),
2429 array( 'ORDER BY' => 'fa_timestamp DESC' )
2432 $idsPresent = array();
2433 $storeBatch = array();
2434 $insertBatch = array();
2435 $insertCurrent = false;
2436 $deleteIds = array();
2438 $archiveNames = array();
2440 foreach ( $result as $row ) {
2441 $idsPresent[] = $row->fa_id
;
2443 if ( $row->fa_name
!= $this->file
->getName() ) {
2444 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2445 $status->failCount++
;
2449 if ( $row->fa_storage_key
== '' ) {
2450 // Revision was missing pre-deletion
2451 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2452 $status->failCount++
;
2456 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2457 $row->fa_storage_key
;
2458 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2460 if ( isset( $row->fa_sha1
) ) {
2461 $sha1 = $row->fa_sha1
;
2463 // old row, populate from key
2464 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2468 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2469 $sha1 = substr( $sha1, 1 );
2472 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2473 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2474 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2475 ||
is_null( $row->fa_metadata
)
2477 // Refresh our metadata
2478 // Required for a new current revision; nice for older ones too. :)
2479 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2482 'minor_mime' => $row->fa_minor_mime
,
2483 'major_mime' => $row->fa_major_mime
,
2484 'media_type' => $row->fa_media_type
,
2485 'metadata' => $row->fa_metadata
2489 if ( $first && !$exists ) {
2490 // This revision will be published as the new current version
2491 $destRel = $this->file
->getRel();
2492 $insertCurrent = array(
2493 'img_name' => $row->fa_name
,
2494 'img_size' => $row->fa_size
,
2495 'img_width' => $row->fa_width
,
2496 'img_height' => $row->fa_height
,
2497 'img_metadata' => $props['metadata'],
2498 'img_bits' => $row->fa_bits
,
2499 'img_media_type' => $props['media_type'],
2500 'img_major_mime' => $props['major_mime'],
2501 'img_minor_mime' => $props['minor_mime'],
2502 'img_description' => $row->fa_description
,
2503 'img_user' => $row->fa_user
,
2504 'img_user_text' => $row->fa_user_text
,
2505 'img_timestamp' => $row->fa_timestamp
,
2509 // The live (current) version cannot be hidden!
2510 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2511 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2512 $this->cleanupBatch
[] = $row->fa_storage_key
;
2515 $archiveName = $row->fa_archive_name
;
2517 if ( $archiveName == '' ) {
2518 // This was originally a current version; we
2519 // have to devise a new archive name for it.
2520 // Format is <timestamp of archiving>!<name>
2521 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2524 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2526 } while ( isset( $archiveNames[$archiveName] ) );
2529 $archiveNames[$archiveName] = true;
2530 $destRel = $this->file
->getArchiveRel( $archiveName );
2531 $insertBatch[] = array(
2532 'oi_name' => $row->fa_name
,
2533 'oi_archive_name' => $archiveName,
2534 'oi_size' => $row->fa_size
,
2535 'oi_width' => $row->fa_width
,
2536 'oi_height' => $row->fa_height
,
2537 'oi_bits' => $row->fa_bits
,
2538 'oi_description' => $row->fa_description
,
2539 'oi_user' => $row->fa_user
,
2540 'oi_user_text' => $row->fa_user_text
,
2541 'oi_timestamp' => $row->fa_timestamp
,
2542 'oi_metadata' => $props['metadata'],
2543 'oi_media_type' => $props['media_type'],
2544 'oi_major_mime' => $props['major_mime'],
2545 'oi_minor_mime' => $props['minor_mime'],
2546 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2547 'oi_sha1' => $sha1 );
2550 $deleteIds[] = $row->fa_id
;
2552 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2553 // private files can stay where they are
2554 $status->successCount++
;
2556 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2557 $this->cleanupBatch
[] = $row->fa_storage_key
;
2565 // Add a warning to the status object for missing IDs
2566 $missingIds = array_diff( $this->ids
, $idsPresent );
2568 foreach ( $missingIds as $id ) {
2569 $status->error( 'undelete-missing-filearchive', $id );
2572 // Remove missing files from batch, so we don't get errors when undeleting them
2573 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2575 // Run the store batch
2576 // Use the OVERWRITE_SAME flag to smooth over a common error
2577 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2578 $status->merge( $storeStatus );
2580 if ( !$status->isGood() ) {
2581 // Even if some files could be copied, fail entirely as that is the
2582 // easiest thing to do without data loss
2583 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2584 $status->ok
= false;
2585 $this->file
->unlock();
2590 // Run the DB updates
2591 // Because we have locked the image row, key conflicts should be rare.
2592 // If they do occur, we can roll back the transaction at this time with
2593 // no data loss, but leaving unregistered files scattered throughout the
2595 // This is not ideal, which is why it's important to lock the image row.
2596 if ( $insertCurrent ) {
2597 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2600 if ( $insertBatch ) {
2601 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2605 $dbw->delete( 'filearchive',
2606 array( 'fa_id' => $deleteIds ),
2610 // If store batch is empty (all files are missing), deletion is to be considered successful
2611 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2613 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2615 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2617 $this->file
->purgeEverything();
2619 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2620 $this->file
->purgeDescription();
2621 $this->file
->purgeHistory();
2625 $this->file
->unlock();
2631 * Removes non-existent files from a store batch.
2632 * @param array $triplets
2635 function removeNonexistentFiles( $triplets ) {
2636 $files = $filteredTriplets = array();
2637 foreach ( $triplets as $file ) {
2638 $files[$file[0]] = $file[0];
2641 $result = $this->file
->repo
->fileExistsBatch( $files );
2643 foreach ( $triplets as $file ) {
2644 if ( $result[$file[0]] ) {
2645 $filteredTriplets[] = $file;
2649 return $filteredTriplets;
2653 * Removes non-existent files from a cleanup batch.
2654 * @param array $batch
2657 function removeNonexistentFromCleanup( $batch ) {
2658 $files = $newBatch = array();
2659 $repo = $this->file
->repo
;
2661 foreach ( $batch as $file ) {
2662 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2663 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2666 $result = $repo->fileExistsBatch( $files );
2668 foreach ( $batch as $file ) {
2669 if ( $result[$file] ) {
2670 $newBatch[] = $file;
2678 * Delete unused files in the deleted zone.
2679 * This should be called from outside the transaction in which execute() was called.
2680 * @return FileRepoStatus
2682 function cleanup() {
2683 if ( !$this->cleanupBatch
) {
2684 return $this->file
->repo
->newGood();
2687 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2689 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2695 * Cleanup a failed batch. The batch was only partially successful, so
2696 * rollback by removing all items that were succesfully copied.
2698 * @param Status $storeStatus
2699 * @param array $storeBatch
2701 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2702 $cleanupBatch = array();
2704 foreach ( $storeStatus->success
as $i => $success ) {
2705 // Check if this item of the batch was successfully copied
2707 // Item was successfully copied and needs to be removed again
2708 // Extract ($dstZone, $dstRel) from the batch
2709 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2712 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2716 # ------------------------------------------------------------------------------
2719 * Helper class for file movement
2720 * @ingroup FileAbstraction
2722 class LocalFileMoveBatch
{
2723 /** @var LocalFile */
2733 protected $oldCount;
2737 /** @var DatabaseBase */
2742 * @param Title $target
2744 function __construct( File
$file, Title
$target ) {
2745 $this->file
= $file;
2746 $this->target
= $target;
2747 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2748 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2749 $this->oldName
= $this->file
->getName();
2750 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2751 $this->oldRel
= $this->oldHash
. $this->oldName
;
2752 $this->newRel
= $this->newHash
. $this->newName
;
2753 $this->db
= $file->getRepo()->getMasterDb();
2757 * Add the current image to the batch
2759 function addCurrent() {
2760 $this->cur
= array( $this->oldRel
, $this->newRel
);
2764 * Add the old versions of the image to the batch
2765 * @return array List of archive names from old versions
2767 function addOlds() {
2768 $archiveBase = 'archive';
2769 $this->olds
= array();
2770 $this->oldCount
= 0;
2771 $archiveNames = array();
2773 $result = $this->db
->select( 'oldimage',
2774 array( 'oi_archive_name', 'oi_deleted' ),
2775 array( 'oi_name' => $this->oldName
),
2777 array( 'FOR UPDATE' ) // ignore snapshot
2780 foreach ( $result as $row ) {
2781 $archiveNames[] = $row->oi_archive_name
;
2782 $oldName = $row->oi_archive_name
;
2783 $bits = explode( '!', $oldName, 2 );
2785 if ( count( $bits ) != 2 ) {
2786 wfDebug( "Old file name missing !: '$oldName' \n" );
2790 list( $timestamp, $filename ) = $bits;
2792 if ( $this->oldName
!= $filename ) {
2793 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2799 // Do we want to add those to oldCount?
2800 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2804 $this->olds
[] = array(
2805 "{$archiveBase}/{$this->oldHash}{$oldName}",
2806 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2810 return $archiveNames;
2815 * @return FileRepoStatus
2817 function execute() {
2818 $repo = $this->file
->repo
;
2819 $status = $repo->newGood();
2821 $triplets = $this->getMoveTriplets();
2822 $triplets = $this->removeNonexistentFiles( $triplets );
2823 $destFile = wfLocalFile( $this->target
);
2825 $this->file
->lock(); // begin
2826 $destFile->lock(); // quickly fail if destination is not available
2827 // Rename the file versions metadata in the DB.
2828 // This implicitly locks the destination file, which avoids race conditions.
2829 // If we moved the files from A -> C before DB updates, another process could
2830 // move files from B -> C at this point, causing storeBatch() to fail and thus
2831 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2832 $statusDb = $this->doDBUpdates();
2833 if ( !$statusDb->isGood() ) {
2834 $destFile->unlock();
2835 $this->file
->unlockAndRollback();
2836 $statusDb->ok
= false;
2840 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2841 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2843 // Copy the files into their new location.
2844 // If a prior process fataled copying or cleaning up files we tolerate any
2845 // of the existing files if they are identical to the ones being stored.
2846 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2847 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2848 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2849 if ( !$statusMove->isGood() ) {
2850 // Delete any files copied over (while the destination is still locked)
2851 $this->cleanupTarget( $triplets );
2852 $destFile->unlock();
2853 $this->file
->unlockAndRollback(); // unlocks the destination
2854 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2855 $statusMove->ok
= false;
2859 $destFile->unlock();
2860 $this->file
->unlock(); // done
2862 // Everything went ok, remove the source files
2863 $this->cleanupSource( $triplets );
2865 $status->merge( $statusDb );
2866 $status->merge( $statusMove );
2872 * Do the database updates and return a new FileRepoStatus indicating how
2873 * many rows where updated.
2875 * @return FileRepoStatus
2877 function doDBUpdates() {
2878 $repo = $this->file
->repo
;
2879 $status = $repo->newGood();
2882 // Update current image
2885 array( 'img_name' => $this->newName
),
2886 array( 'img_name' => $this->oldName
),
2890 if ( $dbw->affectedRows() ) {
2891 $status->successCount++
;
2893 $status->failCount++
;
2894 $status->fatal( 'imageinvalidfilename' );
2899 // Update old images
2903 'oi_name' => $this->newName
,
2904 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2905 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2907 array( 'oi_name' => $this->oldName
),
2911 $affected = $dbw->affectedRows();
2912 $total = $this->oldCount
;
2913 $status->successCount +
= $affected;
2914 // Bug 34934: $total is based on files that actually exist.
2915 // There may be more DB rows than such files, in which case $affected
2916 // can be greater than $total. We use max() to avoid negatives here.
2917 $status->failCount +
= max( 0, $total - $affected );
2918 if ( $status->failCount
) {
2919 $status->error( 'imageinvalidfilename' );
2926 * Generate triplets for FileRepo::storeBatch().
2929 function getMoveTriplets() {
2930 $moves = array_merge( array( $this->cur
), $this->olds
);
2931 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2933 foreach ( $moves as $move ) {
2934 // $move: (oldRelativePath, newRelativePath)
2935 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2936 $triplets[] = array( $srcUrl, 'public', $move[1] );
2939 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2947 * Removes non-existent files from move batch.
2948 * @param array $triplets
2951 function removeNonexistentFiles( $triplets ) {
2954 foreach ( $triplets as $file ) {
2955 $files[$file[0]] = $file[0];
2958 $result = $this->file
->repo
->fileExistsBatch( $files );
2959 $filteredTriplets = array();
2961 foreach ( $triplets as $file ) {
2962 if ( $result[$file[0]] ) {
2963 $filteredTriplets[] = $file;
2965 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2969 return $filteredTriplets;
2973 * Cleanup a partially moved array of triplets by deleting the target
2974 * files. Called if something went wrong half way.
2976 function cleanupTarget( $triplets ) {
2977 // Create dest pairs from the triplets
2979 foreach ( $triplets as $triplet ) {
2980 // $triplet: (old source virtual URL, dst zone, dest rel)
2981 $pairs[] = array( $triplet[1], $triplet[2] );
2984 $this->file
->repo
->cleanupBatch( $pairs );
2988 * Cleanup a fully moved array of triplets by deleting the source files.
2989 * Called at the end of the move process if everything else went ok.
2991 function cleanupSource( $triplets ) {
2992 // Create source file names from the triplets
2994 foreach ( $triplets as $triplet ) {
2995 $files[] = $triplet[0];
2998 $this->file
->repo
->cleanupBatch( $files );