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
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.
211 function __construct( $title, $repo ) {
212 parent
::__construct( $title, $repo );
214 $this->metadata
= '';
215 $this->historyLine
= 0;
216 $this->historyRes
= null;
217 $this->dataLoaded
= false;
218 $this->extraDataLoaded
= false;
220 $this->assertRepoDefined();
221 $this->assertTitleDefined();
225 * Get the memcached key for the main data for this file, or false if
226 * there is no access to the shared cache.
229 function getCacheKey() {
230 $hashedName = md5( $this->getName() );
232 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
236 * Try to load file metadata from memcached. Returns true on success.
239 function loadFromCache() {
242 wfProfileIn( __METHOD__
);
243 $this->dataLoaded
= false;
244 $this->extraDataLoaded
= false;
245 $key = $this->getCacheKey();
248 wfProfileOut( __METHOD__
);
253 $cachedValues = $wgMemc->get( $key );
255 // Check if the key existed and belongs to this version of MediaWiki
256 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
257 wfDebug( "Pulling file metadata from cache key $key\n" );
258 $this->fileExists
= $cachedValues['fileExists'];
259 if ( $this->fileExists
) {
260 $this->setProps( $cachedValues );
262 $this->dataLoaded
= true;
263 $this->extraDataLoaded
= true;
264 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
265 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
269 if ( $this->dataLoaded
) {
270 wfIncrStats( 'image_cache_hit' );
272 wfIncrStats( 'image_cache_miss' );
275 wfProfileOut( __METHOD__
);
277 return $this->dataLoaded
;
281 * Save the file metadata to memcached
283 function saveToCache() {
287 $key = $this->getCacheKey();
293 $fields = $this->getCacheFields( '' );
294 $cache = array( 'version' => MW_FILE_VERSION
);
295 $cache['fileExists'] = $this->fileExists
;
297 if ( $this->fileExists
) {
298 foreach ( $fields as $field ) {
299 $cache[$field] = $this->$field;
303 // Strip off excessive entries from the subset of fields that can become large.
304 // If the cache value gets to large it will not fit in memcached and nothing will
305 // get cached at all, causing master queries for any file access.
306 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
307 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
308 unset( $cache[$field] ); // don't let the value get too big
312 // Cache presence for 1 week and negatives for 1 day
313 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
317 * Load metadata from the file itself
319 function loadFromFile() {
320 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
321 $this->setProps( $props );
325 * @param $prefix string
328 function getCacheFields( $prefix = 'img_' ) {
329 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
330 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
331 'user_text', 'description' );
332 static $results = array();
334 if ( $prefix == '' ) {
338 if ( !isset( $results[$prefix] ) ) {
339 $prefixedFields = array();
340 foreach ( $fields as $field ) {
341 $prefixedFields[] = $prefix . $field;
343 $results[$prefix] = $prefixedFields;
346 return $results[$prefix];
350 * @param string $prefix
353 function getLazyCacheFields( $prefix = 'img_' ) {
354 static $fields = array( 'metadata' );
355 static $results = array();
357 if ( $prefix == '' ) {
361 if ( !isset( $results[$prefix] ) ) {
362 $prefixedFields = array();
363 foreach ( $fields as $field ) {
364 $prefixedFields[] = $prefix . $field;
366 $results[$prefix] = $prefixedFields;
369 return $results[$prefix];
373 * Load file metadata from the DB
375 function loadFromDB() {
376 # Polymorphic function name to distinguish foreign and local fetches
377 $fname = get_class( $this ) . '::' . __FUNCTION__
;
378 wfProfileIn( $fname );
380 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
381 $this->dataLoaded
= true;
382 $this->extraDataLoaded
= true;
384 $dbr = $this->repo
->getMasterDB();
385 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
386 array( 'img_name' => $this->getName() ), $fname );
389 $this->loadFromRow( $row );
391 $this->fileExists
= false;
394 wfProfileOut( $fname );
398 * Load lazy file metadata from the DB.
399 * This covers fields that are sometimes not cached.
401 protected function loadExtraFromDB() {
402 # Polymorphic function name to distinguish foreign and local fetches
403 $fname = get_class( $this ) . '::' . __FUNCTION__
;
404 wfProfileIn( $fname );
406 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
407 $this->extraDataLoaded
= true;
409 $dbr = $this->repo
->getSlaveDB();
410 // In theory the file could have just been renamed/deleted...oh well
411 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
412 array( 'img_name' => $this->getName() ), $fname );
414 if ( !$row ) { // fallback to master
415 $dbr = $this->repo
->getMasterDB();
416 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
417 array( 'img_name' => $this->getName() ), $fname );
421 foreach ( $this->unprefixRow( $row, 'img_' ) as $name => $value ) {
422 $this->$name = $value;
425 wfProfileOut( $fname );
426 throw new MWException( "Could not find data for image '{$this->getName()}'." );
429 wfProfileOut( $fname );
433 * @param array $row Row
434 * @param string $prefix
435 * @throws MWException
438 protected function unprefixRow( $row, $prefix = 'img_' ) {
439 $array = (array)$row;
440 $prefixLength = strlen( $prefix );
442 // Sanity check prefix once
443 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
444 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
448 foreach ( $array as $name => $value ) {
449 $decoded[substr( $name, $prefixLength )] = $value;
456 * Decode a row from the database (either object or array) to an array
457 * with timestamps and MIME types decoded, and the field prefix removed.
459 * @param $prefix string
460 * @throws MWException
463 function decodeRow( $row, $prefix = 'img_' ) {
464 $decoded = $this->unprefixRow( $row, $prefix );
466 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
468 if ( empty( $decoded['major_mime'] ) ) {
469 $decoded['mime'] = 'unknown/unknown';
471 if ( !$decoded['minor_mime'] ) {
472 $decoded['minor_mime'] = 'unknown';
474 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
477 # Trim zero padding from char/binary field
478 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
484 * Load file metadata from a DB result row
486 function loadFromRow( $row, $prefix = 'img_' ) {
487 $this->dataLoaded
= true;
488 $this->extraDataLoaded
= true;
490 $array = $this->decodeRow( $row, $prefix );
492 foreach ( $array as $name => $value ) {
493 $this->$name = $value;
496 $this->fileExists
= true;
497 $this->maybeUpgradeRow();
501 * Load file metadata from cache or DB, unless already loaded
502 * @param integer $flags
504 function load( $flags = 0 ) {
505 if ( !$this->dataLoaded
) {
506 if ( !$this->loadFromCache() ) {
508 $this->saveToCache();
510 $this->dataLoaded
= true;
512 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
513 $this->loadExtraFromDB();
518 * Upgrade a row if it needs it
520 function maybeUpgradeRow() {
521 global $wgUpdateCompatibleMetadata;
522 if ( wfReadOnly() ) {
526 if ( is_null( $this->media_type
) ||
527 $this->mime
== 'image/svg'
530 $this->upgraded
= true;
532 $handler = $this->getHandler();
534 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
535 if ( $validity === MediaHandler
::METADATA_BAD
536 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
539 $this->upgraded
= true;
545 function getUpgraded() {
546 return $this->upgraded
;
550 * Fix assorted version-related problems with the image row by reloading it from the file
552 function upgradeRow() {
553 wfProfileIn( __METHOD__
);
555 $this->lock(); // begin
557 $this->loadFromFile();
559 # Don't destroy file info of missing files
560 if ( !$this->fileExists
) {
561 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
562 wfProfileOut( __METHOD__
);
567 $dbw = $this->repo
->getMasterDB();
568 list( $major, $minor ) = self
::splitMime( $this->mime
);
570 if ( wfReadOnly() ) {
571 wfProfileOut( __METHOD__
);
575 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
577 $dbw->update( 'image',
579 'img_size' => $this->size
, // sanity
580 'img_width' => $this->width
,
581 'img_height' => $this->height
,
582 'img_bits' => $this->bits
,
583 'img_media_type' => $this->media_type
,
584 'img_major_mime' => $major,
585 'img_minor_mime' => $minor,
586 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
587 'img_sha1' => $this->sha1
,
589 array( 'img_name' => $this->getName() ),
593 $this->saveToCache();
595 $this->unlock(); // done
597 wfProfileOut( __METHOD__
);
601 * Set properties in this object to be equal to those given in the
602 * associative array $info. Only cacheable fields can be set.
603 * All fields *must* be set in $info except for getLazyCacheFields().
605 * If 'mime' is given, it will be split into major_mime/minor_mime.
606 * If major_mime/minor_mime are given, $this->mime will also be set.
608 function setProps( $info ) {
609 $this->dataLoaded
= true;
610 $fields = $this->getCacheFields( '' );
611 $fields[] = 'fileExists';
613 foreach ( $fields as $field ) {
614 if ( isset( $info[$field] ) ) {
615 $this->$field = $info[$field];
619 // Fix up mime fields
620 if ( isset( $info['major_mime'] ) ) {
621 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
622 } elseif ( isset( $info['mime'] ) ) {
623 $this->mime
= $info['mime'];
624 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
628 /** splitMime inherited */
629 /** getName inherited */
630 /** getTitle inherited */
631 /** getURL inherited */
632 /** getViewURL inherited */
633 /** getPath inherited */
634 /** isVisible inhereted */
639 function isMissing() {
640 if ( $this->missing
=== null ) {
641 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
642 $this->missing
= !$fileExists;
645 return $this->missing
;
649 * Return the width of the image
654 public function getWidth( $page = 1 ) {
657 if ( $this->isMultipage() ) {
658 $handler = $this->getHandler();
662 $dim = $handler->getPageDimensions( $this, $page );
664 return $dim['width'];
666 // For non-paged media, the false goes through an
667 // intval, turning failure into 0, so do same here.
676 * Return the height of the image
681 public function getHeight( $page = 1 ) {
684 if ( $this->isMultipage() ) {
685 $handler = $this->getHandler();
689 $dim = $handler->getPageDimensions( $this, $page );
691 return $dim['height'];
693 // For non-paged media, the false goes through an
694 // intval, turning failure into 0, so do same here.
698 return $this->height
;
703 * Returns ID or name of user who uploaded the file
705 * @param string $type 'text' or 'id'
708 function getUser( $type = 'text' ) {
711 if ( $type == 'text' ) {
712 return $this->user_text
;
713 } elseif ( $type == 'id' ) {
719 * Get handler-specific metadata
722 function getMetadata() {
723 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
724 return $this->metadata
;
730 function getBitDepth() {
737 * Returns the size of the image file, in bytes
740 public function getSize() {
747 * Returns the mime type of the file.
750 function getMimeType() {
757 * Returns the type of the media in the file.
758 * Use the value returned by this function with the MEDIATYPE_xxx constants.
761 function getMediaType() {
764 return $this->media_type
;
767 /** canRender inherited */
768 /** mustRender inherited */
769 /** allowInlineDisplay inherited */
770 /** isSafeFile inherited */
771 /** isTrustedFile inherited */
774 * Returns true if the file exists on disk.
775 * @return bool Whether file exist on disk.
777 public function exists() {
780 return $this->fileExists
;
783 /** getTransformScript inherited */
784 /** getUnscaledThumb inherited */
785 /** thumbName inherited */
786 /** createThumb inherited */
787 /** transform inherited */
790 * Fix thumbnail files from 1.4 or before, with extreme prejudice
791 * @todo Do we still care about this? Perhaps a maintenance script
792 * can be made instead. Enabling this code results in a serious
793 * RTT regression for wikis without 404 handling.
795 function migrateThumbFile( $thumbName ) {
796 /* Old code for bug 2532
797 $thumbDir = $this->getThumbPath();
798 $thumbPath = "$thumbDir/$thumbName";
799 if ( is_dir( $thumbPath ) ) {
800 // Directory where file should be
801 // This happened occasionally due to broken migration code in 1.5
802 // Rename to broken-*
803 for ( $i = 0; $i < 100; $i++ ) {
804 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
805 if ( !file_exists( $broken ) ) {
806 rename( $thumbPath, $broken );
810 // Doesn't exist anymore
815 if ( $this->repo->fileExists( $thumbDir ) ) {
816 // Delete file where directory should be
817 $this->repo->cleanupBatch( array( $thumbDir ) );
822 /** getHandler inherited */
823 /** iconThumb inherited */
824 /** getLastError inherited */
827 * Get all thumbnail names previously generated for this file
828 * @param string|bool $archiveName Name of an archive file, default false
829 * @return array first element is the base dir, then files in that base dir.
831 function getThumbnails( $archiveName = false ) {
832 if ( $archiveName ) {
833 $dir = $this->getArchiveThumbPath( $archiveName );
835 $dir = $this->getThumbPath();
838 $backend = $this->repo
->getBackend();
839 $files = array( $dir );
841 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
842 foreach ( $iterator as $file ) {
845 } catch ( FileBackendError
$e ) {
846 } // suppress (bug 54674)
852 * Refresh metadata in memcached, but don't touch thumbnails or squid
854 function purgeMetadataCache() {
856 $this->saveToCache();
857 $this->purgeHistory();
861 * Purge the shared history (OldLocalFile) cache.
863 * @note This used to purge old thumbnails as well.
865 function purgeHistory() {
868 $hashedName = md5( $this->getName() );
869 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
872 $wgMemc->delete( $oldKey );
877 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
879 * @param array $options An array potentially with the key forThumbRefresh.
881 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
883 function purgeCache( $options = array() ) {
884 wfProfileIn( __METHOD__
);
885 // Refresh metadata cache
886 $this->purgeMetadataCache();
889 $this->purgeThumbnails( $options );
891 // Purge squid cache for this file
892 SquidUpdate
::purge( array( $this->getURL() ) );
893 wfProfileOut( __METHOD__
);
897 * Delete cached transformed files for an archived version only.
898 * @param string $archiveName Name of the archived file
900 function purgeOldThumbnails( $archiveName ) {
902 wfProfileIn( __METHOD__
);
904 // Get a list of old thumbnails and URLs
905 $files = $this->getThumbnails( $archiveName );
906 $dir = array_shift( $files );
907 $this->purgeThumbList( $dir, $files );
909 // Purge any custom thumbnail caches
910 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
915 foreach ( $files as $file ) {
916 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
918 SquidUpdate
::purge( $urls );
921 wfProfileOut( __METHOD__
);
925 * Delete cached transformed files for the current version only.
927 function purgeThumbnails( $options = array() ) {
929 wfProfileIn( __METHOD__
);
932 $files = $this->getThumbnails();
933 // Always purge all files from squid regardless of handler filters
936 foreach ( $files as $file ) {
937 $urls[] = $this->getThumbUrl( $file );
939 array_shift( $urls ); // don't purge directory
942 // Give media handler a chance to filter the file purge list
943 if ( !empty( $options['forThumbRefresh'] ) ) {
944 $handler = $this->getHandler();
946 $handler->filterThumbnailPurgeList( $files, $options );
950 $dir = array_shift( $files );
951 $this->purgeThumbList( $dir, $files );
953 // Purge any custom thumbnail caches
954 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
958 SquidUpdate
::purge( $urls );
961 wfProfileOut( __METHOD__
);
965 * Delete a list of thumbnails visible at urls
966 * @param string $dir Base dir of the files.
967 * @param array $files Array of strings: relative filenames (to $dir)
969 protected function purgeThumbList( $dir, $files ) {
970 $fileListDebug = strtr(
971 var_export( $files, true ),
974 wfDebug( __METHOD__
. ": $fileListDebug\n" );
976 $purgeList = array();
977 foreach ( $files as $file ) {
978 # Check that the base file name is part of the thumb name
979 # This is a basic sanity check to avoid erasing unrelated directories
980 if ( strpos( $file, $this->getName() ) !== false
981 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
983 $purgeList[] = "{$dir}/{$file}";
987 # Delete the thumbnails
988 $this->repo
->quickPurgeBatch( $purgeList );
989 # Clear out the thumbnail directory if empty
990 $this->repo
->quickCleanDir( $dir );
993 /** purgeDescription inherited */
994 /** purgeEverything inherited */
997 * @param int $limit Optional: Limit to number of results
998 * @param int $start Optional: Timestamp, start from
999 * @param int $end Optional: Timestamp, end at
1003 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1004 $dbr = $this->repo
->getSlaveDB();
1005 $tables = array( 'oldimage' );
1006 $fields = OldLocalFile
::selectFields();
1007 $conds = $opts = $join_conds = array();
1008 $eq = $inc ?
'=' : '';
1009 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1012 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1016 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1020 $opts['LIMIT'] = $limit;
1023 // Search backwards for time > x queries
1024 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1025 $opts['ORDER BY'] = "oi_timestamp $order";
1026 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1028 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1029 &$conds, &$opts, &$join_conds ) );
1031 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1034 foreach ( $res as $row ) {
1035 $r[] = $this->repo
->newFileFromRow( $row );
1038 if ( $order == 'ASC' ) {
1039 $r = array_reverse( $r ); // make sure it ends up descending
1046 * Returns the history of this file, line by line.
1047 * starts with current version, then old versions.
1048 * uses $this->historyLine to check which line to return:
1049 * 0 return line for current version
1050 * 1 query for old versions, return first one
1051 * 2, ... return next old version from above query
1054 public function nextHistoryLine() {
1055 # Polymorphic function name to distinguish foreign and local fetches
1056 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1058 $dbr = $this->repo
->getSlaveDB();
1060 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1061 $this->historyRes
= $dbr->select( 'image',
1064 "'' AS oi_archive_name",
1068 array( 'img_name' => $this->title
->getDBkey() ),
1072 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1073 $this->historyRes
= null;
1077 } elseif ( $this->historyLine
== 1 ) {
1078 $this->historyRes
= $dbr->select( 'oldimage', '*',
1079 array( 'oi_name' => $this->title
->getDBkey() ),
1081 array( 'ORDER BY' => 'oi_timestamp DESC' )
1084 $this->historyLine++
;
1086 return $dbr->fetchObject( $this->historyRes
);
1090 * Reset the history pointer to the first element of the history
1092 public function resetHistory() {
1093 $this->historyLine
= 0;
1095 if ( !is_null( $this->historyRes
) ) {
1096 $this->historyRes
= null;
1100 /** getHashPath inherited */
1101 /** getRel inherited */
1102 /** getUrlRel inherited */
1103 /** getArchiveRel inherited */
1104 /** getArchivePath inherited */
1105 /** getThumbPath inherited */
1106 /** getArchiveUrl inherited */
1107 /** getThumbUrl inherited */
1108 /** getArchiveVirtualUrl inherited */
1109 /** getThumbVirtualUrl inherited */
1110 /** isHashed inherited */
1113 * Upload a file and record it in the DB
1114 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1115 * @param string $comment Upload description
1116 * @param string $pageText Text to use for the new description page,
1117 * if a new description page is created
1118 * @param int|bool $flags Flags for publish()
1119 * @param array|bool $props File properties, if known. This can be used to
1120 * reduce the upload time when uploading virtual URLs for which the file
1121 * info is already known
1122 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1124 * @param User|null $user User object or null to use $wgUser
1126 * @return FileRepoStatus object. On success, the value member contains the
1127 * archive name, or an empty string if it was a new file.
1129 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1130 $timestamp = false, $user = null
1134 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1135 return $this->readOnlyFatalStatus();
1139 wfProfileIn( __METHOD__
. '-getProps' );
1140 if ( $this->repo
->isVirtualUrl( $srcPath )
1141 || FileBackend
::isStoragePath( $srcPath )
1143 $props = $this->repo
->getFileProps( $srcPath );
1145 $props = FSFile
::getPropsFromPath( $srcPath );
1147 wfProfileOut( __METHOD__
. '-getProps' );
1151 $handler = MediaHandler
::getHandler( $props['mime'] );
1153 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1155 $options['headers'] = array();
1158 // Trim spaces on user supplied text
1159 $comment = trim( $comment );
1161 // truncate nicely or the DB will do it for us
1162 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1163 $comment = $wgContLang->truncate( $comment, 255 );
1164 $this->lock(); // begin
1165 $status = $this->publish( $srcPath, $flags, $options );
1167 if ( $status->successCount
> 0 ) {
1168 # Essentially we are displacing any existing current file and saving
1169 # a new current file at the old location. If just the first succeeded,
1170 # we still need to displace the current DB entry and put in a new one.
1171 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1172 $status->fatal( 'filenotfound', $srcPath );
1176 $this->unlock(); // done
1182 * Record a file upload in the upload log and the image table
1183 * @param string $oldver
1184 * @param string $desc
1185 * @param string $license
1186 * @param string $copyStatus
1187 * @param string $source
1188 * @param bool $watch
1189 * @param string|bool $timestamp
1190 * @param User|null $user User object or null to use $wgUser
1193 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1194 $watch = false, $timestamp = false, User
$user = null ) {
1200 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1202 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1207 $user->addWatch( $this->getTitle() );
1214 * Record a file upload in the upload log and the image table
1215 * @param string $oldver
1216 * @param string $comment
1217 * @param string $pageText
1218 * @param bool|array $props
1219 * @param string|bool $timestamp
1220 * @param null|User $user
1223 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1226 wfProfileIn( __METHOD__
);
1228 if ( is_null( $user ) ) {
1233 $dbw = $this->repo
->getMasterDB();
1234 $dbw->begin( __METHOD__
);
1237 wfProfileIn( __METHOD__
. '-getProps' );
1238 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1239 wfProfileOut( __METHOD__
. '-getProps' );
1242 if ( $timestamp === false ) {
1243 $timestamp = $dbw->timestamp();
1246 $props['description'] = $comment;
1247 $props['user'] = $user->getId();
1248 $props['user_text'] = $user->getName();
1249 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1250 $this->setProps( $props );
1252 # Fail now if the file isn't there
1253 if ( !$this->fileExists
) {
1254 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1255 wfProfileOut( __METHOD__
);
1262 # Test to see if the row exists using INSERT IGNORE
1263 # This avoids race conditions by locking the row until the commit, and also
1264 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1265 $dbw->insert( 'image',
1267 'img_name' => $this->getName(),
1268 'img_size' => $this->size
,
1269 'img_width' => intval( $this->width
),
1270 'img_height' => intval( $this->height
),
1271 'img_bits' => $this->bits
,
1272 'img_media_type' => $this->media_type
,
1273 'img_major_mime' => $this->major_mime
,
1274 'img_minor_mime' => $this->minor_mime
,
1275 'img_timestamp' => $timestamp,
1276 'img_description' => $comment,
1277 'img_user' => $user->getId(),
1278 'img_user_text' => $user->getName(),
1279 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1280 'img_sha1' => $this->sha1
1285 if ( $dbw->affectedRows() == 0 ) {
1286 # (bug 34993) Note: $oldver can be empty here, if the previous
1287 # version of the file was broken. Allow registration of the new
1288 # version to continue anyway, because that's better than having
1289 # an image that's not fixable by user operations.
1292 # Collision, this is an update of a file
1293 # Insert previous contents into oldimage
1294 $dbw->insertSelect( 'oldimage', 'image',
1296 'oi_name' => 'img_name',
1297 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1298 'oi_size' => 'img_size',
1299 'oi_width' => 'img_width',
1300 'oi_height' => 'img_height',
1301 'oi_bits' => 'img_bits',
1302 'oi_timestamp' => 'img_timestamp',
1303 'oi_description' => 'img_description',
1304 'oi_user' => 'img_user',
1305 'oi_user_text' => 'img_user_text',
1306 'oi_metadata' => 'img_metadata',
1307 'oi_media_type' => 'img_media_type',
1308 'oi_major_mime' => 'img_major_mime',
1309 'oi_minor_mime' => 'img_minor_mime',
1310 'oi_sha1' => 'img_sha1'
1312 array( 'img_name' => $this->getName() ),
1316 # Update the current image row
1317 $dbw->update( 'image',
1319 'img_size' => $this->size
,
1320 'img_width' => intval( $this->width
),
1321 'img_height' => intval( $this->height
),
1322 'img_bits' => $this->bits
,
1323 'img_media_type' => $this->media_type
,
1324 'img_major_mime' => $this->major_mime
,
1325 'img_minor_mime' => $this->minor_mime
,
1326 'img_timestamp' => $timestamp,
1327 'img_description' => $comment,
1328 'img_user' => $user->getId(),
1329 'img_user_text' => $user->getName(),
1330 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1331 'img_sha1' => $this->sha1
1333 array( 'img_name' => $this->getName() ),
1337 # This is a new file, so update the image count
1338 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1341 $descTitle = $this->getTitle();
1342 $wikiPage = new WikiFilePage( $descTitle );
1343 $wikiPage->setFile( $this );
1346 $action = $reupload ?
'overwrite' : 'upload';
1348 $logEntry = new ManualLogEntry( 'upload', $action );
1349 $logEntry->setPerformer( $user );
1350 $logEntry->setComment( $comment );
1351 $logEntry->setTarget( $descTitle );
1353 // Allow people using the api to associate log entries with the upload.
1354 // Log has a timestamp, but sometimes different from upload timestamp.
1355 $logEntry->setParameters(
1357 'img_sha1' => $this->sha1
,
1358 'img_timestamp' => $timestamp,
1361 // Note we keep $logId around since during new image
1362 // creation, page doesn't exist yet, so log_page = 0
1363 // but we want it to point to the page we're making,
1364 // so we later modify the log entry.
1365 // For a similar reason, we avoid making an RC entry
1366 // now and wait until the page exists.
1367 $logId = $logEntry->insert();
1369 $exists = $descTitle->exists();
1371 // Page exists, do RC entry now (otherwise we wait for later).
1372 $logEntry->publish( $logId );
1374 wfProfileIn( __METHOD__
. '-edit' );
1377 # Create a null revision
1378 $latest = $descTitle->getLatestRevID();
1379 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1381 $nullRevision = Revision
::newNullRevision(
1383 $descTitle->getArticleID(),
1387 if ( !is_null( $nullRevision ) ) {
1388 $nullRevision->insertOn( $dbw );
1390 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1391 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1395 # Commit the transaction now, in case something goes wrong later
1396 # The most important thing is that files don't get lost, especially archives
1397 # NOTE: once we have support for nested transactions, the commit may be moved
1398 # to after $wikiPage->doEdit has been called.
1399 $dbw->commit( __METHOD__
);
1402 # Invalidate the cache for the description page
1403 $descTitle->invalidateCache();
1404 $descTitle->purgeSquid();
1406 # New file; create the description page.
1407 # There's already a log entry, so don't make a second RC entry
1408 # Squid and file cache for the description page are purged by doEditContent.
1409 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1410 $status = $wikiPage->doEditContent(
1413 EDIT_NEW | EDIT_SUPPRESS_RC
,
1418 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1419 // Now that the page exists, make an RC entry.
1420 $logEntry->publish( $logId );
1421 if ( isset( $status->value
['revision'] ) ) {
1422 $dbw->update( 'logging',
1423 array( 'log_page' => $status->value
['revision']->getPage() ),
1424 array( 'log_id' => $logId ),
1428 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1431 wfProfileOut( __METHOD__
. '-edit' );
1433 # Save to cache and purge the squid
1434 # We shall not saveToCache before the commit since otherwise
1435 # in case of a rollback there is an usable file from memcached
1436 # which in fact doesn't really exist (bug 24978)
1437 $this->saveToCache();
1440 # Delete old thumbnails
1441 wfProfileIn( __METHOD__
. '-purge' );
1442 $this->purgeThumbnails();
1443 wfProfileOut( __METHOD__
. '-purge' );
1445 # Remove the old file from the squid cache
1446 SquidUpdate
::purge( array( $this->getURL() ) );
1449 # Hooks, hooks, the magic of hooks...
1450 wfProfileIn( __METHOD__
. '-hooks' );
1451 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1452 wfProfileOut( __METHOD__
. '-hooks' );
1454 # Invalidate cache for all pages using this file
1455 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1456 $update->doUpdate();
1458 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1461 wfProfileOut( __METHOD__
);
1467 * Move or copy a file to its public location. If a file exists at the
1468 * destination, move it to an archive. Returns a FileRepoStatus object with
1469 * the archive name in the "value" member on success.
1471 * The archive name should be passed through to recordUpload for database
1474 * @param string $srcPath Local filesystem path to the source image
1475 * @param int $flags A bitwise combination of:
1476 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1477 * @param array $options Optional additional parameters
1478 * @return FileRepoStatus On success, the value member contains the
1479 * archive name, or an empty string if it was a new file.
1481 function publish( $srcPath, $flags = 0, array $options = array() ) {
1482 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1486 * Move or copy a file to a specified location. Returns a FileRepoStatus
1487 * object with the archive name in the "value" member on success.
1489 * The archive name should be passed through to recordUpload for database
1492 * @param string $srcPath Local filesystem path to the source image
1493 * @param string $dstRel Target relative path
1494 * @param int $flags A bitwise combination of:
1495 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1496 * @param array $options Optional additional parameters
1497 * @return FileRepoStatus On success, the value member contains the
1498 * archive name, or an empty string if it was a new file.
1500 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1501 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1502 return $this->readOnlyFatalStatus();
1505 $this->lock(); // begin
1507 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1508 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1509 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1510 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1512 if ( $status->value
== 'new' ) {
1513 $status->value
= '';
1515 $status->value
= $archiveName;
1518 $this->unlock(); // done
1523 /** getLinksTo inherited */
1524 /** getExifData inherited */
1525 /** isLocal inherited */
1526 /** wasDeleted inherited */
1529 * Move file to the new title
1531 * Move current, old version and all thumbnails
1532 * to the new filename. Old file is deleted.
1534 * Cache purging is done; checks for validity
1535 * and logging are caller's responsibility
1537 * @param Title $target New file name
1538 * @return FileRepoStatus
1540 function move( $target ) {
1541 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1542 return $this->readOnlyFatalStatus();
1545 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1546 $batch = new LocalFileMoveBatch( $this, $target );
1548 $this->lock(); // begin
1549 $batch->addCurrent();
1550 $archiveNames = $batch->addOlds();
1551 $status = $batch->execute();
1552 $this->unlock(); // done
1554 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1556 // Purge the source and target files...
1557 $oldTitleFile = wfLocalFile( $this->title
);
1558 $newTitleFile = wfLocalFile( $target );
1559 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1560 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1561 $this->getRepo()->getMasterDB()->onTransactionIdle(
1562 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1563 $oldTitleFile->purgeEverything();
1564 foreach ( $archiveNames as $archiveName ) {
1565 $oldTitleFile->purgeOldThumbnails( $archiveName );
1567 $newTitleFile->purgeEverything();
1571 if ( $status->isOK() ) {
1572 // Now switch the object
1573 $this->title
= $target;
1574 // Force regeneration of the name and hashpath
1575 unset( $this->name
);
1576 unset( $this->hashPath
);
1583 * Delete all versions of the file.
1585 * Moves the files into an archive directory (or deletes them)
1586 * and removes the database rows.
1588 * Cache purging is done; logging is caller's responsibility.
1590 * @param string $reason
1591 * @param bool $suppress
1592 * @return FileRepoStatus
1594 function delete( $reason, $suppress = false ) {
1595 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1596 return $this->readOnlyFatalStatus();
1599 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1601 $this->lock(); // begin
1602 $batch->addCurrent();
1603 # Get old version relative paths
1604 $archiveNames = $batch->addOlds();
1605 $status = $batch->execute();
1606 $this->unlock(); // done
1608 if ( $status->isOK() ) {
1609 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1612 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1613 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1615 $this->getRepo()->getMasterDB()->onTransactionIdle(
1616 function () use ( $file, $archiveNames ) {
1619 $file->purgeEverything();
1620 foreach ( $archiveNames as $archiveName ) {
1621 $file->purgeOldThumbnails( $archiveName );
1624 if ( $wgUseSquid ) {
1626 $purgeUrls = array();
1627 foreach ( $archiveNames as $archiveName ) {
1628 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1630 SquidUpdate
::purge( $purgeUrls );
1639 * Delete an old version of the file.
1641 * Moves the file into an archive directory (or deletes it)
1642 * and removes the database row.
1644 * Cache purging is done; logging is caller's responsibility.
1646 * @param string $archiveName
1647 * @param string $reason
1648 * @param bool $suppress
1649 * @throws MWException Exception on database or file store failure
1650 * @return FileRepoStatus
1652 function deleteOld( $archiveName, $reason, $suppress = false ) {
1654 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1655 return $this->readOnlyFatalStatus();
1658 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1660 $this->lock(); // begin
1661 $batch->addOld( $archiveName );
1662 $status = $batch->execute();
1663 $this->unlock(); // done
1665 $this->purgeOldThumbnails( $archiveName );
1666 if ( $status->isOK() ) {
1667 $this->purgeDescription();
1668 $this->purgeHistory();
1671 if ( $wgUseSquid ) {
1673 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1680 * Restore all or specified deleted revisions to the given file.
1681 * Permissions and logging are left to the caller.
1683 * May throw database exceptions on error.
1685 * @param array $versions set of record ids of deleted items to restore,
1686 * or empty to restore all revisions.
1687 * @param bool $unsuppress
1688 * @return FileRepoStatus
1690 function restore( $versions = array(), $unsuppress = false ) {
1691 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1692 return $this->readOnlyFatalStatus();
1695 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1697 $this->lock(); // begin
1701 $batch->addIds( $versions );
1703 $status = $batch->execute();
1704 if ( $status->isGood() ) {
1705 $cleanupStatus = $batch->cleanup();
1706 $cleanupStatus->successCount
= 0;
1707 $cleanupStatus->failCount
= 0;
1708 $status->merge( $cleanupStatus );
1710 $this->unlock(); // done
1715 /** isMultipage inherited */
1716 /** pageCount inherited */
1717 /** scaleHeight inherited */
1718 /** getImageSize inherited */
1721 * Get the URL of the file description page.
1724 function getDescriptionUrl() {
1725 return $this->title
->getLocalURL();
1729 * Get the HTML text of the description page
1730 * This is not used by ImagePage for local files, since (among other things)
1731 * it skips the parser cache.
1733 * @param Language $lang What language to get description in (Optional)
1734 * @return bool|mixed
1736 function getDescriptionText( $lang = null ) {
1737 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1741 $content = $revision->getContent();
1745 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1747 return $pout->getText();
1751 * @param int $audience
1755 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1757 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1759 } elseif ( $audience == self
::FOR_THIS_USER
1760 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1764 return $this->description
;
1769 * @return bool|string
1771 function getTimestamp() {
1774 return $this->timestamp
;
1780 function getSha1() {
1782 // Initialise now if necessary
1783 if ( $this->sha1
== '' && $this->fileExists
) {
1784 $this->lock(); // begin
1786 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1787 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1788 $dbw = $this->repo
->getMasterDB();
1789 $dbw->update( 'image',
1790 array( 'img_sha1' => $this->sha1
),
1791 array( 'img_name' => $this->getName() ),
1793 $this->saveToCache();
1796 $this->unlock(); // done
1803 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1805 function isCacheable() {
1808 // If extra data (metadata) was not loaded then it must have been large
1809 return $this->extraDataLoaded
1810 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1814 * Start a transaction and lock the image for update
1815 * Increments a reference counter if the lock is already held
1816 * @throws MWException
1817 * @return bool True if the image exists, false otherwise
1820 $dbw = $this->repo
->getMasterDB();
1822 if ( !$this->locked
) {
1823 if ( !$dbw->trxLevel() ) {
1824 $dbw->begin( __METHOD__
);
1825 $this->lockedOwnTrx
= true;
1828 // Bug 54736: use simple lock to handle when the file does not exist.
1829 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1830 $cache = wfGetMainCache();
1831 $key = $this->getCacheKey();
1832 if ( !$cache->lock( $key, 60 ) ) {
1833 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1835 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1836 $cache->unlock( $key ); // release on commit
1840 return $dbw->selectField( 'image', '1',
1841 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1845 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1846 * the transaction and thereby releases the image lock.
1849 if ( $this->locked
) {
1851 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1852 $dbw = $this->repo
->getMasterDB();
1853 $dbw->commit( __METHOD__
);
1854 $this->lockedOwnTrx
= false;
1860 * Roll back the DB transaction and mark the image unlocked
1862 function unlockAndRollback() {
1863 $this->locked
= false;
1864 $dbw = $this->repo
->getMasterDB();
1865 $dbw->rollback( __METHOD__
);
1866 $this->lockedOwnTrx
= false;
1872 protected function readOnlyFatalStatus() {
1873 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1874 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1876 } // LocalFile class
1878 # ------------------------------------------------------------------------------
1881 * Helper class for file deletion
1882 * @ingroup FileAbstraction
1884 class LocalFileDeleteBatch
{
1885 /** @var LocalFile */
1892 private $srcRels = array();
1895 private $archiveUrls = array();
1897 /** @var array Items to be processed in the deletion batch */
1898 private $deletionBatch;
1900 /** @var bool Wether to suppress all suppressable fields when deleting */
1903 /** @var FileRepoStatus */
1908 * @param string $reason
1909 * @param bool $suppress
1911 function __construct( File
$file, $reason = '', $suppress = false ) {
1912 $this->file
= $file;
1913 $this->reason
= $reason;
1914 $this->suppress
= $suppress;
1915 $this->status
= $file->repo
->newGood();
1918 function addCurrent() {
1919 $this->srcRels
['.'] = $this->file
->getRel();
1923 * @param string $oldName
1925 function addOld( $oldName ) {
1926 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1927 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1931 * Add the old versions of the image to the batch
1932 * @return array List of archive names from old versions
1934 function addOlds() {
1935 $archiveNames = array();
1937 $dbw = $this->file
->repo
->getMasterDB();
1938 $result = $dbw->select( 'oldimage',
1939 array( 'oi_archive_name' ),
1940 array( 'oi_name' => $this->file
->getName() ),
1944 foreach ( $result as $row ) {
1945 $this->addOld( $row->oi_archive_name
);
1946 $archiveNames[] = $row->oi_archive_name
;
1949 return $archiveNames;
1955 function getOldRels() {
1956 if ( !isset( $this->srcRels
['.'] ) ) {
1957 $oldRels =& $this->srcRels
;
1958 $deleteCurrent = false;
1960 $oldRels = $this->srcRels
;
1961 unset( $oldRels['.'] );
1962 $deleteCurrent = true;
1965 return array( $oldRels, $deleteCurrent );
1971 protected function getHashes() {
1973 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1975 if ( $deleteCurrent ) {
1976 $hashes['.'] = $this->file
->getSha1();
1979 if ( count( $oldRels ) ) {
1980 $dbw = $this->file
->repo
->getMasterDB();
1981 $res = $dbw->select(
1983 array( 'oi_archive_name', 'oi_sha1' ),
1984 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1988 foreach ( $res as $row ) {
1989 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1990 // Get the hash from the file
1991 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1992 $props = $this->file
->repo
->getFileProps( $oldUrl );
1994 if ( $props['fileExists'] ) {
1995 // Upgrade the oldimage row
1996 $dbw->update( 'oldimage',
1997 array( 'oi_sha1' => $props['sha1'] ),
1998 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2000 $hashes[$row->oi_archive_name
] = $props['sha1'];
2002 $hashes[$row->oi_archive_name
] = false;
2005 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2010 $missing = array_diff_key( $this->srcRels
, $hashes );
2012 foreach ( $missing as $name => $rel ) {
2013 $this->status
->error( 'filedelete-old-unregistered', $name );
2016 foreach ( $hashes as $name => $hash ) {
2018 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2019 unset( $hashes[$name] );
2026 function doDBInserts() {
2029 $dbw = $this->file
->repo
->getMasterDB();
2030 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2031 $encUserId = $dbw->addQuotes( $wgUser->getId() );
2032 $encReason = $dbw->addQuotes( $this->reason
);
2033 $encGroup = $dbw->addQuotes( 'deleted' );
2034 $ext = $this->file
->getExtension();
2035 $dotExt = $ext === '' ?
'' : ".$ext";
2036 $encExt = $dbw->addQuotes( $dotExt );
2037 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2039 // Bitfields to further suppress the content
2040 if ( $this->suppress
) {
2042 // This should be 15...
2043 $bitfield |
= Revision
::DELETED_TEXT
;
2044 $bitfield |
= Revision
::DELETED_COMMENT
;
2045 $bitfield |
= Revision
::DELETED_USER
;
2046 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2048 $bitfield = 'oi_deleted';
2051 if ( $deleteCurrent ) {
2052 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2053 $where = array( 'img_name' => $this->file
->getName() );
2054 $dbw->insertSelect( 'filearchive', 'image',
2056 'fa_storage_group' => $encGroup,
2057 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
2058 'fa_deleted_user' => $encUserId,
2059 'fa_deleted_timestamp' => $encTimestamp,
2060 'fa_deleted_reason' => $encReason,
2061 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2063 'fa_name' => 'img_name',
2064 'fa_archive_name' => 'NULL',
2065 'fa_size' => 'img_size',
2066 'fa_width' => 'img_width',
2067 'fa_height' => 'img_height',
2068 'fa_metadata' => 'img_metadata',
2069 'fa_bits' => 'img_bits',
2070 'fa_media_type' => 'img_media_type',
2071 'fa_major_mime' => 'img_major_mime',
2072 'fa_minor_mime' => 'img_minor_mime',
2073 'fa_description' => 'img_description',
2074 'fa_user' => 'img_user',
2075 'fa_user_text' => 'img_user_text',
2076 'fa_timestamp' => 'img_timestamp',
2077 'fa_sha1' => 'img_sha1',
2078 ), $where, __METHOD__
);
2081 if ( count( $oldRels ) ) {
2082 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2084 'oi_name' => $this->file
->getName(),
2085 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
2086 $dbw->insertSelect( 'filearchive', 'oldimage',
2088 'fa_storage_group' => $encGroup,
2089 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
2090 'fa_deleted_user' => $encUserId,
2091 'fa_deleted_timestamp' => $encTimestamp,
2092 'fa_deleted_reason' => $encReason,
2093 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2095 'fa_name' => 'oi_name',
2096 'fa_archive_name' => 'oi_archive_name',
2097 'fa_size' => 'oi_size',
2098 'fa_width' => 'oi_width',
2099 'fa_height' => 'oi_height',
2100 'fa_metadata' => 'oi_metadata',
2101 'fa_bits' => 'oi_bits',
2102 'fa_media_type' => 'oi_media_type',
2103 'fa_major_mime' => 'oi_major_mime',
2104 'fa_minor_mime' => 'oi_minor_mime',
2105 'fa_description' => 'oi_description',
2106 'fa_user' => 'oi_user',
2107 'fa_user_text' => 'oi_user_text',
2108 'fa_timestamp' => 'oi_timestamp',
2109 'fa_sha1' => 'oi_sha1',
2110 ), $where, __METHOD__
);
2114 function doDBDeletes() {
2115 $dbw = $this->file
->repo
->getMasterDB();
2116 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2118 if ( count( $oldRels ) ) {
2119 $dbw->delete( 'oldimage',
2121 'oi_name' => $this->file
->getName(),
2122 'oi_archive_name' => array_keys( $oldRels )
2126 if ( $deleteCurrent ) {
2127 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2132 * Run the transaction
2133 * @return FileRepoStatus
2135 function execute() {
2136 wfProfileIn( __METHOD__
);
2138 $this->file
->lock();
2139 // Leave private files alone
2140 $privateFiles = array();
2141 list( $oldRels, ) = $this->getOldRels();
2142 $dbw = $this->file
->repo
->getMasterDB();
2144 if ( !empty( $oldRels ) ) {
2145 $res = $dbw->select( 'oldimage',
2146 array( 'oi_archive_name' ),
2147 array( 'oi_name' => $this->file
->getName(),
2148 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
2149 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2152 foreach ( $res as $row ) {
2153 $privateFiles[$row->oi_archive_name
] = 1;
2156 // Prepare deletion batch
2157 $hashes = $this->getHashes();
2158 $this->deletionBatch
= array();
2159 $ext = $this->file
->getExtension();
2160 $dotExt = $ext === '' ?
'' : ".$ext";
2162 foreach ( $this->srcRels
as $name => $srcRel ) {
2163 // Skip files that have no hash (missing source).
2164 // Keep private files where they are.
2165 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2166 $hash = $hashes[$name];
2167 $key = $hash . $dotExt;
2168 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2169 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2173 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2174 // We acquire this lock by running the inserts now, before the file operations.
2176 // This potentially has poor lock contention characteristics -- an alternative
2177 // scheme would be to insert stub filearchive entries with no fa_name and commit
2178 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2179 $this->doDBInserts();
2181 // Removes non-existent file from the batch, so we don't get errors.
2182 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2184 // Execute the file deletion batch
2185 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2187 if ( !$status->isGood() ) {
2188 $this->status
->merge( $status );
2191 if ( !$this->status
->isOK() ) {
2192 // Critical file deletion error
2193 // Roll back inserts, release lock and abort
2194 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2195 $this->file
->unlockAndRollback();
2196 wfProfileOut( __METHOD__
);
2198 return $this->status
;
2201 // Delete image/oldimage rows
2202 $this->doDBDeletes();
2204 // Commit and return
2205 $this->file
->unlock();
2206 wfProfileOut( __METHOD__
);
2208 return $this->status
;
2212 * Removes non-existent files from a deletion batch.
2213 * @param $batch array
2216 function removeNonexistentFiles( $batch ) {
2217 $files = $newBatch = array();
2219 foreach ( $batch as $batchItem ) {
2220 list( $src, ) = $batchItem;
2221 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2224 $result = $this->file
->repo
->fileExistsBatch( $files );
2226 foreach ( $batch as $batchItem ) {
2227 if ( $result[$batchItem[0]] ) {
2228 $newBatch[] = $batchItem;
2236 # ------------------------------------------------------------------------------
2239 * Helper class for file undeletion
2240 * @ingroup FileAbstraction
2242 class LocalFileRestoreBatch
{
2243 /** @var LocalFile */
2246 /** @var array List of file IDs to restore */
2247 private $cleanupBatch;
2249 /** @var array List of file IDs to restore */
2252 /** @var bool Add all revisions of the file */
2255 /** @var bool Wether to remove all settings for suppressed fields */
2256 private $unsuppress = false;
2260 * @param bool $unsuppress
2262 function __construct( File
$file, $unsuppress = false ) {
2263 $this->file
= $file;
2264 $this->cleanupBatch
= $this->ids
= array();
2265 $this->ids
= array();
2266 $this->unsuppress
= $unsuppress;
2272 function addId( $fa_id ) {
2273 $this->ids
[] = $fa_id;
2277 * Add a whole lot of files by ID
2279 function addIds( $ids ) {
2280 $this->ids
= array_merge( $this->ids
, $ids );
2284 * Add all revisions of the file
2291 * Run the transaction, except the cleanup batch.
2292 * The cleanup batch should be run in a separate transaction, because it locks different
2293 * rows and there's no need to keep the image row locked while it's acquiring those locks
2294 * The caller may have its own transaction open.
2295 * So we save the batch and let the caller call cleanup()
2296 * @return FileRepoStatus
2298 function execute() {
2301 if ( !$this->all
&& !$this->ids
) {
2303 return $this->file
->repo
->newGood();
2306 $exists = $this->file
->lock();
2307 $dbw = $this->file
->repo
->getMasterDB();
2308 $status = $this->file
->repo
->newGood();
2310 // Fetch all or selected archived revisions for the file,
2311 // sorted from the most recent to the oldest.
2312 $conditions = array( 'fa_name' => $this->file
->getName() );
2314 if ( !$this->all
) {
2315 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2318 $result = $dbw->select(
2320 ArchivedFile
::selectFields(),
2323 array( 'ORDER BY' => 'fa_timestamp DESC' )
2326 $idsPresent = array();
2327 $storeBatch = array();
2328 $insertBatch = array();
2329 $insertCurrent = false;
2330 $deleteIds = array();
2332 $archiveNames = array();
2334 foreach ( $result as $row ) {
2335 $idsPresent[] = $row->fa_id
;
2337 if ( $row->fa_name
!= $this->file
->getName() ) {
2338 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2339 $status->failCount++
;
2343 if ( $row->fa_storage_key
== '' ) {
2344 // Revision was missing pre-deletion
2345 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2346 $status->failCount++
;
2350 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2351 $row->fa_storage_key
;
2352 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2354 if ( isset( $row->fa_sha1
) ) {
2355 $sha1 = $row->fa_sha1
;
2357 // old row, populate from key
2358 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2362 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2363 $sha1 = substr( $sha1, 1 );
2366 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2367 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2368 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2369 ||
is_null( $row->fa_metadata
)
2371 // Refresh our metadata
2372 // Required for a new current revision; nice for older ones too. :)
2373 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2376 'minor_mime' => $row->fa_minor_mime
,
2377 'major_mime' => $row->fa_major_mime
,
2378 'media_type' => $row->fa_media_type
,
2379 'metadata' => $row->fa_metadata
2383 if ( $first && !$exists ) {
2384 // This revision will be published as the new current version
2385 $destRel = $this->file
->getRel();
2386 $insertCurrent = array(
2387 'img_name' => $row->fa_name
,
2388 'img_size' => $row->fa_size
,
2389 'img_width' => $row->fa_width
,
2390 'img_height' => $row->fa_height
,
2391 'img_metadata' => $props['metadata'],
2392 'img_bits' => $row->fa_bits
,
2393 'img_media_type' => $props['media_type'],
2394 'img_major_mime' => $props['major_mime'],
2395 'img_minor_mime' => $props['minor_mime'],
2396 'img_description' => $row->fa_description
,
2397 'img_user' => $row->fa_user
,
2398 'img_user_text' => $row->fa_user_text
,
2399 'img_timestamp' => $row->fa_timestamp
,
2403 // The live (current) version cannot be hidden!
2404 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2405 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2406 $this->cleanupBatch
[] = $row->fa_storage_key
;
2409 $archiveName = $row->fa_archive_name
;
2411 if ( $archiveName == '' ) {
2412 // This was originally a current version; we
2413 // have to devise a new archive name for it.
2414 // Format is <timestamp of archiving>!<name>
2415 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2418 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2420 } while ( isset( $archiveNames[$archiveName] ) );
2423 $archiveNames[$archiveName] = true;
2424 $destRel = $this->file
->getArchiveRel( $archiveName );
2425 $insertBatch[] = array(
2426 'oi_name' => $row->fa_name
,
2427 'oi_archive_name' => $archiveName,
2428 'oi_size' => $row->fa_size
,
2429 'oi_width' => $row->fa_width
,
2430 'oi_height' => $row->fa_height
,
2431 'oi_bits' => $row->fa_bits
,
2432 'oi_description' => $row->fa_description
,
2433 'oi_user' => $row->fa_user
,
2434 'oi_user_text' => $row->fa_user_text
,
2435 'oi_timestamp' => $row->fa_timestamp
,
2436 'oi_metadata' => $props['metadata'],
2437 'oi_media_type' => $props['media_type'],
2438 'oi_major_mime' => $props['major_mime'],
2439 'oi_minor_mime' => $props['minor_mime'],
2440 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2441 'oi_sha1' => $sha1 );
2444 $deleteIds[] = $row->fa_id
;
2446 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2447 // private files can stay where they are
2448 $status->successCount++
;
2450 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2451 $this->cleanupBatch
[] = $row->fa_storage_key
;
2459 // Add a warning to the status object for missing IDs
2460 $missingIds = array_diff( $this->ids
, $idsPresent );
2462 foreach ( $missingIds as $id ) {
2463 $status->error( 'undelete-missing-filearchive', $id );
2466 // Remove missing files from batch, so we don't get errors when undeleting them
2467 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2469 // Run the store batch
2470 // Use the OVERWRITE_SAME flag to smooth over a common error
2471 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2472 $status->merge( $storeStatus );
2474 if ( !$status->isGood() ) {
2475 // Even if some files could be copied, fail entirely as that is the
2476 // easiest thing to do without data loss
2477 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2478 $status->ok
= false;
2479 $this->file
->unlock();
2484 // Run the DB updates
2485 // Because we have locked the image row, key conflicts should be rare.
2486 // If they do occur, we can roll back the transaction at this time with
2487 // no data loss, but leaving unregistered files scattered throughout the
2489 // This is not ideal, which is why it's important to lock the image row.
2490 if ( $insertCurrent ) {
2491 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2494 if ( $insertBatch ) {
2495 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2499 $dbw->delete( 'filearchive',
2500 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2504 // If store batch is empty (all files are missing), deletion is to be considered successful
2505 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2507 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2509 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2511 $this->file
->purgeEverything();
2513 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2514 $this->file
->purgeDescription();
2515 $this->file
->purgeHistory();
2519 $this->file
->unlock();
2525 * Removes non-existent files from a store batch.
2526 * @param array $triplets
2529 function removeNonexistentFiles( $triplets ) {
2530 $files = $filteredTriplets = array();
2531 foreach ( $triplets as $file ) {
2532 $files[$file[0]] = $file[0];
2535 $result = $this->file
->repo
->fileExistsBatch( $files );
2537 foreach ( $triplets as $file ) {
2538 if ( $result[$file[0]] ) {
2539 $filteredTriplets[] = $file;
2543 return $filteredTriplets;
2547 * Removes non-existent files from a cleanup batch.
2548 * @param array $batch
2551 function removeNonexistentFromCleanup( $batch ) {
2552 $files = $newBatch = array();
2553 $repo = $this->file
->repo
;
2555 foreach ( $batch as $file ) {
2556 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2557 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2560 $result = $repo->fileExistsBatch( $files );
2562 foreach ( $batch as $file ) {
2563 if ( $result[$file] ) {
2564 $newBatch[] = $file;
2572 * Delete unused files in the deleted zone.
2573 * This should be called from outside the transaction in which execute() was called.
2574 * @return FileRepoStatus
2576 function cleanup() {
2577 if ( !$this->cleanupBatch
) {
2578 return $this->file
->repo
->newGood();
2581 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2583 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2589 * Cleanup a failed batch. The batch was only partially successful, so
2590 * rollback by removing all items that were succesfully copied.
2592 * @param Status $storeStatus
2593 * @param array $storeBatch
2595 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2596 $cleanupBatch = array();
2598 foreach ( $storeStatus->success
as $i => $success ) {
2599 // Check if this item of the batch was successfully copied
2601 // Item was successfully copied and needs to be removed again
2602 // Extract ($dstZone, $dstRel) from the batch
2603 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2606 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2610 # ------------------------------------------------------------------------------
2613 * Helper class for file movement
2614 * @ingroup FileAbstraction
2616 class LocalFileMoveBatch
{
2617 /** @var LocalFile */
2630 protected $oldCount;
2635 /** @var DatabaseBase */
2640 * @param Title $target
2642 function __construct( File
$file, Title
$target ) {
2643 $this->file
= $file;
2644 $this->target
= $target;
2645 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2646 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2647 $this->oldName
= $this->file
->getName();
2648 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2649 $this->oldRel
= $this->oldHash
. $this->oldName
;
2650 $this->newRel
= $this->newHash
. $this->newName
;
2651 $this->db
= $file->getRepo()->getMasterDb();
2655 * Add the current image to the batch
2657 function addCurrent() {
2658 $this->cur
= array( $this->oldRel
, $this->newRel
);
2662 * Add the old versions of the image to the batch
2663 * @return array List of archive names from old versions
2665 function addOlds() {
2666 $archiveBase = 'archive';
2667 $this->olds
= array();
2668 $this->oldCount
= 0;
2669 $archiveNames = array();
2671 $result = $this->db
->select( 'oldimage',
2672 array( 'oi_archive_name', 'oi_deleted' ),
2673 array( 'oi_name' => $this->oldName
),
2677 foreach ( $result as $row ) {
2678 $archiveNames[] = $row->oi_archive_name
;
2679 $oldName = $row->oi_archive_name
;
2680 $bits = explode( '!', $oldName, 2 );
2682 if ( count( $bits ) != 2 ) {
2683 wfDebug( "Old file name missing !: '$oldName' \n" );
2687 list( $timestamp, $filename ) = $bits;
2689 if ( $this->oldName
!= $filename ) {
2690 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2696 // Do we want to add those to oldCount?
2697 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2701 $this->olds
[] = array(
2702 "{$archiveBase}/{$this->oldHash}{$oldName}",
2703 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2707 return $archiveNames;
2712 * @return FileRepoStatus
2714 function execute() {
2715 $repo = $this->file
->repo
;
2716 $status = $repo->newGood();
2718 $triplets = $this->getMoveTriplets();
2719 $triplets = $this->removeNonexistentFiles( $triplets );
2721 $this->file
->lock(); // begin
2722 // Rename the file versions metadata in the DB.
2723 // This implicitly locks the destination file, which avoids race conditions.
2724 // If we moved the files from A -> C before DB updates, another process could
2725 // move files from B -> C at this point, causing storeBatch() to fail and thus
2726 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2727 $statusDb = $this->doDBUpdates();
2728 if ( !$statusDb->isGood() ) {
2729 $this->file
->unlockAndRollback();
2730 $statusDb->ok
= false;
2734 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2735 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2737 // Copy the files into their new location.
2738 // If a prior process fataled copying or cleaning up files we tolerate any
2739 // of the existing files if they are identical to the ones being stored.
2740 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2741 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2742 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2743 if ( !$statusMove->isGood() ) {
2744 // Delete any files copied over (while the destination is still locked)
2745 $this->cleanupTarget( $triplets );
2746 $this->file
->unlockAndRollback(); // unlocks the destination
2747 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2748 $statusMove->ok
= false;
2752 $this->file
->unlock(); // done
2754 // Everything went ok, remove the source files
2755 $this->cleanupSource( $triplets );
2757 $status->merge( $statusDb );
2758 $status->merge( $statusMove );
2764 * Do the database updates and return a new FileRepoStatus indicating how
2765 * many rows where updated.
2767 * @return FileRepoStatus
2769 function doDBUpdates() {
2770 $repo = $this->file
->repo
;
2771 $status = $repo->newGood();
2774 // Update current image
2777 array( 'img_name' => $this->newName
),
2778 array( 'img_name' => $this->oldName
),
2782 if ( $dbw->affectedRows() ) {
2783 $status->successCount++
;
2785 $status->failCount++
;
2786 $status->fatal( 'imageinvalidfilename' );
2791 // Update old images
2795 'oi_name' => $this->newName
,
2796 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2797 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2799 array( 'oi_name' => $this->oldName
),
2803 $affected = $dbw->affectedRows();
2804 $total = $this->oldCount
;
2805 $status->successCount +
= $affected;
2806 // Bug 34934: $total is based on files that actually exist.
2807 // There may be more DB rows than such files, in which case $affected
2808 // can be greater than $total. We use max() to avoid negatives here.
2809 $status->failCount +
= max( 0, $total - $affected );
2810 if ( $status->failCount
) {
2811 $status->error( 'imageinvalidfilename' );
2818 * Generate triplets for FileRepo::storeBatch().
2821 function getMoveTriplets() {
2822 $moves = array_merge( array( $this->cur
), $this->olds
);
2823 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2825 foreach ( $moves as $move ) {
2826 // $move: (oldRelativePath, newRelativePath)
2827 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2828 $triplets[] = array( $srcUrl, 'public', $move[1] );
2831 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2839 * Removes non-existent files from move batch.
2840 * @param array $triplets
2843 function removeNonexistentFiles( $triplets ) {
2846 foreach ( $triplets as $file ) {
2847 $files[$file[0]] = $file[0];
2850 $result = $this->file
->repo
->fileExistsBatch( $files );
2851 $filteredTriplets = array();
2853 foreach ( $triplets as $file ) {
2854 if ( $result[$file[0]] ) {
2855 $filteredTriplets[] = $file;
2857 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2861 return $filteredTriplets;
2865 * Cleanup a partially moved array of triplets by deleting the target
2866 * files. Called if something went wrong half way.
2868 function cleanupTarget( $triplets ) {
2869 // Create dest pairs from the triplets
2871 foreach ( $triplets as $triplet ) {
2872 // $triplet: (old source virtual URL, dst zone, dest rel)
2873 $pairs[] = array( $triplet[1], $triplet[2] );
2876 $this->file
->repo
->cleanupBatch( $pairs );
2880 * Cleanup a fully moved array of triplets by deleting the source files.
2881 * Called at the end of the move process if everything else went ok.
2883 function cleanupSource( $triplets ) {
2884 // Create source file names from the triplets
2886 foreach ( $triplets as $triplet ) {
2887 $files[] = $triplet[0];
2890 $this->file
->repo
->cleanupBatch( $files );