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 if ( $this->repo
->oldFileFromRowFactory
) {
998 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
1000 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
1004 if ( $order == 'ASC' ) {
1005 $r = array_reverse( $r ); // make sure it ends up descending
1012 * Return the history of this file, line by line.
1013 * starts with current version, then old versions.
1014 * uses $this->historyLine to check which line to return:
1015 * 0 return line for current version
1016 * 1 query for old versions, return first one
1017 * 2, ... return next old version from above query
1020 public function nextHistoryLine() {
1021 # Polymorphic function name to distinguish foreign and local fetches
1022 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1024 $dbr = $this->repo
->getSlaveDB();
1026 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1027 $this->historyRes
= $dbr->select( 'image',
1030 "'' AS oi_archive_name",
1034 array( 'img_name' => $this->title
->getDBkey() ),
1038 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1039 $this->historyRes
= null;
1043 } elseif ( $this->historyLine
== 1 ) {
1044 $this->historyRes
= $dbr->select( 'oldimage', '*',
1045 array( 'oi_name' => $this->title
->getDBkey() ),
1047 array( 'ORDER BY' => 'oi_timestamp DESC' )
1050 $this->historyLine++
;
1052 return $dbr->fetchObject( $this->historyRes
);
1056 * Reset the history pointer to the first element of the history
1058 public function resetHistory() {
1059 $this->historyLine
= 0;
1061 if ( !is_null( $this->historyRes
) ) {
1062 $this->historyRes
= null;
1066 /** getHashPath inherited */
1067 /** getRel inherited */
1068 /** getUrlRel inherited */
1069 /** getArchiveRel inherited */
1070 /** getArchivePath inherited */
1071 /** getThumbPath inherited */
1072 /** getArchiveUrl inherited */
1073 /** getThumbUrl inherited */
1074 /** getArchiveVirtualUrl inherited */
1075 /** getThumbVirtualUrl inherited */
1076 /** isHashed inherited */
1079 * Upload a file and record it in the DB
1080 * @param string $srcPath source storage path, virtual URL, or filesystem path
1081 * @param string $comment upload description
1082 * @param string $pageText text to use for the new description page,
1083 * if a new description page is created
1084 * @param $flags Integer|bool: flags for publish()
1085 * @param array|bool $props File properties, if known. This can be used to reduce the
1086 * upload time when uploading virtual URLs for which the file info
1088 * @param string|bool $timestamp timestamp for img_timestamp, or false to use the current time
1089 * @param $user User|null: User object or null to use $wgUser
1091 * @return FileRepoStatus object. On success, the value member contains the
1092 * archive name, or an empty string if it was a new file.
1094 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1095 $timestamp = false, $user = null
1099 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1100 return $this->readOnlyFatalStatus();
1104 wfProfileIn( __METHOD__
. '-getProps' );
1105 if ( $this->repo
->isVirtualUrl( $srcPath )
1106 || FileBackend
::isStoragePath( $srcPath )
1108 $props = $this->repo
->getFileProps( $srcPath );
1110 $props = FSFile
::getPropsFromPath( $srcPath );
1112 wfProfileOut( __METHOD__
. '-getProps' );
1116 $handler = MediaHandler
::getHandler( $props['mime'] );
1118 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1120 $options['headers'] = array();
1123 // Trim spaces on user supplied text
1124 $comment = trim( $comment );
1126 // truncate nicely or the DB will do it for us
1127 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1128 $comment = $wgContLang->truncate( $comment, 255 );
1129 $this->lock(); // begin
1130 $status = $this->publish( $srcPath, $flags, $options );
1132 if ( $status->successCount
> 0 ) {
1133 # Essentially we are displacing any existing current file and saving
1134 # a new current file at the old location. If just the first succeeded,
1135 # we still need to displace the current DB entry and put in a new one.
1136 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1137 $status->fatal( 'filenotfound', $srcPath );
1141 $this->unlock(); // done
1147 * Record a file upload in the upload log and the image table
1149 * @param $desc string
1150 * @param $license string
1151 * @param $copyStatus string
1152 * @param $source string
1153 * @param $watch bool
1154 * @param $timestamp string|bool
1155 * @param $user User object or null to use $wgUser
1158 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1159 $watch = false, $timestamp = false, User
$user = null ) {
1165 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1167 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1172 $user->addWatch( $this->getTitle() );
1179 * Record a file upload in the upload log and the image table
1181 * @param $comment string
1182 * @param $pageText string
1183 * @param $props bool|array
1184 * @param $timestamp bool|string
1185 * @param $user null|User
1188 function recordUpload2(
1189 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1191 wfProfileIn( __METHOD__
);
1193 if ( is_null( $user ) ) {
1198 $dbw = $this->repo
->getMasterDB();
1199 $dbw->begin( __METHOD__
);
1202 wfProfileIn( __METHOD__
. '-getProps' );
1203 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1204 wfProfileOut( __METHOD__
. '-getProps' );
1207 if ( $timestamp === false ) {
1208 $timestamp = $dbw->timestamp();
1211 $props['description'] = $comment;
1212 $props['user'] = $user->getId();
1213 $props['user_text'] = $user->getName();
1214 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1215 $this->setProps( $props );
1217 # Fail now if the file isn't there
1218 if ( !$this->fileExists
) {
1219 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1220 wfProfileOut( __METHOD__
);
1227 # Test to see if the row exists using INSERT IGNORE
1228 # This avoids race conditions by locking the row until the commit, and also
1229 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1230 $dbw->insert( 'image',
1232 'img_name' => $this->getName(),
1233 'img_size' => $this->size
,
1234 'img_width' => intval( $this->width
),
1235 'img_height' => intval( $this->height
),
1236 'img_bits' => $this->bits
,
1237 'img_media_type' => $this->media_type
,
1238 'img_major_mime' => $this->major_mime
,
1239 'img_minor_mime' => $this->minor_mime
,
1240 'img_timestamp' => $timestamp,
1241 'img_description' => $comment,
1242 'img_user' => $user->getId(),
1243 'img_user_text' => $user->getName(),
1244 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1245 'img_sha1' => $this->sha1
1250 if ( $dbw->affectedRows() == 0 ) {
1251 # (bug 34993) Note: $oldver can be empty here, if the previous
1252 # version of the file was broken. Allow registration of the new
1253 # version to continue anyway, because that's better than having
1254 # an image that's not fixable by user operations.
1257 # Collision, this is an update of a file
1258 # Insert previous contents into oldimage
1259 $dbw->insertSelect( 'oldimage', 'image',
1261 'oi_name' => 'img_name',
1262 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1263 'oi_size' => 'img_size',
1264 'oi_width' => 'img_width',
1265 'oi_height' => 'img_height',
1266 'oi_bits' => 'img_bits',
1267 'oi_timestamp' => 'img_timestamp',
1268 'oi_description' => 'img_description',
1269 'oi_user' => 'img_user',
1270 'oi_user_text' => 'img_user_text',
1271 'oi_metadata' => 'img_metadata',
1272 'oi_media_type' => 'img_media_type',
1273 'oi_major_mime' => 'img_major_mime',
1274 'oi_minor_mime' => 'img_minor_mime',
1275 'oi_sha1' => 'img_sha1'
1277 array( 'img_name' => $this->getName() ),
1281 # Update the current image row
1282 $dbw->update( 'image',
1284 'img_size' => $this->size
,
1285 'img_width' => intval( $this->width
),
1286 'img_height' => intval( $this->height
),
1287 'img_bits' => $this->bits
,
1288 'img_media_type' => $this->media_type
,
1289 'img_major_mime' => $this->major_mime
,
1290 'img_minor_mime' => $this->minor_mime
,
1291 'img_timestamp' => $timestamp,
1292 'img_description' => $comment,
1293 'img_user' => $user->getId(),
1294 'img_user_text' => $user->getName(),
1295 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1296 'img_sha1' => $this->sha1
1298 array( 'img_name' => $this->getName() ),
1302 # This is a new file, so update the image count
1303 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1306 $descTitle = $this->getTitle();
1307 $wikiPage = new WikiFilePage( $descTitle );
1308 $wikiPage->setFile( $this );
1311 $action = $reupload ?
'overwrite' : 'upload';
1313 $logEntry = new ManualLogEntry( 'upload', $action );
1314 $logEntry->setPerformer( $user );
1315 $logEntry->setComment( $comment );
1316 $logEntry->setTarget( $descTitle );
1318 // Allow people using the api to associate log entries with the upload.
1319 // Log has a timestamp, but sometimes different from upload timestamp.
1320 $logEntry->setParameters(
1322 'img_sha1' => $this->sha1
,
1323 'img_timestamp' => $timestamp,
1326 // Note we keep $logId around since during new image
1327 // creation, page doesn't exist yet, so log_page = 0
1328 // but we want it to point to the page we're making,
1329 // so we later modify the log entry.
1330 // For a similar reason, we avoid making an RC entry
1331 // now and wait until the page exists.
1332 $logId = $logEntry->insert();
1334 $exists = $descTitle->exists();
1336 // Page exists, do RC entry now (otherwise we wait for later).
1337 $logEntry->publish( $logId );
1339 wfProfileIn( __METHOD__
. '-edit' );
1342 # Create a null revision
1343 $latest = $descTitle->getLatestRevID();
1344 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1346 $nullRevision = Revision
::newNullRevision(
1348 $descTitle->getArticleID(),
1352 if ( !is_null( $nullRevision ) ) {
1353 $nullRevision->insertOn( $dbw );
1355 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1356 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1360 # Commit the transaction now, in case something goes wrong later
1361 # The most important thing is that files don't get lost, especially archives
1362 # NOTE: once we have support for nested transactions, the commit may be moved
1363 # to after $wikiPage->doEdit has been called.
1364 $dbw->commit( __METHOD__
);
1367 # Invalidate the cache for the description page
1368 $descTitle->invalidateCache();
1369 $descTitle->purgeSquid();
1371 # New file; create the description page.
1372 # There's already a log entry, so don't make a second RC entry
1373 # Squid and file cache for the description page are purged by doEditContent.
1374 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1375 $status = $wikiPage->doEditContent(
1378 EDIT_NEW | EDIT_SUPPRESS_RC
,
1383 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1384 // Now that the page exists, make an RC entry.
1385 $logEntry->publish( $logId );
1386 if ( isset( $status->value
['revision'] ) ) {
1387 $dbw->update( 'logging',
1388 array( 'log_page' => $status->value
['revision']->getPage() ),
1389 array( 'log_id' => $logId ),
1393 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1396 wfProfileOut( __METHOD__
. '-edit' );
1398 # Save to cache and purge the squid
1399 # We shall not saveToCache before the commit since otherwise
1400 # in case of a rollback there is an usable file from memcached
1401 # which in fact doesn't really exist (bug 24978)
1402 $this->saveToCache();
1405 # Delete old thumbnails
1406 wfProfileIn( __METHOD__
. '-purge' );
1407 $this->purgeThumbnails();
1408 wfProfileOut( __METHOD__
. '-purge' );
1410 # Remove the old file from the squid cache
1411 SquidUpdate
::purge( array( $this->getURL() ) );
1414 # Hooks, hooks, the magic of hooks...
1415 wfProfileIn( __METHOD__
. '-hooks' );
1416 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1417 wfProfileOut( __METHOD__
. '-hooks' );
1419 # Invalidate cache for all pages using this file
1420 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1421 $update->doUpdate();
1423 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1426 # Invalidate cache for all pages that redirects on this page
1427 $redirs = $this->getTitle()->getRedirectsHere();
1429 foreach ( $redirs as $redir ) {
1430 if ( !$reupload && $redir->getNamespace() === NS_FILE
) {
1431 LinksUpdate
::queueRecursiveJobsForTable( $redir, 'imagelinks' );
1433 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1434 $update->doUpdate();
1437 wfProfileOut( __METHOD__
);
1443 * Move or copy a file to its public location. If a file exists at the
1444 * destination, move it to an archive. Returns a FileRepoStatus object with
1445 * the archive name in the "value" member on success.
1447 * The archive name should be passed through to recordUpload for database
1450 * @param string $srcPath local filesystem path to the source image
1451 * @param $flags Integer: a bitwise combination of:
1452 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1453 * @param array $options Optional additional parameters
1454 * @return FileRepoStatus object. On success, the value member contains the
1455 * archive name, or an empty string if it was a new file.
1457 function publish( $srcPath, $flags = 0, array $options = array() ) {
1458 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1462 * Move or copy a file to a specified location. Returns a FileRepoStatus
1463 * object with the archive name in the "value" member on success.
1465 * The archive name should be passed through to recordUpload for database
1468 * @param string $srcPath local filesystem path to the source image
1469 * @param string $dstRel target relative path
1470 * @param $flags Integer: a bitwise combination of:
1471 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1472 * @param array $options Optional additional parameters
1473 * @return FileRepoStatus object. On success, the value member contains the
1474 * archive name, or an empty string if it was a new file.
1476 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1477 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1478 return $this->readOnlyFatalStatus();
1481 $this->lock(); // begin
1483 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1484 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1485 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1486 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1488 if ( $status->value
== 'new' ) {
1489 $status->value
= '';
1491 $status->value
= $archiveName;
1494 $this->unlock(); // done
1499 /** getLinksTo inherited */
1500 /** getExifData inherited */
1501 /** isLocal inherited */
1502 /** wasDeleted inherited */
1505 * Move file to the new title
1507 * Move current, old version and all thumbnails
1508 * to the new filename. Old file is deleted.
1510 * Cache purging is done; checks for validity
1511 * and logging are caller's responsibility
1513 * @param $target Title New file name
1514 * @return FileRepoStatus object.
1516 function move( $target ) {
1517 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1518 return $this->readOnlyFatalStatus();
1521 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1522 $batch = new LocalFileMoveBatch( $this, $target );
1524 $this->lock(); // begin
1525 $batch->addCurrent();
1526 $archiveNames = $batch->addOlds();
1527 $status = $batch->execute();
1528 $this->unlock(); // done
1530 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1532 // Purge the source and target files...
1533 $oldTitleFile = wfLocalFile( $this->title
);
1534 $newTitleFile = wfLocalFile( $target );
1535 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1536 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1537 $this->getRepo()->getMasterDB()->onTransactionIdle(
1538 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1539 $oldTitleFile->purgeEverything();
1540 foreach ( $archiveNames as $archiveName ) {
1541 $oldTitleFile->purgeOldThumbnails( $archiveName );
1543 $newTitleFile->purgeEverything();
1547 if ( $status->isOK() ) {
1548 // Now switch the object
1549 $this->title
= $target;
1550 // Force regeneration of the name and hashpath
1551 unset( $this->name
);
1552 unset( $this->hashPath
);
1559 * Delete all versions of the file.
1561 * Moves the files into an archive directory (or deletes them)
1562 * and removes the database rows.
1564 * Cache purging is done; logging is caller's responsibility.
1568 * @return FileRepoStatus object.
1570 function delete( $reason, $suppress = false ) {
1571 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1572 return $this->readOnlyFatalStatus();
1575 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1577 $this->lock(); // begin
1578 $batch->addCurrent();
1579 # Get old version relative paths
1580 $archiveNames = $batch->addOlds();
1581 $status = $batch->execute();
1582 $this->unlock(); // done
1584 if ( $status->isOK() ) {
1585 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1588 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1589 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1591 $this->getRepo()->getMasterDB()->onTransactionIdle(
1592 function () use ( $file, $archiveNames ) {
1595 $file->purgeEverything();
1596 foreach ( $archiveNames as $archiveName ) {
1597 $file->purgeOldThumbnails( $archiveName );
1600 if ( $wgUseSquid ) {
1602 $purgeUrls = array();
1603 foreach ( $archiveNames as $archiveName ) {
1604 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1606 SquidUpdate
::purge( $purgeUrls );
1615 * Delete an old version of the file.
1617 * Moves the file into an archive directory (or deletes it)
1618 * and removes the database row.
1620 * Cache purging is done; logging is caller's responsibility.
1622 * @param $archiveName String
1623 * @param $reason String
1624 * @param $suppress Boolean
1625 * @throws MWException or FSException on database or file store failure
1626 * @return FileRepoStatus object.
1628 function deleteOld( $archiveName, $reason, $suppress = false ) {
1630 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1631 return $this->readOnlyFatalStatus();
1634 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1636 $this->lock(); // begin
1637 $batch->addOld( $archiveName );
1638 $status = $batch->execute();
1639 $this->unlock(); // done
1641 $this->purgeOldThumbnails( $archiveName );
1642 if ( $status->isOK() ) {
1643 $this->purgeDescription();
1644 $this->purgeHistory();
1647 if ( $wgUseSquid ) {
1649 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1656 * Restore all or specified deleted revisions to the given file.
1657 * Permissions and logging are left to the caller.
1659 * May throw database exceptions on error.
1661 * @param array $versions set of record ids of deleted items to restore,
1662 * or empty to restore all revisions.
1663 * @param $unsuppress Boolean
1664 * @return FileRepoStatus
1666 function restore( $versions = array(), $unsuppress = false ) {
1667 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1668 return $this->readOnlyFatalStatus();
1671 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1673 $this->lock(); // begin
1677 $batch->addIds( $versions );
1679 $status = $batch->execute();
1680 if ( $status->isGood() ) {
1681 $cleanupStatus = $batch->cleanup();
1682 $cleanupStatus->successCount
= 0;
1683 $cleanupStatus->failCount
= 0;
1684 $status->merge( $cleanupStatus );
1686 $this->unlock(); // done
1691 /** isMultipage inherited */
1692 /** pageCount inherited */
1693 /** scaleHeight inherited */
1694 /** getImageSize inherited */
1697 * Get the URL of the file description page.
1700 function getDescriptionUrl() {
1701 return $this->title
->getLocalURL();
1705 * Get the HTML text of the description page
1706 * This is not used by ImagePage for local files, since (among other things)
1707 * it skips the parser cache.
1709 * @param $lang Language What language to get description in (Optional)
1710 * @return bool|mixed
1712 function getDescriptionText( $lang = null ) {
1713 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1717 $content = $revision->getContent();
1721 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1723 return $pout->getText();
1729 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1731 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1733 } elseif ( $audience == self
::FOR_THIS_USER
1734 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1738 return $this->description
;
1743 * @return bool|string
1745 function getTimestamp() {
1748 return $this->timestamp
;
1754 function getSha1() {
1756 // Initialise now if necessary
1757 if ( $this->sha1
== '' && $this->fileExists
) {
1758 $this->lock(); // begin
1760 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1761 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1762 $dbw = $this->repo
->getMasterDB();
1763 $dbw->update( 'image',
1764 array( 'img_sha1' => $this->sha1
),
1765 array( 'img_name' => $this->getName() ),
1767 $this->saveToCache();
1770 $this->unlock(); // done
1777 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1779 function isCacheable() {
1782 // If extra data (metadata) was not loaded then it must have been large
1783 return $this->extraDataLoaded
1784 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1788 * Start a transaction and lock the image for update
1789 * Increments a reference counter if the lock is already held
1790 * @return boolean True if the image exists, false otherwise
1793 $dbw = $this->repo
->getMasterDB();
1795 if ( !$this->locked
) {
1796 if ( !$dbw->trxLevel() ) {
1797 $dbw->begin( __METHOD__
);
1798 $this->lockedOwnTrx
= true;
1801 // Bug 54736: use simple lock to handle when the file does not exist.
1802 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1803 $cache = wfGetMainCache();
1804 $key = $this->getCacheKey();
1805 if ( !$cache->lock( $key, 60 ) ) {
1806 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1808 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1809 $cache->unlock( $key ); // release on commit
1813 return $dbw->selectField( 'image', '1',
1814 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1818 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1819 * the transaction and thereby releases the image lock.
1822 if ( $this->locked
) {
1824 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1825 $dbw = $this->repo
->getMasterDB();
1826 $dbw->commit( __METHOD__
);
1827 $this->lockedOwnTrx
= false;
1833 * Roll back the DB transaction and mark the image unlocked
1835 function unlockAndRollback() {
1836 $this->locked
= false;
1837 $dbw = $this->repo
->getMasterDB();
1838 $dbw->rollback( __METHOD__
);
1839 $this->lockedOwnTrx
= false;
1845 protected function readOnlyFatalStatus() {
1846 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1847 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1849 } // LocalFile class
1851 # ------------------------------------------------------------------------------
1854 * Helper class for file deletion
1855 * @ingroup FileAbstraction
1857 class LocalFileDeleteBatch
{
1864 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1869 * @param $reason string
1870 * @param $suppress bool
1872 function __construct( File
$file, $reason = '', $suppress = false ) {
1873 $this->file
= $file;
1874 $this->reason
= $reason;
1875 $this->suppress
= $suppress;
1876 $this->status
= $file->repo
->newGood();
1879 function addCurrent() {
1880 $this->srcRels
['.'] = $this->file
->getRel();
1884 * @param $oldName string
1886 function addOld( $oldName ) {
1887 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1888 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1892 * Add the old versions of the image to the batch
1893 * @return Array List of archive names from old versions
1895 function addOlds() {
1896 $archiveNames = array();
1898 $dbw = $this->file
->repo
->getMasterDB();
1899 $result = $dbw->select( 'oldimage',
1900 array( 'oi_archive_name' ),
1901 array( 'oi_name' => $this->file
->getName() ),
1905 foreach ( $result as $row ) {
1906 $this->addOld( $row->oi_archive_name
);
1907 $archiveNames[] = $row->oi_archive_name
;
1910 return $archiveNames;
1916 function getOldRels() {
1917 if ( !isset( $this->srcRels
['.'] ) ) {
1918 $oldRels =& $this->srcRels
;
1919 $deleteCurrent = false;
1921 $oldRels = $this->srcRels
;
1922 unset( $oldRels['.'] );
1923 $deleteCurrent = true;
1926 return array( $oldRels, $deleteCurrent );
1932 protected function getHashes() {
1934 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1936 if ( $deleteCurrent ) {
1937 $hashes['.'] = $this->file
->getSha1();
1940 if ( count( $oldRels ) ) {
1941 $dbw = $this->file
->repo
->getMasterDB();
1942 $res = $dbw->select(
1944 array( 'oi_archive_name', 'oi_sha1' ),
1945 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1949 foreach ( $res as $row ) {
1950 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1951 // Get the hash from the file
1952 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1953 $props = $this->file
->repo
->getFileProps( $oldUrl );
1955 if ( $props['fileExists'] ) {
1956 // Upgrade the oldimage row
1957 $dbw->update( 'oldimage',
1958 array( 'oi_sha1' => $props['sha1'] ),
1959 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1961 $hashes[$row->oi_archive_name
] = $props['sha1'];
1963 $hashes[$row->oi_archive_name
] = false;
1966 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1971 $missing = array_diff_key( $this->srcRels
, $hashes );
1973 foreach ( $missing as $name => $rel ) {
1974 $this->status
->error( 'filedelete-old-unregistered', $name );
1977 foreach ( $hashes as $name => $hash ) {
1979 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1980 unset( $hashes[$name] );
1987 function doDBInserts() {
1990 $dbw = $this->file
->repo
->getMasterDB();
1991 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1992 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1993 $encReason = $dbw->addQuotes( $this->reason
);
1994 $encGroup = $dbw->addQuotes( 'deleted' );
1995 $ext = $this->file
->getExtension();
1996 $dotExt = $ext === '' ?
'' : ".$ext";
1997 $encExt = $dbw->addQuotes( $dotExt );
1998 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2000 // Bitfields to further suppress the content
2001 if ( $this->suppress
) {
2003 // This should be 15...
2004 $bitfield |
= Revision
::DELETED_TEXT
;
2005 $bitfield |
= Revision
::DELETED_COMMENT
;
2006 $bitfield |
= Revision
::DELETED_USER
;
2007 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2009 $bitfield = 'oi_deleted';
2012 if ( $deleteCurrent ) {
2013 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2014 $where = array( 'img_name' => $this->file
->getName() );
2015 $dbw->insertSelect( 'filearchive', 'image',
2017 'fa_storage_group' => $encGroup,
2018 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
2019 'fa_deleted_user' => $encUserId,
2020 'fa_deleted_timestamp' => $encTimestamp,
2021 'fa_deleted_reason' => $encReason,
2022 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2024 'fa_name' => 'img_name',
2025 'fa_archive_name' => 'NULL',
2026 'fa_size' => 'img_size',
2027 'fa_width' => 'img_width',
2028 'fa_height' => 'img_height',
2029 'fa_metadata' => 'img_metadata',
2030 'fa_bits' => 'img_bits',
2031 'fa_media_type' => 'img_media_type',
2032 'fa_major_mime' => 'img_major_mime',
2033 'fa_minor_mime' => 'img_minor_mime',
2034 'fa_description' => 'img_description',
2035 'fa_user' => 'img_user',
2036 'fa_user_text' => 'img_user_text',
2037 'fa_timestamp' => 'img_timestamp',
2038 'fa_sha1' => 'img_sha1',
2039 ), $where, __METHOD__
);
2042 if ( count( $oldRels ) ) {
2043 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2045 'oi_name' => $this->file
->getName(),
2046 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
2047 $dbw->insertSelect( 'filearchive', 'oldimage',
2049 'fa_storage_group' => $encGroup,
2050 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
2051 'fa_deleted_user' => $encUserId,
2052 'fa_deleted_timestamp' => $encTimestamp,
2053 'fa_deleted_reason' => $encReason,
2054 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2056 'fa_name' => 'oi_name',
2057 'fa_archive_name' => 'oi_archive_name',
2058 'fa_size' => 'oi_size',
2059 'fa_width' => 'oi_width',
2060 'fa_height' => 'oi_height',
2061 'fa_metadata' => 'oi_metadata',
2062 'fa_bits' => 'oi_bits',
2063 'fa_media_type' => 'oi_media_type',
2064 'fa_major_mime' => 'oi_major_mime',
2065 'fa_minor_mime' => 'oi_minor_mime',
2066 'fa_description' => 'oi_description',
2067 'fa_user' => 'oi_user',
2068 'fa_user_text' => 'oi_user_text',
2069 'fa_timestamp' => 'oi_timestamp',
2070 'fa_sha1' => 'oi_sha1',
2071 ), $where, __METHOD__
);
2075 function doDBDeletes() {
2076 $dbw = $this->file
->repo
->getMasterDB();
2077 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2079 if ( count( $oldRels ) ) {
2080 $dbw->delete( 'oldimage',
2082 'oi_name' => $this->file
->getName(),
2083 'oi_archive_name' => array_keys( $oldRels )
2087 if ( $deleteCurrent ) {
2088 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2093 * Run the transaction
2094 * @return FileRepoStatus
2096 function execute() {
2097 wfProfileIn( __METHOD__
);
2099 $this->file
->lock();
2100 // Leave private files alone
2101 $privateFiles = array();
2102 list( $oldRels, ) = $this->getOldRels();
2103 $dbw = $this->file
->repo
->getMasterDB();
2105 if ( !empty( $oldRels ) ) {
2106 $res = $dbw->select( 'oldimage',
2107 array( 'oi_archive_name' ),
2108 array( 'oi_name' => $this->file
->getName(),
2109 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
2110 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2113 foreach ( $res as $row ) {
2114 $privateFiles[$row->oi_archive_name
] = 1;
2117 // Prepare deletion batch
2118 $hashes = $this->getHashes();
2119 $this->deletionBatch
= array();
2120 $ext = $this->file
->getExtension();
2121 $dotExt = $ext === '' ?
'' : ".$ext";
2123 foreach ( $this->srcRels
as $name => $srcRel ) {
2124 // Skip files that have no hash (missing source).
2125 // Keep private files where they are.
2126 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2127 $hash = $hashes[$name];
2128 $key = $hash . $dotExt;
2129 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2130 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2134 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2135 // We acquire this lock by running the inserts now, before the file operations.
2137 // This potentially has poor lock contention characteristics -- an alternative
2138 // scheme would be to insert stub filearchive entries with no fa_name and commit
2139 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2140 $this->doDBInserts();
2142 // Removes non-existent file from the batch, so we don't get errors.
2143 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2145 // Execute the file deletion batch
2146 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2148 if ( !$status->isGood() ) {
2149 $this->status
->merge( $status );
2152 if ( !$this->status
->isOK() ) {
2153 // Critical file deletion error
2154 // Roll back inserts, release lock and abort
2155 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2156 $this->file
->unlockAndRollback();
2157 wfProfileOut( __METHOD__
);
2159 return $this->status
;
2162 // Delete image/oldimage rows
2163 $this->doDBDeletes();
2165 // Commit and return
2166 $this->file
->unlock();
2167 wfProfileOut( __METHOD__
);
2169 return $this->status
;
2173 * Removes non-existent files from a deletion batch.
2174 * @param $batch array
2177 function removeNonexistentFiles( $batch ) {
2178 $files = $newBatch = array();
2180 foreach ( $batch as $batchItem ) {
2181 list( $src, ) = $batchItem;
2182 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2185 $result = $this->file
->repo
->fileExistsBatch( $files );
2187 foreach ( $batch as $batchItem ) {
2188 if ( $result[$batchItem[0]] ) {
2189 $newBatch[] = $batchItem;
2197 # ------------------------------------------------------------------------------
2200 * Helper class for file undeletion
2201 * @ingroup FileAbstraction
2203 class LocalFileRestoreBatch
{
2209 var $cleanupBatch, $ids, $all, $unsuppress = false;
2213 * @param $unsuppress bool
2215 function __construct( File
$file, $unsuppress = false ) {
2216 $this->file
= $file;
2217 $this->cleanupBatch
= $this->ids
= array();
2218 $this->ids
= array();
2219 $this->unsuppress
= $unsuppress;
2225 function addId( $fa_id ) {
2226 $this->ids
[] = $fa_id;
2230 * Add a whole lot of files by ID
2232 function addIds( $ids ) {
2233 $this->ids
= array_merge( $this->ids
, $ids );
2237 * Add all revisions of the file
2244 * Run the transaction, except the cleanup batch.
2245 * The cleanup batch should be run in a separate transaction, because it locks different
2246 * rows and there's no need to keep the image row locked while it's acquiring those locks
2247 * The caller may have its own transaction open.
2248 * So we save the batch and let the caller call cleanup()
2249 * @return FileRepoStatus
2251 function execute() {
2254 if ( !$this->all
&& !$this->ids
) {
2256 return $this->file
->repo
->newGood();
2259 $exists = $this->file
->lock();
2260 $dbw = $this->file
->repo
->getMasterDB();
2261 $status = $this->file
->repo
->newGood();
2263 // Fetch all or selected archived revisions for the file,
2264 // sorted from the most recent to the oldest.
2265 $conditions = array( 'fa_name' => $this->file
->getName() );
2267 if ( !$this->all
) {
2268 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2271 $result = $dbw->select(
2273 ArchivedFile
::selectFields(),
2276 array( 'ORDER BY' => 'fa_timestamp DESC' )
2279 $idsPresent = array();
2280 $storeBatch = array();
2281 $insertBatch = array();
2282 $insertCurrent = false;
2283 $deleteIds = array();
2285 $archiveNames = array();
2287 foreach ( $result as $row ) {
2288 $idsPresent[] = $row->fa_id
;
2290 if ( $row->fa_name
!= $this->file
->getName() ) {
2291 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2292 $status->failCount++
;
2296 if ( $row->fa_storage_key
== '' ) {
2297 // Revision was missing pre-deletion
2298 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2299 $status->failCount++
;
2303 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2304 $row->fa_storage_key
;
2305 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2307 if ( isset( $row->fa_sha1
) ) {
2308 $sha1 = $row->fa_sha1
;
2310 // old row, populate from key
2311 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2315 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2316 $sha1 = substr( $sha1, 1 );
2319 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2320 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2321 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2322 ||
is_null( $row->fa_metadata
)
2324 // Refresh our metadata
2325 // Required for a new current revision; nice for older ones too. :)
2326 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2329 'minor_mime' => $row->fa_minor_mime
,
2330 'major_mime' => $row->fa_major_mime
,
2331 'media_type' => $row->fa_media_type
,
2332 'metadata' => $row->fa_metadata
2336 if ( $first && !$exists ) {
2337 // This revision will be published as the new current version
2338 $destRel = $this->file
->getRel();
2339 $insertCurrent = array(
2340 'img_name' => $row->fa_name
,
2341 'img_size' => $row->fa_size
,
2342 'img_width' => $row->fa_width
,
2343 'img_height' => $row->fa_height
,
2344 'img_metadata' => $props['metadata'],
2345 'img_bits' => $row->fa_bits
,
2346 'img_media_type' => $props['media_type'],
2347 'img_major_mime' => $props['major_mime'],
2348 'img_minor_mime' => $props['minor_mime'],
2349 'img_description' => $row->fa_description
,
2350 'img_user' => $row->fa_user
,
2351 'img_user_text' => $row->fa_user_text
,
2352 'img_timestamp' => $row->fa_timestamp
,
2356 // The live (current) version cannot be hidden!
2357 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2358 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2359 $this->cleanupBatch
[] = $row->fa_storage_key
;
2362 $archiveName = $row->fa_archive_name
;
2364 if ( $archiveName == '' ) {
2365 // This was originally a current version; we
2366 // have to devise a new archive name for it.
2367 // Format is <timestamp of archiving>!<name>
2368 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2371 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2373 } while ( isset( $archiveNames[$archiveName] ) );
2376 $archiveNames[$archiveName] = true;
2377 $destRel = $this->file
->getArchiveRel( $archiveName );
2378 $insertBatch[] = array(
2379 'oi_name' => $row->fa_name
,
2380 'oi_archive_name' => $archiveName,
2381 'oi_size' => $row->fa_size
,
2382 'oi_width' => $row->fa_width
,
2383 'oi_height' => $row->fa_height
,
2384 'oi_bits' => $row->fa_bits
,
2385 'oi_description' => $row->fa_description
,
2386 'oi_user' => $row->fa_user
,
2387 'oi_user_text' => $row->fa_user_text
,
2388 'oi_timestamp' => $row->fa_timestamp
,
2389 'oi_metadata' => $props['metadata'],
2390 'oi_media_type' => $props['media_type'],
2391 'oi_major_mime' => $props['major_mime'],
2392 'oi_minor_mime' => $props['minor_mime'],
2393 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2394 'oi_sha1' => $sha1 );
2397 $deleteIds[] = $row->fa_id
;
2399 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2400 // private files can stay where they are
2401 $status->successCount++
;
2403 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2404 $this->cleanupBatch
[] = $row->fa_storage_key
;
2412 // Add a warning to the status object for missing IDs
2413 $missingIds = array_diff( $this->ids
, $idsPresent );
2415 foreach ( $missingIds as $id ) {
2416 $status->error( 'undelete-missing-filearchive', $id );
2419 // Remove missing files from batch, so we don't get errors when undeleting them
2420 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2422 // Run the store batch
2423 // Use the OVERWRITE_SAME flag to smooth over a common error
2424 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2425 $status->merge( $storeStatus );
2427 if ( !$status->isGood() ) {
2428 // Even if some files could be copied, fail entirely as that is the
2429 // easiest thing to do without data loss
2430 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2431 $status->ok
= false;
2432 $this->file
->unlock();
2437 // Run the DB updates
2438 // Because we have locked the image row, key conflicts should be rare.
2439 // If they do occur, we can roll back the transaction at this time with
2440 // no data loss, but leaving unregistered files scattered throughout the
2442 // This is not ideal, which is why it's important to lock the image row.
2443 if ( $insertCurrent ) {
2444 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2447 if ( $insertBatch ) {
2448 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2452 $dbw->delete( 'filearchive',
2453 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2457 // If store batch is empty (all files are missing), deletion is to be considered successful
2458 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2460 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2462 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2464 $this->file
->purgeEverything();
2466 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2467 $this->file
->purgeDescription();
2468 $this->file
->purgeHistory();
2472 $this->file
->unlock();
2478 * Removes non-existent files from a store batch.
2479 * @param $triplets array
2482 function removeNonexistentFiles( $triplets ) {
2483 $files = $filteredTriplets = array();
2484 foreach ( $triplets as $file ) {
2485 $files[$file[0]] = $file[0];
2488 $result = $this->file
->repo
->fileExistsBatch( $files );
2490 foreach ( $triplets as $file ) {
2491 if ( $result[$file[0]] ) {
2492 $filteredTriplets[] = $file;
2496 return $filteredTriplets;
2500 * Removes non-existent files from a cleanup batch.
2501 * @param $batch array
2504 function removeNonexistentFromCleanup( $batch ) {
2505 $files = $newBatch = array();
2506 $repo = $this->file
->repo
;
2508 foreach ( $batch as $file ) {
2509 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2510 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2513 $result = $repo->fileExistsBatch( $files );
2515 foreach ( $batch as $file ) {
2516 if ( $result[$file] ) {
2517 $newBatch[] = $file;
2525 * Delete unused files in the deleted zone.
2526 * This should be called from outside the transaction in which execute() was called.
2527 * @return FileRepoStatus
2529 function cleanup() {
2530 if ( !$this->cleanupBatch
) {
2531 return $this->file
->repo
->newGood();
2534 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2536 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2542 * Cleanup a failed batch. The batch was only partially successful, so
2543 * rollback by removing all items that were succesfully copied.
2545 * @param Status $storeStatus
2546 * @param array $storeBatch
2548 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2549 $cleanupBatch = array();
2551 foreach ( $storeStatus->success
as $i => $success ) {
2552 // Check if this item of the batch was successfully copied
2554 // Item was successfully copied and needs to be removed again
2555 // Extract ($dstZone, $dstRel) from the batch
2556 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2559 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2563 # ------------------------------------------------------------------------------
2566 * Helper class for file movement
2567 * @ingroup FileAbstraction
2569 class LocalFileMoveBatch
{
2581 var $cur, $olds, $oldCount, $archive;
2590 * @param Title $target
2592 function __construct( File
$file, Title
$target ) {
2593 $this->file
= $file;
2594 $this->target
= $target;
2595 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2596 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2597 $this->oldName
= $this->file
->getName();
2598 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2599 $this->oldRel
= $this->oldHash
. $this->oldName
;
2600 $this->newRel
= $this->newHash
. $this->newName
;
2601 $this->db
= $file->getRepo()->getMasterDb();
2605 * Add the current image to the batch
2607 function addCurrent() {
2608 $this->cur
= array( $this->oldRel
, $this->newRel
);
2612 * Add the old versions of the image to the batch
2613 * @return Array List of archive names from old versions
2615 function addOlds() {
2616 $archiveBase = 'archive';
2617 $this->olds
= array();
2618 $this->oldCount
= 0;
2619 $archiveNames = array();
2621 $result = $this->db
->select( 'oldimage',
2622 array( 'oi_archive_name', 'oi_deleted' ),
2623 array( 'oi_name' => $this->oldName
),
2627 foreach ( $result as $row ) {
2628 $archiveNames[] = $row->oi_archive_name
;
2629 $oldName = $row->oi_archive_name
;
2630 $bits = explode( '!', $oldName, 2 );
2632 if ( count( $bits ) != 2 ) {
2633 wfDebug( "Old file name missing !: '$oldName' \n" );
2637 list( $timestamp, $filename ) = $bits;
2639 if ( $this->oldName
!= $filename ) {
2640 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2646 // Do we want to add those to oldCount?
2647 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2651 $this->olds
[] = array(
2652 "{$archiveBase}/{$this->oldHash}{$oldName}",
2653 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2657 return $archiveNames;
2662 * @return FileRepoStatus
2664 function execute() {
2665 $repo = $this->file
->repo
;
2666 $status = $repo->newGood();
2668 $triplets = $this->getMoveTriplets();
2669 $triplets = $this->removeNonexistentFiles( $triplets );
2671 $this->file
->lock(); // begin
2672 // Rename the file versions metadata in the DB.
2673 // This implicitly locks the destination file, which avoids race conditions.
2674 // If we moved the files from A -> C before DB updates, another process could
2675 // move files from B -> C at this point, causing storeBatch() to fail and thus
2676 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2677 $statusDb = $this->doDBUpdates();
2678 if ( !$statusDb->isGood() ) {
2679 $this->file
->unlockAndRollback();
2680 $statusDb->ok
= false;
2684 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2685 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2687 // Copy the files into their new location.
2688 // If a prior process fataled copying or cleaning up files we tolerate any
2689 // of the existing files if they are identical to the ones being stored.
2690 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2691 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2692 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2693 if ( !$statusMove->isGood() ) {
2694 // Delete any files copied over (while the destination is still locked)
2695 $this->cleanupTarget( $triplets );
2696 $this->file
->unlockAndRollback(); // unlocks the destination
2697 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2698 $statusMove->ok
= false;
2702 $this->file
->unlock(); // done
2704 // Everything went ok, remove the source files
2705 $this->cleanupSource( $triplets );
2707 $status->merge( $statusDb );
2708 $status->merge( $statusMove );
2714 * Do the database updates and return a new FileRepoStatus indicating how
2715 * many rows where updated.
2717 * @return FileRepoStatus
2719 function doDBUpdates() {
2720 $repo = $this->file
->repo
;
2721 $status = $repo->newGood();
2724 // Update current image
2727 array( 'img_name' => $this->newName
),
2728 array( 'img_name' => $this->oldName
),
2732 if ( $dbw->affectedRows() ) {
2733 $status->successCount++
;
2735 $status->failCount++
;
2736 $status->fatal( 'imageinvalidfilename' );
2741 // Update old images
2745 'oi_name' => $this->newName
,
2746 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2747 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2749 array( 'oi_name' => $this->oldName
),
2753 $affected = $dbw->affectedRows();
2754 $total = $this->oldCount
;
2755 $status->successCount +
= $affected;
2756 // Bug 34934: $total is based on files that actually exist.
2757 // There may be more DB rows than such files, in which case $affected
2758 // can be greater than $total. We use max() to avoid negatives here.
2759 $status->failCount +
= max( 0, $total - $affected );
2760 if ( $status->failCount
) {
2761 $status->error( 'imageinvalidfilename' );
2768 * Generate triplets for FileRepo::storeBatch().
2771 function getMoveTriplets() {
2772 $moves = array_merge( array( $this->cur
), $this->olds
);
2773 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2775 foreach ( $moves as $move ) {
2776 // $move: (oldRelativePath, newRelativePath)
2777 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2778 $triplets[] = array( $srcUrl, 'public', $move[1] );
2781 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2789 * Removes non-existent files from move batch.
2790 * @param $triplets array
2793 function removeNonexistentFiles( $triplets ) {
2796 foreach ( $triplets as $file ) {
2797 $files[$file[0]] = $file[0];
2800 $result = $this->file
->repo
->fileExistsBatch( $files );
2801 $filteredTriplets = array();
2803 foreach ( $triplets as $file ) {
2804 if ( $result[$file[0]] ) {
2805 $filteredTriplets[] = $file;
2807 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2811 return $filteredTriplets;
2815 * Cleanup a partially moved array of triplets by deleting the target
2816 * files. Called if something went wrong half way.
2818 function cleanupTarget( $triplets ) {
2819 // Create dest pairs from the triplets
2821 foreach ( $triplets as $triplet ) {
2822 // $triplet: (old source virtual URL, dst zone, dest rel)
2823 $pairs[] = array( $triplet[1], $triplet[2] );
2826 $this->file
->repo
->cleanupBatch( $pairs );
2830 * Cleanup a fully moved array of triplets by deleting the source files.
2831 * Called at the end of the move process if everything else went ok.
2833 function cleanupSource( $triplets ) {
2834 // Create source file names from the triplets
2836 foreach ( $triplets as $triplet ) {
2837 $files[] = $triplet[0];
2840 $this->file
->repo
->cleanupBatch( $files );