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 const LOAD_ALL
= 1; // integer; load all the lazy fields too (like metadata)
127 * Create a LocalFile from a title
128 * Do not call this except from inside a repo class.
130 * Note: $unused param is only here to avoid an E_STRICT
132 * @param Title $title
133 * @param FileRepo $repo
134 * @param null $unused
138 static function newFromTitle( $title, $repo, $unused = null ) {
139 return new self( $title, $repo );
143 * Create a LocalFile from a title
144 * Do not call this except from inside a repo class.
146 * @param stdClass $row
147 * @param FileRepo $repo
151 static function newFromRow( $row, $repo ) {
152 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
153 $file = new self( $title, $repo );
154 $file->loadFromRow( $row );
160 * Create a LocalFile from a SHA-1 key
161 * Do not call this except from inside a repo class.
163 * @param string $sha1 base-36 SHA-1
164 * @param LocalRepo $repo
165 * @param string|bool $timestamp MW_timestamp (optional)
166 * @return bool|LocalFile
168 static function newFromKey( $sha1, $repo, $timestamp = false ) {
169 $dbr = $repo->getSlaveDB();
171 $conds = array( 'img_sha1' => $sha1 );
173 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
176 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
178 return self
::newFromRow( $row, $repo );
185 * Fields in the image table
188 static function selectFields() {
209 * Do not call this except from inside a repo class.
210 * @param Title $title
211 * @param FileRepo $repo
213 function __construct( $title, $repo ) {
214 parent
::__construct( $title, $repo );
216 $this->metadata
= '';
217 $this->historyLine
= 0;
218 $this->historyRes
= null;
219 $this->dataLoaded
= false;
220 $this->extraDataLoaded
= false;
222 $this->assertRepoDefined();
223 $this->assertTitleDefined();
227 * Get the memcached key for the main data for this file, or false if
228 * there is no access to the shared cache.
231 function getCacheKey() {
232 $hashedName = md5( $this->getName() );
234 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
238 * Try to load file metadata from memcached. Returns true on success.
241 function loadFromCache() {
244 wfProfileIn( __METHOD__
);
245 $this->dataLoaded
= false;
246 $this->extraDataLoaded
= false;
247 $key = $this->getCacheKey();
250 wfProfileOut( __METHOD__
);
255 $cachedValues = $wgMemc->get( $key );
257 // Check if the key existed and belongs to this version of MediaWiki
258 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
259 wfDebug( "Pulling file metadata from cache key $key\n" );
260 $this->fileExists
= $cachedValues['fileExists'];
261 if ( $this->fileExists
) {
262 $this->setProps( $cachedValues );
264 $this->dataLoaded
= true;
265 $this->extraDataLoaded
= true;
266 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
267 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
271 if ( $this->dataLoaded
) {
272 wfIncrStats( 'image_cache_hit' );
274 wfIncrStats( 'image_cache_miss' );
277 wfProfileOut( __METHOD__
);
279 return $this->dataLoaded
;
283 * Save the file metadata to memcached
285 function saveToCache() {
289 $key = $this->getCacheKey();
295 $fields = $this->getCacheFields( '' );
296 $cache = array( 'version' => MW_FILE_VERSION
);
297 $cache['fileExists'] = $this->fileExists
;
299 if ( $this->fileExists
) {
300 foreach ( $fields as $field ) {
301 $cache[$field] = $this->$field;
305 // Strip off excessive entries from the subset of fields that can become large.
306 // If the cache value gets to large it will not fit in memcached and nothing will
307 // get cached at all, causing master queries for any file access.
308 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
309 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
310 unset( $cache[$field] ); // don't let the value get too big
314 // Cache presence for 1 week and negatives for 1 day
315 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
319 * Load metadata from the file itself
321 function loadFromFile() {
322 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
323 $this->setProps( $props );
327 * @param string $prefix
330 function getCacheFields( $prefix = 'img_' ) {
331 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
332 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
333 'user_text', 'description' );
334 static $results = array();
336 if ( $prefix == '' ) {
340 if ( !isset( $results[$prefix] ) ) {
341 $prefixedFields = array();
342 foreach ( $fields as $field ) {
343 $prefixedFields[] = $prefix . $field;
345 $results[$prefix] = $prefixedFields;
348 return $results[$prefix];
352 * @param string $prefix
355 function getLazyCacheFields( $prefix = 'img_' ) {
356 static $fields = array( 'metadata' );
357 static $results = array();
359 if ( $prefix == '' ) {
363 if ( !isset( $results[$prefix] ) ) {
364 $prefixedFields = array();
365 foreach ( $fields as $field ) {
366 $prefixedFields[] = $prefix . $field;
368 $results[$prefix] = $prefixedFields;
371 return $results[$prefix];
375 * Load file metadata from the DB
377 function loadFromDB() {
378 # Polymorphic function name to distinguish foreign and local fetches
379 $fname = get_class( $this ) . '::' . __FUNCTION__
;
380 wfProfileIn( $fname );
382 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
383 $this->dataLoaded
= true;
384 $this->extraDataLoaded
= true;
386 $dbr = $this->repo
->getMasterDB();
387 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
388 array( 'img_name' => $this->getName() ), $fname );
391 $this->loadFromRow( $row );
393 $this->fileExists
= false;
396 wfProfileOut( $fname );
400 * Load lazy file metadata from the DB.
401 * This covers fields that are sometimes not cached.
403 protected function loadExtraFromDB() {
404 # Polymorphic function name to distinguish foreign and local fetches
405 $fname = get_class( $this ) . '::' . __FUNCTION__
;
406 wfProfileIn( $fname );
408 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
409 $this->extraDataLoaded
= true;
411 $dbr = $this->repo
->getSlaveDB();
412 // In theory the file could have just been renamed/deleted...oh well
413 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
414 array( 'img_name' => $this->getName() ), $fname );
416 if ( !$row ) { // fallback to master
417 $dbr = $this->repo
->getMasterDB();
418 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
419 array( 'img_name' => $this->getName() ), $fname );
423 foreach ( $this->unprefixRow( $row, 'img_' ) as $name => $value ) {
424 $this->$name = $value;
427 wfProfileOut( $fname );
428 throw new MWException( "Could not find data for image '{$this->getName()}'." );
431 wfProfileOut( $fname );
435 * @param array $row Row
436 * @param string $prefix
437 * @throws MWException
440 protected function unprefixRow( $row, $prefix = 'img_' ) {
441 $array = (array)$row;
442 $prefixLength = strlen( $prefix );
444 // Sanity check prefix once
445 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
446 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
450 foreach ( $array as $name => $value ) {
451 $decoded[substr( $name, $prefixLength )] = $value;
458 * Decode a row from the database (either object or array) to an array
459 * with timestamps and MIME types decoded, and the field prefix removed.
461 * @param string $prefix
462 * @throws MWException
465 function decodeRow( $row, $prefix = 'img_' ) {
466 $decoded = $this->unprefixRow( $row, $prefix );
468 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
470 if ( empty( $decoded['major_mime'] ) ) {
471 $decoded['mime'] = 'unknown/unknown';
473 if ( !$decoded['minor_mime'] ) {
474 $decoded['minor_mime'] = 'unknown';
476 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
479 # Trim zero padding from char/binary field
480 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
486 * Load file metadata from a DB result row
489 * @param string $prefix
491 function loadFromRow( $row, $prefix = 'img_' ) {
492 $this->dataLoaded
= true;
493 $this->extraDataLoaded
= true;
495 $array = $this->decodeRow( $row, $prefix );
497 foreach ( $array as $name => $value ) {
498 $this->$name = $value;
501 $this->fileExists
= true;
502 $this->maybeUpgradeRow();
506 * Load file metadata from cache or DB, unless already loaded
509 function load( $flags = 0 ) {
510 if ( !$this->dataLoaded
) {
511 if ( !$this->loadFromCache() ) {
513 $this->saveToCache();
515 $this->dataLoaded
= true;
517 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
518 $this->loadExtraFromDB();
523 * Upgrade a row if it needs it
525 function maybeUpgradeRow() {
526 global $wgUpdateCompatibleMetadata;
527 if ( wfReadOnly() ) {
531 if ( is_null( $this->media_type
) ||
532 $this->mime
== 'image/svg'
535 $this->upgraded
= true;
537 $handler = $this->getHandler();
539 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
540 if ( $validity === MediaHandler
::METADATA_BAD
541 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
544 $this->upgraded
= true;
550 function getUpgraded() {
551 return $this->upgraded
;
555 * Fix assorted version-related problems with the image row by reloading it from the file
557 function upgradeRow() {
558 wfProfileIn( __METHOD__
);
560 $this->lock(); // begin
562 $this->loadFromFile();
564 # Don't destroy file info of missing files
565 if ( !$this->fileExists
) {
566 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
567 wfProfileOut( __METHOD__
);
572 $dbw = $this->repo
->getMasterDB();
573 list( $major, $minor ) = self
::splitMime( $this->mime
);
575 if ( wfReadOnly() ) {
576 wfProfileOut( __METHOD__
);
580 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
582 $dbw->update( 'image',
584 'img_size' => $this->size
, // sanity
585 'img_width' => $this->width
,
586 'img_height' => $this->height
,
587 'img_bits' => $this->bits
,
588 'img_media_type' => $this->media_type
,
589 'img_major_mime' => $major,
590 'img_minor_mime' => $minor,
591 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
592 'img_sha1' => $this->sha1
,
594 array( 'img_name' => $this->getName() ),
598 $this->saveToCache();
600 $this->unlock(); // done
602 wfProfileOut( __METHOD__
);
606 * Set properties in this object to be equal to those given in the
607 * associative array $info. Only cacheable fields can be set.
608 * All fields *must* be set in $info except for getLazyCacheFields().
610 * If 'mime' is given, it will be split into major_mime/minor_mime.
611 * If major_mime/minor_mime are given, $this->mime will also be set.
615 function setProps( $info ) {
616 $this->dataLoaded
= true;
617 $fields = $this->getCacheFields( '' );
618 $fields[] = 'fileExists';
620 foreach ( $fields as $field ) {
621 if ( isset( $info[$field] ) ) {
622 $this->$field = $info[$field];
626 // Fix up mime fields
627 if ( isset( $info['major_mime'] ) ) {
628 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
629 } elseif ( isset( $info['mime'] ) ) {
630 $this->mime
= $info['mime'];
631 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
635 /** splitMime inherited */
636 /** getName inherited */
637 /** getTitle inherited */
638 /** getURL inherited */
639 /** getViewURL inherited */
640 /** getPath inherited */
641 /** isVisible inhereted */
646 function isMissing() {
647 if ( $this->missing
=== null ) {
648 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
649 $this->missing
= !$fileExists;
652 return $this->missing
;
656 * Return the width of the image
661 public function getWidth( $page = 1 ) {
664 if ( $this->isMultipage() ) {
665 $handler = $this->getHandler();
669 $dim = $handler->getPageDimensions( $this, $page );
671 return $dim['width'];
673 // For non-paged media, the false goes through an
674 // intval, turning failure into 0, so do same here.
683 * Return the height of the image
688 public function getHeight( $page = 1 ) {
691 if ( $this->isMultipage() ) {
692 $handler = $this->getHandler();
696 $dim = $handler->getPageDimensions( $this, $page );
698 return $dim['height'];
700 // For non-paged media, the false goes through an
701 // intval, turning failure into 0, so do same here.
705 return $this->height
;
710 * Returns ID or name of user who uploaded the file
712 * @param string $type 'text' or 'id'
715 function getUser( $type = 'text' ) {
718 if ( $type == 'text' ) {
719 return $this->user_text
;
720 } elseif ( $type == 'id' ) {
726 * Get handler-specific metadata
729 function getMetadata() {
730 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
731 return $this->metadata
;
737 function getBitDepth() {
744 * Returns the size of the image file, in bytes
747 public function getSize() {
754 * Returns the mime type of the file.
757 function getMimeType() {
764 * Returns the type of the media in the file.
765 * Use the value returned by this function with the MEDIATYPE_xxx constants.
768 function getMediaType() {
771 return $this->media_type
;
774 /** canRender inherited */
775 /** mustRender inherited */
776 /** allowInlineDisplay inherited */
777 /** isSafeFile inherited */
778 /** isTrustedFile inherited */
781 * Returns true if the file exists on disk.
782 * @return bool Whether file exist on disk.
784 public function exists() {
787 return $this->fileExists
;
790 /** getTransformScript inherited */
791 /** getUnscaledThumb inherited */
792 /** thumbName inherited */
793 /** createThumb inherited */
794 /** transform inherited */
797 * Fix thumbnail files from 1.4 or before, with extreme prejudice
798 * @todo Do we still care about this? Perhaps a maintenance script
799 * can be made instead. Enabling this code results in a serious
800 * RTT regression for wikis without 404 handling.
802 * @param string $thumbName
804 function migrateThumbFile( $thumbName ) {
805 /* Old code for bug 2532
806 $thumbDir = $this->getThumbPath();
807 $thumbPath = "$thumbDir/$thumbName";
808 if ( is_dir( $thumbPath ) ) {
809 // Directory where file should be
810 // This happened occasionally due to broken migration code in 1.5
811 // Rename to broken-*
812 for ( $i = 0; $i < 100; $i++ ) {
813 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
814 if ( !file_exists( $broken ) ) {
815 rename( $thumbPath, $broken );
819 // Doesn't exist anymore
824 if ( $this->repo->fileExists( $thumbDir ) ) {
825 // Delete file where directory should be
826 $this->repo->cleanupBatch( array( $thumbDir ) );
831 /** getHandler inherited */
832 /** iconThumb inherited */
833 /** getLastError inherited */
836 * Get all thumbnail names previously generated for this file
837 * @param string|bool $archiveName Name of an archive file, default false
838 * @return array first element is the base dir, then files in that base dir.
840 function getThumbnails( $archiveName = false ) {
841 if ( $archiveName ) {
842 $dir = $this->getArchiveThumbPath( $archiveName );
844 $dir = $this->getThumbPath();
847 $backend = $this->repo
->getBackend();
848 $files = array( $dir );
850 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
851 foreach ( $iterator as $file ) {
854 } catch ( FileBackendError
$e ) {
855 } // suppress (bug 54674)
861 * Refresh metadata in memcached, but don't touch thumbnails or squid
863 function purgeMetadataCache() {
865 $this->saveToCache();
866 $this->purgeHistory();
870 * Purge the shared history (OldLocalFile) cache.
872 * @note This used to purge old thumbnails as well.
874 function purgeHistory() {
877 $hashedName = md5( $this->getName() );
878 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
881 $wgMemc->delete( $oldKey );
886 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
888 * @param array $options An array potentially with the key forThumbRefresh.
890 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
892 function purgeCache( $options = array() ) {
893 wfProfileIn( __METHOD__
);
894 // Refresh metadata cache
895 $this->purgeMetadataCache();
898 $this->purgeThumbnails( $options );
900 // Purge squid cache for this file
901 SquidUpdate
::purge( array( $this->getURL() ) );
902 wfProfileOut( __METHOD__
);
906 * Delete cached transformed files for an archived version only.
907 * @param string $archiveName Name of the archived file
909 function purgeOldThumbnails( $archiveName ) {
911 wfProfileIn( __METHOD__
);
913 // Get a list of old thumbnails and URLs
914 $files = $this->getThumbnails( $archiveName );
916 // Purge any custom thumbnail caches
917 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
919 $dir = array_shift( $files );
920 $this->purgeThumbList( $dir, $files );
925 foreach ( $files as $file ) {
926 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
928 SquidUpdate
::purge( $urls );
931 wfProfileOut( __METHOD__
);
935 * Delete cached transformed files for the current version only.
937 function purgeThumbnails( $options = array() ) {
939 wfProfileIn( __METHOD__
);
942 $files = $this->getThumbnails();
943 // Always purge all files from squid regardless of handler filters
946 foreach ( $files as $file ) {
947 $urls[] = $this->getThumbUrl( $file );
949 array_shift( $urls ); // don't purge directory
952 // Give media handler a chance to filter the file purge list
953 if ( !empty( $options['forThumbRefresh'] ) ) {
954 $handler = $this->getHandler();
956 $handler->filterThumbnailPurgeList( $files, $options );
960 // Purge any custom thumbnail caches
961 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
963 $dir = array_shift( $files );
964 $this->purgeThumbList( $dir, $files );
968 SquidUpdate
::purge( $urls );
971 wfProfileOut( __METHOD__
);
975 * Delete a list of thumbnails visible at urls
976 * @param string $dir Base dir of the files.
977 * @param array $files Array of strings: relative filenames (to $dir)
979 protected function purgeThumbList( $dir, $files ) {
980 $fileListDebug = strtr(
981 var_export( $files, true ),
984 wfDebug( __METHOD__
. ": $fileListDebug\n" );
986 $purgeList = array();
987 foreach ( $files as $file ) {
988 # Check that the base file name is part of the thumb name
989 # This is a basic sanity check to avoid erasing unrelated directories
990 if ( strpos( $file, $this->getName() ) !== false
991 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
993 $purgeList[] = "{$dir}/{$file}";
997 # Delete the thumbnails
998 $this->repo
->quickPurgeBatch( $purgeList );
999 # Clear out the thumbnail directory if empty
1000 $this->repo
->quickCleanDir( $dir );
1003 /** purgeDescription inherited */
1004 /** purgeEverything inherited */
1007 * @param int $limit Optional: Limit to number of results
1008 * @param int $start Optional: Timestamp, start from
1009 * @param int $end Optional: Timestamp, end at
1013 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1014 $dbr = $this->repo
->getSlaveDB();
1015 $tables = array( 'oldimage' );
1016 $fields = OldLocalFile
::selectFields();
1017 $conds = $opts = $join_conds = array();
1018 $eq = $inc ?
'=' : '';
1019 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1022 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1026 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1030 $opts['LIMIT'] = $limit;
1033 // Search backwards for time > x queries
1034 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1035 $opts['ORDER BY'] = "oi_timestamp $order";
1036 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1038 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1039 &$conds, &$opts, &$join_conds ) );
1041 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1044 foreach ( $res as $row ) {
1045 $r[] = $this->repo
->newFileFromRow( $row );
1048 if ( $order == 'ASC' ) {
1049 $r = array_reverse( $r ); // make sure it ends up descending
1056 * Returns the history of this file, line by line.
1057 * starts with current version, then old versions.
1058 * uses $this->historyLine to check which line to return:
1059 * 0 return line for current version
1060 * 1 query for old versions, return first one
1061 * 2, ... return next old version from above query
1064 public function nextHistoryLine() {
1065 # Polymorphic function name to distinguish foreign and local fetches
1066 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1068 $dbr = $this->repo
->getSlaveDB();
1070 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1071 $this->historyRes
= $dbr->select( 'image',
1074 "'' AS oi_archive_name",
1078 array( 'img_name' => $this->title
->getDBkey() ),
1082 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1083 $this->historyRes
= null;
1087 } elseif ( $this->historyLine
== 1 ) {
1088 $this->historyRes
= $dbr->select( 'oldimage', '*',
1089 array( 'oi_name' => $this->title
->getDBkey() ),
1091 array( 'ORDER BY' => 'oi_timestamp DESC' )
1094 $this->historyLine++
;
1096 return $dbr->fetchObject( $this->historyRes
);
1100 * Reset the history pointer to the first element of the history
1102 public function resetHistory() {
1103 $this->historyLine
= 0;
1105 if ( !is_null( $this->historyRes
) ) {
1106 $this->historyRes
= null;
1110 /** getHashPath inherited */
1111 /** getRel inherited */
1112 /** getUrlRel inherited */
1113 /** getArchiveRel inherited */
1114 /** getArchivePath inherited */
1115 /** getThumbPath inherited */
1116 /** getArchiveUrl inherited */
1117 /** getThumbUrl inherited */
1118 /** getArchiveVirtualUrl inherited */
1119 /** getThumbVirtualUrl inherited */
1120 /** isHashed inherited */
1123 * Upload a file and record it in the DB
1124 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1125 * @param string $comment Upload description
1126 * @param string $pageText Text to use for the new description page,
1127 * if a new description page is created
1128 * @param int|bool $flags Flags for publish()
1129 * @param array|bool $props File properties, if known. This can be used to
1130 * reduce the upload time when uploading virtual URLs for which the file
1131 * info is already known
1132 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1134 * @param User|null $user User object or null to use $wgUser
1136 * @return FileRepoStatus On success, the value member contains the
1137 * archive name, or an empty string if it was a new file.
1139 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1140 $timestamp = false, $user = null
1144 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1145 return $this->readOnlyFatalStatus();
1149 wfProfileIn( __METHOD__
. '-getProps' );
1150 if ( $this->repo
->isVirtualUrl( $srcPath )
1151 || FileBackend
::isStoragePath( $srcPath )
1153 $props = $this->repo
->getFileProps( $srcPath );
1155 $props = FSFile
::getPropsFromPath( $srcPath );
1157 wfProfileOut( __METHOD__
. '-getProps' );
1161 $handler = MediaHandler
::getHandler( $props['mime'] );
1163 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1165 $options['headers'] = array();
1168 // Trim spaces on user supplied text
1169 $comment = trim( $comment );
1171 // Truncate nicely or the DB will do it for us
1172 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1173 $comment = $wgContLang->truncate( $comment, 255 );
1174 $this->lock(); // begin
1175 $status = $this->publish( $srcPath, $flags, $options );
1177 if ( $status->successCount
>= 2 ) {
1178 // There will be a copy+(one of move,copy,store).
1179 // The first succeeding does not commit us to updating the DB
1180 // since it simply copied the current version to a timestamped file name.
1181 // It is only *preferable* to avoid leaving such files orphaned.
1182 // Once the second operation goes through, then the current version was
1183 // updated and we must therefore update the DB too.
1184 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1185 $status->fatal( 'filenotfound', $srcPath );
1189 $this->unlock(); // done
1195 * Record a file upload in the upload log and the image table
1196 * @param string $oldver
1197 * @param string $desc
1198 * @param string $license
1199 * @param string $copyStatus
1200 * @param string $source
1201 * @param bool $watch
1202 * @param string|bool $timestamp
1203 * @param User|null $user User object or null to use $wgUser
1206 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1207 $watch = false, $timestamp = false, User
$user = null ) {
1213 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1215 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1220 $user->addWatch( $this->getTitle() );
1227 * Record a file upload in the upload log and the image table
1228 * @param string $oldver
1229 * @param string $comment
1230 * @param string $pageText
1231 * @param bool|array $props
1232 * @param string|bool $timestamp
1233 * @param null|User $user
1236 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1239 wfProfileIn( __METHOD__
);
1241 if ( is_null( $user ) ) {
1246 $dbw = $this->repo
->getMasterDB();
1247 $dbw->begin( __METHOD__
);
1250 wfProfileIn( __METHOD__
. '-getProps' );
1251 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1252 wfProfileOut( __METHOD__
. '-getProps' );
1255 if ( $timestamp === false ) {
1256 $timestamp = $dbw->timestamp();
1259 $props['description'] = $comment;
1260 $props['user'] = $user->getId();
1261 $props['user_text'] = $user->getName();
1262 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1263 $this->setProps( $props );
1265 # Fail now if the file isn't there
1266 if ( !$this->fileExists
) {
1267 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1268 wfProfileOut( __METHOD__
);
1275 # Test to see if the row exists using INSERT IGNORE
1276 # This avoids race conditions by locking the row until the commit, and also
1277 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1278 $dbw->insert( 'image',
1280 'img_name' => $this->getName(),
1281 'img_size' => $this->size
,
1282 'img_width' => intval( $this->width
),
1283 'img_height' => intval( $this->height
),
1284 'img_bits' => $this->bits
,
1285 'img_media_type' => $this->media_type
,
1286 'img_major_mime' => $this->major_mime
,
1287 'img_minor_mime' => $this->minor_mime
,
1288 'img_timestamp' => $timestamp,
1289 'img_description' => $comment,
1290 'img_user' => $user->getId(),
1291 'img_user_text' => $user->getName(),
1292 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1293 'img_sha1' => $this->sha1
1298 if ( $dbw->affectedRows() == 0 ) {
1299 # (bug 34993) Note: $oldver can be empty here, if the previous
1300 # version of the file was broken. Allow registration of the new
1301 # version to continue anyway, because that's better than having
1302 # an image that's not fixable by user operations.
1305 # Collision, this is an update of a file
1306 # Insert previous contents into oldimage
1307 $dbw->insertSelect( 'oldimage', 'image',
1309 'oi_name' => 'img_name',
1310 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1311 'oi_size' => 'img_size',
1312 'oi_width' => 'img_width',
1313 'oi_height' => 'img_height',
1314 'oi_bits' => 'img_bits',
1315 'oi_timestamp' => 'img_timestamp',
1316 'oi_description' => 'img_description',
1317 'oi_user' => 'img_user',
1318 'oi_user_text' => 'img_user_text',
1319 'oi_metadata' => 'img_metadata',
1320 'oi_media_type' => 'img_media_type',
1321 'oi_major_mime' => 'img_major_mime',
1322 'oi_minor_mime' => 'img_minor_mime',
1323 'oi_sha1' => 'img_sha1'
1325 array( 'img_name' => $this->getName() ),
1329 # Update the current image row
1330 $dbw->update( 'image',
1332 'img_size' => $this->size
,
1333 'img_width' => intval( $this->width
),
1334 'img_height' => intval( $this->height
),
1335 'img_bits' => $this->bits
,
1336 'img_media_type' => $this->media_type
,
1337 'img_major_mime' => $this->major_mime
,
1338 'img_minor_mime' => $this->minor_mime
,
1339 'img_timestamp' => $timestamp,
1340 'img_description' => $comment,
1341 'img_user' => $user->getId(),
1342 'img_user_text' => $user->getName(),
1343 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1344 'img_sha1' => $this->sha1
1346 array( 'img_name' => $this->getName() ),
1350 # This is a new file, so update the image count
1351 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1354 $descTitle = $this->getTitle();
1355 $wikiPage = new WikiFilePage( $descTitle );
1356 $wikiPage->setFile( $this );
1359 $action = $reupload ?
'overwrite' : 'upload';
1361 $logEntry = new ManualLogEntry( 'upload', $action );
1362 $logEntry->setPerformer( $user );
1363 $logEntry->setComment( $comment );
1364 $logEntry->setTarget( $descTitle );
1366 // Allow people using the api to associate log entries with the upload.
1367 // Log has a timestamp, but sometimes different from upload timestamp.
1368 $logEntry->setParameters(
1370 'img_sha1' => $this->sha1
,
1371 'img_timestamp' => $timestamp,
1374 // Note we keep $logId around since during new image
1375 // creation, page doesn't exist yet, so log_page = 0
1376 // but we want it to point to the page we're making,
1377 // so we later modify the log entry.
1378 // For a similar reason, we avoid making an RC entry
1379 // now and wait until the page exists.
1380 $logId = $logEntry->insert();
1382 $exists = $descTitle->exists();
1384 // Page exists, do RC entry now (otherwise we wait for later).
1385 $logEntry->publish( $logId );
1387 wfProfileIn( __METHOD__
. '-edit' );
1390 # Create a null revision
1391 $latest = $descTitle->getLatestRevID();
1392 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1394 $nullRevision = Revision
::newNullRevision(
1396 $descTitle->getArticleID(),
1400 if ( !is_null( $nullRevision ) ) {
1401 $nullRevision->insertOn( $dbw );
1403 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1404 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1408 # Commit the transaction now, in case something goes wrong later
1409 # The most important thing is that files don't get lost, especially archives
1410 # NOTE: once we have support for nested transactions, the commit may be moved
1411 # to after $wikiPage->doEdit has been called.
1412 $dbw->commit( __METHOD__
);
1415 # We shall not saveToCache before the commit since otherwise
1416 # in case of a rollback there is an usable file from memcached
1417 # which in fact doesn't really exist (bug 24978)
1418 $this->saveToCache();
1421 # Invalidate the cache for the description page
1422 $descTitle->invalidateCache();
1423 $descTitle->purgeSquid();
1425 # New file; create the description page.
1426 # There's already a log entry, so don't make a second RC entry
1427 # Squid and file cache for the description page are purged by doEditContent.
1428 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1429 $status = $wikiPage->doEditContent(
1432 EDIT_NEW | EDIT_SUPPRESS_RC
,
1437 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1438 // Now that the page exists, make an RC entry.
1439 $logEntry->publish( $logId );
1440 if ( isset( $status->value
['revision'] ) ) {
1441 $dbw->update( 'logging',
1442 array( 'log_page' => $status->value
['revision']->getPage() ),
1443 array( 'log_id' => $logId ),
1447 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1450 wfProfileOut( __METHOD__
. '-edit' );
1454 # Delete old thumbnails
1455 wfProfileIn( __METHOD__
. '-purge' );
1456 $this->purgeThumbnails();
1457 wfProfileOut( __METHOD__
. '-purge' );
1459 # Remove the old file from the squid cache
1460 SquidUpdate
::purge( array( $this->getURL() ) );
1463 # Hooks, hooks, the magic of hooks...
1464 wfProfileIn( __METHOD__
. '-hooks' );
1465 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1466 wfProfileOut( __METHOD__
. '-hooks' );
1468 # Invalidate cache for all pages using this file
1469 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1470 $update->doUpdate();
1472 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1475 wfProfileOut( __METHOD__
);
1481 * Move or copy a file to its public location. If a file exists at the
1482 * destination, move it to an archive. Returns a FileRepoStatus object with
1483 * the archive name in the "value" member on success.
1485 * The archive name should be passed through to recordUpload for database
1488 * @param string $srcPath Local filesystem path to the source image
1489 * @param int $flags A bitwise combination of:
1490 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1491 * @param array $options Optional additional parameters
1492 * @return FileRepoStatus On success, the value member contains the
1493 * archive name, or an empty string if it was a new file.
1495 function publish( $srcPath, $flags = 0, array $options = array() ) {
1496 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1500 * Move or copy a file to a specified location. Returns a FileRepoStatus
1501 * object with the archive name in the "value" member on success.
1503 * The archive name should be passed through to recordUpload for database
1506 * @param string $srcPath Local filesystem path to the source image
1507 * @param string $dstRel Target relative path
1508 * @param int $flags A bitwise combination of:
1509 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1510 * @param array $options Optional additional parameters
1511 * @return FileRepoStatus On success, the value member contains the
1512 * archive name, or an empty string if it was a new file.
1514 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1515 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1516 return $this->readOnlyFatalStatus();
1519 $this->lock(); // begin
1521 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1522 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1523 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1524 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1526 if ( $status->value
== 'new' ) {
1527 $status->value
= '';
1529 $status->value
= $archiveName;
1532 $this->unlock(); // done
1537 /** getLinksTo inherited */
1538 /** getExifData inherited */
1539 /** isLocal inherited */
1540 /** wasDeleted inherited */
1543 * Move file to the new title
1545 * Move current, old version and all thumbnails
1546 * to the new filename. Old file is deleted.
1548 * Cache purging is done; checks for validity
1549 * and logging are caller's responsibility
1551 * @param Title $target New file name
1552 * @return FileRepoStatus
1554 function move( $target ) {
1555 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1556 return $this->readOnlyFatalStatus();
1559 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1560 $batch = new LocalFileMoveBatch( $this, $target );
1562 $this->lock(); // begin
1563 $batch->addCurrent();
1564 $archiveNames = $batch->addOlds();
1565 $status = $batch->execute();
1566 $this->unlock(); // done
1568 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1570 // Purge the source and target files...
1571 $oldTitleFile = wfLocalFile( $this->title
);
1572 $newTitleFile = wfLocalFile( $target );
1573 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1574 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1575 $this->getRepo()->getMasterDB()->onTransactionIdle(
1576 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1577 $oldTitleFile->purgeEverything();
1578 foreach ( $archiveNames as $archiveName ) {
1579 $oldTitleFile->purgeOldThumbnails( $archiveName );
1581 $newTitleFile->purgeEverything();
1585 if ( $status->isOK() ) {
1586 // Now switch the object
1587 $this->title
= $target;
1588 // Force regeneration of the name and hashpath
1589 unset( $this->name
);
1590 unset( $this->hashPath
);
1597 * Delete all versions of the file.
1599 * Moves the files into an archive directory (or deletes them)
1600 * and removes the database rows.
1602 * Cache purging is done; logging is caller's responsibility.
1604 * @param string $reason
1605 * @param bool $suppress
1606 * @return FileRepoStatus
1608 function delete( $reason, $suppress = false ) {
1609 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1610 return $this->readOnlyFatalStatus();
1613 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1615 $this->lock(); // begin
1616 $batch->addCurrent();
1617 # Get old version relative paths
1618 $archiveNames = $batch->addOlds();
1619 $status = $batch->execute();
1620 $this->unlock(); // done
1622 if ( $status->isOK() ) {
1623 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1626 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1627 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1629 $this->getRepo()->getMasterDB()->onTransactionIdle(
1630 function () use ( $file, $archiveNames ) {
1633 $file->purgeEverything();
1634 foreach ( $archiveNames as $archiveName ) {
1635 $file->purgeOldThumbnails( $archiveName );
1638 if ( $wgUseSquid ) {
1640 $purgeUrls = array();
1641 foreach ( $archiveNames as $archiveName ) {
1642 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1644 SquidUpdate
::purge( $purgeUrls );
1653 * Delete an old version of the file.
1655 * Moves the file into an archive directory (or deletes it)
1656 * and removes the database row.
1658 * Cache purging is done; logging is caller's responsibility.
1660 * @param string $archiveName
1661 * @param string $reason
1662 * @param bool $suppress
1663 * @throws MWException Exception on database or file store failure
1664 * @return FileRepoStatus
1666 function deleteOld( $archiveName, $reason, $suppress = false ) {
1668 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1669 return $this->readOnlyFatalStatus();
1672 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1674 $this->lock(); // begin
1675 $batch->addOld( $archiveName );
1676 $status = $batch->execute();
1677 $this->unlock(); // done
1679 $this->purgeOldThumbnails( $archiveName );
1680 if ( $status->isOK() ) {
1681 $this->purgeDescription();
1682 $this->purgeHistory();
1685 if ( $wgUseSquid ) {
1687 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1694 * Restore all or specified deleted revisions to the given file.
1695 * Permissions and logging are left to the caller.
1697 * May throw database exceptions on error.
1699 * @param array $versions Set of record ids of deleted items to restore,
1700 * or empty to restore all revisions.
1701 * @param bool $unsuppress
1702 * @return FileRepoStatus
1704 function restore( $versions = array(), $unsuppress = false ) {
1705 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1706 return $this->readOnlyFatalStatus();
1709 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1711 $this->lock(); // begin
1715 $batch->addIds( $versions );
1717 $status = $batch->execute();
1718 if ( $status->isGood() ) {
1719 $cleanupStatus = $batch->cleanup();
1720 $cleanupStatus->successCount
= 0;
1721 $cleanupStatus->failCount
= 0;
1722 $status->merge( $cleanupStatus );
1724 $this->unlock(); // done
1729 /** isMultipage inherited */
1730 /** pageCount inherited */
1731 /** scaleHeight inherited */
1732 /** getImageSize inherited */
1735 * Get the URL of the file description page.
1738 function getDescriptionUrl() {
1739 return $this->title
->getLocalURL();
1743 * Get the HTML text of the description page
1744 * This is not used by ImagePage for local files, since (among other things)
1745 * it skips the parser cache.
1747 * @param Language $lang What language to get description in (Optional)
1748 * @return bool|mixed
1750 function getDescriptionText( $lang = null ) {
1751 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1755 $content = $revision->getContent();
1759 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1761 return $pout->getText();
1765 * @param int $audience
1769 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1771 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1773 } elseif ( $audience == self
::FOR_THIS_USER
1774 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1778 return $this->description
;
1783 * @return bool|string
1785 function getTimestamp() {
1788 return $this->timestamp
;
1794 function getSha1() {
1796 // Initialise now if necessary
1797 if ( $this->sha1
== '' && $this->fileExists
) {
1798 $this->lock(); // begin
1800 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1801 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1802 $dbw = $this->repo
->getMasterDB();
1803 $dbw->update( 'image',
1804 array( 'img_sha1' => $this->sha1
),
1805 array( 'img_name' => $this->getName() ),
1807 $this->saveToCache();
1810 $this->unlock(); // done
1817 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1819 function isCacheable() {
1822 // If extra data (metadata) was not loaded then it must have been large
1823 return $this->extraDataLoaded
1824 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1828 * Start a transaction and lock the image for update
1829 * Increments a reference counter if the lock is already held
1830 * @throws MWException
1831 * @return bool True if the image exists, false otherwise
1834 $dbw = $this->repo
->getMasterDB();
1836 if ( !$this->locked
) {
1837 if ( !$dbw->trxLevel() ) {
1838 $dbw->begin( __METHOD__
);
1839 $this->lockedOwnTrx
= true;
1842 // Bug 54736: use simple lock to handle when the file does not exist.
1843 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1844 $cache = wfGetMainCache();
1845 $key = $this->getCacheKey();
1846 if ( !$cache->lock( $key, 5 ) ) {
1847 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1849 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1850 $cache->unlock( $key ); // release on commit
1854 return $dbw->selectField( 'image', '1',
1855 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1859 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1860 * the transaction and thereby releases the image lock.
1863 if ( $this->locked
) {
1865 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1866 $dbw = $this->repo
->getMasterDB();
1867 $dbw->commit( __METHOD__
);
1868 $this->lockedOwnTrx
= false;
1874 * Roll back the DB transaction and mark the image unlocked
1876 function unlockAndRollback() {
1877 $this->locked
= false;
1878 $dbw = $this->repo
->getMasterDB();
1879 $dbw->rollback( __METHOD__
);
1880 $this->lockedOwnTrx
= false;
1886 protected function readOnlyFatalStatus() {
1887 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1888 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1892 * Clean up any dangling locks
1894 function __destruct() {
1897 } // LocalFile class
1899 # ------------------------------------------------------------------------------
1902 * Helper class for file deletion
1903 * @ingroup FileAbstraction
1905 class LocalFileDeleteBatch
{
1906 /** @var LocalFile */
1913 private $srcRels = array();
1916 private $archiveUrls = array();
1918 /** @var array Items to be processed in the deletion batch */
1919 private $deletionBatch;
1921 /** @var bool Wether to suppress all suppressable fields when deleting */
1924 /** @var FileRepoStatus */
1929 * @param string $reason
1930 * @param bool $suppress
1932 function __construct( File
$file, $reason = '', $suppress = false ) {
1933 $this->file
= $file;
1934 $this->reason
= $reason;
1935 $this->suppress
= $suppress;
1936 $this->status
= $file->repo
->newGood();
1939 function addCurrent() {
1940 $this->srcRels
['.'] = $this->file
->getRel();
1944 * @param string $oldName
1946 function addOld( $oldName ) {
1947 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1948 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1952 * Add the old versions of the image to the batch
1953 * @return array List of archive names from old versions
1955 function addOlds() {
1956 $archiveNames = array();
1958 $dbw = $this->file
->repo
->getMasterDB();
1959 $result = $dbw->select( 'oldimage',
1960 array( 'oi_archive_name' ),
1961 array( 'oi_name' => $this->file
->getName() ),
1965 foreach ( $result as $row ) {
1966 $this->addOld( $row->oi_archive_name
);
1967 $archiveNames[] = $row->oi_archive_name
;
1970 return $archiveNames;
1976 function getOldRels() {
1977 if ( !isset( $this->srcRels
['.'] ) ) {
1978 $oldRels =& $this->srcRels
;
1979 $deleteCurrent = false;
1981 $oldRels = $this->srcRels
;
1982 unset( $oldRels['.'] );
1983 $deleteCurrent = true;
1986 return array( $oldRels, $deleteCurrent );
1992 protected function getHashes() {
1994 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1996 if ( $deleteCurrent ) {
1997 $hashes['.'] = $this->file
->getSha1();
2000 if ( count( $oldRels ) ) {
2001 $dbw = $this->file
->repo
->getMasterDB();
2002 $res = $dbw->select(
2004 array( 'oi_archive_name', 'oi_sha1' ),
2005 array( 'oi_archive_name' => array_keys( $oldRels ),
2006 'oi_name' => $this->file
->getName() ), // performance
2010 foreach ( $res as $row ) {
2011 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2012 // Get the hash from the file
2013 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2014 $props = $this->file
->repo
->getFileProps( $oldUrl );
2016 if ( $props['fileExists'] ) {
2017 // Upgrade the oldimage row
2018 $dbw->update( 'oldimage',
2019 array( 'oi_sha1' => $props['sha1'] ),
2020 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2022 $hashes[$row->oi_archive_name
] = $props['sha1'];
2024 $hashes[$row->oi_archive_name
] = false;
2027 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2032 $missing = array_diff_key( $this->srcRels
, $hashes );
2034 foreach ( $missing as $name => $rel ) {
2035 $this->status
->error( 'filedelete-old-unregistered', $name );
2038 foreach ( $hashes as $name => $hash ) {
2040 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2041 unset( $hashes[$name] );
2048 function doDBInserts() {
2051 $dbw = $this->file
->repo
->getMasterDB();
2052 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2053 $encUserId = $dbw->addQuotes( $wgUser->getId() );
2054 $encReason = $dbw->addQuotes( $this->reason
);
2055 $encGroup = $dbw->addQuotes( 'deleted' );
2056 $ext = $this->file
->getExtension();
2057 $dotExt = $ext === '' ?
'' : ".$ext";
2058 $encExt = $dbw->addQuotes( $dotExt );
2059 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2061 // Bitfields to further suppress the content
2062 if ( $this->suppress
) {
2064 // This should be 15...
2065 $bitfield |
= Revision
::DELETED_TEXT
;
2066 $bitfield |
= Revision
::DELETED_COMMENT
;
2067 $bitfield |
= Revision
::DELETED_USER
;
2068 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2070 $bitfield = 'oi_deleted';
2073 if ( $deleteCurrent ) {
2074 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2075 $where = array( 'img_name' => $this->file
->getName() );
2076 $dbw->insertSelect( 'filearchive', 'image',
2078 'fa_storage_group' => $encGroup,
2079 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
2080 'fa_deleted_user' => $encUserId,
2081 'fa_deleted_timestamp' => $encTimestamp,
2082 'fa_deleted_reason' => $encReason,
2083 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2085 'fa_name' => 'img_name',
2086 'fa_archive_name' => 'NULL',
2087 'fa_size' => 'img_size',
2088 'fa_width' => 'img_width',
2089 'fa_height' => 'img_height',
2090 'fa_metadata' => 'img_metadata',
2091 'fa_bits' => 'img_bits',
2092 'fa_media_type' => 'img_media_type',
2093 'fa_major_mime' => 'img_major_mime',
2094 'fa_minor_mime' => 'img_minor_mime',
2095 'fa_description' => 'img_description',
2096 'fa_user' => 'img_user',
2097 'fa_user_text' => 'img_user_text',
2098 'fa_timestamp' => 'img_timestamp',
2099 'fa_sha1' => 'img_sha1',
2100 ), $where, __METHOD__
);
2103 if ( count( $oldRels ) ) {
2104 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2106 'oi_name' => $this->file
->getName(),
2107 'oi_archive_name' => array_keys( $oldRels ) );
2108 $dbw->insertSelect( 'filearchive', 'oldimage',
2110 'fa_storage_group' => $encGroup,
2111 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
2112 'fa_deleted_user' => $encUserId,
2113 'fa_deleted_timestamp' => $encTimestamp,
2114 'fa_deleted_reason' => $encReason,
2115 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2117 'fa_name' => 'oi_name',
2118 'fa_archive_name' => 'oi_archive_name',
2119 'fa_size' => 'oi_size',
2120 'fa_width' => 'oi_width',
2121 'fa_height' => 'oi_height',
2122 'fa_metadata' => 'oi_metadata',
2123 'fa_bits' => 'oi_bits',
2124 'fa_media_type' => 'oi_media_type',
2125 'fa_major_mime' => 'oi_major_mime',
2126 'fa_minor_mime' => 'oi_minor_mime',
2127 'fa_description' => 'oi_description',
2128 'fa_user' => 'oi_user',
2129 'fa_user_text' => 'oi_user_text',
2130 'fa_timestamp' => 'oi_timestamp',
2131 'fa_sha1' => 'oi_sha1',
2132 ), $where, __METHOD__
);
2136 function doDBDeletes() {
2137 $dbw = $this->file
->repo
->getMasterDB();
2138 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2140 if ( count( $oldRels ) ) {
2141 $dbw->delete( 'oldimage',
2143 'oi_name' => $this->file
->getName(),
2144 'oi_archive_name' => array_keys( $oldRels )
2148 if ( $deleteCurrent ) {
2149 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2154 * Run the transaction
2155 * @return FileRepoStatus
2157 function execute() {
2158 wfProfileIn( __METHOD__
);
2160 $this->file
->lock();
2161 // Leave private files alone
2162 $privateFiles = array();
2163 list( $oldRels, ) = $this->getOldRels();
2164 $dbw = $this->file
->repo
->getMasterDB();
2166 if ( !empty( $oldRels ) ) {
2167 $res = $dbw->select( 'oldimage',
2168 array( 'oi_archive_name' ),
2169 array( 'oi_name' => $this->file
->getName(),
2170 'oi_archive_name' => array_keys( $oldRels ),
2171 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2174 foreach ( $res as $row ) {
2175 $privateFiles[$row->oi_archive_name
] = 1;
2178 // Prepare deletion batch
2179 $hashes = $this->getHashes();
2180 $this->deletionBatch
= array();
2181 $ext = $this->file
->getExtension();
2182 $dotExt = $ext === '' ?
'' : ".$ext";
2184 foreach ( $this->srcRels
as $name => $srcRel ) {
2185 // Skip files that have no hash (missing source).
2186 // Keep private files where they are.
2187 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2188 $hash = $hashes[$name];
2189 $key = $hash . $dotExt;
2190 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2191 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2195 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2196 // We acquire this lock by running the inserts now, before the file operations.
2198 // This potentially has poor lock contention characteristics -- an alternative
2199 // scheme would be to insert stub filearchive entries with no fa_name and commit
2200 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2201 $this->doDBInserts();
2203 // Removes non-existent file from the batch, so we don't get errors.
2204 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2206 // Execute the file deletion batch
2207 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2209 if ( !$status->isGood() ) {
2210 $this->status
->merge( $status );
2213 if ( !$this->status
->isOK() ) {
2214 // Critical file deletion error
2215 // Roll back inserts, release lock and abort
2216 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2217 $this->file
->unlockAndRollback();
2218 wfProfileOut( __METHOD__
);
2220 return $this->status
;
2223 // Delete image/oldimage rows
2224 $this->doDBDeletes();
2226 // Commit and return
2227 $this->file
->unlock();
2228 wfProfileOut( __METHOD__
);
2230 return $this->status
;
2234 * Removes non-existent files from a deletion batch.
2235 * @param array $batch
2238 function removeNonexistentFiles( $batch ) {
2239 $files = $newBatch = array();
2241 foreach ( $batch as $batchItem ) {
2242 list( $src, ) = $batchItem;
2243 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2246 $result = $this->file
->repo
->fileExistsBatch( $files );
2248 foreach ( $batch as $batchItem ) {
2249 if ( $result[$batchItem[0]] ) {
2250 $newBatch[] = $batchItem;
2258 # ------------------------------------------------------------------------------
2261 * Helper class for file undeletion
2262 * @ingroup FileAbstraction
2264 class LocalFileRestoreBatch
{
2265 /** @var LocalFile */
2268 /** @var array List of file IDs to restore */
2269 private $cleanupBatch;
2271 /** @var array List of file IDs to restore */
2274 /** @var bool Add all revisions of the file */
2277 /** @var bool Wether to remove all settings for suppressed fields */
2278 private $unsuppress = false;
2282 * @param bool $unsuppress
2284 function __construct( File
$file, $unsuppress = false ) {
2285 $this->file
= $file;
2286 $this->cleanupBatch
= $this->ids
= array();
2287 $this->ids
= array();
2288 $this->unsuppress
= $unsuppress;
2294 function addId( $fa_id ) {
2295 $this->ids
[] = $fa_id;
2299 * Add a whole lot of files by ID
2301 function addIds( $ids ) {
2302 $this->ids
= array_merge( $this->ids
, $ids );
2306 * Add all revisions of the file
2313 * Run the transaction, except the cleanup batch.
2314 * The cleanup batch should be run in a separate transaction, because it locks different
2315 * rows and there's no need to keep the image row locked while it's acquiring those locks
2316 * The caller may have its own transaction open.
2317 * So we save the batch and let the caller call cleanup()
2318 * @return FileRepoStatus
2320 function execute() {
2323 if ( !$this->all
&& !$this->ids
) {
2325 return $this->file
->repo
->newGood();
2328 $exists = $this->file
->lock();
2329 $dbw = $this->file
->repo
->getMasterDB();
2330 $status = $this->file
->repo
->newGood();
2332 // Fetch all or selected archived revisions for the file,
2333 // sorted from the most recent to the oldest.
2334 $conditions = array( 'fa_name' => $this->file
->getName() );
2336 if ( !$this->all
) {
2337 $conditions['fa_id'] = $this->ids
;
2340 $result = $dbw->select(
2342 ArchivedFile
::selectFields(),
2345 array( 'ORDER BY' => 'fa_timestamp DESC' )
2348 $idsPresent = array();
2349 $storeBatch = array();
2350 $insertBatch = array();
2351 $insertCurrent = false;
2352 $deleteIds = array();
2354 $archiveNames = array();
2356 foreach ( $result as $row ) {
2357 $idsPresent[] = $row->fa_id
;
2359 if ( $row->fa_name
!= $this->file
->getName() ) {
2360 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2361 $status->failCount++
;
2365 if ( $row->fa_storage_key
== '' ) {
2366 // Revision was missing pre-deletion
2367 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2368 $status->failCount++
;
2372 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2373 $row->fa_storage_key
;
2374 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2376 if ( isset( $row->fa_sha1
) ) {
2377 $sha1 = $row->fa_sha1
;
2379 // old row, populate from key
2380 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2384 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2385 $sha1 = substr( $sha1, 1 );
2388 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2389 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2390 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2391 ||
is_null( $row->fa_metadata
)
2393 // Refresh our metadata
2394 // Required for a new current revision; nice for older ones too. :)
2395 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2398 'minor_mime' => $row->fa_minor_mime
,
2399 'major_mime' => $row->fa_major_mime
,
2400 'media_type' => $row->fa_media_type
,
2401 'metadata' => $row->fa_metadata
2405 if ( $first && !$exists ) {
2406 // This revision will be published as the new current version
2407 $destRel = $this->file
->getRel();
2408 $insertCurrent = array(
2409 'img_name' => $row->fa_name
,
2410 'img_size' => $row->fa_size
,
2411 'img_width' => $row->fa_width
,
2412 'img_height' => $row->fa_height
,
2413 'img_metadata' => $props['metadata'],
2414 'img_bits' => $row->fa_bits
,
2415 'img_media_type' => $props['media_type'],
2416 'img_major_mime' => $props['major_mime'],
2417 'img_minor_mime' => $props['minor_mime'],
2418 'img_description' => $row->fa_description
,
2419 'img_user' => $row->fa_user
,
2420 'img_user_text' => $row->fa_user_text
,
2421 'img_timestamp' => $row->fa_timestamp
,
2425 // The live (current) version cannot be hidden!
2426 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2427 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2428 $this->cleanupBatch
[] = $row->fa_storage_key
;
2431 $archiveName = $row->fa_archive_name
;
2433 if ( $archiveName == '' ) {
2434 // This was originally a current version; we
2435 // have to devise a new archive name for it.
2436 // Format is <timestamp of archiving>!<name>
2437 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2440 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2442 } while ( isset( $archiveNames[$archiveName] ) );
2445 $archiveNames[$archiveName] = true;
2446 $destRel = $this->file
->getArchiveRel( $archiveName );
2447 $insertBatch[] = array(
2448 'oi_name' => $row->fa_name
,
2449 'oi_archive_name' => $archiveName,
2450 'oi_size' => $row->fa_size
,
2451 'oi_width' => $row->fa_width
,
2452 'oi_height' => $row->fa_height
,
2453 'oi_bits' => $row->fa_bits
,
2454 'oi_description' => $row->fa_description
,
2455 'oi_user' => $row->fa_user
,
2456 'oi_user_text' => $row->fa_user_text
,
2457 'oi_timestamp' => $row->fa_timestamp
,
2458 'oi_metadata' => $props['metadata'],
2459 'oi_media_type' => $props['media_type'],
2460 'oi_major_mime' => $props['major_mime'],
2461 'oi_minor_mime' => $props['minor_mime'],
2462 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2463 'oi_sha1' => $sha1 );
2466 $deleteIds[] = $row->fa_id
;
2468 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2469 // private files can stay where they are
2470 $status->successCount++
;
2472 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2473 $this->cleanupBatch
[] = $row->fa_storage_key
;
2481 // Add a warning to the status object for missing IDs
2482 $missingIds = array_diff( $this->ids
, $idsPresent );
2484 foreach ( $missingIds as $id ) {
2485 $status->error( 'undelete-missing-filearchive', $id );
2488 // Remove missing files from batch, so we don't get errors when undeleting them
2489 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2491 // Run the store batch
2492 // Use the OVERWRITE_SAME flag to smooth over a common error
2493 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2494 $status->merge( $storeStatus );
2496 if ( !$status->isGood() ) {
2497 // Even if some files could be copied, fail entirely as that is the
2498 // easiest thing to do without data loss
2499 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2500 $status->ok
= false;
2501 $this->file
->unlock();
2506 // Run the DB updates
2507 // Because we have locked the image row, key conflicts should be rare.
2508 // If they do occur, we can roll back the transaction at this time with
2509 // no data loss, but leaving unregistered files scattered throughout the
2511 // This is not ideal, which is why it's important to lock the image row.
2512 if ( $insertCurrent ) {
2513 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2516 if ( $insertBatch ) {
2517 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2521 $dbw->delete( 'filearchive',
2522 array( 'fa_id' => $deleteIds ),
2526 // If store batch is empty (all files are missing), deletion is to be considered successful
2527 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2529 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2531 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2533 $this->file
->purgeEverything();
2535 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2536 $this->file
->purgeDescription();
2537 $this->file
->purgeHistory();
2541 $this->file
->unlock();
2547 * Removes non-existent files from a store batch.
2548 * @param array $triplets
2551 function removeNonexistentFiles( $triplets ) {
2552 $files = $filteredTriplets = array();
2553 foreach ( $triplets as $file ) {
2554 $files[$file[0]] = $file[0];
2557 $result = $this->file
->repo
->fileExistsBatch( $files );
2559 foreach ( $triplets as $file ) {
2560 if ( $result[$file[0]] ) {
2561 $filteredTriplets[] = $file;
2565 return $filteredTriplets;
2569 * Removes non-existent files from a cleanup batch.
2570 * @param array $batch
2573 function removeNonexistentFromCleanup( $batch ) {
2574 $files = $newBatch = array();
2575 $repo = $this->file
->repo
;
2577 foreach ( $batch as $file ) {
2578 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2579 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2582 $result = $repo->fileExistsBatch( $files );
2584 foreach ( $batch as $file ) {
2585 if ( $result[$file] ) {
2586 $newBatch[] = $file;
2594 * Delete unused files in the deleted zone.
2595 * This should be called from outside the transaction in which execute() was called.
2596 * @return FileRepoStatus
2598 function cleanup() {
2599 if ( !$this->cleanupBatch
) {
2600 return $this->file
->repo
->newGood();
2603 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2605 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2611 * Cleanup a failed batch. The batch was only partially successful, so
2612 * rollback by removing all items that were succesfully copied.
2614 * @param Status $storeStatus
2615 * @param array $storeBatch
2617 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2618 $cleanupBatch = array();
2620 foreach ( $storeStatus->success
as $i => $success ) {
2621 // Check if this item of the batch was successfully copied
2623 // Item was successfully copied and needs to be removed again
2624 // Extract ($dstZone, $dstRel) from the batch
2625 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2628 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2632 # ------------------------------------------------------------------------------
2635 * Helper class for file movement
2636 * @ingroup FileAbstraction
2638 class LocalFileMoveBatch
{
2639 /** @var LocalFile */
2649 protected $oldCount;
2653 /** @var DatabaseBase */
2658 * @param Title $target
2660 function __construct( File
$file, Title
$target ) {
2661 $this->file
= $file;
2662 $this->target
= $target;
2663 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2664 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2665 $this->oldName
= $this->file
->getName();
2666 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2667 $this->oldRel
= $this->oldHash
. $this->oldName
;
2668 $this->newRel
= $this->newHash
. $this->newName
;
2669 $this->db
= $file->getRepo()->getMasterDb();
2673 * Add the current image to the batch
2675 function addCurrent() {
2676 $this->cur
= array( $this->oldRel
, $this->newRel
);
2680 * Add the old versions of the image to the batch
2681 * @return array List of archive names from old versions
2683 function addOlds() {
2684 $archiveBase = 'archive';
2685 $this->olds
= array();
2686 $this->oldCount
= 0;
2687 $archiveNames = array();
2689 $result = $this->db
->select( 'oldimage',
2690 array( 'oi_archive_name', 'oi_deleted' ),
2691 array( 'oi_name' => $this->oldName
),
2695 foreach ( $result as $row ) {
2696 $archiveNames[] = $row->oi_archive_name
;
2697 $oldName = $row->oi_archive_name
;
2698 $bits = explode( '!', $oldName, 2 );
2700 if ( count( $bits ) != 2 ) {
2701 wfDebug( "Old file name missing !: '$oldName' \n" );
2705 list( $timestamp, $filename ) = $bits;
2707 if ( $this->oldName
!= $filename ) {
2708 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2714 // Do we want to add those to oldCount?
2715 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2719 $this->olds
[] = array(
2720 "{$archiveBase}/{$this->oldHash}{$oldName}",
2721 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2725 return $archiveNames;
2730 * @return FileRepoStatus
2732 function execute() {
2733 $repo = $this->file
->repo
;
2734 $status = $repo->newGood();
2736 $triplets = $this->getMoveTriplets();
2737 $triplets = $this->removeNonexistentFiles( $triplets );
2738 $destFile = wfLocalFile( $this->target
);
2740 $this->file
->lock(); // begin
2741 $destFile->lock(); // quickly fail if destination is not available
2742 // Rename the file versions metadata in the DB.
2743 // This implicitly locks the destination file, which avoids race conditions.
2744 // If we moved the files from A -> C before DB updates, another process could
2745 // move files from B -> C at this point, causing storeBatch() to fail and thus
2746 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2747 $statusDb = $this->doDBUpdates();
2748 if ( !$statusDb->isGood() ) {
2749 $this->file
->unlockAndRollback();
2750 $statusDb->ok
= false;
2754 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2755 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2757 // Copy the files into their new location.
2758 // If a prior process fataled copying or cleaning up files we tolerate any
2759 // of the existing files if they are identical to the ones being stored.
2760 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2761 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2762 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2763 if ( !$statusMove->isGood() ) {
2764 // Delete any files copied over (while the destination is still locked)
2765 $this->cleanupTarget( $triplets );
2766 $this->file
->unlockAndRollback(); // unlocks the destination
2767 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2768 $statusMove->ok
= false;
2772 $destFile->unlock();
2773 $this->file
->unlock(); // done
2775 // Everything went ok, remove the source files
2776 $this->cleanupSource( $triplets );
2778 $status->merge( $statusDb );
2779 $status->merge( $statusMove );
2785 * Do the database updates and return a new FileRepoStatus indicating how
2786 * many rows where updated.
2788 * @return FileRepoStatus
2790 function doDBUpdates() {
2791 $repo = $this->file
->repo
;
2792 $status = $repo->newGood();
2795 // Update current image
2798 array( 'img_name' => $this->newName
),
2799 array( 'img_name' => $this->oldName
),
2803 if ( $dbw->affectedRows() ) {
2804 $status->successCount++
;
2806 $status->failCount++
;
2807 $status->fatal( 'imageinvalidfilename' );
2812 // Update old images
2816 'oi_name' => $this->newName
,
2817 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2818 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2820 array( 'oi_name' => $this->oldName
),
2824 $affected = $dbw->affectedRows();
2825 $total = $this->oldCount
;
2826 $status->successCount +
= $affected;
2827 // Bug 34934: $total is based on files that actually exist.
2828 // There may be more DB rows than such files, in which case $affected
2829 // can be greater than $total. We use max() to avoid negatives here.
2830 $status->failCount +
= max( 0, $total - $affected );
2831 if ( $status->failCount
) {
2832 $status->error( 'imageinvalidfilename' );
2839 * Generate triplets for FileRepo::storeBatch().
2842 function getMoveTriplets() {
2843 $moves = array_merge( array( $this->cur
), $this->olds
);
2844 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2846 foreach ( $moves as $move ) {
2847 // $move: (oldRelativePath, newRelativePath)
2848 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2849 $triplets[] = array( $srcUrl, 'public', $move[1] );
2852 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2860 * Removes non-existent files from move batch.
2861 * @param array $triplets
2864 function removeNonexistentFiles( $triplets ) {
2867 foreach ( $triplets as $file ) {
2868 $files[$file[0]] = $file[0];
2871 $result = $this->file
->repo
->fileExistsBatch( $files );
2872 $filteredTriplets = array();
2874 foreach ( $triplets as $file ) {
2875 if ( $result[$file[0]] ) {
2876 $filteredTriplets[] = $file;
2878 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2882 return $filteredTriplets;
2886 * Cleanup a partially moved array of triplets by deleting the target
2887 * files. Called if something went wrong half way.
2889 function cleanupTarget( $triplets ) {
2890 // Create dest pairs from the triplets
2892 foreach ( $triplets as $triplet ) {
2893 // $triplet: (old source virtual URL, dst zone, dest rel)
2894 $pairs[] = array( $triplet[1], $triplet[2] );
2897 $this->file
->repo
->cleanupBatch( $pairs );
2901 * Cleanup a fully moved array of triplets by deleting the source files.
2902 * Called at the end of the move process if everything else went ok.
2904 function cleanupSource( $triplets ) {
2905 // Create source file names from the triplets
2907 foreach ( $triplets as $triplet ) {
2908 $files[] = $triplet[0];
2911 $this->file
->repo
->cleanupBatch( $files );