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
) {
597 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
598 wfProfileOut( __METHOD__
);
603 $dbw = $this->repo
->getMasterDB();
604 list( $major, $minor ) = self
::splitMime( $this->mime
);
606 if ( wfReadOnly() ) {
607 wfProfileOut( __METHOD__
);
611 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
613 $dbw->update( 'image',
615 'img_size' => $this->size
, // sanity
616 'img_width' => $this->width
,
617 'img_height' => $this->height
,
618 'img_bits' => $this->bits
,
619 'img_media_type' => $this->media_type
,
620 'img_major_mime' => $major,
621 'img_minor_mime' => $minor,
622 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
623 'img_sha1' => $this->sha1
,
625 array( 'img_name' => $this->getName() ),
629 $this->saveToCache();
631 $this->unlock(); // done
633 wfProfileOut( __METHOD__
);
637 * Set properties in this object to be equal to those given in the
638 * associative array $info. Only cacheable fields can be set.
639 * All fields *must* be set in $info except for getLazyCacheFields().
641 * If 'mime' is given, it will be split into major_mime/minor_mime.
642 * If major_mime/minor_mime are given, $this->mime will also be set.
646 function setProps( $info ) {
647 $this->dataLoaded
= true;
648 $fields = $this->getCacheFields( '' );
649 $fields[] = 'fileExists';
651 foreach ( $fields as $field ) {
652 if ( isset( $info[$field] ) ) {
653 $this->$field = $info[$field];
657 // Fix up mime fields
658 if ( isset( $info['major_mime'] ) ) {
659 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
660 } elseif ( isset( $info['mime'] ) ) {
661 $this->mime
= $info['mime'];
662 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
666 /** splitMime inherited */
667 /** getName inherited */
668 /** getTitle inherited */
669 /** getURL inherited */
670 /** getViewURL inherited */
671 /** getPath inherited */
672 /** isVisible inhereted */
677 function isMissing() {
678 if ( $this->missing
=== null ) {
679 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
680 $this->missing
= !$fileExists;
683 return $this->missing
;
687 * Return the width of the image
692 public function getWidth( $page = 1 ) {
695 if ( $this->isMultipage() ) {
696 $handler = $this->getHandler();
700 $dim = $handler->getPageDimensions( $this, $page );
702 return $dim['width'];
704 // For non-paged media, the false goes through an
705 // intval, turning failure into 0, so do same here.
714 * Return the height of the image
719 public function getHeight( $page = 1 ) {
722 if ( $this->isMultipage() ) {
723 $handler = $this->getHandler();
727 $dim = $handler->getPageDimensions( $this, $page );
729 return $dim['height'];
731 // For non-paged media, the false goes through an
732 // intval, turning failure into 0, so do same here.
736 return $this->height
;
741 * Returns ID or name of user who uploaded the file
743 * @param string $type 'text' or 'id'
746 function getUser( $type = 'text' ) {
749 if ( $type == 'text' ) {
750 return $this->user_text
;
751 } elseif ( $type == 'id' ) {
757 * Get handler-specific metadata
760 function getMetadata() {
761 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
762 return $this->metadata
;
768 function getBitDepth() {
775 * Returns the size of the image file, in bytes
778 public function getSize() {
785 * Returns the mime type of the file.
788 function getMimeType() {
795 * Returns the type of the media in the file.
796 * Use the value returned by this function with the MEDIATYPE_xxx constants.
799 function getMediaType() {
802 return $this->media_type
;
805 /** canRender inherited */
806 /** mustRender inherited */
807 /** allowInlineDisplay inherited */
808 /** isSafeFile inherited */
809 /** isTrustedFile inherited */
812 * Returns true if the file exists on disk.
813 * @return bool Whether file exist on disk.
815 public function exists() {
818 return $this->fileExists
;
821 /** getTransformScript inherited */
822 /** getUnscaledThumb inherited */
823 /** thumbName inherited */
824 /** createThumb inherited */
825 /** transform inherited */
827 /** getHandler inherited */
828 /** iconThumb inherited */
829 /** getLastError inherited */
832 * Get all thumbnail names previously generated for this file
833 * @param string|bool $archiveName Name of an archive file, default false
834 * @return array first element is the base dir, then files in that base dir.
836 function getThumbnails( $archiveName = false ) {
837 if ( $archiveName ) {
838 $dir = $this->getArchiveThumbPath( $archiveName );
840 $dir = $this->getThumbPath();
843 $backend = $this->repo
->getBackend();
844 $files = array( $dir );
846 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
847 foreach ( $iterator as $file ) {
850 } catch ( FileBackendError
$e ) {
851 } // suppress (bug 54674)
857 * Refresh metadata in memcached, but don't touch thumbnails or squid
859 function purgeMetadataCache() {
861 $this->saveToCache();
862 $this->purgeHistory();
866 * Purge the shared history (OldLocalFile) cache.
868 * @note This used to purge old thumbnails as well.
870 function purgeHistory() {
873 $hashedName = md5( $this->getName() );
874 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
877 $wgMemc->delete( $oldKey );
882 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
884 * @param array $options An array potentially with the key forThumbRefresh.
886 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
888 function purgeCache( $options = array() ) {
889 wfProfileIn( __METHOD__
);
890 // Refresh metadata cache
891 $this->purgeMetadataCache();
894 $this->purgeThumbnails( $options );
896 // Purge squid cache for this file
897 SquidUpdate
::purge( array( $this->getURL() ) );
898 wfProfileOut( __METHOD__
);
902 * Delete cached transformed files for an archived version only.
903 * @param string $archiveName Name of the archived file
905 function purgeOldThumbnails( $archiveName ) {
907 wfProfileIn( __METHOD__
);
909 // Get a list of old thumbnails and URLs
910 $files = $this->getThumbnails( $archiveName );
912 // Purge any custom thumbnail caches
913 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
915 $dir = array_shift( $files );
916 $this->purgeThumbList( $dir, $files );
921 foreach ( $files as $file ) {
922 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
924 SquidUpdate
::purge( $urls );
927 wfProfileOut( __METHOD__
);
931 * Delete cached transformed files for the current version only.
933 function purgeThumbnails( $options = array() ) {
935 wfProfileIn( __METHOD__
);
938 $files = $this->getThumbnails();
939 // Always purge all files from squid regardless of handler filters
942 foreach ( $files as $file ) {
943 $urls[] = $this->getThumbUrl( $file );
945 array_shift( $urls ); // don't purge directory
948 // Give media handler a chance to filter the file purge list
949 if ( !empty( $options['forThumbRefresh'] ) ) {
950 $handler = $this->getHandler();
952 $handler->filterThumbnailPurgeList( $files, $options );
956 // Purge any custom thumbnail caches
957 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
959 $dir = array_shift( $files );
960 $this->purgeThumbList( $dir, $files );
964 SquidUpdate
::purge( $urls );
967 wfProfileOut( __METHOD__
);
971 * Delete a list of thumbnails visible at urls
972 * @param string $dir Base dir of the files.
973 * @param array $files Array of strings: relative filenames (to $dir)
975 protected function purgeThumbList( $dir, $files ) {
976 $fileListDebug = strtr(
977 var_export( $files, true ),
980 wfDebug( __METHOD__
. ": $fileListDebug\n" );
982 $purgeList = array();
983 foreach ( $files as $file ) {
984 # Check that the base file name is part of the thumb name
985 # This is a basic sanity check to avoid erasing unrelated directories
986 if ( strpos( $file, $this->getName() ) !== false
987 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
989 $purgeList[] = "{$dir}/{$file}";
993 # Delete the thumbnails
994 $this->repo
->quickPurgeBatch( $purgeList );
995 # Clear out the thumbnail directory if empty
996 $this->repo
->quickCleanDir( $dir );
999 /** purgeDescription inherited */
1000 /** purgeEverything inherited */
1003 * @param int $limit Optional: Limit to number of results
1004 * @param int $start Optional: Timestamp, start from
1005 * @param int $end Optional: Timestamp, end at
1009 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1010 $dbr = $this->repo
->getSlaveDB();
1011 $tables = array( 'oldimage' );
1012 $fields = OldLocalFile
::selectFields();
1013 $conds = $opts = $join_conds = array();
1014 $eq = $inc ?
'=' : '';
1015 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1018 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1022 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1026 $opts['LIMIT'] = $limit;
1029 // Search backwards for time > x queries
1030 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1031 $opts['ORDER BY'] = "oi_timestamp $order";
1032 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1034 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1035 &$conds, &$opts, &$join_conds ) );
1037 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1040 foreach ( $res as $row ) {
1041 $r[] = $this->repo
->newFileFromRow( $row );
1044 if ( $order == 'ASC' ) {
1045 $r = array_reverse( $r ); // make sure it ends up descending
1052 * Returns the history of this file, line by line.
1053 * starts with current version, then old versions.
1054 * uses $this->historyLine to check which line to return:
1055 * 0 return line for current version
1056 * 1 query for old versions, return first one
1057 * 2, ... return next old version from above query
1060 public function nextHistoryLine() {
1061 # Polymorphic function name to distinguish foreign and local fetches
1062 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1064 $dbr = $this->repo
->getSlaveDB();
1066 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1067 $this->historyRes
= $dbr->select( 'image',
1070 "'' AS oi_archive_name",
1074 array( 'img_name' => $this->title
->getDBkey() ),
1078 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1079 $this->historyRes
= null;
1083 } elseif ( $this->historyLine
== 1 ) {
1084 $this->historyRes
= $dbr->select( 'oldimage', '*',
1085 array( 'oi_name' => $this->title
->getDBkey() ),
1087 array( 'ORDER BY' => 'oi_timestamp DESC' )
1090 $this->historyLine++
;
1092 return $dbr->fetchObject( $this->historyRes
);
1096 * Reset the history pointer to the first element of the history
1098 public function resetHistory() {
1099 $this->historyLine
= 0;
1101 if ( !is_null( $this->historyRes
) ) {
1102 $this->historyRes
= null;
1106 /** getHashPath inherited */
1107 /** getRel inherited */
1108 /** getUrlRel inherited */
1109 /** getArchiveRel inherited */
1110 /** getArchivePath inherited */
1111 /** getThumbPath inherited */
1112 /** getArchiveUrl inherited */
1113 /** getThumbUrl inherited */
1114 /** getArchiveVirtualUrl inherited */
1115 /** getThumbVirtualUrl inherited */
1116 /** isHashed inherited */
1119 * Upload a file and record it in the DB
1120 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1121 * @param string $comment Upload description
1122 * @param string $pageText Text to use for the new description page,
1123 * if a new description page is created
1124 * @param int|bool $flags Flags for publish()
1125 * @param array|bool $props File properties, if known. This can be used to
1126 * reduce the upload time when uploading virtual URLs for which the file
1127 * info is already known
1128 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1130 * @param User|null $user User object or null to use $wgUser
1132 * @return FileRepoStatus On success, the value member contains the
1133 * archive name, or an empty string if it was a new file.
1135 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1136 $timestamp = false, $user = null
1140 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1141 return $this->readOnlyFatalStatus();
1145 wfProfileIn( __METHOD__
. '-getProps' );
1146 if ( $this->repo
->isVirtualUrl( $srcPath )
1147 || FileBackend
::isStoragePath( $srcPath )
1149 $props = $this->repo
->getFileProps( $srcPath );
1151 $props = FSFile
::getPropsFromPath( $srcPath );
1153 wfProfileOut( __METHOD__
. '-getProps' );
1157 $handler = MediaHandler
::getHandler( $props['mime'] );
1159 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1161 $options['headers'] = array();
1164 // Trim spaces on user supplied text
1165 $comment = trim( $comment );
1167 // Truncate nicely or the DB will do it for us
1168 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1169 $comment = $wgContLang->truncate( $comment, 255 );
1170 $this->lock(); // begin
1171 $status = $this->publish( $srcPath, $flags, $options );
1173 if ( $status->successCount
>= 2 ) {
1174 // There will be a copy+(one of move,copy,store).
1175 // The first succeeding does not commit us to updating the DB
1176 // since it simply copied the current version to a timestamped file name.
1177 // It is only *preferable* to avoid leaving such files orphaned.
1178 // Once the second operation goes through, then the current version was
1179 // updated and we must therefore update the DB too.
1180 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1181 $status->fatal( 'filenotfound', $srcPath );
1185 $this->unlock(); // done
1191 * Record a file upload in the upload log and the image table
1192 * @param string $oldver
1193 * @param string $desc
1194 * @param string $license
1195 * @param string $copyStatus
1196 * @param string $source
1197 * @param bool $watch
1198 * @param string|bool $timestamp
1199 * @param User|null $user User object or null to use $wgUser
1202 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1203 $watch = false, $timestamp = false, User
$user = null ) {
1209 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1211 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1216 $user->addWatch( $this->getTitle() );
1223 * Record a file upload in the upload log and the image table
1224 * @param string $oldver
1225 * @param string $comment
1226 * @param string $pageText
1227 * @param bool|array $props
1228 * @param string|bool $timestamp
1229 * @param null|User $user
1232 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1235 wfProfileIn( __METHOD__
);
1237 if ( is_null( $user ) ) {
1242 $dbw = $this->repo
->getMasterDB();
1243 $dbw->begin( __METHOD__
);
1246 wfProfileIn( __METHOD__
. '-getProps' );
1247 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1248 wfProfileOut( __METHOD__
. '-getProps' );
1251 if ( $timestamp === false ) {
1252 $timestamp = $dbw->timestamp();
1255 $props['description'] = $comment;
1256 $props['user'] = $user->getId();
1257 $props['user_text'] = $user->getName();
1258 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1259 $this->setProps( $props );
1261 # Fail now if the file isn't there
1262 if ( !$this->fileExists
) {
1263 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1264 wfProfileOut( __METHOD__
);
1271 # Test to see if the row exists using INSERT IGNORE
1272 # This avoids race conditions by locking the row until the commit, and also
1273 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1274 $dbw->insert( 'image',
1276 'img_name' => $this->getName(),
1277 'img_size' => $this->size
,
1278 'img_width' => intval( $this->width
),
1279 'img_height' => intval( $this->height
),
1280 'img_bits' => $this->bits
,
1281 'img_media_type' => $this->media_type
,
1282 'img_major_mime' => $this->major_mime
,
1283 'img_minor_mime' => $this->minor_mime
,
1284 'img_timestamp' => $timestamp,
1285 'img_description' => $comment,
1286 'img_user' => $user->getId(),
1287 'img_user_text' => $user->getName(),
1288 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1289 'img_sha1' => $this->sha1
1294 if ( $dbw->affectedRows() == 0 ) {
1295 # (bug 34993) Note: $oldver can be empty here, if the previous
1296 # version of the file was broken. Allow registration of the new
1297 # version to continue anyway, because that's better than having
1298 # an image that's not fixable by user operations.
1301 # Collision, this is an update of a file
1302 # Insert previous contents into oldimage
1303 $dbw->insertSelect( 'oldimage', 'image',
1305 'oi_name' => 'img_name',
1306 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1307 'oi_size' => 'img_size',
1308 'oi_width' => 'img_width',
1309 'oi_height' => 'img_height',
1310 'oi_bits' => 'img_bits',
1311 'oi_timestamp' => 'img_timestamp',
1312 'oi_description' => 'img_description',
1313 'oi_user' => 'img_user',
1314 'oi_user_text' => 'img_user_text',
1315 'oi_metadata' => 'img_metadata',
1316 'oi_media_type' => 'img_media_type',
1317 'oi_major_mime' => 'img_major_mime',
1318 'oi_minor_mime' => 'img_minor_mime',
1319 'oi_sha1' => 'img_sha1'
1321 array( 'img_name' => $this->getName() ),
1325 # Update the current image row
1326 $dbw->update( 'image',
1328 'img_size' => $this->size
,
1329 'img_width' => intval( $this->width
),
1330 'img_height' => intval( $this->height
),
1331 'img_bits' => $this->bits
,
1332 'img_media_type' => $this->media_type
,
1333 'img_major_mime' => $this->major_mime
,
1334 'img_minor_mime' => $this->minor_mime
,
1335 'img_timestamp' => $timestamp,
1336 'img_description' => $comment,
1337 'img_user' => $user->getId(),
1338 'img_user_text' => $user->getName(),
1339 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1340 'img_sha1' => $this->sha1
1342 array( 'img_name' => $this->getName() ),
1346 # This is a new file, so update the image count
1347 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1350 $descTitle = $this->getTitle();
1351 $wikiPage = new WikiFilePage( $descTitle );
1352 $wikiPage->setFile( $this );
1355 $action = $reupload ?
'overwrite' : 'upload';
1357 $logEntry = new ManualLogEntry( 'upload', $action );
1358 $logEntry->setPerformer( $user );
1359 $logEntry->setComment( $comment );
1360 $logEntry->setTarget( $descTitle );
1362 // Allow people using the api to associate log entries with the upload.
1363 // Log has a timestamp, but sometimes different from upload timestamp.
1364 $logEntry->setParameters(
1366 'img_sha1' => $this->sha1
,
1367 'img_timestamp' => $timestamp,
1370 // Note we keep $logId around since during new image
1371 // creation, page doesn't exist yet, so log_page = 0
1372 // but we want it to point to the page we're making,
1373 // so we later modify the log entry.
1374 // For a similar reason, we avoid making an RC entry
1375 // now and wait until the page exists.
1376 $logId = $logEntry->insert();
1378 $exists = $descTitle->exists();
1380 // Page exists, do RC entry now (otherwise we wait for later).
1381 $logEntry->publish( $logId );
1383 wfProfileIn( __METHOD__
. '-edit' );
1386 # Create a null revision
1387 $latest = $descTitle->getLatestRevID();
1388 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1390 $nullRevision = Revision
::newNullRevision(
1392 $descTitle->getArticleID(),
1397 if ( !is_null( $nullRevision ) ) {
1398 $nullRevision->insertOn( $dbw );
1400 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1401 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1405 # Commit the transaction now, in case something goes wrong later
1406 # The most important thing is that files don't get lost, especially archives
1407 # NOTE: once we have support for nested transactions, the commit may be moved
1408 # to after $wikiPage->doEdit has been called.
1409 $dbw->commit( __METHOD__
);
1412 # We shall not saveToCache before the commit since otherwise
1413 # in case of a rollback there is an usable file from memcached
1414 # which in fact doesn't really exist (bug 24978)
1415 $this->saveToCache();
1418 # Invalidate the cache for the description page
1419 $descTitle->invalidateCache();
1420 $descTitle->purgeSquid();
1422 # New file; create the description page.
1423 # There's already a log entry, so don't make a second RC entry
1424 # Squid and file cache for the description page are purged by doEditContent.
1425 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1426 $status = $wikiPage->doEditContent(
1429 EDIT_NEW | EDIT_SUPPRESS_RC
,
1434 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1435 // Now that the page exists, make an RC entry.
1436 $logEntry->publish( $logId );
1437 if ( isset( $status->value
['revision'] ) ) {
1438 $dbw->update( 'logging',
1439 array( 'log_page' => $status->value
['revision']->getPage() ),
1440 array( 'log_id' => $logId ),
1444 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1447 wfProfileOut( __METHOD__
. '-edit' );
1450 # Delete old thumbnails
1451 wfProfileIn( __METHOD__
. '-purge' );
1452 $this->purgeThumbnails();
1453 wfProfileOut( __METHOD__
. '-purge' );
1455 # Remove the old file from the squid cache
1456 SquidUpdate
::purge( array( $this->getURL() ) );
1459 # Hooks, hooks, the magic of hooks...
1460 wfProfileIn( __METHOD__
. '-hooks' );
1461 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1462 wfProfileOut( __METHOD__
. '-hooks' );
1464 # Invalidate cache for all pages using this file
1465 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1466 $update->doUpdate();
1468 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1471 wfProfileOut( __METHOD__
);
1477 * Move or copy a file to its public location. If a file exists at the
1478 * destination, move it to an archive. Returns a FileRepoStatus object with
1479 * the archive name in the "value" member on success.
1481 * The archive name should be passed through to recordUpload for database
1484 * @param string $srcPath Local filesystem path to the source image
1485 * @param int $flags A bitwise combination of:
1486 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1487 * @param array $options Optional additional parameters
1488 * @return FileRepoStatus On success, the value member contains the
1489 * archive name, or an empty string if it was a new file.
1491 function publish( $srcPath, $flags = 0, array $options = array() ) {
1492 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1496 * Move or copy a file to a specified location. Returns a FileRepoStatus
1497 * object with the archive name in the "value" member on success.
1499 * The archive name should be passed through to recordUpload for database
1502 * @param string $srcPath Local filesystem path to the source image
1503 * @param string $dstRel Target relative path
1504 * @param int $flags A bitwise combination of:
1505 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1506 * @param array $options Optional additional parameters
1507 * @return FileRepoStatus On success, the value member contains the
1508 * archive name, or an empty string if it was a new file.
1510 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1511 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1512 return $this->readOnlyFatalStatus();
1515 $this->lock(); // begin
1517 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1518 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1519 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1520 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1522 if ( $status->value
== 'new' ) {
1523 $status->value
= '';
1525 $status->value
= $archiveName;
1528 $this->unlock(); // done
1533 /** getLinksTo inherited */
1534 /** getExifData inherited */
1535 /** isLocal inherited */
1536 /** wasDeleted inherited */
1539 * Move file to the new title
1541 * Move current, old version and all thumbnails
1542 * to the new filename. Old file is deleted.
1544 * Cache purging is done; checks for validity
1545 * and logging are caller's responsibility
1547 * @param Title $target New file name
1548 * @return FileRepoStatus
1550 function move( $target ) {
1551 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1552 return $this->readOnlyFatalStatus();
1555 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1556 $batch = new LocalFileMoveBatch( $this, $target );
1558 $this->lock(); // begin
1559 $batch->addCurrent();
1560 $archiveNames = $batch->addOlds();
1561 $status = $batch->execute();
1562 $this->unlock(); // done
1564 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1566 // Purge the source and target files...
1567 $oldTitleFile = wfLocalFile( $this->title
);
1568 $newTitleFile = wfLocalFile( $target );
1569 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1570 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1571 $this->getRepo()->getMasterDB()->onTransactionIdle(
1572 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1573 $oldTitleFile->purgeEverything();
1574 foreach ( $archiveNames as $archiveName ) {
1575 $oldTitleFile->purgeOldThumbnails( $archiveName );
1577 $newTitleFile->purgeEverything();
1581 if ( $status->isOK() ) {
1582 // Now switch the object
1583 $this->title
= $target;
1584 // Force regeneration of the name and hashpath
1585 unset( $this->name
);
1586 unset( $this->hashPath
);
1593 * Delete all versions of the file.
1595 * Moves the files into an archive directory (or deletes them)
1596 * and removes the database rows.
1598 * Cache purging is done; logging is caller's responsibility.
1600 * @param string $reason
1601 * @param bool $suppress
1602 * @return FileRepoStatus
1604 function delete( $reason, $suppress = false ) {
1605 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1606 return $this->readOnlyFatalStatus();
1609 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1611 $this->lock(); // begin
1612 $batch->addCurrent();
1613 # Get old version relative paths
1614 $archiveNames = $batch->addOlds();
1615 $status = $batch->execute();
1616 $this->unlock(); // done
1618 if ( $status->isOK() ) {
1619 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1622 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1623 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1625 $this->getRepo()->getMasterDB()->onTransactionIdle(
1626 function () use ( $file, $archiveNames ) {
1629 $file->purgeEverything();
1630 foreach ( $archiveNames as $archiveName ) {
1631 $file->purgeOldThumbnails( $archiveName );
1634 if ( $wgUseSquid ) {
1636 $purgeUrls = array();
1637 foreach ( $archiveNames as $archiveName ) {
1638 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1640 SquidUpdate
::purge( $purgeUrls );
1649 * Delete an old version of the file.
1651 * Moves the file into an archive directory (or deletes it)
1652 * and removes the database row.
1654 * Cache purging is done; logging is caller's responsibility.
1656 * @param string $archiveName
1657 * @param string $reason
1658 * @param bool $suppress
1659 * @throws MWException Exception on database or file store failure
1660 * @return FileRepoStatus
1662 function deleteOld( $archiveName, $reason, $suppress = false ) {
1664 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1665 return $this->readOnlyFatalStatus();
1668 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1670 $this->lock(); // begin
1671 $batch->addOld( $archiveName );
1672 $status = $batch->execute();
1673 $this->unlock(); // done
1675 $this->purgeOldThumbnails( $archiveName );
1676 if ( $status->isOK() ) {
1677 $this->purgeDescription();
1678 $this->purgeHistory();
1681 if ( $wgUseSquid ) {
1683 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1690 * Restore all or specified deleted revisions to the given file.
1691 * Permissions and logging are left to the caller.
1693 * May throw database exceptions on error.
1695 * @param array $versions Set of record ids of deleted items to restore,
1696 * or empty to restore all revisions.
1697 * @param bool $unsuppress
1698 * @return FileRepoStatus
1700 function restore( $versions = array(), $unsuppress = false ) {
1701 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1702 return $this->readOnlyFatalStatus();
1705 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1707 $this->lock(); // begin
1711 $batch->addIds( $versions );
1713 $status = $batch->execute();
1714 if ( $status->isGood() ) {
1715 $cleanupStatus = $batch->cleanup();
1716 $cleanupStatus->successCount
= 0;
1717 $cleanupStatus->failCount
= 0;
1718 $status->merge( $cleanupStatus );
1720 $this->unlock(); // done
1725 /** isMultipage inherited */
1726 /** pageCount inherited */
1727 /** scaleHeight inherited */
1728 /** getImageSize inherited */
1731 * Get the URL of the file description page.
1734 function getDescriptionUrl() {
1735 return $this->title
->getLocalURL();
1739 * Get the HTML text of the description page
1740 * This is not used by ImagePage for local files, since (among other things)
1741 * it skips the parser cache.
1743 * @param Language $lang What language to get description in (Optional)
1744 * @return bool|mixed
1746 function getDescriptionText( $lang = null ) {
1747 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1751 $content = $revision->getContent();
1755 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1757 return $pout->getText();
1761 * @param int $audience
1765 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1767 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1769 } elseif ( $audience == self
::FOR_THIS_USER
1770 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1774 return $this->description
;
1779 * @return bool|string
1781 function getTimestamp() {
1784 return $this->timestamp
;
1790 function getSha1() {
1792 // Initialise now if necessary
1793 if ( $this->sha1
== '' && $this->fileExists
) {
1794 $this->lock(); // begin
1796 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1797 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1798 $dbw = $this->repo
->getMasterDB();
1799 $dbw->update( 'image',
1800 array( 'img_sha1' => $this->sha1
),
1801 array( 'img_name' => $this->getName() ),
1803 $this->saveToCache();
1806 $this->unlock(); // done
1813 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1815 function isCacheable() {
1818 // If extra data (metadata) was not loaded then it must have been large
1819 return $this->extraDataLoaded
1820 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1824 * Start a transaction and lock the image for update
1825 * Increments a reference counter if the lock is already held
1826 * @throws MWException
1827 * @return bool True if the image exists, false otherwise
1830 $dbw = $this->repo
->getMasterDB();
1832 if ( !$this->locked
) {
1833 if ( !$dbw->trxLevel() ) {
1834 $dbw->begin( __METHOD__
);
1835 $this->lockedOwnTrx
= true;
1838 // Bug 54736: use simple lock to handle when the file does not exist.
1839 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1840 $cache = wfGetMainCache();
1841 $key = $this->getCacheKey();
1842 if ( !$cache->lock( $key, 5 ) ) {
1843 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1845 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1846 $cache->unlock( $key ); // release on commit
1850 $this->markVolatile(); // file may change soon
1852 return $dbw->selectField( 'image', '1',
1853 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1857 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1858 * the transaction and thereby releases the image lock.
1861 if ( $this->locked
) {
1863 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1864 $dbw = $this->repo
->getMasterDB();
1865 $dbw->commit( __METHOD__
);
1866 $this->lockedOwnTrx
= false;
1872 * Mark a file as about to be changed
1874 * This sets a cache key that alters master/slave DB loading behavior
1876 * @return bool Success
1878 protected function markVolatile() {
1881 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1883 $this->lastMarkedVolatile
= time();
1884 return $wgMemc->set( $key, $this->lastMarkedVolatile
, self
::VOLATILE_TTL
);
1891 * Check if a file is about to be changed or has been changed recently
1893 * @see LocalFile::isVolatile()
1894 * @return bool Whether the file is volatile
1896 protected function isVolatile() {
1899 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1901 // repo unavailable; bail.
1905 if ( $this->lastMarkedVolatile
=== 0 ) {
1906 $this->lastMarkedVolatile
= $wgMemc->get( $key ) ?
: 0;
1909 $volatileDuration = time() - $this->lastMarkedVolatile
;
1910 return $volatileDuration <= self
::VOLATILE_TTL
;
1914 * Roll back the DB transaction and mark the image unlocked
1916 function unlockAndRollback() {
1917 $this->locked
= false;
1918 $dbw = $this->repo
->getMasterDB();
1919 $dbw->rollback( __METHOD__
);
1920 $this->lockedOwnTrx
= false;
1926 protected function readOnlyFatalStatus() {
1927 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1928 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1932 * Clean up any dangling locks
1934 function __destruct() {
1937 } // LocalFile class
1939 # ------------------------------------------------------------------------------
1942 * Helper class for file deletion
1943 * @ingroup FileAbstraction
1945 class LocalFileDeleteBatch
{
1946 /** @var LocalFile */
1953 private $srcRels = array();
1956 private $archiveUrls = array();
1958 /** @var array Items to be processed in the deletion batch */
1959 private $deletionBatch;
1961 /** @var bool Wether to suppress all suppressable fields when deleting */
1964 /** @var FileRepoStatus */
1969 * @param string $reason
1970 * @param bool $suppress
1972 function __construct( File
$file, $reason = '', $suppress = false ) {
1973 $this->file
= $file;
1974 $this->reason
= $reason;
1975 $this->suppress
= $suppress;
1976 $this->status
= $file->repo
->newGood();
1979 function addCurrent() {
1980 $this->srcRels
['.'] = $this->file
->getRel();
1984 * @param string $oldName
1986 function addOld( $oldName ) {
1987 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1988 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1992 * Add the old versions of the image to the batch
1993 * @return array List of archive names from old versions
1995 function addOlds() {
1996 $archiveNames = array();
1998 $dbw = $this->file
->repo
->getMasterDB();
1999 $result = $dbw->select( 'oldimage',
2000 array( 'oi_archive_name' ),
2001 array( 'oi_name' => $this->file
->getName() ),
2005 foreach ( $result as $row ) {
2006 $this->addOld( $row->oi_archive_name
);
2007 $archiveNames[] = $row->oi_archive_name
;
2010 return $archiveNames;
2016 function getOldRels() {
2017 if ( !isset( $this->srcRels
['.'] ) ) {
2018 $oldRels =& $this->srcRels
;
2019 $deleteCurrent = false;
2021 $oldRels = $this->srcRels
;
2022 unset( $oldRels['.'] );
2023 $deleteCurrent = true;
2026 return array( $oldRels, $deleteCurrent );
2032 protected function getHashes() {
2034 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2036 if ( $deleteCurrent ) {
2037 $hashes['.'] = $this->file
->getSha1();
2040 if ( count( $oldRels ) ) {
2041 $dbw = $this->file
->repo
->getMasterDB();
2042 $res = $dbw->select(
2044 array( 'oi_archive_name', 'oi_sha1' ),
2045 array( 'oi_archive_name' => array_keys( $oldRels ),
2046 'oi_name' => $this->file
->getName() ), // performance
2050 foreach ( $res as $row ) {
2051 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2052 // Get the hash from the file
2053 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2054 $props = $this->file
->repo
->getFileProps( $oldUrl );
2056 if ( $props['fileExists'] ) {
2057 // Upgrade the oldimage row
2058 $dbw->update( 'oldimage',
2059 array( 'oi_sha1' => $props['sha1'] ),
2060 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2062 $hashes[$row->oi_archive_name
] = $props['sha1'];
2064 $hashes[$row->oi_archive_name
] = false;
2067 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2072 $missing = array_diff_key( $this->srcRels
, $hashes );
2074 foreach ( $missing as $name => $rel ) {
2075 $this->status
->error( 'filedelete-old-unregistered', $name );
2078 foreach ( $hashes as $name => $hash ) {
2080 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2081 unset( $hashes[$name] );
2088 function doDBInserts() {
2091 $dbw = $this->file
->repo
->getMasterDB();
2092 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2093 $encUserId = $dbw->addQuotes( $wgUser->getId() );
2094 $encReason = $dbw->addQuotes( $this->reason
);
2095 $encGroup = $dbw->addQuotes( 'deleted' );
2096 $ext = $this->file
->getExtension();
2097 $dotExt = $ext === '' ?
'' : ".$ext";
2098 $encExt = $dbw->addQuotes( $dotExt );
2099 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2101 // Bitfields to further suppress the content
2102 if ( $this->suppress
) {
2104 // This should be 15...
2105 $bitfield |
= Revision
::DELETED_TEXT
;
2106 $bitfield |
= Revision
::DELETED_COMMENT
;
2107 $bitfield |
= Revision
::DELETED_USER
;
2108 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2110 $bitfield = 'oi_deleted';
2113 if ( $deleteCurrent ) {
2114 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2115 $where = array( 'img_name' => $this->file
->getName() );
2116 $dbw->insertSelect( 'filearchive', 'image',
2118 'fa_storage_group' => $encGroup,
2119 'fa_storage_key' => $dbw->conditional( array( 'img_sha1' => '' ), $dbw->addQuotes( '' ), $concat ),
2120 'fa_deleted_user' => $encUserId,
2121 'fa_deleted_timestamp' => $encTimestamp,
2122 'fa_deleted_reason' => $encReason,
2123 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2125 'fa_name' => 'img_name',
2126 'fa_archive_name' => 'NULL',
2127 'fa_size' => 'img_size',
2128 'fa_width' => 'img_width',
2129 'fa_height' => 'img_height',
2130 'fa_metadata' => 'img_metadata',
2131 'fa_bits' => 'img_bits',
2132 'fa_media_type' => 'img_media_type',
2133 'fa_major_mime' => 'img_major_mime',
2134 'fa_minor_mime' => 'img_minor_mime',
2135 'fa_description' => 'img_description',
2136 'fa_user' => 'img_user',
2137 'fa_user_text' => 'img_user_text',
2138 'fa_timestamp' => 'img_timestamp',
2139 'fa_sha1' => 'img_sha1',
2140 ), $where, __METHOD__
);
2143 if ( count( $oldRels ) ) {
2144 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2146 'oi_name' => $this->file
->getName(),
2147 'oi_archive_name' => array_keys( $oldRels ) );
2148 $dbw->insertSelect( 'filearchive', 'oldimage',
2150 'fa_storage_group' => $encGroup,
2151 'fa_storage_key' => $dbw->conditional( array( 'oi_sha1' => '' ), $dbw->addQuotes( '' ), $concat ),
2152 'fa_deleted_user' => $encUserId,
2153 'fa_deleted_timestamp' => $encTimestamp,
2154 'fa_deleted_reason' => $encReason,
2155 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2157 'fa_name' => 'oi_name',
2158 'fa_archive_name' => 'oi_archive_name',
2159 'fa_size' => 'oi_size',
2160 'fa_width' => 'oi_width',
2161 'fa_height' => 'oi_height',
2162 'fa_metadata' => 'oi_metadata',
2163 'fa_bits' => 'oi_bits',
2164 'fa_media_type' => 'oi_media_type',
2165 'fa_major_mime' => 'oi_major_mime',
2166 'fa_minor_mime' => 'oi_minor_mime',
2167 'fa_description' => 'oi_description',
2168 'fa_user' => 'oi_user',
2169 'fa_user_text' => 'oi_user_text',
2170 'fa_timestamp' => 'oi_timestamp',
2171 'fa_sha1' => 'oi_sha1',
2172 ), $where, __METHOD__
);
2176 function doDBDeletes() {
2177 $dbw = $this->file
->repo
->getMasterDB();
2178 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2180 if ( count( $oldRels ) ) {
2181 $dbw->delete( 'oldimage',
2183 'oi_name' => $this->file
->getName(),
2184 'oi_archive_name' => array_keys( $oldRels )
2188 if ( $deleteCurrent ) {
2189 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2194 * Run the transaction
2195 * @return FileRepoStatus
2197 function execute() {
2198 wfProfileIn( __METHOD__
);
2200 $this->file
->lock();
2201 // Leave private files alone
2202 $privateFiles = array();
2203 list( $oldRels, ) = $this->getOldRels();
2204 $dbw = $this->file
->repo
->getMasterDB();
2206 if ( !empty( $oldRels ) ) {
2207 $res = $dbw->select( 'oldimage',
2208 array( 'oi_archive_name' ),
2209 array( 'oi_name' => $this->file
->getName(),
2210 'oi_archive_name' => array_keys( $oldRels ),
2211 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2214 foreach ( $res as $row ) {
2215 $privateFiles[$row->oi_archive_name
] = 1;
2218 // Prepare deletion batch
2219 $hashes = $this->getHashes();
2220 $this->deletionBatch
= array();
2221 $ext = $this->file
->getExtension();
2222 $dotExt = $ext === '' ?
'' : ".$ext";
2224 foreach ( $this->srcRels
as $name => $srcRel ) {
2225 // Skip files that have no hash (missing source).
2226 // Keep private files where they are.
2227 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2228 $hash = $hashes[$name];
2229 $key = $hash . $dotExt;
2230 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2231 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2235 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2236 // We acquire this lock by running the inserts now, before the file operations.
2238 // This potentially has poor lock contention characteristics -- an alternative
2239 // scheme would be to insert stub filearchive entries with no fa_name and commit
2240 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2241 $this->doDBInserts();
2243 // Removes non-existent file from the batch, so we don't get errors.
2244 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2246 // Execute the file deletion batch
2247 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2249 if ( !$status->isGood() ) {
2250 $this->status
->merge( $status );
2253 if ( !$this->status
->isOK() ) {
2254 // Critical file deletion error
2255 // Roll back inserts, release lock and abort
2256 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2257 $this->file
->unlockAndRollback();
2258 wfProfileOut( __METHOD__
);
2260 return $this->status
;
2263 // Delete image/oldimage rows
2264 $this->doDBDeletes();
2266 // Commit and return
2267 $this->file
->unlock();
2268 wfProfileOut( __METHOD__
);
2270 return $this->status
;
2274 * Removes non-existent files from a deletion batch.
2275 * @param array $batch
2278 function removeNonexistentFiles( $batch ) {
2279 $files = $newBatch = array();
2281 foreach ( $batch as $batchItem ) {
2282 list( $src, ) = $batchItem;
2283 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2286 $result = $this->file
->repo
->fileExistsBatch( $files );
2288 foreach ( $batch as $batchItem ) {
2289 if ( $result[$batchItem[0]] ) {
2290 $newBatch[] = $batchItem;
2298 # ------------------------------------------------------------------------------
2301 * Helper class for file undeletion
2302 * @ingroup FileAbstraction
2304 class LocalFileRestoreBatch
{
2305 /** @var LocalFile */
2308 /** @var array List of file IDs to restore */
2309 private $cleanupBatch;
2311 /** @var array List of file IDs to restore */
2314 /** @var bool Add all revisions of the file */
2317 /** @var bool Wether to remove all settings for suppressed fields */
2318 private $unsuppress = false;
2322 * @param bool $unsuppress
2324 function __construct( File
$file, $unsuppress = false ) {
2325 $this->file
= $file;
2326 $this->cleanupBatch
= $this->ids
= array();
2327 $this->ids
= array();
2328 $this->unsuppress
= $unsuppress;
2334 function addId( $fa_id ) {
2335 $this->ids
[] = $fa_id;
2339 * Add a whole lot of files by ID
2341 function addIds( $ids ) {
2342 $this->ids
= array_merge( $this->ids
, $ids );
2346 * Add all revisions of the file
2353 * Run the transaction, except the cleanup batch.
2354 * The cleanup batch should be run in a separate transaction, because it locks different
2355 * rows and there's no need to keep the image row locked while it's acquiring those locks
2356 * The caller may have its own transaction open.
2357 * So we save the batch and let the caller call cleanup()
2358 * @return FileRepoStatus
2360 function execute() {
2363 if ( !$this->all
&& !$this->ids
) {
2365 return $this->file
->repo
->newGood();
2368 $exists = $this->file
->lock();
2369 $dbw = $this->file
->repo
->getMasterDB();
2370 $status = $this->file
->repo
->newGood();
2372 // Fetch all or selected archived revisions for the file,
2373 // sorted from the most recent to the oldest.
2374 $conditions = array( 'fa_name' => $this->file
->getName() );
2376 if ( !$this->all
) {
2377 $conditions['fa_id'] = $this->ids
;
2380 $result = $dbw->select(
2382 ArchivedFile
::selectFields(),
2385 array( 'ORDER BY' => 'fa_timestamp DESC' )
2388 $idsPresent = array();
2389 $storeBatch = array();
2390 $insertBatch = array();
2391 $insertCurrent = false;
2392 $deleteIds = array();
2394 $archiveNames = array();
2396 foreach ( $result as $row ) {
2397 $idsPresent[] = $row->fa_id
;
2399 if ( $row->fa_name
!= $this->file
->getName() ) {
2400 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2401 $status->failCount++
;
2405 if ( $row->fa_storage_key
== '' ) {
2406 // Revision was missing pre-deletion
2407 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2408 $status->failCount++
;
2412 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2413 $row->fa_storage_key
;
2414 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2416 if ( isset( $row->fa_sha1
) ) {
2417 $sha1 = $row->fa_sha1
;
2419 // old row, populate from key
2420 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2424 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2425 $sha1 = substr( $sha1, 1 );
2428 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2429 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2430 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2431 ||
is_null( $row->fa_metadata
)
2433 // Refresh our metadata
2434 // Required for a new current revision; nice for older ones too. :)
2435 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2438 'minor_mime' => $row->fa_minor_mime
,
2439 'major_mime' => $row->fa_major_mime
,
2440 'media_type' => $row->fa_media_type
,
2441 'metadata' => $row->fa_metadata
2445 if ( $first && !$exists ) {
2446 // This revision will be published as the new current version
2447 $destRel = $this->file
->getRel();
2448 $insertCurrent = array(
2449 'img_name' => $row->fa_name
,
2450 'img_size' => $row->fa_size
,
2451 'img_width' => $row->fa_width
,
2452 'img_height' => $row->fa_height
,
2453 'img_metadata' => $props['metadata'],
2454 'img_bits' => $row->fa_bits
,
2455 'img_media_type' => $props['media_type'],
2456 'img_major_mime' => $props['major_mime'],
2457 'img_minor_mime' => $props['minor_mime'],
2458 'img_description' => $row->fa_description
,
2459 'img_user' => $row->fa_user
,
2460 'img_user_text' => $row->fa_user_text
,
2461 'img_timestamp' => $row->fa_timestamp
,
2465 // The live (current) version cannot be hidden!
2466 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2467 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2468 $this->cleanupBatch
[] = $row->fa_storage_key
;
2471 $archiveName = $row->fa_archive_name
;
2473 if ( $archiveName == '' ) {
2474 // This was originally a current version; we
2475 // have to devise a new archive name for it.
2476 // Format is <timestamp of archiving>!<name>
2477 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2480 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2482 } while ( isset( $archiveNames[$archiveName] ) );
2485 $archiveNames[$archiveName] = true;
2486 $destRel = $this->file
->getArchiveRel( $archiveName );
2487 $insertBatch[] = array(
2488 'oi_name' => $row->fa_name
,
2489 'oi_archive_name' => $archiveName,
2490 'oi_size' => $row->fa_size
,
2491 'oi_width' => $row->fa_width
,
2492 'oi_height' => $row->fa_height
,
2493 'oi_bits' => $row->fa_bits
,
2494 'oi_description' => $row->fa_description
,
2495 'oi_user' => $row->fa_user
,
2496 'oi_user_text' => $row->fa_user_text
,
2497 'oi_timestamp' => $row->fa_timestamp
,
2498 'oi_metadata' => $props['metadata'],
2499 'oi_media_type' => $props['media_type'],
2500 'oi_major_mime' => $props['major_mime'],
2501 'oi_minor_mime' => $props['minor_mime'],
2502 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2503 'oi_sha1' => $sha1 );
2506 $deleteIds[] = $row->fa_id
;
2508 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2509 // private files can stay where they are
2510 $status->successCount++
;
2512 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2513 $this->cleanupBatch
[] = $row->fa_storage_key
;
2521 // Add a warning to the status object for missing IDs
2522 $missingIds = array_diff( $this->ids
, $idsPresent );
2524 foreach ( $missingIds as $id ) {
2525 $status->error( 'undelete-missing-filearchive', $id );
2528 // Remove missing files from batch, so we don't get errors when undeleting them
2529 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2531 // Run the store batch
2532 // Use the OVERWRITE_SAME flag to smooth over a common error
2533 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2534 $status->merge( $storeStatus );
2536 if ( !$status->isGood() ) {
2537 // Even if some files could be copied, fail entirely as that is the
2538 // easiest thing to do without data loss
2539 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2540 $status->ok
= false;
2541 $this->file
->unlock();
2546 // Run the DB updates
2547 // Because we have locked the image row, key conflicts should be rare.
2548 // If they do occur, we can roll back the transaction at this time with
2549 // no data loss, but leaving unregistered files scattered throughout the
2551 // This is not ideal, which is why it's important to lock the image row.
2552 if ( $insertCurrent ) {
2553 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2556 if ( $insertBatch ) {
2557 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2561 $dbw->delete( 'filearchive',
2562 array( 'fa_id' => $deleteIds ),
2566 // If store batch is empty (all files are missing), deletion is to be considered successful
2567 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2569 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2571 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2573 $this->file
->purgeEverything();
2575 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2576 $this->file
->purgeDescription();
2577 $this->file
->purgeHistory();
2581 $this->file
->unlock();
2587 * Removes non-existent files from a store batch.
2588 * @param array $triplets
2591 function removeNonexistentFiles( $triplets ) {
2592 $files = $filteredTriplets = array();
2593 foreach ( $triplets as $file ) {
2594 $files[$file[0]] = $file[0];
2597 $result = $this->file
->repo
->fileExistsBatch( $files );
2599 foreach ( $triplets as $file ) {
2600 if ( $result[$file[0]] ) {
2601 $filteredTriplets[] = $file;
2605 return $filteredTriplets;
2609 * Removes non-existent files from a cleanup batch.
2610 * @param array $batch
2613 function removeNonexistentFromCleanup( $batch ) {
2614 $files = $newBatch = array();
2615 $repo = $this->file
->repo
;
2617 foreach ( $batch as $file ) {
2618 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2619 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2622 $result = $repo->fileExistsBatch( $files );
2624 foreach ( $batch as $file ) {
2625 if ( $result[$file] ) {
2626 $newBatch[] = $file;
2634 * Delete unused files in the deleted zone.
2635 * This should be called from outside the transaction in which execute() was called.
2636 * @return FileRepoStatus
2638 function cleanup() {
2639 if ( !$this->cleanupBatch
) {
2640 return $this->file
->repo
->newGood();
2643 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2645 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2651 * Cleanup a failed batch. The batch was only partially successful, so
2652 * rollback by removing all items that were succesfully copied.
2654 * @param Status $storeStatus
2655 * @param array $storeBatch
2657 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2658 $cleanupBatch = array();
2660 foreach ( $storeStatus->success
as $i => $success ) {
2661 // Check if this item of the batch was successfully copied
2663 // Item was successfully copied and needs to be removed again
2664 // Extract ($dstZone, $dstRel) from the batch
2665 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2668 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2672 # ------------------------------------------------------------------------------
2675 * Helper class for file movement
2676 * @ingroup FileAbstraction
2678 class LocalFileMoveBatch
{
2679 /** @var LocalFile */
2689 protected $oldCount;
2693 /** @var DatabaseBase */
2698 * @param Title $target
2700 function __construct( File
$file, Title
$target ) {
2701 $this->file
= $file;
2702 $this->target
= $target;
2703 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2704 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2705 $this->oldName
= $this->file
->getName();
2706 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2707 $this->oldRel
= $this->oldHash
. $this->oldName
;
2708 $this->newRel
= $this->newHash
. $this->newName
;
2709 $this->db
= $file->getRepo()->getMasterDb();
2713 * Add the current image to the batch
2715 function addCurrent() {
2716 $this->cur
= array( $this->oldRel
, $this->newRel
);
2720 * Add the old versions of the image to the batch
2721 * @return array List of archive names from old versions
2723 function addOlds() {
2724 $archiveBase = 'archive';
2725 $this->olds
= array();
2726 $this->oldCount
= 0;
2727 $archiveNames = array();
2729 $result = $this->db
->select( 'oldimage',
2730 array( 'oi_archive_name', 'oi_deleted' ),
2731 array( 'oi_name' => $this->oldName
),
2735 foreach ( $result as $row ) {
2736 $archiveNames[] = $row->oi_archive_name
;
2737 $oldName = $row->oi_archive_name
;
2738 $bits = explode( '!', $oldName, 2 );
2740 if ( count( $bits ) != 2 ) {
2741 wfDebug( "Old file name missing !: '$oldName' \n" );
2745 list( $timestamp, $filename ) = $bits;
2747 if ( $this->oldName
!= $filename ) {
2748 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2754 // Do we want to add those to oldCount?
2755 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2759 $this->olds
[] = array(
2760 "{$archiveBase}/{$this->oldHash}{$oldName}",
2761 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2765 return $archiveNames;
2770 * @return FileRepoStatus
2772 function execute() {
2773 $repo = $this->file
->repo
;
2774 $status = $repo->newGood();
2776 $triplets = $this->getMoveTriplets();
2777 $triplets = $this->removeNonexistentFiles( $triplets );
2778 $destFile = wfLocalFile( $this->target
);
2780 $this->file
->lock(); // begin
2781 $destFile->lock(); // quickly fail if destination is not available
2782 // Rename the file versions metadata in the DB.
2783 // This implicitly locks the destination file, which avoids race conditions.
2784 // If we moved the files from A -> C before DB updates, another process could
2785 // move files from B -> C at this point, causing storeBatch() to fail and thus
2786 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2787 $statusDb = $this->doDBUpdates();
2788 if ( !$statusDb->isGood() ) {
2789 $this->file
->unlockAndRollback();
2790 $statusDb->ok
= false;
2794 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2795 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2797 // Copy the files into their new location.
2798 // If a prior process fataled copying or cleaning up files we tolerate any
2799 // of the existing files if they are identical to the ones being stored.
2800 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2801 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2802 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2803 if ( !$statusMove->isGood() ) {
2804 // Delete any files copied over (while the destination is still locked)
2805 $this->cleanupTarget( $triplets );
2806 $this->file
->unlockAndRollback(); // unlocks the destination
2807 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2808 $statusMove->ok
= false;
2812 $destFile->unlock();
2813 $this->file
->unlock(); // done
2815 // Everything went ok, remove the source files
2816 $this->cleanupSource( $triplets );
2818 $status->merge( $statusDb );
2819 $status->merge( $statusMove );
2825 * Do the database updates and return a new FileRepoStatus indicating how
2826 * many rows where updated.
2828 * @return FileRepoStatus
2830 function doDBUpdates() {
2831 $repo = $this->file
->repo
;
2832 $status = $repo->newGood();
2835 // Update current image
2838 array( 'img_name' => $this->newName
),
2839 array( 'img_name' => $this->oldName
),
2843 if ( $dbw->affectedRows() ) {
2844 $status->successCount++
;
2846 $status->failCount++
;
2847 $status->fatal( 'imageinvalidfilename' );
2852 // Update old images
2856 'oi_name' => $this->newName
,
2857 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2858 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2860 array( 'oi_name' => $this->oldName
),
2864 $affected = $dbw->affectedRows();
2865 $total = $this->oldCount
;
2866 $status->successCount +
= $affected;
2867 // Bug 34934: $total is based on files that actually exist.
2868 // There may be more DB rows than such files, in which case $affected
2869 // can be greater than $total. We use max() to avoid negatives here.
2870 $status->failCount +
= max( 0, $total - $affected );
2871 if ( $status->failCount
) {
2872 $status->error( 'imageinvalidfilename' );
2879 * Generate triplets for FileRepo::storeBatch().
2882 function getMoveTriplets() {
2883 $moves = array_merge( array( $this->cur
), $this->olds
);
2884 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2886 foreach ( $moves as $move ) {
2887 // $move: (oldRelativePath, newRelativePath)
2888 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2889 $triplets[] = array( $srcUrl, 'public', $move[1] );
2892 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2900 * Removes non-existent files from move batch.
2901 * @param array $triplets
2904 function removeNonexistentFiles( $triplets ) {
2907 foreach ( $triplets as $file ) {
2908 $files[$file[0]] = $file[0];
2911 $result = $this->file
->repo
->fileExistsBatch( $files );
2912 $filteredTriplets = array();
2914 foreach ( $triplets as $file ) {
2915 if ( $result[$file[0]] ) {
2916 $filteredTriplets[] = $file;
2918 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2922 return $filteredTriplets;
2926 * Cleanup a partially moved array of triplets by deleting the target
2927 * files. Called if something went wrong half way.
2929 function cleanupTarget( $triplets ) {
2930 // Create dest pairs from the triplets
2932 foreach ( $triplets as $triplet ) {
2933 // $triplet: (old source virtual URL, dst zone, dest rel)
2934 $pairs[] = array( $triplet[1], $triplet[2] );
2937 $this->file
->repo
->cleanupBatch( $pairs );
2941 * Cleanup a fully moved array of triplets by deleting the source files.
2942 * Called at the end of the move process if everything else went ok.
2944 function cleanupSource( $triplets ) {
2945 // Create source file names from the triplets
2947 foreach ( $triplets as $triplet ) {
2948 $files[] = $triplet[0];
2951 $this->file
->repo
->cleanupBatch( $files );