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 $this->dataLoaded
= false;
251 $this->extraDataLoaded
= false;
252 $key = $this->getCacheKey();
259 $cachedValues = $wgMemc->get( $key );
261 // Check if the key existed and belongs to this version of MediaWiki
262 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
263 wfDebug( "Pulling file metadata from cache key $key\n" );
264 $this->fileExists
= $cachedValues['fileExists'];
265 if ( $this->fileExists
) {
266 $this->setProps( $cachedValues );
268 $this->dataLoaded
= true;
269 $this->extraDataLoaded
= true;
270 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
271 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
275 if ( $this->dataLoaded
) {
276 wfIncrStats( 'image_cache_hit' );
278 wfIncrStats( 'image_cache_miss' );
282 return $this->dataLoaded
;
286 * Save the file metadata to memcached
288 function saveToCache() {
292 $key = $this->getCacheKey();
298 $fields = $this->getCacheFields( '' );
299 $cache = array( 'version' => MW_FILE_VERSION
);
300 $cache['fileExists'] = $this->fileExists
;
302 if ( $this->fileExists
) {
303 foreach ( $fields as $field ) {
304 $cache[$field] = $this->$field;
308 // Strip off excessive entries from the subset of fields that can become large.
309 // If the cache value gets to large it will not fit in memcached and nothing will
310 // get cached at all, causing master queries for any file access.
311 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
312 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
313 unset( $cache[$field] ); // don't let the value get too big
317 // Cache presence for 1 week and negatives for 1 day
318 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
322 * Load metadata from the file itself
324 function loadFromFile() {
325 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
326 $this->setProps( $props );
330 * @param string $prefix
333 function getCacheFields( $prefix = 'img_' ) {
334 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
335 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
336 'user_text', 'description' );
337 static $results = array();
339 if ( $prefix == '' ) {
343 if ( !isset( $results[$prefix] ) ) {
344 $prefixedFields = array();
345 foreach ( $fields as $field ) {
346 $prefixedFields[] = $prefix . $field;
348 $results[$prefix] = $prefixedFields;
351 return $results[$prefix];
355 * @param string $prefix
358 function getLazyCacheFields( $prefix = 'img_' ) {
359 static $fields = array( 'metadata' );
360 static $results = array();
362 if ( $prefix == '' ) {
366 if ( !isset( $results[$prefix] ) ) {
367 $prefixedFields = array();
368 foreach ( $fields as $field ) {
369 $prefixedFields[] = $prefix . $field;
371 $results[$prefix] = $prefixedFields;
374 return $results[$prefix];
378 * Load file metadata from the DB
381 function loadFromDB( $flags = 0 ) {
382 $fname = get_class( $this ) . '::' . __FUNCTION__
;
384 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
385 $this->dataLoaded
= true;
386 $this->extraDataLoaded
= true;
388 $dbr = ( $flags & self
::LOAD_VIA_SLAVE
)
389 ?
$this->repo
->getSlaveDB()
390 : $this->repo
->getMasterDB();
392 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
393 array( 'img_name' => $this->getName() ), $fname );
396 $this->loadFromRow( $row );
398 $this->fileExists
= false;
403 * Load lazy file metadata from the DB.
404 * This covers fields that are sometimes not cached.
406 protected function loadExtraFromDB() {
407 $fname = get_class( $this ) . '::' . __FUNCTION__
;
409 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
410 $this->extraDataLoaded
= true;
412 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getSlaveDB(), $fname );
414 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
418 foreach ( $fieldMap as $name => $value ) {
419 $this->$name = $value;
422 throw new MWException( "Could not find data for image '{$this->getName()}'." );
427 * @param DatabaseBase $dbr
428 * @param string $fname
431 private function loadFieldsWithTimestamp( $dbr, $fname ) {
434 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
435 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
438 $fieldMap = $this->unprefixRow( $row, 'img_' );
440 # File may have been uploaded over in the meantime; check the old versions
441 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
442 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
445 $fieldMap = $this->unprefixRow( $row, 'oi_' );
453 * @param array $row Row
454 * @param string $prefix
455 * @throws MWException
458 protected function unprefixRow( $row, $prefix = 'img_' ) {
459 $array = (array)$row;
460 $prefixLength = strlen( $prefix );
462 // Sanity check prefix once
463 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
464 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
468 foreach ( $array as $name => $value ) {
469 $decoded[substr( $name, $prefixLength )] = $value;
476 * Decode a row from the database (either object or array) to an array
477 * with timestamps and MIME types decoded, and the field prefix removed.
479 * @param string $prefix
480 * @throws MWException
483 function decodeRow( $row, $prefix = 'img_' ) {
484 $decoded = $this->unprefixRow( $row, $prefix );
486 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
488 $decoded['metadata'] = $this->repo
->getSlaveDB()->decodeBlob( $decoded['metadata'] );
490 if ( empty( $decoded['major_mime'] ) ) {
491 $decoded['mime'] = 'unknown/unknown';
493 if ( !$decoded['minor_mime'] ) {
494 $decoded['minor_mime'] = 'unknown';
496 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
499 # Trim zero padding from char/binary field
500 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
506 * Load file metadata from a DB result row
509 * @param string $prefix
511 function loadFromRow( $row, $prefix = 'img_' ) {
512 $this->dataLoaded
= true;
513 $this->extraDataLoaded
= true;
515 $array = $this->decodeRow( $row, $prefix );
517 foreach ( $array as $name => $value ) {
518 $this->$name = $value;
521 $this->fileExists
= true;
522 $this->maybeUpgradeRow();
526 * Load file metadata from cache or DB, unless already loaded
529 function load( $flags = 0 ) {
530 if ( !$this->dataLoaded
) {
531 if ( !$this->loadFromCache() ) {
532 $this->loadFromDB( $this->isVolatile() ?
0 : self
::LOAD_VIA_SLAVE
);
533 $this->saveToCache();
535 $this->dataLoaded
= true;
537 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
538 $this->loadExtraFromDB();
543 * Upgrade a row if it needs it
545 function maybeUpgradeRow() {
546 global $wgUpdateCompatibleMetadata;
547 if ( wfReadOnly() ) {
551 if ( is_null( $this->media_type
) ||
552 $this->mime
== 'image/svg'
555 $this->upgraded
= true;
557 $handler = $this->getHandler();
559 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
560 if ( $validity === MediaHandler
::METADATA_BAD
561 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
564 $this->upgraded
= true;
570 function getUpgraded() {
571 return $this->upgraded
;
575 * Fix assorted version-related problems with the image row by reloading it from the file
577 function upgradeRow() {
579 $this->lock(); // begin
581 $this->loadFromFile();
583 # Don't destroy file info of missing files
584 if ( !$this->fileExists
) {
586 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
591 $dbw = $this->repo
->getMasterDB();
592 list( $major, $minor ) = self
::splitMime( $this->mime
);
594 if ( wfReadOnly() ) {
599 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
601 $dbw->update( 'image',
603 'img_size' => $this->size
, // sanity
604 'img_width' => $this->width
,
605 'img_height' => $this->height
,
606 'img_bits' => $this->bits
,
607 'img_media_type' => $this->media_type
,
608 'img_major_mime' => $major,
609 'img_minor_mime' => $minor,
610 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
611 'img_sha1' => $this->sha1
,
613 array( 'img_name' => $this->getName() ),
617 $this->saveToCache();
619 $this->unlock(); // done
624 * Set properties in this object to be equal to those given in the
625 * associative array $info. Only cacheable fields can be set.
626 * All fields *must* be set in $info except for getLazyCacheFields().
628 * If 'mime' is given, it will be split into major_mime/minor_mime.
629 * If major_mime/minor_mime are given, $this->mime will also be set.
633 function setProps( $info ) {
634 $this->dataLoaded
= true;
635 $fields = $this->getCacheFields( '' );
636 $fields[] = 'fileExists';
638 foreach ( $fields as $field ) {
639 if ( isset( $info[$field] ) ) {
640 $this->$field = $info[$field];
644 // Fix up mime fields
645 if ( isset( $info['major_mime'] ) ) {
646 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
647 } elseif ( isset( $info['mime'] ) ) {
648 $this->mime
= $info['mime'];
649 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
653 /** splitMime inherited */
654 /** getName inherited */
655 /** getTitle inherited */
656 /** getURL inherited */
657 /** getViewURL inherited */
658 /** getPath inherited */
659 /** isVisible inherited */
664 function isMissing() {
665 if ( $this->missing
=== null ) {
666 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
667 $this->missing
= !$fileExists;
670 return $this->missing
;
674 * Return the width of the image
679 public function getWidth( $page = 1 ) {
682 if ( $this->isMultipage() ) {
683 $handler = $this->getHandler();
687 $dim = $handler->getPageDimensions( $this, $page );
689 return $dim['width'];
691 // For non-paged media, the false goes through an
692 // intval, turning failure into 0, so do same here.
701 * Return the height of the image
706 public function getHeight( $page = 1 ) {
709 if ( $this->isMultipage() ) {
710 $handler = $this->getHandler();
714 $dim = $handler->getPageDimensions( $this, $page );
716 return $dim['height'];
718 // For non-paged media, the false goes through an
719 // intval, turning failure into 0, so do same here.
723 return $this->height
;
728 * Returns ID or name of user who uploaded the file
730 * @param string $type 'text' or 'id'
733 function getUser( $type = 'text' ) {
736 if ( $type == 'text' ) {
737 return $this->user_text
;
738 } elseif ( $type == 'id' ) {
744 * Get handler-specific metadata
747 function getMetadata() {
748 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
749 return $this->metadata
;
755 function getBitDepth() {
762 * Returns the size of the image file, in bytes
765 public function getSize() {
772 * Returns the MIME type of the file.
775 function getMimeType() {
782 * Returns the type of the media in the file.
783 * Use the value returned by this function with the MEDIATYPE_xxx constants.
786 function getMediaType() {
789 return $this->media_type
;
792 /** canRender inherited */
793 /** mustRender inherited */
794 /** allowInlineDisplay inherited */
795 /** isSafeFile inherited */
796 /** isTrustedFile inherited */
799 * Returns true if the file exists on disk.
800 * @return bool Whether file exist on disk.
802 public function exists() {
805 return $this->fileExists
;
808 /** getTransformScript inherited */
809 /** getUnscaledThumb inherited */
810 /** thumbName inherited */
811 /** createThumb inherited */
812 /** transform inherited */
814 /** getHandler inherited */
815 /** iconThumb inherited */
816 /** getLastError inherited */
819 * Get all thumbnail names previously generated for this file
820 * @param string|bool $archiveName Name of an archive file, default false
821 * @return array First element is the base dir, then files in that base dir.
823 function getThumbnails( $archiveName = false ) {
824 if ( $archiveName ) {
825 $dir = $this->getArchiveThumbPath( $archiveName );
827 $dir = $this->getThumbPath();
830 $backend = $this->repo
->getBackend();
831 $files = array( $dir );
833 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
834 foreach ( $iterator as $file ) {
837 } catch ( FileBackendError
$e ) {
838 } // suppress (bug 54674)
844 * Refresh metadata in memcached, but don't touch thumbnails or squid
846 function purgeMetadataCache() {
848 $this->saveToCache();
849 $this->purgeHistory();
853 * Purge the shared history (OldLocalFile) cache.
855 * @note This used to purge old thumbnails as well.
857 function purgeHistory() {
860 $hashedName = md5( $this->getName() );
861 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
864 $wgMemc->delete( $oldKey );
869 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
871 * @param array $options An array potentially with the key forThumbRefresh.
873 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
875 function purgeCache( $options = array() ) {
876 // Refresh metadata cache
877 $this->purgeMetadataCache();
880 $this->purgeThumbnails( $options );
882 // Purge squid cache for this file
883 SquidUpdate
::purge( array( $this->getURL() ) );
887 * Delete cached transformed files for an archived version only.
888 * @param string $archiveName Name of the archived file
890 function purgeOldThumbnails( $archiveName ) {
893 // Get a list of old thumbnails and URLs
894 $files = $this->getThumbnails( $archiveName );
896 // Purge any custom thumbnail caches
897 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
899 $dir = array_shift( $files );
900 $this->purgeThumbList( $dir, $files );
905 foreach ( $files as $file ) {
906 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
908 SquidUpdate
::purge( $urls );
914 * Delete cached transformed files for the current version only.
915 * @param array $options
917 function purgeThumbnails( $options = array() ) {
921 $files = $this->getThumbnails();
922 // Always purge all files from squid regardless of handler filters
925 foreach ( $files as $file ) {
926 $urls[] = $this->getThumbUrl( $file );
928 array_shift( $urls ); // don't purge directory
931 // Give media handler a chance to filter the file purge list
932 if ( !empty( $options['forThumbRefresh'] ) ) {
933 $handler = $this->getHandler();
935 $handler->filterThumbnailPurgeList( $files, $options );
939 // Purge any custom thumbnail caches
940 Hooks
::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
942 $dir = array_shift( $files );
943 $this->purgeThumbList( $dir, $files );
947 SquidUpdate
::purge( $urls );
953 * Delete a list of thumbnails visible at urls
954 * @param string $dir Base dir of the files.
955 * @param array $files Array of strings: relative filenames (to $dir)
957 protected function purgeThumbList( $dir, $files ) {
958 $fileListDebug = strtr(
959 var_export( $files, true ),
962 wfDebug( __METHOD__
. ": $fileListDebug\n" );
964 $purgeList = array();
965 foreach ( $files as $file ) {
966 # Check that the base file name is part of the thumb name
967 # This is a basic sanity check to avoid erasing unrelated directories
968 if ( strpos( $file, $this->getName() ) !== false
969 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
971 $purgeList[] = "{$dir}/{$file}";
975 # Delete the thumbnails
976 $this->repo
->quickPurgeBatch( $purgeList );
977 # Clear out the thumbnail directory if empty
978 $this->repo
->quickCleanDir( $dir );
981 /** purgeDescription inherited */
982 /** purgeEverything inherited */
985 * @param int $limit Optional: Limit to number of results
986 * @param int $start Optional: Timestamp, start from
987 * @param int $end Optional: Timestamp, end at
991 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
992 $dbr = $this->repo
->getSlaveDB();
993 $tables = array( 'oldimage' );
994 $fields = OldLocalFile
::selectFields();
995 $conds = $opts = $join_conds = array();
996 $eq = $inc ?
'=' : '';
997 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1000 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1004 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1008 $opts['LIMIT'] = $limit;
1011 // Search backwards for time > x queries
1012 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1013 $opts['ORDER BY'] = "oi_timestamp $order";
1014 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1016 Hooks
::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1017 &$conds, &$opts, &$join_conds ) );
1019 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1022 foreach ( $res as $row ) {
1023 $r[] = $this->repo
->newFileFromRow( $row );
1026 if ( $order == 'ASC' ) {
1027 $r = array_reverse( $r ); // make sure it ends up descending
1034 * Returns the history of this file, line by line.
1035 * starts with current version, then old versions.
1036 * uses $this->historyLine to check which line to return:
1037 * 0 return line for current version
1038 * 1 query for old versions, return first one
1039 * 2, ... return next old version from above query
1042 public function nextHistoryLine() {
1043 # Polymorphic function name to distinguish foreign and local fetches
1044 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1046 $dbr = $this->repo
->getSlaveDB();
1048 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1049 $this->historyRes
= $dbr->select( 'image',
1052 "'' AS oi_archive_name",
1056 array( 'img_name' => $this->title
->getDBkey() ),
1060 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1061 $this->historyRes
= null;
1065 } elseif ( $this->historyLine
== 1 ) {
1066 $this->historyRes
= $dbr->select( 'oldimage', '*',
1067 array( 'oi_name' => $this->title
->getDBkey() ),
1069 array( 'ORDER BY' => 'oi_timestamp DESC' )
1072 $this->historyLine++
;
1074 return $dbr->fetchObject( $this->historyRes
);
1078 * Reset the history pointer to the first element of the history
1080 public function resetHistory() {
1081 $this->historyLine
= 0;
1083 if ( !is_null( $this->historyRes
) ) {
1084 $this->historyRes
= null;
1088 /** getHashPath inherited */
1089 /** getRel inherited */
1090 /** getUrlRel inherited */
1091 /** getArchiveRel inherited */
1092 /** getArchivePath inherited */
1093 /** getThumbPath inherited */
1094 /** getArchiveUrl inherited */
1095 /** getThumbUrl inherited */
1096 /** getArchiveVirtualUrl inherited */
1097 /** getThumbVirtualUrl inherited */
1098 /** isHashed inherited */
1101 * Upload a file and record it in the DB
1102 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1103 * @param string $comment Upload description
1104 * @param string $pageText Text to use for the new description page,
1105 * if a new description page is created
1106 * @param int|bool $flags Flags for publish()
1107 * @param array|bool $props File properties, if known. This can be used to
1108 * reduce the upload time when uploading virtual URLs for which the file
1109 * info is already known
1110 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1112 * @param User|null $user User object or null to use $wgUser
1114 * @return FileRepoStatus On success, the value member contains the
1115 * archive name, or an empty string if it was a new file.
1117 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1118 $timestamp = false, $user = null
1122 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1123 return $this->readOnlyFatalStatus();
1127 if ( $this->repo
->isVirtualUrl( $srcPath )
1128 || FileBackend
::isStoragePath( $srcPath )
1130 $props = $this->repo
->getFileProps( $srcPath );
1132 $props = FSFile
::getPropsFromPath( $srcPath );
1137 $handler = MediaHandler
::getHandler( $props['mime'] );
1139 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1141 $options['headers'] = array();
1144 // Trim spaces on user supplied text
1145 $comment = trim( $comment );
1147 // Truncate nicely or the DB will do it for us
1148 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1149 $comment = $wgContLang->truncate( $comment, 255 );
1150 $this->lock(); // begin
1151 $status = $this->publish( $srcPath, $flags, $options );
1153 if ( $status->successCount
>= 2 ) {
1154 // There will be a copy+(one of move,copy,store).
1155 // The first succeeding does not commit us to updating the DB
1156 // since it simply copied the current version to a timestamped file name.
1157 // It is only *preferable* to avoid leaving such files orphaned.
1158 // Once the second operation goes through, then the current version was
1159 // updated and we must therefore update the DB too.
1160 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1161 $status->fatal( 'filenotfound', $srcPath );
1165 $this->unlock(); // done
1171 * Record a file upload in the upload log and the image table
1172 * @param string $oldver
1173 * @param string $desc
1174 * @param string $license
1175 * @param string $copyStatus
1176 * @param string $source
1177 * @param bool $watch
1178 * @param string|bool $timestamp
1179 * @param User|null $user User object or null to use $wgUser
1182 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1183 $watch = false, $timestamp = false, User
$user = null ) {
1189 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1191 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1196 $user->addWatch( $this->getTitle() );
1203 * Record a file upload in the upload log and the image table
1204 * @param string $oldver
1205 * @param string $comment
1206 * @param string $pageText
1207 * @param bool|array $props
1208 * @param string|bool $timestamp
1209 * @param null|User $user
1212 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1216 if ( is_null( $user ) ) {
1221 $dbw = $this->repo
->getMasterDB();
1222 $dbw->begin( __METHOD__
);
1225 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1228 # Imports or such might force a certain timestamp; otherwise we generate
1229 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1230 if ( $timestamp === false ) {
1231 $timestamp = $dbw->timestamp();
1232 $allowTimeKludge = true;
1234 $allowTimeKludge = false;
1237 $props['description'] = $comment;
1238 $props['user'] = $user->getId();
1239 $props['user_text'] = $user->getName();
1240 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1241 $this->setProps( $props );
1243 # Fail now if the file isn't there
1244 if ( !$this->fileExists
) {
1245 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1246 $dbw->rollback( __METHOD__
);
1253 # Test to see if the row exists using INSERT IGNORE
1254 # This avoids race conditions by locking the row until the commit, and also
1255 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1256 $dbw->insert( 'image',
1258 'img_name' => $this->getName(),
1259 'img_size' => $this->size
,
1260 'img_width' => intval( $this->width
),
1261 'img_height' => intval( $this->height
),
1262 'img_bits' => $this->bits
,
1263 'img_media_type' => $this->media_type
,
1264 'img_major_mime' => $this->major_mime
,
1265 'img_minor_mime' => $this->minor_mime
,
1266 'img_timestamp' => $timestamp,
1267 'img_description' => $comment,
1268 'img_user' => $user->getId(),
1269 'img_user_text' => $user->getName(),
1270 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1271 'img_sha1' => $this->sha1
1276 if ( $dbw->affectedRows() == 0 ) {
1277 if ( $allowTimeKludge ) {
1278 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1279 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1280 array( 'img_name' => $this->getName() ),
1282 array( 'LOCK IN SHARE MODE' ) );
1283 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1284 # Avoid a timestamp that is not newer than the last version
1285 # TODO: the image/oldimage tables should be like page/revision with an ID field
1286 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1287 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1288 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1289 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1293 # (bug 34993) Note: $oldver can be empty here, if the previous
1294 # version of the file was broken. Allow registration of the new
1295 # version to continue anyway, because that's better than having
1296 # an image that's not fixable by user operations.
1299 # Collision, this is an update of a file
1300 # Insert previous contents into oldimage
1301 $dbw->insertSelect( 'oldimage', 'image',
1303 'oi_name' => 'img_name',
1304 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1305 'oi_size' => 'img_size',
1306 'oi_width' => 'img_width',
1307 'oi_height' => 'img_height',
1308 'oi_bits' => 'img_bits',
1309 'oi_timestamp' => 'img_timestamp',
1310 'oi_description' => 'img_description',
1311 'oi_user' => 'img_user',
1312 'oi_user_text' => 'img_user_text',
1313 'oi_metadata' => 'img_metadata',
1314 'oi_media_type' => 'img_media_type',
1315 'oi_major_mime' => 'img_major_mime',
1316 'oi_minor_mime' => 'img_minor_mime',
1317 'oi_sha1' => 'img_sha1'
1319 array( 'img_name' => $this->getName() ),
1323 # Update the current image row
1324 $dbw->update( 'image',
1326 'img_size' => $this->size
,
1327 'img_width' => intval( $this->width
),
1328 'img_height' => intval( $this->height
),
1329 'img_bits' => $this->bits
,
1330 'img_media_type' => $this->media_type
,
1331 'img_major_mime' => $this->major_mime
,
1332 'img_minor_mime' => $this->minor_mime
,
1333 'img_timestamp' => $timestamp,
1334 'img_description' => $comment,
1335 'img_user' => $user->getId(),
1336 'img_user_text' => $user->getName(),
1337 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1338 'img_sha1' => $this->sha1
1340 array( 'img_name' => $this->getName() ),
1344 # This is a new file, so update the image count
1345 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1348 $descTitle = $this->getTitle();
1349 $wikiPage = new WikiFilePage( $descTitle );
1350 $wikiPage->setFile( $this );
1353 $action = $reupload ?
'overwrite' : 'upload';
1355 $logEntry = new ManualLogEntry( 'upload', $action );
1356 $logEntry->setPerformer( $user );
1357 $logEntry->setComment( $comment );
1358 $logEntry->setTarget( $descTitle );
1360 // Allow people using the api to associate log entries with the upload.
1361 // Log has a timestamp, but sometimes different from upload timestamp.
1362 $logEntry->setParameters(
1364 'img_sha1' => $this->sha1
,
1365 'img_timestamp' => $timestamp,
1368 // Note we keep $logId around since during new image
1369 // creation, page doesn't exist yet, so log_page = 0
1370 // but we want it to point to the page we're making,
1371 // so we later modify the log entry.
1372 // For a similar reason, we avoid making an RC entry
1373 // now and wait until the page exists.
1374 $logId = $logEntry->insert();
1376 $exists = $descTitle->exists();
1378 // Page exists, do RC entry now (otherwise we wait for later).
1379 $logEntry->publish( $logId );
1383 # Create a null revision
1384 $latest = $descTitle->getLatestRevID();
1385 // Use own context to get the action text in content language
1386 $formatter = LogFormatter
::newFromEntry( $logEntry );
1387 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1388 $editSummary = $formatter->getPlainActionText();
1390 $nullRevision = Revision
::newNullRevision(
1392 $descTitle->getArticleID(),
1397 if ( !is_null( $nullRevision ) ) {
1398 $nullRevision->insertOn( $dbw );
1400 Hooks
::run( '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
1449 # Delete old thumbnails
1450 $this->purgeThumbnails();
1452 # Remove the old file from the squid cache
1453 SquidUpdate
::purge( array( $this->getURL() ) );
1456 # Hooks, hooks, the magic of hooks...
1457 Hooks
::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1459 # Invalidate cache for all pages using this file
1460 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1461 $update->doUpdate();
1463 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1471 * Move or copy a file to its public location. If a file exists at the
1472 * destination, move it to an archive. Returns a FileRepoStatus object with
1473 * the archive name in the "value" member on success.
1475 * The archive name should be passed through to recordUpload for database
1478 * @param string $srcPath Local filesystem path to the source image
1479 * @param int $flags A bitwise combination of:
1480 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1481 * @param array $options Optional additional parameters
1482 * @return FileRepoStatus On success, the value member contains the
1483 * archive name, or an empty string if it was a new file.
1485 function publish( $srcPath, $flags = 0, array $options = array() ) {
1486 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1490 * Move or copy a file to a specified location. Returns a FileRepoStatus
1491 * object with the archive name in the "value" member on success.
1493 * The archive name should be passed through to recordUpload for database
1496 * @param string $srcPath Local filesystem path to the source image
1497 * @param string $dstRel Target relative path
1498 * @param int $flags A bitwise combination of:
1499 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1500 * @param array $options Optional additional parameters
1501 * @return FileRepoStatus On success, the value member contains the
1502 * archive name, or an empty string if it was a new file.
1504 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1505 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1506 return $this->readOnlyFatalStatus();
1509 $this->lock(); // begin
1511 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1512 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1513 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1514 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1516 if ( $status->value
== 'new' ) {
1517 $status->value
= '';
1519 $status->value
= $archiveName;
1522 $this->unlock(); // done
1527 /** getLinksTo inherited */
1528 /** getExifData inherited */
1529 /** isLocal inherited */
1530 /** wasDeleted inherited */
1533 * Move file to the new title
1535 * Move current, old version and all thumbnails
1536 * to the new filename. Old file is deleted.
1538 * Cache purging is done; checks for validity
1539 * and logging are caller's responsibility
1541 * @param Title $target New file name
1542 * @return FileRepoStatus
1544 function move( $target ) {
1545 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1546 return $this->readOnlyFatalStatus();
1549 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1550 $batch = new LocalFileMoveBatch( $this, $target );
1552 $this->lock(); // begin
1553 $batch->addCurrent();
1554 $archiveNames = $batch->addOlds();
1555 $status = $batch->execute();
1556 $this->unlock(); // done
1558 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1560 // Purge the source and target files...
1561 $oldTitleFile = wfLocalFile( $this->title
);
1562 $newTitleFile = wfLocalFile( $target );
1563 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1564 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1565 $this->getRepo()->getMasterDB()->onTransactionIdle(
1566 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1567 $oldTitleFile->purgeEverything();
1568 foreach ( $archiveNames as $archiveName ) {
1569 $oldTitleFile->purgeOldThumbnails( $archiveName );
1571 $newTitleFile->purgeEverything();
1575 if ( $status->isOK() ) {
1576 // Now switch the object
1577 $this->title
= $target;
1578 // Force regeneration of the name and hashpath
1579 unset( $this->name
);
1580 unset( $this->hashPath
);
1587 * Delete all versions of the file.
1589 * Moves the files into an archive directory (or deletes them)
1590 * and removes the database rows.
1592 * Cache purging is done; logging is caller's responsibility.
1594 * @param string $reason
1595 * @param bool $suppress
1596 * @param User|null $user
1597 * @return FileRepoStatus
1599 function delete( $reason, $suppress = false, $user = null ) {
1600 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1601 return $this->readOnlyFatalStatus();
1604 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1606 $this->lock(); // begin
1607 $batch->addCurrent();
1608 # Get old version relative paths
1609 $archiveNames = $batch->addOlds();
1610 $status = $batch->execute();
1611 $this->unlock(); // done
1613 if ( $status->isOK() ) {
1614 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1617 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1618 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1620 $this->getRepo()->getMasterDB()->onTransactionIdle(
1621 function () use ( $file, $archiveNames ) {
1624 $file->purgeEverything();
1625 foreach ( $archiveNames as $archiveName ) {
1626 $file->purgeOldThumbnails( $archiveName );
1629 if ( $wgUseSquid ) {
1631 $purgeUrls = array();
1632 foreach ( $archiveNames as $archiveName ) {
1633 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1635 SquidUpdate
::purge( $purgeUrls );
1644 * Delete an old version of the file.
1646 * Moves the file into an archive directory (or deletes it)
1647 * and removes the database row.
1649 * Cache purging is done; logging is caller's responsibility.
1651 * @param string $archiveName
1652 * @param string $reason
1653 * @param bool $suppress
1654 * @param User|null $user
1655 * @throws MWException Exception on database or file store failure
1656 * @return FileRepoStatus
1658 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1660 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1661 return $this->readOnlyFatalStatus();
1664 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1666 $this->lock(); // begin
1667 $batch->addOld( $archiveName );
1668 $status = $batch->execute();
1669 $this->unlock(); // done
1671 $this->purgeOldThumbnails( $archiveName );
1672 if ( $status->isOK() ) {
1673 $this->purgeDescription();
1674 $this->purgeHistory();
1677 if ( $wgUseSquid ) {
1679 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1686 * Restore all or specified deleted revisions to the given file.
1687 * Permissions and logging are left to the caller.
1689 * May throw database exceptions on error.
1691 * @param array $versions Set of record ids of deleted items to restore,
1692 * or empty to restore all revisions.
1693 * @param bool $unsuppress
1694 * @return FileRepoStatus
1696 function restore( $versions = array(), $unsuppress = false ) {
1697 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1698 return $this->readOnlyFatalStatus();
1701 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1703 $this->lock(); // begin
1707 $batch->addIds( $versions );
1709 $status = $batch->execute();
1710 if ( $status->isGood() ) {
1711 $cleanupStatus = $batch->cleanup();
1712 $cleanupStatus->successCount
= 0;
1713 $cleanupStatus->failCount
= 0;
1714 $status->merge( $cleanupStatus );
1716 $this->unlock(); // done
1721 /** isMultipage inherited */
1722 /** pageCount inherited */
1723 /** scaleHeight inherited */
1724 /** getImageSize inherited */
1727 * Get the URL of the file description page.
1730 function getDescriptionUrl() {
1731 return $this->title
->getLocalURL();
1735 * Get the HTML text of the description page
1736 * This is not used by ImagePage for local files, since (among other things)
1737 * it skips the parser cache.
1739 * @param Language $lang What language to get description in (Optional)
1740 * @return bool|mixed
1742 function getDescriptionText( $lang = null ) {
1743 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1747 $content = $revision->getContent();
1751 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1753 return $pout->getText();
1757 * @param int $audience
1761 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1763 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1765 } elseif ( $audience == self
::FOR_THIS_USER
1766 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1770 return $this->description
;
1775 * @return bool|string
1777 function getTimestamp() {
1780 return $this->timestamp
;
1786 function getSha1() {
1788 // Initialise now if necessary
1789 if ( $this->sha1
== '' && $this->fileExists
) {
1790 $this->lock(); // begin
1792 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1793 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1794 $dbw = $this->repo
->getMasterDB();
1795 $dbw->update( 'image',
1796 array( 'img_sha1' => $this->sha1
),
1797 array( 'img_name' => $this->getName() ),
1799 $this->saveToCache();
1802 $this->unlock(); // done
1809 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1811 function isCacheable() {
1814 // If extra data (metadata) was not loaded then it must have been large
1815 return $this->extraDataLoaded
1816 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1820 * Start a transaction and lock the image for update
1821 * Increments a reference counter if the lock is already held
1822 * @throws MWException Throws an error if the lock was not acquired
1823 * @return bool Whether the file lock owns/spawned the DB transaction
1826 $dbw = $this->repo
->getMasterDB();
1828 if ( !$this->locked
) {
1829 if ( !$dbw->trxLevel() ) {
1830 $dbw->begin( __METHOD__
);
1831 $this->lockedOwnTrx
= true;
1834 // Bug 54736: use simple lock to handle when the file does not exist.
1835 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1836 // Also, that would cause contention on INSERT of similarly named rows.
1837 $backend = $this->getRepo()->getBackend();
1838 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1839 $status = $backend->lockFiles( $lockPaths, LockManager
::LOCK_EX
, 5 );
1840 if ( !$status->isGood() ) {
1841 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1843 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1844 $backend->unlockFiles( $lockPaths, LockManager
::LOCK_EX
); // release on commit
1848 $this->markVolatile(); // file may change soon
1850 return $this->lockedOwnTrx
;
1854 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1855 * the transaction and thereby releases the image lock.
1858 if ( $this->locked
) {
1860 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1861 $dbw = $this->repo
->getMasterDB();
1862 $dbw->commit( __METHOD__
);
1863 $this->lockedOwnTrx
= false;
1869 * Mark a file as about to be changed
1871 * This sets a cache key that alters master/slave DB loading behavior
1873 * @return bool Success
1875 protected function markVolatile() {
1878 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1880 $this->lastMarkedVolatile
= time();
1881 return $wgMemc->set( $key, $this->lastMarkedVolatile
, self
::VOLATILE_TTL
);
1888 * Check if a file is about to be changed or has been changed recently
1890 * @see LocalFile::isVolatile()
1891 * @return bool Whether the file is volatile
1893 protected function isVolatile() {
1896 $key = $this->repo
->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1898 // repo unavailable; bail.
1902 if ( $this->lastMarkedVolatile
=== 0 ) {
1903 $this->lastMarkedVolatile
= $wgMemc->get( $key ) ?
: 0;
1906 $volatileDuration = time() - $this->lastMarkedVolatile
;
1907 return $volatileDuration <= self
::VOLATILE_TTL
;
1911 * Roll back the DB transaction and mark the image unlocked
1913 function unlockAndRollback() {
1914 $this->locked
= false;
1915 $dbw = $this->repo
->getMasterDB();
1916 $dbw->rollback( __METHOD__
);
1917 $this->lockedOwnTrx
= false;
1923 protected function readOnlyFatalStatus() {
1924 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1925 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1929 * Clean up any dangling locks
1931 function __destruct() {
1934 } // LocalFile class
1936 # ------------------------------------------------------------------------------
1939 * Helper class for file deletion
1940 * @ingroup FileAbstraction
1942 class LocalFileDeleteBatch
{
1943 /** @var LocalFile */
1950 private $srcRels = array();
1953 private $archiveUrls = array();
1955 /** @var array Items to be processed in the deletion batch */
1956 private $deletionBatch;
1958 /** @var bool Whether to suppress all suppressable fields when deleting */
1961 /** @var FileRepoStatus */
1969 * @param string $reason
1970 * @param bool $suppress
1971 * @param User|null $user
1973 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
1974 $this->file
= $file;
1975 $this->reason
= $reason;
1976 $this->suppress
= $suppress;
1978 $this->user
= $user;
1981 $this->user
= $wgUser;
1983 $this->status
= $file->repo
->newGood();
1986 function addCurrent() {
1987 $this->srcRels
['.'] = $this->file
->getRel();
1991 * @param string $oldName
1993 function addOld( $oldName ) {
1994 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1995 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1999 * Add the old versions of the image to the batch
2000 * @return array List of archive names from old versions
2002 function addOlds() {
2003 $archiveNames = array();
2005 $dbw = $this->file
->repo
->getMasterDB();
2006 $result = $dbw->select( 'oldimage',
2007 array( 'oi_archive_name' ),
2008 array( 'oi_name' => $this->file
->getName() ),
2012 foreach ( $result as $row ) {
2013 $this->addOld( $row->oi_archive_name
);
2014 $archiveNames[] = $row->oi_archive_name
;
2017 return $archiveNames;
2023 function getOldRels() {
2024 if ( !isset( $this->srcRels
['.'] ) ) {
2025 $oldRels =& $this->srcRels
;
2026 $deleteCurrent = false;
2028 $oldRels = $this->srcRels
;
2029 unset( $oldRels['.'] );
2030 $deleteCurrent = true;
2033 return array( $oldRels, $deleteCurrent );
2039 protected function getHashes() {
2041 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2043 if ( $deleteCurrent ) {
2044 $hashes['.'] = $this->file
->getSha1();
2047 if ( count( $oldRels ) ) {
2048 $dbw = $this->file
->repo
->getMasterDB();
2049 $res = $dbw->select(
2051 array( 'oi_archive_name', 'oi_sha1' ),
2052 array( 'oi_archive_name' => array_keys( $oldRels ),
2053 'oi_name' => $this->file
->getName() ), // performance
2057 foreach ( $res as $row ) {
2058 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2059 // Get the hash from the file
2060 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2061 $props = $this->file
->repo
->getFileProps( $oldUrl );
2063 if ( $props['fileExists'] ) {
2064 // Upgrade the oldimage row
2065 $dbw->update( 'oldimage',
2066 array( 'oi_sha1' => $props['sha1'] ),
2067 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2069 $hashes[$row->oi_archive_name
] = $props['sha1'];
2071 $hashes[$row->oi_archive_name
] = false;
2074 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2079 $missing = array_diff_key( $this->srcRels
, $hashes );
2081 foreach ( $missing as $name => $rel ) {
2082 $this->status
->error( 'filedelete-old-unregistered', $name );
2085 foreach ( $hashes as $name => $hash ) {
2087 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2088 unset( $hashes[$name] );
2095 function doDBInserts() {
2096 $dbw = $this->file
->repo
->getMasterDB();
2097 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2098 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2099 $encReason = $dbw->addQuotes( $this->reason
);
2100 $encGroup = $dbw->addQuotes( 'deleted' );
2101 $ext = $this->file
->getExtension();
2102 $dotExt = $ext === '' ?
'' : ".$ext";
2103 $encExt = $dbw->addQuotes( $dotExt );
2104 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2106 // Bitfields to further suppress the content
2107 if ( $this->suppress
) {
2109 // This should be 15...
2110 $bitfield |
= Revision
::DELETED_TEXT
;
2111 $bitfield |
= Revision
::DELETED_COMMENT
;
2112 $bitfield |
= Revision
::DELETED_USER
;
2113 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2115 $bitfield = 'oi_deleted';
2118 if ( $deleteCurrent ) {
2119 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2120 $where = array( 'img_name' => $this->file
->getName() );
2121 $dbw->insertSelect( 'filearchive', 'image',
2123 'fa_storage_group' => $encGroup,
2124 'fa_storage_key' => $dbw->conditional(
2125 array( 'img_sha1' => '' ),
2126 $dbw->addQuotes( '' ),
2129 'fa_deleted_user' => $encUserId,
2130 'fa_deleted_timestamp' => $encTimestamp,
2131 'fa_deleted_reason' => $encReason,
2132 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2134 'fa_name' => 'img_name',
2135 'fa_archive_name' => 'NULL',
2136 'fa_size' => 'img_size',
2137 'fa_width' => 'img_width',
2138 'fa_height' => 'img_height',
2139 'fa_metadata' => 'img_metadata',
2140 'fa_bits' => 'img_bits',
2141 'fa_media_type' => 'img_media_type',
2142 'fa_major_mime' => 'img_major_mime',
2143 'fa_minor_mime' => 'img_minor_mime',
2144 'fa_description' => 'img_description',
2145 'fa_user' => 'img_user',
2146 'fa_user_text' => 'img_user_text',
2147 'fa_timestamp' => 'img_timestamp',
2148 'fa_sha1' => 'img_sha1',
2149 ), $where, __METHOD__
);
2152 if ( count( $oldRels ) ) {
2153 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2155 'oi_name' => $this->file
->getName(),
2156 'oi_archive_name' => array_keys( $oldRels ) );
2157 $dbw->insertSelect( 'filearchive', 'oldimage',
2159 'fa_storage_group' => $encGroup,
2160 'fa_storage_key' => $dbw->conditional(
2161 array( 'oi_sha1' => '' ),
2162 $dbw->addQuotes( '' ),
2165 'fa_deleted_user' => $encUserId,
2166 'fa_deleted_timestamp' => $encTimestamp,
2167 'fa_deleted_reason' => $encReason,
2168 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2170 'fa_name' => 'oi_name',
2171 'fa_archive_name' => 'oi_archive_name',
2172 'fa_size' => 'oi_size',
2173 'fa_width' => 'oi_width',
2174 'fa_height' => 'oi_height',
2175 'fa_metadata' => 'oi_metadata',
2176 'fa_bits' => 'oi_bits',
2177 'fa_media_type' => 'oi_media_type',
2178 'fa_major_mime' => 'oi_major_mime',
2179 'fa_minor_mime' => 'oi_minor_mime',
2180 'fa_description' => 'oi_description',
2181 'fa_user' => 'oi_user',
2182 'fa_user_text' => 'oi_user_text',
2183 'fa_timestamp' => 'oi_timestamp',
2184 'fa_sha1' => 'oi_sha1',
2185 ), $where, __METHOD__
);
2189 function doDBDeletes() {
2190 $dbw = $this->file
->repo
->getMasterDB();
2191 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2193 if ( count( $oldRels ) ) {
2194 $dbw->delete( 'oldimage',
2196 'oi_name' => $this->file
->getName(),
2197 'oi_archive_name' => array_keys( $oldRels )
2201 if ( $deleteCurrent ) {
2202 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2207 * Run the transaction
2208 * @return FileRepoStatus
2210 function execute() {
2212 $this->file
->lock();
2214 // Prepare deletion batch
2215 $hashes = $this->getHashes();
2216 $this->deletionBatch
= array();
2217 $ext = $this->file
->getExtension();
2218 $dotExt = $ext === '' ?
'' : ".$ext";
2220 foreach ( $this->srcRels
as $name => $srcRel ) {
2221 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2222 if ( isset( $hashes[$name] ) ) {
2223 $hash = $hashes[$name];
2224 $key = $hash . $dotExt;
2225 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2226 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2230 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2231 // We acquire this lock by running the inserts now, before the file operations.
2233 // This potentially has poor lock contention characteristics -- an alternative
2234 // scheme would be to insert stub filearchive entries with no fa_name and commit
2235 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2236 $this->doDBInserts();
2238 // Removes non-existent file from the batch, so we don't get errors.
2239 // This also handles files in the 'deleted' zone deleted via revision deletion.
2240 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2241 if ( !$checkStatus->isGood() ) {
2242 $this->status
->merge( $checkStatus );
2243 return $this->status
;
2245 $this->deletionBatch
= $checkStatus->value
;
2247 // Execute the file deletion batch
2248 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2250 if ( !$status->isGood() ) {
2251 $this->status
->merge( $status );
2254 if ( !$this->status
->isOK() ) {
2255 // Critical file deletion error
2256 // Roll back inserts, release lock and abort
2257 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2258 $this->file
->unlockAndRollback();
2260 return $this->status
;
2263 // Delete image/oldimage rows
2264 $this->doDBDeletes();
2266 // Commit and return
2267 $this->file
->unlock();
2269 return $this->status
;
2273 * Removes non-existent files from a deletion batch.
2274 * @param array $batch
2277 function removeNonexistentFiles( $batch ) {
2278 $files = $newBatch = array();
2280 foreach ( $batch as $batchItem ) {
2281 list( $src, ) = $batchItem;
2282 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2285 $result = $this->file
->repo
->fileExistsBatch( $files );
2286 if ( in_array( null, $result, true ) ) {
2287 return Status
::newFatal( 'backend-fail-internal',
2288 $this->file
->repo
->getBackend()->getName() );
2291 foreach ( $batch as $batchItem ) {
2292 if ( $result[$batchItem[0]] ) {
2293 $newBatch[] = $batchItem;
2297 return Status
::newGood( $newBatch );
2301 # ------------------------------------------------------------------------------
2304 * Helper class for file undeletion
2305 * @ingroup FileAbstraction
2307 class LocalFileRestoreBatch
{
2308 /** @var LocalFile */
2311 /** @var array List of file IDs to restore */
2312 private $cleanupBatch;
2314 /** @var array List of file IDs to restore */
2317 /** @var bool Add all revisions of the file */
2320 /** @var bool Whether to remove all settings for suppressed fields */
2321 private $unsuppress = false;
2325 * @param bool $unsuppress
2327 function __construct( File
$file, $unsuppress = false ) {
2328 $this->file
= $file;
2329 $this->cleanupBatch
= $this->ids
= array();
2330 $this->ids
= array();
2331 $this->unsuppress
= $unsuppress;
2338 function addId( $fa_id ) {
2339 $this->ids
[] = $fa_id;
2343 * Add a whole lot of files by ID
2346 function addIds( $ids ) {
2347 $this->ids
= array_merge( $this->ids
, $ids );
2351 * Add all revisions of the file
2358 * Run the transaction, except the cleanup batch.
2359 * The cleanup batch should be run in a separate transaction, because it locks different
2360 * rows and there's no need to keep the image row locked while it's acquiring those locks
2361 * The caller may have its own transaction open.
2362 * So we save the batch and let the caller call cleanup()
2363 * @return FileRepoStatus
2365 function execute() {
2368 if ( !$this->all
&& !$this->ids
) {
2370 return $this->file
->repo
->newGood();
2373 $lockOwnsTrx = $this->file
->lock();
2375 $dbw = $this->file
->repo
->getMasterDB();
2376 $status = $this->file
->repo
->newGood();
2378 $exists = (bool)$dbw->selectField( 'image', '1',
2379 array( 'img_name' => $this->file
->getName() ),
2381 // The lock() should already prevents changes, but this still may need
2382 // to bypass any transaction snapshot. However, if lock() started the
2383 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2384 $lockOwnsTrx ?
array() : array( 'LOCK IN SHARE MODE' )
2387 // Fetch all or selected archived revisions for the file,
2388 // sorted from the most recent to the oldest.
2389 $conditions = array( 'fa_name' => $this->file
->getName() );
2391 if ( !$this->all
) {
2392 $conditions['fa_id'] = $this->ids
;
2395 $result = $dbw->select(
2397 ArchivedFile
::selectFields(),
2400 array( 'ORDER BY' => 'fa_timestamp DESC' )
2403 $idsPresent = array();
2404 $storeBatch = array();
2405 $insertBatch = array();
2406 $insertCurrent = false;
2407 $deleteIds = array();
2409 $archiveNames = array();
2411 foreach ( $result as $row ) {
2412 $idsPresent[] = $row->fa_id
;
2414 if ( $row->fa_name
!= $this->file
->getName() ) {
2415 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2416 $status->failCount++
;
2420 if ( $row->fa_storage_key
== '' ) {
2421 // Revision was missing pre-deletion
2422 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2423 $status->failCount++
;
2427 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2428 $row->fa_storage_key
;
2429 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2431 if ( isset( $row->fa_sha1
) ) {
2432 $sha1 = $row->fa_sha1
;
2434 // old row, populate from key
2435 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2439 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2440 $sha1 = substr( $sha1, 1 );
2443 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2444 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2445 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2446 ||
is_null( $row->fa_metadata
)
2448 // Refresh our metadata
2449 // Required for a new current revision; nice for older ones too. :)
2450 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2453 'minor_mime' => $row->fa_minor_mime
,
2454 'major_mime' => $row->fa_major_mime
,
2455 'media_type' => $row->fa_media_type
,
2456 'metadata' => $row->fa_metadata
2460 if ( $first && !$exists ) {
2461 // This revision will be published as the new current version
2462 $destRel = $this->file
->getRel();
2463 $insertCurrent = array(
2464 'img_name' => $row->fa_name
,
2465 'img_size' => $row->fa_size
,
2466 'img_width' => $row->fa_width
,
2467 'img_height' => $row->fa_height
,
2468 'img_metadata' => $props['metadata'],
2469 'img_bits' => $row->fa_bits
,
2470 'img_media_type' => $props['media_type'],
2471 'img_major_mime' => $props['major_mime'],
2472 'img_minor_mime' => $props['minor_mime'],
2473 'img_description' => $row->fa_description
,
2474 'img_user' => $row->fa_user
,
2475 'img_user_text' => $row->fa_user_text
,
2476 'img_timestamp' => $row->fa_timestamp
,
2480 // The live (current) version cannot be hidden!
2481 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2482 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2483 $this->cleanupBatch
[] = $row->fa_storage_key
;
2486 $archiveName = $row->fa_archive_name
;
2488 if ( $archiveName == '' ) {
2489 // This was originally a current version; we
2490 // have to devise a new archive name for it.
2491 // Format is <timestamp of archiving>!<name>
2492 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2495 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2497 } while ( isset( $archiveNames[$archiveName] ) );
2500 $archiveNames[$archiveName] = true;
2501 $destRel = $this->file
->getArchiveRel( $archiveName );
2502 $insertBatch[] = array(
2503 'oi_name' => $row->fa_name
,
2504 'oi_archive_name' => $archiveName,
2505 'oi_size' => $row->fa_size
,
2506 'oi_width' => $row->fa_width
,
2507 'oi_height' => $row->fa_height
,
2508 'oi_bits' => $row->fa_bits
,
2509 'oi_description' => $row->fa_description
,
2510 'oi_user' => $row->fa_user
,
2511 'oi_user_text' => $row->fa_user_text
,
2512 'oi_timestamp' => $row->fa_timestamp
,
2513 'oi_metadata' => $props['metadata'],
2514 'oi_media_type' => $props['media_type'],
2515 'oi_major_mime' => $props['major_mime'],
2516 'oi_minor_mime' => $props['minor_mime'],
2517 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2518 'oi_sha1' => $sha1 );
2521 $deleteIds[] = $row->fa_id
;
2523 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2524 // private files can stay where they are
2525 $status->successCount++
;
2527 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2528 $this->cleanupBatch
[] = $row->fa_storage_key
;
2536 // Add a warning to the status object for missing IDs
2537 $missingIds = array_diff( $this->ids
, $idsPresent );
2539 foreach ( $missingIds as $id ) {
2540 $status->error( 'undelete-missing-filearchive', $id );
2543 // Remove missing files from batch, so we don't get errors when undeleting them
2544 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2545 if ( !$checkStatus->isGood() ) {
2546 $status->merge( $checkStatus );
2549 $storeBatch = $checkStatus->value
;
2551 // Run the store batch
2552 // Use the OVERWRITE_SAME flag to smooth over a common error
2553 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2554 $status->merge( $storeStatus );
2556 if ( !$status->isGood() ) {
2557 // Even if some files could be copied, fail entirely as that is the
2558 // easiest thing to do without data loss
2559 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2560 $status->ok
= false;
2561 $this->file
->unlock();
2566 // Run the DB updates
2567 // Because we have locked the image row, key conflicts should be rare.
2568 // If they do occur, we can roll back the transaction at this time with
2569 // no data loss, but leaving unregistered files scattered throughout the
2571 // This is not ideal, which is why it's important to lock the image row.
2572 if ( $insertCurrent ) {
2573 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2576 if ( $insertBatch ) {
2577 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2581 $dbw->delete( 'filearchive',
2582 array( 'fa_id' => $deleteIds ),
2586 // If store batch is empty (all files are missing), deletion is to be considered successful
2587 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2589 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2591 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2593 $this->file
->purgeEverything();
2595 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2596 $this->file
->purgeDescription();
2597 $this->file
->purgeHistory();
2601 $this->file
->unlock();
2607 * Removes non-existent files from a store batch.
2608 * @param array $triplets
2611 function removeNonexistentFiles( $triplets ) {
2612 $files = $filteredTriplets = array();
2613 foreach ( $triplets as $file ) {
2614 $files[$file[0]] = $file[0];
2617 $result = $this->file
->repo
->fileExistsBatch( $files );
2618 if ( in_array( null, $result, true ) ) {
2619 return Status
::newFatal( 'backend-fail-internal',
2620 $this->file
->repo
->getBackend()->getName() );
2623 foreach ( $triplets as $file ) {
2624 if ( $result[$file[0]] ) {
2625 $filteredTriplets[] = $file;
2629 return Status
::newGood( $filteredTriplets );
2633 * Removes non-existent files from a cleanup batch.
2634 * @param array $batch
2637 function removeNonexistentFromCleanup( $batch ) {
2638 $files = $newBatch = array();
2639 $repo = $this->file
->repo
;
2641 foreach ( $batch as $file ) {
2642 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2643 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2646 $result = $repo->fileExistsBatch( $files );
2648 foreach ( $batch as $file ) {
2649 if ( $result[$file] ) {
2650 $newBatch[] = $file;
2658 * Delete unused files in the deleted zone.
2659 * This should be called from outside the transaction in which execute() was called.
2660 * @return FileRepoStatus
2662 function cleanup() {
2663 if ( !$this->cleanupBatch
) {
2664 return $this->file
->repo
->newGood();
2667 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2669 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2675 * Cleanup a failed batch. The batch was only partially successful, so
2676 * rollback by removing all items that were succesfully copied.
2678 * @param Status $storeStatus
2679 * @param array $storeBatch
2681 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2682 $cleanupBatch = array();
2684 foreach ( $storeStatus->success
as $i => $success ) {
2685 // Check if this item of the batch was successfully copied
2687 // Item was successfully copied and needs to be removed again
2688 // Extract ($dstZone, $dstRel) from the batch
2689 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2692 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2696 # ------------------------------------------------------------------------------
2699 * Helper class for file movement
2700 * @ingroup FileAbstraction
2702 class LocalFileMoveBatch
{
2703 /** @var LocalFile */
2713 protected $oldCount;
2717 /** @var DatabaseBase */
2722 * @param Title $target
2724 function __construct( File
$file, Title
$target ) {
2725 $this->file
= $file;
2726 $this->target
= $target;
2727 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2728 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2729 $this->oldName
= $this->file
->getName();
2730 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2731 $this->oldRel
= $this->oldHash
. $this->oldName
;
2732 $this->newRel
= $this->newHash
. $this->newName
;
2733 $this->db
= $file->getRepo()->getMasterDb();
2737 * Add the current image to the batch
2739 function addCurrent() {
2740 $this->cur
= array( $this->oldRel
, $this->newRel
);
2744 * Add the old versions of the image to the batch
2745 * @return array List of archive names from old versions
2747 function addOlds() {
2748 $archiveBase = 'archive';
2749 $this->olds
= array();
2750 $this->oldCount
= 0;
2751 $archiveNames = array();
2753 $result = $this->db
->select( 'oldimage',
2754 array( 'oi_archive_name', 'oi_deleted' ),
2755 array( 'oi_name' => $this->oldName
),
2757 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2760 foreach ( $result as $row ) {
2761 $archiveNames[] = $row->oi_archive_name
;
2762 $oldName = $row->oi_archive_name
;
2763 $bits = explode( '!', $oldName, 2 );
2765 if ( count( $bits ) != 2 ) {
2766 wfDebug( "Old file name missing !: '$oldName' \n" );
2770 list( $timestamp, $filename ) = $bits;
2772 if ( $this->oldName
!= $filename ) {
2773 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2779 // Do we want to add those to oldCount?
2780 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2784 $this->olds
[] = array(
2785 "{$archiveBase}/{$this->oldHash}{$oldName}",
2786 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2790 return $archiveNames;
2795 * @return FileRepoStatus
2797 function execute() {
2798 $repo = $this->file
->repo
;
2799 $status = $repo->newGood();
2801 $triplets = $this->getMoveTriplets();
2802 $checkStatus = $this->removeNonexistentFiles( $triplets );
2803 if ( !$checkStatus->isGood() ) {
2804 $status->merge( $checkStatus );
2807 $triplets = $checkStatus->value
;
2808 $destFile = wfLocalFile( $this->target
);
2810 $this->file
->lock(); // begin
2811 $destFile->lock(); // quickly fail if destination is not available
2812 // Rename the file versions metadata in the DB.
2813 // This implicitly locks the destination file, which avoids race conditions.
2814 // If we moved the files from A -> C before DB updates, another process could
2815 // move files from B -> C at this point, causing storeBatch() to fail and thus
2816 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2817 $statusDb = $this->doDBUpdates();
2818 if ( !$statusDb->isGood() ) {
2819 $destFile->unlock();
2820 $this->file
->unlockAndRollback();
2821 $statusDb->ok
= false;
2825 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2826 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2828 // Copy the files into their new location.
2829 // If a prior process fataled copying or cleaning up files we tolerate any
2830 // of the existing files if they are identical to the ones being stored.
2831 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2832 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2833 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2834 if ( !$statusMove->isGood() ) {
2835 // Delete any files copied over (while the destination is still locked)
2836 $this->cleanupTarget( $triplets );
2837 $destFile->unlock();
2838 $this->file
->unlockAndRollback(); // unlocks the destination
2839 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2840 $statusMove->ok
= false;
2844 $destFile->unlock();
2845 $this->file
->unlock(); // done
2847 // Everything went ok, remove the source files
2848 $this->cleanupSource( $triplets );
2850 $status->merge( $statusDb );
2851 $status->merge( $statusMove );
2857 * Do the database updates and return a new FileRepoStatus indicating how
2858 * many rows where updated.
2860 * @return FileRepoStatus
2862 function doDBUpdates() {
2863 $repo = $this->file
->repo
;
2864 $status = $repo->newGood();
2867 // Update current image
2870 array( 'img_name' => $this->newName
),
2871 array( 'img_name' => $this->oldName
),
2875 if ( $dbw->affectedRows() ) {
2876 $status->successCount++
;
2878 $status->failCount++
;
2879 $status->fatal( 'imageinvalidfilename' );
2884 // Update old images
2888 'oi_name' => $this->newName
,
2889 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2890 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2892 array( 'oi_name' => $this->oldName
),
2896 $affected = $dbw->affectedRows();
2897 $total = $this->oldCount
;
2898 $status->successCount +
= $affected;
2899 // Bug 34934: $total is based on files that actually exist.
2900 // There may be more DB rows than such files, in which case $affected
2901 // can be greater than $total. We use max() to avoid negatives here.
2902 $status->failCount +
= max( 0, $total - $affected );
2903 if ( $status->failCount
) {
2904 $status->error( 'imageinvalidfilename' );
2911 * Generate triplets for FileRepo::storeBatch().
2914 function getMoveTriplets() {
2915 $moves = array_merge( array( $this->cur
), $this->olds
);
2916 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2918 foreach ( $moves as $move ) {
2919 // $move: (oldRelativePath, newRelativePath)
2920 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2921 $triplets[] = array( $srcUrl, 'public', $move[1] );
2924 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2932 * Removes non-existent files from move batch.
2933 * @param array $triplets
2936 function removeNonexistentFiles( $triplets ) {
2939 foreach ( $triplets as $file ) {
2940 $files[$file[0]] = $file[0];
2943 $result = $this->file
->repo
->fileExistsBatch( $files );
2944 if ( in_array( null, $result, true ) ) {
2945 return Status
::newFatal( 'backend-fail-internal',
2946 $this->file
->repo
->getBackend()->getName() );
2949 $filteredTriplets = array();
2950 foreach ( $triplets as $file ) {
2951 if ( $result[$file[0]] ) {
2952 $filteredTriplets[] = $file;
2954 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2958 return Status
::newGood( $filteredTriplets );
2962 * Cleanup a partially moved array of triplets by deleting the target
2963 * files. Called if something went wrong half way.
2964 * @param array $triplets
2966 function cleanupTarget( $triplets ) {
2967 // Create dest pairs from the triplets
2969 foreach ( $triplets as $triplet ) {
2970 // $triplet: (old source virtual URL, dst zone, dest rel)
2971 $pairs[] = array( $triplet[1], $triplet[2] );
2974 $this->file
->repo
->cleanupBatch( $pairs );
2978 * Cleanup a fully moved array of triplets by deleting the source files.
2979 * Called at the end of the move process if everything else went ok.
2980 * @param array $triplets
2982 function cleanupSource( $triplets ) {
2983 // Create source file names from the triplets
2985 foreach ( $triplets as $triplet ) {
2986 $files[] = $triplet[0];
2989 $this->file
->repo
->cleanupBatch( $files );