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;
53 $fileExists, # does the file exist on disk? (loadFromXxx)
54 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
55 $historyRes, # result of the query for the file's history (nextHistoryLine)
58 $bits, # --- returned by getimagesize (loadFromXxx)
60 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
61 $mime, # MIME type, determined by MimeMagic::guessMimeType
62 $major_mime, # Major mime type
63 $minor_mime, # Minor mime type
64 $size, # Size in bytes (loadFromXxx)
65 $metadata, # Handler-specific metadata
66 $timestamp, # Upload timestamp
67 $sha1, # SHA-1 base 36 content hash
68 $user, $user_text, # User, who uploaded the file
69 $description, # Description of current revision of the file
70 $dataLoaded, # Whether or not core data has been loaded from the database (loadFromXxx)
71 $extraDataLoaded, # Whether or not lazy-loaded data has been loaded from the database
72 $upgraded, # Whether the row was upgraded on load
73 $locked, # True if the image row is locked
74 $lockedOwnTrx, # True if the image row is locked with a lock initiated transaction
75 $missing, # True if file is not present in file system. Not to be cached in memcached
76 $deleted; # Bitfield akin to rev_deleted
85 protected $repoClass = 'LocalRepo';
87 const LOAD_ALL
= 1; // integer; load all the lazy fields too (like metadata)
90 * Create a LocalFile from a title
91 * Do not call this except from inside a repo class.
93 * Note: $unused param is only here to avoid an E_STRICT
101 static function newFromTitle( $title, $repo, $unused = null ) {
102 return new self( $title, $repo );
106 * Create a LocalFile from a title
107 * Do not call this except from inside a repo class.
114 static function newFromRow( $row, $repo ) {
115 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
116 $file = new self( $title, $repo );
117 $file->loadFromRow( $row );
123 * Create a LocalFile from a SHA-1 key
124 * Do not call this except from inside a repo class.
126 * @param string $sha1 base-36 SHA-1
127 * @param $repo LocalRepo
128 * @param string|bool $timestamp MW_timestamp (optional)
130 * @return bool|LocalFile
132 static function newFromKey( $sha1, $repo, $timestamp = false ) {
133 $dbr = $repo->getSlaveDB();
135 $conds = array( 'img_sha1' => $sha1 );
137 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
140 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
142 return self
::newFromRow( $row, $repo );
149 * Fields in the image table
152 static function selectFields() {
173 * Do not call this except from inside a repo class.
175 function __construct( $title, $repo ) {
176 parent
::__construct( $title, $repo );
178 $this->metadata
= '';
179 $this->historyLine
= 0;
180 $this->historyRes
= null;
181 $this->dataLoaded
= false;
182 $this->extraDataLoaded
= false;
184 $this->assertRepoDefined();
185 $this->assertTitleDefined();
189 * Get the memcached key for the main data for this file, or false if
190 * there is no access to the shared cache.
193 function getCacheKey() {
194 $hashedName = md5( $this->getName() );
196 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
200 * Try to load file metadata from memcached. Returns true on success.
203 function loadFromCache() {
206 wfProfileIn( __METHOD__
);
207 $this->dataLoaded
= false;
208 $this->extraDataLoaded
= false;
209 $key = $this->getCacheKey();
212 wfProfileOut( __METHOD__
);
217 $cachedValues = $wgMemc->get( $key );
219 // Check if the key existed and belongs to this version of MediaWiki
220 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
221 wfDebug( "Pulling file metadata from cache key $key\n" );
222 $this->fileExists
= $cachedValues['fileExists'];
223 if ( $this->fileExists
) {
224 $this->setProps( $cachedValues );
226 $this->dataLoaded
= true;
227 $this->extraDataLoaded
= true;
228 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
229 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
233 if ( $this->dataLoaded
) {
234 wfIncrStats( 'image_cache_hit' );
236 wfIncrStats( 'image_cache_miss' );
239 wfProfileOut( __METHOD__
);
241 return $this->dataLoaded
;
245 * Save the file metadata to memcached
247 function saveToCache() {
251 $key = $this->getCacheKey();
257 $fields = $this->getCacheFields( '' );
258 $cache = array( 'version' => MW_FILE_VERSION
);
259 $cache['fileExists'] = $this->fileExists
;
261 if ( $this->fileExists
) {
262 foreach ( $fields as $field ) {
263 $cache[$field] = $this->$field;
267 // Strip off excessive entries from the subset of fields that can become large.
268 // If the cache value gets to large it will not fit in memcached and nothing will
269 // get cached at all, causing master queries for any file access.
270 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
271 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
272 unset( $cache[$field] ); // don't let the value get too big
276 // Cache presence for 1 week and negatives for 1 day
277 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
281 * Load metadata from the file itself
283 function loadFromFile() {
284 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
285 $this->setProps( $props );
289 * @param $prefix string
292 function getCacheFields( $prefix = 'img_' ) {
293 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
294 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
295 'user_text', 'description' );
296 static $results = array();
298 if ( $prefix == '' ) {
302 if ( !isset( $results[$prefix] ) ) {
303 $prefixedFields = array();
304 foreach ( $fields as $field ) {
305 $prefixedFields[] = $prefix . $field;
307 $results[$prefix] = $prefixedFields;
310 return $results[$prefix];
316 function getLazyCacheFields( $prefix = 'img_' ) {
317 static $fields = array( 'metadata' );
318 static $results = array();
320 if ( $prefix == '' ) {
324 if ( !isset( $results[$prefix] ) ) {
325 $prefixedFields = array();
326 foreach ( $fields as $field ) {
327 $prefixedFields[] = $prefix . $field;
329 $results[$prefix] = $prefixedFields;
332 return $results[$prefix];
336 * Load file metadata from the DB
338 function loadFromDB() {
339 # Polymorphic function name to distinguish foreign and local fetches
340 $fname = get_class( $this ) . '::' . __FUNCTION__
;
341 wfProfileIn( $fname );
343 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
344 $this->dataLoaded
= true;
345 $this->extraDataLoaded
= true;
347 $dbr = $this->repo
->getMasterDB();
348 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
349 array( 'img_name' => $this->getName() ), $fname );
352 $this->loadFromRow( $row );
354 $this->fileExists
= false;
357 wfProfileOut( $fname );
361 * Load lazy file metadata from the DB.
362 * This covers fields that are sometimes not cached.
364 protected function loadExtraFromDB() {
365 # Polymorphic function name to distinguish foreign and local fetches
366 $fname = get_class( $this ) . '::' . __FUNCTION__
;
367 wfProfileIn( $fname );
369 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
370 $this->extraDataLoaded
= true;
372 $dbr = $this->repo
->getSlaveDB();
373 // In theory the file could have just been renamed/deleted...oh well
374 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
375 array( 'img_name' => $this->getName() ), $fname );
377 if ( !$row ) { // fallback to master
378 $dbr = $this->repo
->getMasterDB();
379 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
380 array( 'img_name' => $this->getName() ), $fname );
384 foreach ( $this->unprefixRow( $row, 'img_' ) as $name => $value ) {
385 $this->$name = $value;
388 wfProfileOut( $fname );
389 throw new MWException( "Could not find data for image '{$this->getName()}'." );
392 wfProfileOut( $fname );
397 * @param $prefix string
400 protected function unprefixRow( $row, $prefix = 'img_' ) {
401 $array = (array)$row;
402 $prefixLength = strlen( $prefix );
404 // Sanity check prefix once
405 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
406 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
410 foreach ( $array as $name => $value ) {
411 $decoded[substr( $name, $prefixLength )] = $value;
418 * Decode a row from the database (either object or array) to an array
419 * with timestamps and MIME types decoded, and the field prefix removed.
421 * @param $prefix string
422 * @throws MWException
425 function decodeRow( $row, $prefix = 'img_' ) {
426 $decoded = $this->unprefixRow( $row, $prefix );
428 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
430 if ( empty( $decoded['major_mime'] ) ) {
431 $decoded['mime'] = 'unknown/unknown';
433 if ( !$decoded['minor_mime'] ) {
434 $decoded['minor_mime'] = 'unknown';
436 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
439 # Trim zero padding from char/binary field
440 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
446 * Load file metadata from a DB result row
448 function loadFromRow( $row, $prefix = 'img_' ) {
449 $this->dataLoaded
= true;
450 $this->extraDataLoaded
= true;
452 $array = $this->decodeRow( $row, $prefix );
454 foreach ( $array as $name => $value ) {
455 $this->$name = $value;
458 $this->fileExists
= true;
459 $this->maybeUpgradeRow();
463 * Load file metadata from cache or DB, unless already loaded
464 * @param integer $flags
466 function load( $flags = 0 ) {
467 if ( !$this->dataLoaded
) {
468 if ( !$this->loadFromCache() ) {
470 $this->saveToCache();
472 $this->dataLoaded
= true;
474 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
475 $this->loadExtraFromDB();
480 * Upgrade a row if it needs it
482 function maybeUpgradeRow() {
483 global $wgUpdateCompatibleMetadata;
484 if ( wfReadOnly() ) {
488 if ( is_null( $this->media_type
) ||
489 $this->mime
== 'image/svg'
492 $this->upgraded
= true;
494 $handler = $this->getHandler();
496 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
497 if ( $validity === MediaHandler
::METADATA_BAD
498 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
501 $this->upgraded
= true;
507 function getUpgraded() {
508 return $this->upgraded
;
512 * Fix assorted version-related problems with the image row by reloading it from the file
514 function upgradeRow() {
515 wfProfileIn( __METHOD__
);
517 $this->lock(); // begin
519 $this->loadFromFile();
521 # Don't destroy file info of missing files
522 if ( !$this->fileExists
) {
523 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
524 wfProfileOut( __METHOD__
);
529 $dbw = $this->repo
->getMasterDB();
530 list( $major, $minor ) = self
::splitMime( $this->mime
);
532 if ( wfReadOnly() ) {
533 wfProfileOut( __METHOD__
);
537 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
539 $dbw->update( 'image',
541 'img_size' => $this->size
, // sanity
542 'img_width' => $this->width
,
543 'img_height' => $this->height
,
544 'img_bits' => $this->bits
,
545 'img_media_type' => $this->media_type
,
546 'img_major_mime' => $major,
547 'img_minor_mime' => $minor,
548 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
549 'img_sha1' => $this->sha1
,
551 array( 'img_name' => $this->getName() ),
555 $this->saveToCache();
557 $this->unlock(); // done
559 wfProfileOut( __METHOD__
);
563 * Set properties in this object to be equal to those given in the
564 * associative array $info. Only cacheable fields can be set.
565 * All fields *must* be set in $info except for getLazyCacheFields().
567 * If 'mime' is given, it will be split into major_mime/minor_mime.
568 * If major_mime/minor_mime are given, $this->mime will also be set.
570 function setProps( $info ) {
571 $this->dataLoaded
= true;
572 $fields = $this->getCacheFields( '' );
573 $fields[] = 'fileExists';
575 foreach ( $fields as $field ) {
576 if ( isset( $info[$field] ) ) {
577 $this->$field = $info[$field];
581 // Fix up mime fields
582 if ( isset( $info['major_mime'] ) ) {
583 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
584 } elseif ( isset( $info['mime'] ) ) {
585 $this->mime
= $info['mime'];
586 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
590 /** splitMime inherited */
591 /** getName inherited */
592 /** getTitle inherited */
593 /** getURL inherited */
594 /** getViewURL inherited */
595 /** getPath inherited */
596 /** isVisible inhereted */
601 function isMissing() {
602 if ( $this->missing
=== null ) {
603 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
604 $this->missing
= !$fileExists;
607 return $this->missing
;
611 * Return the width of the image
616 public function getWidth( $page = 1 ) {
619 if ( $this->isMultipage() ) {
620 $handler = $this->getHandler();
624 $dim = $handler->getPageDimensions( $this, $page );
626 return $dim['width'];
628 // For non-paged media, the false goes through an
629 // intval, turning failure into 0, so do same here.
638 * Return the height of the image
643 public function getHeight( $page = 1 ) {
646 if ( $this->isMultipage() ) {
647 $handler = $this->getHandler();
651 $dim = $handler->getPageDimensions( $this, $page );
653 return $dim['height'];
655 // For non-paged media, the false goes through an
656 // intval, turning failure into 0, so do same here.
660 return $this->height
;
665 * Returns ID or name of user who uploaded the file
667 * @param string $type 'text' or 'id'
670 function getUser( $type = 'text' ) {
673 if ( $type == 'text' ) {
674 return $this->user_text
;
675 } elseif ( $type == 'id' ) {
681 * Get handler-specific metadata
684 function getMetadata() {
685 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
686 return $this->metadata
;
692 function getBitDepth() {
699 * Return the size of the image file, in bytes
702 public function getSize() {
709 * Returns the mime type of the file.
712 function getMimeType() {
719 * Return the type of the media in the file.
720 * Use the value returned by this function with the MEDIATYPE_xxx constants.
723 function getMediaType() {
726 return $this->media_type
;
729 /** canRender inherited */
730 /** mustRender inherited */
731 /** allowInlineDisplay inherited */
732 /** isSafeFile inherited */
733 /** isTrustedFile inherited */
736 * Returns true if the file exists on disk.
737 * @return boolean Whether file exist on disk.
739 public function exists() {
742 return $this->fileExists
;
745 /** getTransformScript inherited */
746 /** getUnscaledThumb inherited */
747 /** thumbName inherited */
748 /** createThumb inherited */
749 /** transform inherited */
752 * Fix thumbnail files from 1.4 or before, with extreme prejudice
753 * @todo : do we still care about this? Perhaps a maintenance script
754 * can be made instead. Enabling this code results in a serious
755 * RTT regression for wikis without 404 handling.
757 function migrateThumbFile( $thumbName ) {
758 /* Old code for bug 2532
759 $thumbDir = $this->getThumbPath();
760 $thumbPath = "$thumbDir/$thumbName";
761 if ( is_dir( $thumbPath ) ) {
762 // Directory where file should be
763 // This happened occasionally due to broken migration code in 1.5
764 // Rename to broken-*
765 for ( $i = 0; $i < 100; $i++ ) {
766 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
767 if ( !file_exists( $broken ) ) {
768 rename( $thumbPath, $broken );
772 // Doesn't exist anymore
777 if ( $this->repo->fileExists( $thumbDir ) ) {
778 // Delete file where directory should be
779 $this->repo->cleanupBatch( array( $thumbDir ) );
784 /** getHandler inherited */
785 /** iconThumb inherited */
786 /** getLastError inherited */
789 * Get all thumbnail names previously generated for this file
790 * @param string|bool $archiveName Name of an archive file, default false
791 * @return array first element is the base dir, then files in that base dir.
793 function getThumbnails( $archiveName = false ) {
794 if ( $archiveName ) {
795 $dir = $this->getArchiveThumbPath( $archiveName );
797 $dir = $this->getThumbPath();
800 $backend = $this->repo
->getBackend();
801 $files = array( $dir );
803 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
804 foreach ( $iterator as $file ) {
807 } catch ( FileBackendError
$e ) {
808 } // suppress (bug 54674)
814 * Refresh metadata in memcached, but don't touch thumbnails or squid
816 function purgeMetadataCache() {
818 $this->saveToCache();
819 $this->purgeHistory();
823 * Purge the shared history (OldLocalFile) cache.
825 * @note This used to purge old thumbnails as well.
827 function purgeHistory() {
830 $hashedName = md5( $this->getName() );
831 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
834 $wgMemc->delete( $oldKey );
839 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
841 * @param Array $options An array potentially with the key forThumbRefresh.
843 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
845 function purgeCache( $options = array() ) {
846 wfProfileIn( __METHOD__
);
847 // Refresh metadata cache
848 $this->purgeMetadataCache();
851 $this->purgeThumbnails( $options );
853 // Purge squid cache for this file
854 SquidUpdate
::purge( array( $this->getURL() ) );
855 wfProfileOut( __METHOD__
);
859 * Delete cached transformed files for an archived version only.
860 * @param string $archiveName name of the archived file
862 function purgeOldThumbnails( $archiveName ) {
864 wfProfileIn( __METHOD__
);
866 // Get a list of old thumbnails and URLs
867 $files = $this->getThumbnails( $archiveName );
868 $dir = array_shift( $files );
869 $this->purgeThumbList( $dir, $files );
871 // Purge any custom thumbnail caches
872 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
877 foreach ( $files as $file ) {
878 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
880 SquidUpdate
::purge( $urls );
883 wfProfileOut( __METHOD__
);
887 * Delete cached transformed files for the current version only.
889 function purgeThumbnails( $options = array() ) {
891 wfProfileIn( __METHOD__
);
894 $files = $this->getThumbnails();
895 // Always purge all files from squid regardless of handler filters
898 foreach ( $files as $file ) {
899 $urls[] = $this->getThumbUrl( $file );
901 array_shift( $urls ); // don't purge directory
904 // Give media handler a chance to filter the file purge list
905 if ( !empty( $options['forThumbRefresh'] ) ) {
906 $handler = $this->getHandler();
908 $handler->filterThumbnailPurgeList( $files, $options );
912 $dir = array_shift( $files );
913 $this->purgeThumbList( $dir, $files );
915 // Purge any custom thumbnail caches
916 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
920 SquidUpdate
::purge( $urls );
923 wfProfileOut( __METHOD__
);
927 * Delete a list of thumbnails visible at urls
928 * @param string $dir base dir of the files.
929 * @param array $files of strings: relative filenames (to $dir)
931 protected function purgeThumbList( $dir, $files ) {
932 $fileListDebug = strtr(
933 var_export( $files, true ),
936 wfDebug( __METHOD__
. ": $fileListDebug\n" );
938 $purgeList = array();
939 foreach ( $files as $file ) {
940 # Check that the base file name is part of the thumb name
941 # This is a basic sanity check to avoid erasing unrelated directories
942 if ( strpos( $file, $this->getName() ) !== false
943 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
945 $purgeList[] = "{$dir}/{$file}";
949 # Delete the thumbnails
950 $this->repo
->quickPurgeBatch( $purgeList );
951 # Clear out the thumbnail directory if empty
952 $this->repo
->quickCleanDir( $dir );
955 /** purgeDescription inherited */
956 /** purgeEverything inherited */
965 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
966 $dbr = $this->repo
->getSlaveDB();
967 $tables = array( 'oldimage' );
968 $fields = OldLocalFile
::selectFields();
969 $conds = $opts = $join_conds = array();
970 $eq = $inc ?
'=' : '';
971 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
974 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
978 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
982 $opts['LIMIT'] = $limit;
985 // Search backwards for time > x queries
986 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
987 $opts['ORDER BY'] = "oi_timestamp $order";
988 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
990 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
991 &$conds, &$opts, &$join_conds ) );
993 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
996 foreach ( $res as $row ) {
997 $r[] = $this->repo
->newFileFromRow( $row );
1000 if ( $order == 'ASC' ) {
1001 $r = array_reverse( $r ); // make sure it ends up descending
1008 * Return the history of this file, line by line.
1009 * starts with current version, then old versions.
1010 * uses $this->historyLine to check which line to return:
1011 * 0 return line for current version
1012 * 1 query for old versions, return first one
1013 * 2, ... return next old version from above query
1016 public function nextHistoryLine() {
1017 # Polymorphic function name to distinguish foreign and local fetches
1018 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1020 $dbr = $this->repo
->getSlaveDB();
1022 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1023 $this->historyRes
= $dbr->select( 'image',
1026 "'' AS oi_archive_name",
1030 array( 'img_name' => $this->title
->getDBkey() ),
1034 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1035 $this->historyRes
= null;
1039 } elseif ( $this->historyLine
== 1 ) {
1040 $this->historyRes
= $dbr->select( 'oldimage', '*',
1041 array( 'oi_name' => $this->title
->getDBkey() ),
1043 array( 'ORDER BY' => 'oi_timestamp DESC' )
1046 $this->historyLine++
;
1048 return $dbr->fetchObject( $this->historyRes
);
1052 * Reset the history pointer to the first element of the history
1054 public function resetHistory() {
1055 $this->historyLine
= 0;
1057 if ( !is_null( $this->historyRes
) ) {
1058 $this->historyRes
= null;
1062 /** getHashPath inherited */
1063 /** getRel inherited */
1064 /** getUrlRel inherited */
1065 /** getArchiveRel inherited */
1066 /** getArchivePath inherited */
1067 /** getThumbPath inherited */
1068 /** getArchiveUrl inherited */
1069 /** getThumbUrl inherited */
1070 /** getArchiveVirtualUrl inherited */
1071 /** getThumbVirtualUrl inherited */
1072 /** isHashed inherited */
1075 * Upload a file and record it in the DB
1076 * @param string $srcPath source storage path, virtual URL, or filesystem path
1077 * @param string $comment upload description
1078 * @param string $pageText text to use for the new description page,
1079 * if a new description page is created
1080 * @param $flags Integer|bool: flags for publish()
1081 * @param array|bool $props File properties, if known. This can be used to reduce the
1082 * upload time when uploading virtual URLs for which the file info
1084 * @param string|bool $timestamp timestamp for img_timestamp, or false to use the current time
1085 * @param $user User|null: User object or null to use $wgUser
1087 * @return FileRepoStatus object. On success, the value member contains the
1088 * archive name, or an empty string if it was a new file.
1090 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1091 $timestamp = false, $user = null
1095 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1096 return $this->readOnlyFatalStatus();
1100 wfProfileIn( __METHOD__
. '-getProps' );
1101 if ( $this->repo
->isVirtualUrl( $srcPath )
1102 || FileBackend
::isStoragePath( $srcPath )
1104 $props = $this->repo
->getFileProps( $srcPath );
1106 $props = FSFile
::getPropsFromPath( $srcPath );
1108 wfProfileOut( __METHOD__
. '-getProps' );
1112 $handler = MediaHandler
::getHandler( $props['mime'] );
1114 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1116 $options['headers'] = array();
1119 // Trim spaces on user supplied text
1120 $comment = trim( $comment );
1122 // truncate nicely or the DB will do it for us
1123 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1124 $comment = $wgContLang->truncate( $comment, 255 );
1125 $this->lock(); // begin
1126 $status = $this->publish( $srcPath, $flags, $options );
1128 if ( $status->successCount
> 0 ) {
1129 # Essentially we are displacing any existing current file and saving
1130 # a new current file at the old location. If just the first succeeded,
1131 # we still need to displace the current DB entry and put in a new one.
1132 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1133 $status->fatal( 'filenotfound', $srcPath );
1137 $this->unlock(); // done
1143 * Record a file upload in the upload log and the image table
1145 * @param $desc string
1146 * @param $license string
1147 * @param $copyStatus string
1148 * @param $source string
1149 * @param $watch bool
1150 * @param $timestamp string|bool
1151 * @param $user User object or null to use $wgUser
1154 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1155 $watch = false, $timestamp = false, User
$user = null ) {
1161 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1163 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1168 $user->addWatch( $this->getTitle() );
1175 * Record a file upload in the upload log and the image table
1177 * @param $comment string
1178 * @param $pageText string
1179 * @param $props bool|array
1180 * @param $timestamp bool|string
1181 * @param $user null|User
1184 function recordUpload2(
1185 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1187 wfProfileIn( __METHOD__
);
1189 if ( is_null( $user ) ) {
1194 $dbw = $this->repo
->getMasterDB();
1195 $dbw->begin( __METHOD__
);
1198 wfProfileIn( __METHOD__
. '-getProps' );
1199 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1200 wfProfileOut( __METHOD__
. '-getProps' );
1203 if ( $timestamp === false ) {
1204 $timestamp = $dbw->timestamp();
1207 $props['description'] = $comment;
1208 $props['user'] = $user->getId();
1209 $props['user_text'] = $user->getName();
1210 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1211 $this->setProps( $props );
1213 # Fail now if the file isn't there
1214 if ( !$this->fileExists
) {
1215 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1216 wfProfileOut( __METHOD__
);
1223 # Test to see if the row exists using INSERT IGNORE
1224 # This avoids race conditions by locking the row until the commit, and also
1225 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1226 $dbw->insert( 'image',
1228 'img_name' => $this->getName(),
1229 'img_size' => $this->size
,
1230 'img_width' => intval( $this->width
),
1231 'img_height' => intval( $this->height
),
1232 'img_bits' => $this->bits
,
1233 'img_media_type' => $this->media_type
,
1234 'img_major_mime' => $this->major_mime
,
1235 'img_minor_mime' => $this->minor_mime
,
1236 'img_timestamp' => $timestamp,
1237 'img_description' => $comment,
1238 'img_user' => $user->getId(),
1239 'img_user_text' => $user->getName(),
1240 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1241 'img_sha1' => $this->sha1
1246 if ( $dbw->affectedRows() == 0 ) {
1247 # (bug 34993) Note: $oldver can be empty here, if the previous
1248 # version of the file was broken. Allow registration of the new
1249 # version to continue anyway, because that's better than having
1250 # an image that's not fixable by user operations.
1253 # Collision, this is an update of a file
1254 # Insert previous contents into oldimage
1255 $dbw->insertSelect( 'oldimage', 'image',
1257 'oi_name' => 'img_name',
1258 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1259 'oi_size' => 'img_size',
1260 'oi_width' => 'img_width',
1261 'oi_height' => 'img_height',
1262 'oi_bits' => 'img_bits',
1263 'oi_timestamp' => 'img_timestamp',
1264 'oi_description' => 'img_description',
1265 'oi_user' => 'img_user',
1266 'oi_user_text' => 'img_user_text',
1267 'oi_metadata' => 'img_metadata',
1268 'oi_media_type' => 'img_media_type',
1269 'oi_major_mime' => 'img_major_mime',
1270 'oi_minor_mime' => 'img_minor_mime',
1271 'oi_sha1' => 'img_sha1'
1273 array( 'img_name' => $this->getName() ),
1277 # Update the current image row
1278 $dbw->update( 'image',
1280 'img_size' => $this->size
,
1281 'img_width' => intval( $this->width
),
1282 'img_height' => intval( $this->height
),
1283 'img_bits' => $this->bits
,
1284 'img_media_type' => $this->media_type
,
1285 'img_major_mime' => $this->major_mime
,
1286 'img_minor_mime' => $this->minor_mime
,
1287 'img_timestamp' => $timestamp,
1288 'img_description' => $comment,
1289 'img_user' => $user->getId(),
1290 'img_user_text' => $user->getName(),
1291 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1292 'img_sha1' => $this->sha1
1294 array( 'img_name' => $this->getName() ),
1298 # This is a new file, so update the image count
1299 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1302 $descTitle = $this->getTitle();
1303 $wikiPage = new WikiFilePage( $descTitle );
1304 $wikiPage->setFile( $this );
1307 $action = $reupload ?
'overwrite' : 'upload';
1309 $logEntry = new ManualLogEntry( 'upload', $action );
1310 $logEntry->setPerformer( $user );
1311 $logEntry->setComment( $comment );
1312 $logEntry->setTarget( $descTitle );
1314 // Allow people using the api to associate log entries with the upload.
1315 // Log has a timestamp, but sometimes different from upload timestamp.
1316 $logEntry->setParameters(
1318 'img_sha1' => $this->sha1
,
1319 'img_timestamp' => $timestamp,
1322 // Note we keep $logId around since during new image
1323 // creation, page doesn't exist yet, so log_page = 0
1324 // but we want it to point to the page we're making,
1325 // so we later modify the log entry.
1326 // For a similar reason, we avoid making an RC entry
1327 // now and wait until the page exists.
1328 $logId = $logEntry->insert();
1330 $exists = $descTitle->exists();
1332 // Page exists, do RC entry now (otherwise we wait for later).
1333 $logEntry->publish( $logId );
1335 wfProfileIn( __METHOD__
. '-edit' );
1338 # Create a null revision
1339 $latest = $descTitle->getLatestRevID();
1340 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1342 $nullRevision = Revision
::newNullRevision(
1344 $descTitle->getArticleID(),
1348 if ( !is_null( $nullRevision ) ) {
1349 $nullRevision->insertOn( $dbw );
1351 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1352 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1356 # Commit the transaction now, in case something goes wrong later
1357 # The most important thing is that files don't get lost, especially archives
1358 # NOTE: once we have support for nested transactions, the commit may be moved
1359 # to after $wikiPage->doEdit has been called.
1360 $dbw->commit( __METHOD__
);
1363 # Invalidate the cache for the description page
1364 $descTitle->invalidateCache();
1365 $descTitle->purgeSquid();
1367 # New file; create the description page.
1368 # There's already a log entry, so don't make a second RC entry
1369 # Squid and file cache for the description page are purged by doEditContent.
1370 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1371 $status = $wikiPage->doEditContent(
1374 EDIT_NEW | EDIT_SUPPRESS_RC
,
1379 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1380 // Now that the page exists, make an RC entry.
1381 $logEntry->publish( $logId );
1382 if ( isset( $status->value
['revision'] ) ) {
1383 $dbw->update( 'logging',
1384 array( 'log_page' => $status->value
['revision']->getPage() ),
1385 array( 'log_id' => $logId ),
1389 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1392 wfProfileOut( __METHOD__
. '-edit' );
1394 # Save to cache and purge the squid
1395 # We shall not saveToCache before the commit since otherwise
1396 # in case of a rollback there is an usable file from memcached
1397 # which in fact doesn't really exist (bug 24978)
1398 $this->saveToCache();
1401 # Delete old thumbnails
1402 wfProfileIn( __METHOD__
. '-purge' );
1403 $this->purgeThumbnails();
1404 wfProfileOut( __METHOD__
. '-purge' );
1406 # Remove the old file from the squid cache
1407 SquidUpdate
::purge( array( $this->getURL() ) );
1410 # Hooks, hooks, the magic of hooks...
1411 wfProfileIn( __METHOD__
. '-hooks' );
1412 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1413 wfProfileOut( __METHOD__
. '-hooks' );
1415 # Invalidate cache for all pages using this file
1416 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1417 $update->doUpdate();
1419 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1422 # Invalidate cache for all pages that redirects on this page
1423 $redirs = $this->getTitle()->getRedirectsHere();
1425 foreach ( $redirs as $redir ) {
1426 if ( !$reupload && $redir->getNamespace() === NS_FILE
) {
1427 LinksUpdate
::queueRecursiveJobsForTable( $redir, 'imagelinks' );
1429 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1430 $update->doUpdate();
1433 wfProfileOut( __METHOD__
);
1439 * Move or copy a file to its public location. If a file exists at the
1440 * destination, move it to an archive. Returns a FileRepoStatus object with
1441 * the archive name in the "value" member on success.
1443 * The archive name should be passed through to recordUpload for database
1446 * @param string $srcPath local filesystem path to the source image
1447 * @param $flags Integer: a bitwise combination of:
1448 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1449 * @param array $options Optional additional parameters
1450 * @return FileRepoStatus object. On success, the value member contains the
1451 * archive name, or an empty string if it was a new file.
1453 function publish( $srcPath, $flags = 0, array $options = array() ) {
1454 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1458 * Move or copy a file to a specified location. Returns a FileRepoStatus
1459 * object with the archive name in the "value" member on success.
1461 * The archive name should be passed through to recordUpload for database
1464 * @param string $srcPath local filesystem path to the source image
1465 * @param string $dstRel target relative path
1466 * @param $flags Integer: a bitwise combination of:
1467 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1468 * @param array $options Optional additional parameters
1469 * @return FileRepoStatus object. On success, the value member contains the
1470 * archive name, or an empty string if it was a new file.
1472 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1473 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1474 return $this->readOnlyFatalStatus();
1477 $this->lock(); // begin
1479 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1480 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1481 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1482 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1484 if ( $status->value
== 'new' ) {
1485 $status->value
= '';
1487 $status->value
= $archiveName;
1490 $this->unlock(); // done
1495 /** getLinksTo inherited */
1496 /** getExifData inherited */
1497 /** isLocal inherited */
1498 /** wasDeleted inherited */
1501 * Move file to the new title
1503 * Move current, old version and all thumbnails
1504 * to the new filename. Old file is deleted.
1506 * Cache purging is done; checks for validity
1507 * and logging are caller's responsibility
1509 * @param $target Title New file name
1510 * @return FileRepoStatus object.
1512 function move( $target ) {
1513 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1514 return $this->readOnlyFatalStatus();
1517 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1518 $batch = new LocalFileMoveBatch( $this, $target );
1520 $this->lock(); // begin
1521 $batch->addCurrent();
1522 $archiveNames = $batch->addOlds();
1523 $status = $batch->execute();
1524 $this->unlock(); // done
1526 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1528 // Purge the source and target files...
1529 $oldTitleFile = wfLocalFile( $this->title
);
1530 $newTitleFile = wfLocalFile( $target );
1531 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1532 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1533 $this->getRepo()->getMasterDB()->onTransactionIdle(
1534 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1535 $oldTitleFile->purgeEverything();
1536 foreach ( $archiveNames as $archiveName ) {
1537 $oldTitleFile->purgeOldThumbnails( $archiveName );
1539 $newTitleFile->purgeEverything();
1543 if ( $status->isOK() ) {
1544 // Now switch the object
1545 $this->title
= $target;
1546 // Force regeneration of the name and hashpath
1547 unset( $this->name
);
1548 unset( $this->hashPath
);
1555 * Delete all versions of the file.
1557 * Moves the files into an archive directory (or deletes them)
1558 * and removes the database rows.
1560 * Cache purging is done; logging is caller's responsibility.
1564 * @return FileRepoStatus object.
1566 function delete( $reason, $suppress = false ) {
1567 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1568 return $this->readOnlyFatalStatus();
1571 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1573 $this->lock(); // begin
1574 $batch->addCurrent();
1575 # Get old version relative paths
1576 $archiveNames = $batch->addOlds();
1577 $status = $batch->execute();
1578 $this->unlock(); // done
1580 if ( $status->isOK() ) {
1581 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1584 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1585 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1587 $this->getRepo()->getMasterDB()->onTransactionIdle(
1588 function () use ( $file, $archiveNames ) {
1591 $file->purgeEverything();
1592 foreach ( $archiveNames as $archiveName ) {
1593 $file->purgeOldThumbnails( $archiveName );
1596 if ( $wgUseSquid ) {
1598 $purgeUrls = array();
1599 foreach ( $archiveNames as $archiveName ) {
1600 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1602 SquidUpdate
::purge( $purgeUrls );
1611 * Delete an old version of the file.
1613 * Moves the file into an archive directory (or deletes it)
1614 * and removes the database row.
1616 * Cache purging is done; logging is caller's responsibility.
1618 * @param $archiveName String
1619 * @param $reason String
1620 * @param $suppress Boolean
1621 * @throws MWException or FSException on database or file store failure
1622 * @return FileRepoStatus object.
1624 function deleteOld( $archiveName, $reason, $suppress = false ) {
1626 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1627 return $this->readOnlyFatalStatus();
1630 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1632 $this->lock(); // begin
1633 $batch->addOld( $archiveName );
1634 $status = $batch->execute();
1635 $this->unlock(); // done
1637 $this->purgeOldThumbnails( $archiveName );
1638 if ( $status->isOK() ) {
1639 $this->purgeDescription();
1640 $this->purgeHistory();
1643 if ( $wgUseSquid ) {
1645 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1652 * Restore all or specified deleted revisions to the given file.
1653 * Permissions and logging are left to the caller.
1655 * May throw database exceptions on error.
1657 * @param array $versions set of record ids of deleted items to restore,
1658 * or empty to restore all revisions.
1659 * @param $unsuppress Boolean
1660 * @return FileRepoStatus
1662 function restore( $versions = array(), $unsuppress = false ) {
1663 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1664 return $this->readOnlyFatalStatus();
1667 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1669 $this->lock(); // begin
1673 $batch->addIds( $versions );
1675 $status = $batch->execute();
1676 if ( $status->isGood() ) {
1677 $cleanupStatus = $batch->cleanup();
1678 $cleanupStatus->successCount
= 0;
1679 $cleanupStatus->failCount
= 0;
1680 $status->merge( $cleanupStatus );
1682 $this->unlock(); // done
1687 /** isMultipage inherited */
1688 /** pageCount inherited */
1689 /** scaleHeight inherited */
1690 /** getImageSize inherited */
1693 * Get the URL of the file description page.
1696 function getDescriptionUrl() {
1697 return $this->title
->getLocalURL();
1701 * Get the HTML text of the description page
1702 * This is not used by ImagePage for local files, since (among other things)
1703 * it skips the parser cache.
1705 * @param $lang Language What language to get description in (Optional)
1706 * @return bool|mixed
1708 function getDescriptionText( $lang = null ) {
1709 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1713 $content = $revision->getContent();
1717 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1719 return $pout->getText();
1725 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1727 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1729 } elseif ( $audience == self
::FOR_THIS_USER
1730 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1734 return $this->description
;
1739 * @return bool|string
1741 function getTimestamp() {
1744 return $this->timestamp
;
1750 function getSha1() {
1752 // Initialise now if necessary
1753 if ( $this->sha1
== '' && $this->fileExists
) {
1754 $this->lock(); // begin
1756 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1757 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1758 $dbw = $this->repo
->getMasterDB();
1759 $dbw->update( 'image',
1760 array( 'img_sha1' => $this->sha1
),
1761 array( 'img_name' => $this->getName() ),
1763 $this->saveToCache();
1766 $this->unlock(); // done
1773 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1775 function isCacheable() {
1778 // If extra data (metadata) was not loaded then it must have been large
1779 return $this->extraDataLoaded
1780 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1784 * Start a transaction and lock the image for update
1785 * Increments a reference counter if the lock is already held
1786 * @return boolean True if the image exists, false otherwise
1789 $dbw = $this->repo
->getMasterDB();
1791 if ( !$this->locked
) {
1792 if ( !$dbw->trxLevel() ) {
1793 $dbw->begin( __METHOD__
);
1794 $this->lockedOwnTrx
= true;
1797 // Bug 54736: use simple lock to handle when the file does not exist.
1798 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1799 $cache = wfGetMainCache();
1800 $key = $this->getCacheKey();
1801 if ( !$cache->lock( $key, 60 ) ) {
1802 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1804 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1805 $cache->unlock( $key ); // release on commit
1809 return $dbw->selectField( 'image', '1',
1810 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1814 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1815 * the transaction and thereby releases the image lock.
1818 if ( $this->locked
) {
1820 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1821 $dbw = $this->repo
->getMasterDB();
1822 $dbw->commit( __METHOD__
);
1823 $this->lockedOwnTrx
= false;
1829 * Roll back the DB transaction and mark the image unlocked
1831 function unlockAndRollback() {
1832 $this->locked
= false;
1833 $dbw = $this->repo
->getMasterDB();
1834 $dbw->rollback( __METHOD__
);
1835 $this->lockedOwnTrx
= false;
1841 protected function readOnlyFatalStatus() {
1842 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1843 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1845 } // LocalFile class
1847 # ------------------------------------------------------------------------------
1850 * Helper class for file deletion
1851 * @ingroup FileAbstraction
1853 class LocalFileDeleteBatch
{
1860 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1865 * @param $reason string
1866 * @param $suppress bool
1868 function __construct( File
$file, $reason = '', $suppress = false ) {
1869 $this->file
= $file;
1870 $this->reason
= $reason;
1871 $this->suppress
= $suppress;
1872 $this->status
= $file->repo
->newGood();
1875 function addCurrent() {
1876 $this->srcRels
['.'] = $this->file
->getRel();
1880 * @param $oldName string
1882 function addOld( $oldName ) {
1883 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1884 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1888 * Add the old versions of the image to the batch
1889 * @return Array List of archive names from old versions
1891 function addOlds() {
1892 $archiveNames = array();
1894 $dbw = $this->file
->repo
->getMasterDB();
1895 $result = $dbw->select( 'oldimage',
1896 array( 'oi_archive_name' ),
1897 array( 'oi_name' => $this->file
->getName() ),
1901 foreach ( $result as $row ) {
1902 $this->addOld( $row->oi_archive_name
);
1903 $archiveNames[] = $row->oi_archive_name
;
1906 return $archiveNames;
1912 function getOldRels() {
1913 if ( !isset( $this->srcRels
['.'] ) ) {
1914 $oldRels =& $this->srcRels
;
1915 $deleteCurrent = false;
1917 $oldRels = $this->srcRels
;
1918 unset( $oldRels['.'] );
1919 $deleteCurrent = true;
1922 return array( $oldRels, $deleteCurrent );
1928 protected function getHashes() {
1930 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1932 if ( $deleteCurrent ) {
1933 $hashes['.'] = $this->file
->getSha1();
1936 if ( count( $oldRels ) ) {
1937 $dbw = $this->file
->repo
->getMasterDB();
1938 $res = $dbw->select(
1940 array( 'oi_archive_name', 'oi_sha1' ),
1941 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1945 foreach ( $res as $row ) {
1946 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1947 // Get the hash from the file
1948 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1949 $props = $this->file
->repo
->getFileProps( $oldUrl );
1951 if ( $props['fileExists'] ) {
1952 // Upgrade the oldimage row
1953 $dbw->update( 'oldimage',
1954 array( 'oi_sha1' => $props['sha1'] ),
1955 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1957 $hashes[$row->oi_archive_name
] = $props['sha1'];
1959 $hashes[$row->oi_archive_name
] = false;
1962 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1967 $missing = array_diff_key( $this->srcRels
, $hashes );
1969 foreach ( $missing as $name => $rel ) {
1970 $this->status
->error( 'filedelete-old-unregistered', $name );
1973 foreach ( $hashes as $name => $hash ) {
1975 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1976 unset( $hashes[$name] );
1983 function doDBInserts() {
1986 $dbw = $this->file
->repo
->getMasterDB();
1987 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1988 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1989 $encReason = $dbw->addQuotes( $this->reason
);
1990 $encGroup = $dbw->addQuotes( 'deleted' );
1991 $ext = $this->file
->getExtension();
1992 $dotExt = $ext === '' ?
'' : ".$ext";
1993 $encExt = $dbw->addQuotes( $dotExt );
1994 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1996 // Bitfields to further suppress the content
1997 if ( $this->suppress
) {
1999 // This should be 15...
2000 $bitfield |
= Revision
::DELETED_TEXT
;
2001 $bitfield |
= Revision
::DELETED_COMMENT
;
2002 $bitfield |
= Revision
::DELETED_USER
;
2003 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2005 $bitfield = 'oi_deleted';
2008 if ( $deleteCurrent ) {
2009 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2010 $where = array( 'img_name' => $this->file
->getName() );
2011 $dbw->insertSelect( 'filearchive', 'image',
2013 'fa_storage_group' => $encGroup,
2014 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
2015 'fa_deleted_user' => $encUserId,
2016 'fa_deleted_timestamp' => $encTimestamp,
2017 'fa_deleted_reason' => $encReason,
2018 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2020 'fa_name' => 'img_name',
2021 'fa_archive_name' => 'NULL',
2022 'fa_size' => 'img_size',
2023 'fa_width' => 'img_width',
2024 'fa_height' => 'img_height',
2025 'fa_metadata' => 'img_metadata',
2026 'fa_bits' => 'img_bits',
2027 'fa_media_type' => 'img_media_type',
2028 'fa_major_mime' => 'img_major_mime',
2029 'fa_minor_mime' => 'img_minor_mime',
2030 'fa_description' => 'img_description',
2031 'fa_user' => 'img_user',
2032 'fa_user_text' => 'img_user_text',
2033 'fa_timestamp' => 'img_timestamp',
2034 'fa_sha1' => 'img_sha1',
2035 ), $where, __METHOD__
);
2038 if ( count( $oldRels ) ) {
2039 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2041 'oi_name' => $this->file
->getName(),
2042 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
2043 $dbw->insertSelect( 'filearchive', 'oldimage',
2045 'fa_storage_group' => $encGroup,
2046 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
2047 'fa_deleted_user' => $encUserId,
2048 'fa_deleted_timestamp' => $encTimestamp,
2049 'fa_deleted_reason' => $encReason,
2050 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2052 'fa_name' => 'oi_name',
2053 'fa_archive_name' => 'oi_archive_name',
2054 'fa_size' => 'oi_size',
2055 'fa_width' => 'oi_width',
2056 'fa_height' => 'oi_height',
2057 'fa_metadata' => 'oi_metadata',
2058 'fa_bits' => 'oi_bits',
2059 'fa_media_type' => 'oi_media_type',
2060 'fa_major_mime' => 'oi_major_mime',
2061 'fa_minor_mime' => 'oi_minor_mime',
2062 'fa_description' => 'oi_description',
2063 'fa_user' => 'oi_user',
2064 'fa_user_text' => 'oi_user_text',
2065 'fa_timestamp' => 'oi_timestamp',
2066 'fa_sha1' => 'oi_sha1',
2067 ), $where, __METHOD__
);
2071 function doDBDeletes() {
2072 $dbw = $this->file
->repo
->getMasterDB();
2073 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2075 if ( count( $oldRels ) ) {
2076 $dbw->delete( 'oldimage',
2078 'oi_name' => $this->file
->getName(),
2079 'oi_archive_name' => array_keys( $oldRels )
2083 if ( $deleteCurrent ) {
2084 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2089 * Run the transaction
2090 * @return FileRepoStatus
2092 function execute() {
2093 wfProfileIn( __METHOD__
);
2095 $this->file
->lock();
2096 // Leave private files alone
2097 $privateFiles = array();
2098 list( $oldRels, ) = $this->getOldRels();
2099 $dbw = $this->file
->repo
->getMasterDB();
2101 if ( !empty( $oldRels ) ) {
2102 $res = $dbw->select( 'oldimage',
2103 array( 'oi_archive_name' ),
2104 array( 'oi_name' => $this->file
->getName(),
2105 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
2106 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2109 foreach ( $res as $row ) {
2110 $privateFiles[$row->oi_archive_name
] = 1;
2113 // Prepare deletion batch
2114 $hashes = $this->getHashes();
2115 $this->deletionBatch
= array();
2116 $ext = $this->file
->getExtension();
2117 $dotExt = $ext === '' ?
'' : ".$ext";
2119 foreach ( $this->srcRels
as $name => $srcRel ) {
2120 // Skip files that have no hash (missing source).
2121 // Keep private files where they are.
2122 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2123 $hash = $hashes[$name];
2124 $key = $hash . $dotExt;
2125 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2126 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2130 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2131 // We acquire this lock by running the inserts now, before the file operations.
2133 // This potentially has poor lock contention characteristics -- an alternative
2134 // scheme would be to insert stub filearchive entries with no fa_name and commit
2135 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2136 $this->doDBInserts();
2138 // Removes non-existent file from the batch, so we don't get errors.
2139 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2141 // Execute the file deletion batch
2142 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2144 if ( !$status->isGood() ) {
2145 $this->status
->merge( $status );
2148 if ( !$this->status
->isOK() ) {
2149 // Critical file deletion error
2150 // Roll back inserts, release lock and abort
2151 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2152 $this->file
->unlockAndRollback();
2153 wfProfileOut( __METHOD__
);
2155 return $this->status
;
2158 // Delete image/oldimage rows
2159 $this->doDBDeletes();
2161 // Commit and return
2162 $this->file
->unlock();
2163 wfProfileOut( __METHOD__
);
2165 return $this->status
;
2169 * Removes non-existent files from a deletion batch.
2170 * @param $batch array
2173 function removeNonexistentFiles( $batch ) {
2174 $files = $newBatch = array();
2176 foreach ( $batch as $batchItem ) {
2177 list( $src, ) = $batchItem;
2178 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2181 $result = $this->file
->repo
->fileExistsBatch( $files );
2183 foreach ( $batch as $batchItem ) {
2184 if ( $result[$batchItem[0]] ) {
2185 $newBatch[] = $batchItem;
2193 # ------------------------------------------------------------------------------
2196 * Helper class for file undeletion
2197 * @ingroup FileAbstraction
2199 class LocalFileRestoreBatch
{
2205 var $cleanupBatch, $ids, $all, $unsuppress = false;
2209 * @param $unsuppress bool
2211 function __construct( File
$file, $unsuppress = false ) {
2212 $this->file
= $file;
2213 $this->cleanupBatch
= $this->ids
= array();
2214 $this->ids
= array();
2215 $this->unsuppress
= $unsuppress;
2221 function addId( $fa_id ) {
2222 $this->ids
[] = $fa_id;
2226 * Add a whole lot of files by ID
2228 function addIds( $ids ) {
2229 $this->ids
= array_merge( $this->ids
, $ids );
2233 * Add all revisions of the file
2240 * Run the transaction, except the cleanup batch.
2241 * The cleanup batch should be run in a separate transaction, because it locks different
2242 * rows and there's no need to keep the image row locked while it's acquiring those locks
2243 * The caller may have its own transaction open.
2244 * So we save the batch and let the caller call cleanup()
2245 * @return FileRepoStatus
2247 function execute() {
2250 if ( !$this->all
&& !$this->ids
) {
2252 return $this->file
->repo
->newGood();
2255 $exists = $this->file
->lock();
2256 $dbw = $this->file
->repo
->getMasterDB();
2257 $status = $this->file
->repo
->newGood();
2259 // Fetch all or selected archived revisions for the file,
2260 // sorted from the most recent to the oldest.
2261 $conditions = array( 'fa_name' => $this->file
->getName() );
2263 if ( !$this->all
) {
2264 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2267 $result = $dbw->select(
2269 ArchivedFile
::selectFields(),
2272 array( 'ORDER BY' => 'fa_timestamp DESC' )
2275 $idsPresent = array();
2276 $storeBatch = array();
2277 $insertBatch = array();
2278 $insertCurrent = false;
2279 $deleteIds = array();
2281 $archiveNames = array();
2283 foreach ( $result as $row ) {
2284 $idsPresent[] = $row->fa_id
;
2286 if ( $row->fa_name
!= $this->file
->getName() ) {
2287 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2288 $status->failCount++
;
2292 if ( $row->fa_storage_key
== '' ) {
2293 // Revision was missing pre-deletion
2294 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2295 $status->failCount++
;
2299 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2300 $row->fa_storage_key
;
2301 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2303 if ( isset( $row->fa_sha1
) ) {
2304 $sha1 = $row->fa_sha1
;
2306 // old row, populate from key
2307 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2311 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2312 $sha1 = substr( $sha1, 1 );
2315 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2316 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2317 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2318 ||
is_null( $row->fa_metadata
)
2320 // Refresh our metadata
2321 // Required for a new current revision; nice for older ones too. :)
2322 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2325 'minor_mime' => $row->fa_minor_mime
,
2326 'major_mime' => $row->fa_major_mime
,
2327 'media_type' => $row->fa_media_type
,
2328 'metadata' => $row->fa_metadata
2332 if ( $first && !$exists ) {
2333 // This revision will be published as the new current version
2334 $destRel = $this->file
->getRel();
2335 $insertCurrent = array(
2336 'img_name' => $row->fa_name
,
2337 'img_size' => $row->fa_size
,
2338 'img_width' => $row->fa_width
,
2339 'img_height' => $row->fa_height
,
2340 'img_metadata' => $props['metadata'],
2341 'img_bits' => $row->fa_bits
,
2342 'img_media_type' => $props['media_type'],
2343 'img_major_mime' => $props['major_mime'],
2344 'img_minor_mime' => $props['minor_mime'],
2345 'img_description' => $row->fa_description
,
2346 'img_user' => $row->fa_user
,
2347 'img_user_text' => $row->fa_user_text
,
2348 'img_timestamp' => $row->fa_timestamp
,
2352 // The live (current) version cannot be hidden!
2353 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2354 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2355 $this->cleanupBatch
[] = $row->fa_storage_key
;
2358 $archiveName = $row->fa_archive_name
;
2360 if ( $archiveName == '' ) {
2361 // This was originally a current version; we
2362 // have to devise a new archive name for it.
2363 // Format is <timestamp of archiving>!<name>
2364 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2367 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2369 } while ( isset( $archiveNames[$archiveName] ) );
2372 $archiveNames[$archiveName] = true;
2373 $destRel = $this->file
->getArchiveRel( $archiveName );
2374 $insertBatch[] = array(
2375 'oi_name' => $row->fa_name
,
2376 'oi_archive_name' => $archiveName,
2377 'oi_size' => $row->fa_size
,
2378 'oi_width' => $row->fa_width
,
2379 'oi_height' => $row->fa_height
,
2380 'oi_bits' => $row->fa_bits
,
2381 'oi_description' => $row->fa_description
,
2382 'oi_user' => $row->fa_user
,
2383 'oi_user_text' => $row->fa_user_text
,
2384 'oi_timestamp' => $row->fa_timestamp
,
2385 'oi_metadata' => $props['metadata'],
2386 'oi_media_type' => $props['media_type'],
2387 'oi_major_mime' => $props['major_mime'],
2388 'oi_minor_mime' => $props['minor_mime'],
2389 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2390 'oi_sha1' => $sha1 );
2393 $deleteIds[] = $row->fa_id
;
2395 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2396 // private files can stay where they are
2397 $status->successCount++
;
2399 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2400 $this->cleanupBatch
[] = $row->fa_storage_key
;
2408 // Add a warning to the status object for missing IDs
2409 $missingIds = array_diff( $this->ids
, $idsPresent );
2411 foreach ( $missingIds as $id ) {
2412 $status->error( 'undelete-missing-filearchive', $id );
2415 // Remove missing files from batch, so we don't get errors when undeleting them
2416 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2418 // Run the store batch
2419 // Use the OVERWRITE_SAME flag to smooth over a common error
2420 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2421 $status->merge( $storeStatus );
2423 if ( !$status->isGood() ) {
2424 // Even if some files could be copied, fail entirely as that is the
2425 // easiest thing to do without data loss
2426 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2427 $status->ok
= false;
2428 $this->file
->unlock();
2433 // Run the DB updates
2434 // Because we have locked the image row, key conflicts should be rare.
2435 // If they do occur, we can roll back the transaction at this time with
2436 // no data loss, but leaving unregistered files scattered throughout the
2438 // This is not ideal, which is why it's important to lock the image row.
2439 if ( $insertCurrent ) {
2440 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2443 if ( $insertBatch ) {
2444 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2448 $dbw->delete( 'filearchive',
2449 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2453 // If store batch is empty (all files are missing), deletion is to be considered successful
2454 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2456 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2458 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2460 $this->file
->purgeEverything();
2462 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2463 $this->file
->purgeDescription();
2464 $this->file
->purgeHistory();
2468 $this->file
->unlock();
2474 * Removes non-existent files from a store batch.
2475 * @param $triplets array
2478 function removeNonexistentFiles( $triplets ) {
2479 $files = $filteredTriplets = array();
2480 foreach ( $triplets as $file ) {
2481 $files[$file[0]] = $file[0];
2484 $result = $this->file
->repo
->fileExistsBatch( $files );
2486 foreach ( $triplets as $file ) {
2487 if ( $result[$file[0]] ) {
2488 $filteredTriplets[] = $file;
2492 return $filteredTriplets;
2496 * Removes non-existent files from a cleanup batch.
2497 * @param $batch array
2500 function removeNonexistentFromCleanup( $batch ) {
2501 $files = $newBatch = array();
2502 $repo = $this->file
->repo
;
2504 foreach ( $batch as $file ) {
2505 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2506 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2509 $result = $repo->fileExistsBatch( $files );
2511 foreach ( $batch as $file ) {
2512 if ( $result[$file] ) {
2513 $newBatch[] = $file;
2521 * Delete unused files in the deleted zone.
2522 * This should be called from outside the transaction in which execute() was called.
2523 * @return FileRepoStatus
2525 function cleanup() {
2526 if ( !$this->cleanupBatch
) {
2527 return $this->file
->repo
->newGood();
2530 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2532 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2538 * Cleanup a failed batch. The batch was only partially successful, so
2539 * rollback by removing all items that were succesfully copied.
2541 * @param Status $storeStatus
2542 * @param array $storeBatch
2544 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2545 $cleanupBatch = array();
2547 foreach ( $storeStatus->success
as $i => $success ) {
2548 // Check if this item of the batch was successfully copied
2550 // Item was successfully copied and needs to be removed again
2551 // Extract ($dstZone, $dstRel) from the batch
2552 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2555 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2559 # ------------------------------------------------------------------------------
2562 * Helper class for file movement
2563 * @ingroup FileAbstraction
2565 class LocalFileMoveBatch
{
2577 var $cur, $olds, $oldCount, $archive;
2586 * @param Title $target
2588 function __construct( File
$file, Title
$target ) {
2589 $this->file
= $file;
2590 $this->target
= $target;
2591 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2592 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2593 $this->oldName
= $this->file
->getName();
2594 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2595 $this->oldRel
= $this->oldHash
. $this->oldName
;
2596 $this->newRel
= $this->newHash
. $this->newName
;
2597 $this->db
= $file->getRepo()->getMasterDb();
2601 * Add the current image to the batch
2603 function addCurrent() {
2604 $this->cur
= array( $this->oldRel
, $this->newRel
);
2608 * Add the old versions of the image to the batch
2609 * @return Array List of archive names from old versions
2611 function addOlds() {
2612 $archiveBase = 'archive';
2613 $this->olds
= array();
2614 $this->oldCount
= 0;
2615 $archiveNames = array();
2617 $result = $this->db
->select( 'oldimage',
2618 array( 'oi_archive_name', 'oi_deleted' ),
2619 array( 'oi_name' => $this->oldName
),
2623 foreach ( $result as $row ) {
2624 $archiveNames[] = $row->oi_archive_name
;
2625 $oldName = $row->oi_archive_name
;
2626 $bits = explode( '!', $oldName, 2 );
2628 if ( count( $bits ) != 2 ) {
2629 wfDebug( "Old file name missing !: '$oldName' \n" );
2633 list( $timestamp, $filename ) = $bits;
2635 if ( $this->oldName
!= $filename ) {
2636 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2642 // Do we want to add those to oldCount?
2643 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2647 $this->olds
[] = array(
2648 "{$archiveBase}/{$this->oldHash}{$oldName}",
2649 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2653 return $archiveNames;
2658 * @return FileRepoStatus
2660 function execute() {
2661 $repo = $this->file
->repo
;
2662 $status = $repo->newGood();
2664 $triplets = $this->getMoveTriplets();
2665 $triplets = $this->removeNonexistentFiles( $triplets );
2667 $this->file
->lock(); // begin
2668 // Rename the file versions metadata in the DB.
2669 // This implicitly locks the destination file, which avoids race conditions.
2670 // If we moved the files from A -> C before DB updates, another process could
2671 // move files from B -> C at this point, causing storeBatch() to fail and thus
2672 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2673 $statusDb = $this->doDBUpdates();
2674 if ( !$statusDb->isGood() ) {
2675 $this->file
->unlockAndRollback();
2676 $statusDb->ok
= false;
2680 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2681 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2683 // Copy the files into their new location.
2684 // If a prior process fataled copying or cleaning up files we tolerate any
2685 // of the existing files if they are identical to the ones being stored.
2686 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2687 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2688 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2689 if ( !$statusMove->isGood() ) {
2690 // Delete any files copied over (while the destination is still locked)
2691 $this->cleanupTarget( $triplets );
2692 $this->file
->unlockAndRollback(); // unlocks the destination
2693 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2694 $statusMove->ok
= false;
2698 $this->file
->unlock(); // done
2700 // Everything went ok, remove the source files
2701 $this->cleanupSource( $triplets );
2703 $status->merge( $statusDb );
2704 $status->merge( $statusMove );
2710 * Do the database updates and return a new FileRepoStatus indicating how
2711 * many rows where updated.
2713 * @return FileRepoStatus
2715 function doDBUpdates() {
2716 $repo = $this->file
->repo
;
2717 $status = $repo->newGood();
2720 // Update current image
2723 array( 'img_name' => $this->newName
),
2724 array( 'img_name' => $this->oldName
),
2728 if ( $dbw->affectedRows() ) {
2729 $status->successCount++
;
2731 $status->failCount++
;
2732 $status->fatal( 'imageinvalidfilename' );
2737 // Update old images
2741 'oi_name' => $this->newName
,
2742 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2743 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2745 array( 'oi_name' => $this->oldName
),
2749 $affected = $dbw->affectedRows();
2750 $total = $this->oldCount
;
2751 $status->successCount +
= $affected;
2752 // Bug 34934: $total is based on files that actually exist.
2753 // There may be more DB rows than such files, in which case $affected
2754 // can be greater than $total. We use max() to avoid negatives here.
2755 $status->failCount +
= max( 0, $total - $affected );
2756 if ( $status->failCount
) {
2757 $status->error( 'imageinvalidfilename' );
2764 * Generate triplets for FileRepo::storeBatch().
2767 function getMoveTriplets() {
2768 $moves = array_merge( array( $this->cur
), $this->olds
);
2769 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2771 foreach ( $moves as $move ) {
2772 // $move: (oldRelativePath, newRelativePath)
2773 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2774 $triplets[] = array( $srcUrl, 'public', $move[1] );
2777 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2785 * Removes non-existent files from move batch.
2786 * @param $triplets array
2789 function removeNonexistentFiles( $triplets ) {
2792 foreach ( $triplets as $file ) {
2793 $files[$file[0]] = $file[0];
2796 $result = $this->file
->repo
->fileExistsBatch( $files );
2797 $filteredTriplets = array();
2799 foreach ( $triplets as $file ) {
2800 if ( $result[$file[0]] ) {
2801 $filteredTriplets[] = $file;
2803 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2807 return $filteredTriplets;
2811 * Cleanup a partially moved array of triplets by deleting the target
2812 * files. Called if something went wrong half way.
2814 function cleanupTarget( $triplets ) {
2815 // Create dest pairs from the triplets
2817 foreach ( $triplets as $triplet ) {
2818 // $triplet: (old source virtual URL, dst zone, dest rel)
2819 $pairs[] = array( $triplet[1], $triplet[2] );
2822 $this->file
->repo
->cleanupBatch( $pairs );
2826 * Cleanup a fully moved array of triplets by deleting the source files.
2827 * Called at the end of the move process if everything else went ok.
2829 function cleanupSource( $triplets ) {
2830 // Create source file names from the triplets
2832 foreach ( $triplets as $triplet ) {
2833 $files[] = $triplet[0];
2836 $this->file
->repo
->cleanupBatch( $files );