3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 9 );
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const CACHE_FIELD_MAX_LEN
= 1000;
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
52 /** @var int image width */
55 /** @var int image height */
58 /** @var int Returned by getimagesize (loadFromXxx) */
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
67 /** @var int Size in bytes (loadFromXxx) */
70 /** @var string Handler-specific metadata */
73 /** @var string SHA-1 base 36 content hash */
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
82 /** @var int Bitfield akin to rev_deleted */
86 protected $repoClass = 'LocalRepo';
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
94 /** @var string Major mime type */
97 /** @var string Minor mime type */
100 /** @var string Upload timestamp */
103 /** @var int User ID of uploader */
106 /** @var string User name of uploader */
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var bool Whether the row was upgraded on load */
115 /** @var bool True if the image row is locked */
118 /** @var bool True if the image row is locked with a lock initiated transaction */
119 private $lockedOwnTrx;
121 /** @var bool True if file is not present in file system. Not to be cached in memcached */
124 const LOAD_ALL
= 1; // integer; load all the lazy fields too (like metadata)
127 * Create a LocalFile from a title
128 * Do not call this except from inside a repo class.
130 * Note: $unused param is only here to avoid an E_STRICT
138 static function newFromTitle( $title, $repo, $unused = null ) {
139 return new self( $title, $repo );
143 * Create a LocalFile from a title
144 * Do not call this except from inside a repo class.
151 static function newFromRow( $row, $repo ) {
152 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
153 $file = new self( $title, $repo );
154 $file->loadFromRow( $row );
160 * Create a LocalFile from a SHA-1 key
161 * Do not call this except from inside a repo class.
163 * @param string $sha1 base-36 SHA-1
164 * @param $repo LocalRepo
165 * @param string|bool $timestamp MW_timestamp (optional)
167 * @return bool|LocalFile
169 static function newFromKey( $sha1, $repo, $timestamp = false ) {
170 $dbr = $repo->getSlaveDB();
172 $conds = array( 'img_sha1' => $sha1 );
174 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
177 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
179 return self
::newFromRow( $row, $repo );
186 * Fields in the image table
189 static function selectFields() {
210 * Do not call this except from inside a repo class.
212 function __construct( $title, $repo ) {
213 parent
::__construct( $title, $repo );
215 $this->metadata
= '';
216 $this->historyLine
= 0;
217 $this->historyRes
= null;
218 $this->dataLoaded
= false;
219 $this->extraDataLoaded
= false;
221 $this->assertRepoDefined();
222 $this->assertTitleDefined();
226 * Get the memcached key for the main data for this file, or false if
227 * there is no access to the shared cache.
230 function getCacheKey() {
231 $hashedName = md5( $this->getName() );
233 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
237 * Try to load file metadata from memcached. Returns true on success.
240 function loadFromCache() {
243 wfProfileIn( __METHOD__
);
244 $this->dataLoaded
= false;
245 $this->extraDataLoaded
= false;
246 $key = $this->getCacheKey();
249 wfProfileOut( __METHOD__
);
254 $cachedValues = $wgMemc->get( $key );
256 // Check if the key existed and belongs to this version of MediaWiki
257 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
258 wfDebug( "Pulling file metadata from cache key $key\n" );
259 $this->fileExists
= $cachedValues['fileExists'];
260 if ( $this->fileExists
) {
261 $this->setProps( $cachedValues );
263 $this->dataLoaded
= true;
264 $this->extraDataLoaded
= true;
265 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
266 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
270 if ( $this->dataLoaded
) {
271 wfIncrStats( 'image_cache_hit' );
273 wfIncrStats( 'image_cache_miss' );
276 wfProfileOut( __METHOD__
);
278 return $this->dataLoaded
;
282 * Save the file metadata to memcached
284 function saveToCache() {
288 $key = $this->getCacheKey();
294 $fields = $this->getCacheFields( '' );
295 $cache = array( 'version' => MW_FILE_VERSION
);
296 $cache['fileExists'] = $this->fileExists
;
298 if ( $this->fileExists
) {
299 foreach ( $fields as $field ) {
300 $cache[$field] = $this->$field;
304 // Strip off excessive entries from the subset of fields that can become large.
305 // If the cache value gets to large it will not fit in memcached and nothing will
306 // get cached at all, causing master queries for any file access.
307 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
308 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
309 unset( $cache[$field] ); // don't let the value get too big
313 // Cache presence for 1 week and negatives for 1 day
314 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
318 * Load metadata from the file itself
320 function loadFromFile() {
321 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
322 $this->setProps( $props );
326 * @param $prefix string
329 function getCacheFields( $prefix = 'img_' ) {
330 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
331 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
332 'user_text', 'description' );
333 static $results = array();
335 if ( $prefix == '' ) {
339 if ( !isset( $results[$prefix] ) ) {
340 $prefixedFields = array();
341 foreach ( $fields as $field ) {
342 $prefixedFields[] = $prefix . $field;
344 $results[$prefix] = $prefixedFields;
347 return $results[$prefix];
353 function getLazyCacheFields( $prefix = 'img_' ) {
354 static $fields = array( 'metadata' );
355 static $results = array();
357 if ( $prefix == '' ) {
361 if ( !isset( $results[$prefix] ) ) {
362 $prefixedFields = array();
363 foreach ( $fields as $field ) {
364 $prefixedFields[] = $prefix . $field;
366 $results[$prefix] = $prefixedFields;
369 return $results[$prefix];
373 * Load file metadata from the DB
375 function loadFromDB() {
376 # Polymorphic function name to distinguish foreign and local fetches
377 $fname = get_class( $this ) . '::' . __FUNCTION__
;
378 wfProfileIn( $fname );
380 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
381 $this->dataLoaded
= true;
382 $this->extraDataLoaded
= true;
384 $dbr = $this->repo
->getMasterDB();
385 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
386 array( 'img_name' => $this->getName() ), $fname );
389 $this->loadFromRow( $row );
391 $this->fileExists
= false;
394 wfProfileOut( $fname );
398 * Load lazy file metadata from the DB.
399 * This covers fields that are sometimes not cached.
401 protected function loadExtraFromDB() {
402 # Polymorphic function name to distinguish foreign and local fetches
403 $fname = get_class( $this ) . '::' . __FUNCTION__
;
404 wfProfileIn( $fname );
406 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
407 $this->extraDataLoaded
= true;
409 $dbr = $this->repo
->getSlaveDB();
410 // In theory the file could have just been renamed/deleted...oh well
411 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
412 array( 'img_name' => $this->getName() ), $fname );
414 if ( !$row ) { // fallback to master
415 $dbr = $this->repo
->getMasterDB();
416 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
417 array( 'img_name' => $this->getName() ), $fname );
421 foreach ( $this->unprefixRow( $row, 'img_' ) as $name => $value ) {
422 $this->$name = $value;
425 wfProfileOut( $fname );
426 throw new MWException( "Could not find data for image '{$this->getName()}'." );
429 wfProfileOut( $fname );
434 * @param $prefix string
437 protected function unprefixRow( $row, $prefix = 'img_' ) {
438 $array = (array)$row;
439 $prefixLength = strlen( $prefix );
441 // Sanity check prefix once
442 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
443 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
447 foreach ( $array as $name => $value ) {
448 $decoded[substr( $name, $prefixLength )] = $value;
455 * Decode a row from the database (either object or array) to an array
456 * with timestamps and MIME types decoded, and the field prefix removed.
458 * @param $prefix string
459 * @throws MWException
462 function decodeRow( $row, $prefix = 'img_' ) {
463 $decoded = $this->unprefixRow( $row, $prefix );
465 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
467 if ( empty( $decoded['major_mime'] ) ) {
468 $decoded['mime'] = 'unknown/unknown';
470 if ( !$decoded['minor_mime'] ) {
471 $decoded['minor_mime'] = 'unknown';
473 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
476 # Trim zero padding from char/binary field
477 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
483 * Load file metadata from a DB result row
485 function loadFromRow( $row, $prefix = 'img_' ) {
486 $this->dataLoaded
= true;
487 $this->extraDataLoaded
= true;
489 $array = $this->decodeRow( $row, $prefix );
491 foreach ( $array as $name => $value ) {
492 $this->$name = $value;
495 $this->fileExists
= true;
496 $this->maybeUpgradeRow();
500 * Load file metadata from cache or DB, unless already loaded
501 * @param integer $flags
503 function load( $flags = 0 ) {
504 if ( !$this->dataLoaded
) {
505 if ( !$this->loadFromCache() ) {
507 $this->saveToCache();
509 $this->dataLoaded
= true;
511 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
512 $this->loadExtraFromDB();
517 * Upgrade a row if it needs it
519 function maybeUpgradeRow() {
520 global $wgUpdateCompatibleMetadata;
521 if ( wfReadOnly() ) {
525 if ( is_null( $this->media_type
) ||
526 $this->mime
== 'image/svg'
529 $this->upgraded
= true;
531 $handler = $this->getHandler();
533 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
534 if ( $validity === MediaHandler
::METADATA_BAD
535 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
538 $this->upgraded
= true;
544 function getUpgraded() {
545 return $this->upgraded
;
549 * Fix assorted version-related problems with the image row by reloading it from the file
551 function upgradeRow() {
552 wfProfileIn( __METHOD__
);
554 $this->lock(); // begin
556 $this->loadFromFile();
558 # Don't destroy file info of missing files
559 if ( !$this->fileExists
) {
560 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
561 wfProfileOut( __METHOD__
);
566 $dbw = $this->repo
->getMasterDB();
567 list( $major, $minor ) = self
::splitMime( $this->mime
);
569 if ( wfReadOnly() ) {
570 wfProfileOut( __METHOD__
);
574 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
576 $dbw->update( 'image',
578 'img_size' => $this->size
, // sanity
579 'img_width' => $this->width
,
580 'img_height' => $this->height
,
581 'img_bits' => $this->bits
,
582 'img_media_type' => $this->media_type
,
583 'img_major_mime' => $major,
584 'img_minor_mime' => $minor,
585 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
586 'img_sha1' => $this->sha1
,
588 array( 'img_name' => $this->getName() ),
592 $this->saveToCache();
594 $this->unlock(); // done
596 wfProfileOut( __METHOD__
);
600 * Set properties in this object to be equal to those given in the
601 * associative array $info. Only cacheable fields can be set.
602 * All fields *must* be set in $info except for getLazyCacheFields().
604 * If 'mime' is given, it will be split into major_mime/minor_mime.
605 * If major_mime/minor_mime are given, $this->mime will also be set.
607 function setProps( $info ) {
608 $this->dataLoaded
= true;
609 $fields = $this->getCacheFields( '' );
610 $fields[] = 'fileExists';
612 foreach ( $fields as $field ) {
613 if ( isset( $info[$field] ) ) {
614 $this->$field = $info[$field];
618 // Fix up mime fields
619 if ( isset( $info['major_mime'] ) ) {
620 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
621 } elseif ( isset( $info['mime'] ) ) {
622 $this->mime
= $info['mime'];
623 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
627 /** splitMime inherited */
628 /** getName inherited */
629 /** getTitle inherited */
630 /** getURL inherited */
631 /** getViewURL inherited */
632 /** getPath inherited */
633 /** isVisible inhereted */
638 function isMissing() {
639 if ( $this->missing
=== null ) {
640 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
641 $this->missing
= !$fileExists;
644 return $this->missing
;
648 * Return the width of the image
653 public function getWidth( $page = 1 ) {
656 if ( $this->isMultipage() ) {
657 $handler = $this->getHandler();
661 $dim = $handler->getPageDimensions( $this, $page );
663 return $dim['width'];
665 // For non-paged media, the false goes through an
666 // intval, turning failure into 0, so do same here.
675 * Return the height of the image
680 public function getHeight( $page = 1 ) {
683 if ( $this->isMultipage() ) {
684 $handler = $this->getHandler();
688 $dim = $handler->getPageDimensions( $this, $page );
690 return $dim['height'];
692 // For non-paged media, the false goes through an
693 // intval, turning failure into 0, so do same here.
697 return $this->height
;
702 * Returns ID or name of user who uploaded the file
704 * @param string $type 'text' or 'id'
707 function getUser( $type = 'text' ) {
710 if ( $type == 'text' ) {
711 return $this->user_text
;
712 } elseif ( $type == 'id' ) {
718 * Get handler-specific metadata
721 function getMetadata() {
722 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
723 return $this->metadata
;
729 function getBitDepth() {
736 * Return the size of the image file, in bytes
739 public function getSize() {
746 * Returns the mime type of the file.
749 function getMimeType() {
756 * Return the type of the media in the file.
757 * Use the value returned by this function with the MEDIATYPE_xxx constants.
760 function getMediaType() {
763 return $this->media_type
;
766 /** canRender inherited */
767 /** mustRender inherited */
768 /** allowInlineDisplay inherited */
769 /** isSafeFile inherited */
770 /** isTrustedFile inherited */
773 * Returns true if the file exists on disk.
774 * @return boolean Whether file exist on disk.
776 public function exists() {
779 return $this->fileExists
;
782 /** getTransformScript inherited */
783 /** getUnscaledThumb inherited */
784 /** thumbName inherited */
785 /** createThumb inherited */
786 /** transform inherited */
789 * Fix thumbnail files from 1.4 or before, with extreme prejudice
790 * @todo : do we still care about this? Perhaps a maintenance script
791 * can be made instead. Enabling this code results in a serious
792 * RTT regression for wikis without 404 handling.
794 function migrateThumbFile( $thumbName ) {
795 /* Old code for bug 2532
796 $thumbDir = $this->getThumbPath();
797 $thumbPath = "$thumbDir/$thumbName";
798 if ( is_dir( $thumbPath ) ) {
799 // Directory where file should be
800 // This happened occasionally due to broken migration code in 1.5
801 // Rename to broken-*
802 for ( $i = 0; $i < 100; $i++ ) {
803 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
804 if ( !file_exists( $broken ) ) {
805 rename( $thumbPath, $broken );
809 // Doesn't exist anymore
814 if ( $this->repo->fileExists( $thumbDir ) ) {
815 // Delete file where directory should be
816 $this->repo->cleanupBatch( array( $thumbDir ) );
821 /** getHandler inherited */
822 /** iconThumb inherited */
823 /** getLastError inherited */
826 * Get all thumbnail names previously generated for this file
827 * @param string|bool $archiveName Name of an archive file, default false
828 * @return array first element is the base dir, then files in that base dir.
830 function getThumbnails( $archiveName = false ) {
831 if ( $archiveName ) {
832 $dir = $this->getArchiveThumbPath( $archiveName );
834 $dir = $this->getThumbPath();
837 $backend = $this->repo
->getBackend();
838 $files = array( $dir );
840 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
841 foreach ( $iterator as $file ) {
844 } catch ( FileBackendError
$e ) {
845 } // suppress (bug 54674)
851 * Refresh metadata in memcached, but don't touch thumbnails or squid
853 function purgeMetadataCache() {
855 $this->saveToCache();
856 $this->purgeHistory();
860 * Purge the shared history (OldLocalFile) cache.
862 * @note This used to purge old thumbnails as well.
864 function purgeHistory() {
867 $hashedName = md5( $this->getName() );
868 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
871 $wgMemc->delete( $oldKey );
876 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
878 * @param Array $options An array potentially with the key forThumbRefresh.
880 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
882 function purgeCache( $options = array() ) {
883 wfProfileIn( __METHOD__
);
884 // Refresh metadata cache
885 $this->purgeMetadataCache();
888 $this->purgeThumbnails( $options );
890 // Purge squid cache for this file
891 SquidUpdate
::purge( array( $this->getURL() ) );
892 wfProfileOut( __METHOD__
);
896 * Delete cached transformed files for an archived version only.
897 * @param string $archiveName name of the archived file
899 function purgeOldThumbnails( $archiveName ) {
901 wfProfileIn( __METHOD__
);
903 // Get a list of old thumbnails and URLs
904 $files = $this->getThumbnails( $archiveName );
905 $dir = array_shift( $files );
906 $this->purgeThumbList( $dir, $files );
908 // Purge any custom thumbnail caches
909 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
914 foreach ( $files as $file ) {
915 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
917 SquidUpdate
::purge( $urls );
920 wfProfileOut( __METHOD__
);
924 * Delete cached transformed files for the current version only.
926 function purgeThumbnails( $options = array() ) {
928 wfProfileIn( __METHOD__
);
931 $files = $this->getThumbnails();
932 // Always purge all files from squid regardless of handler filters
935 foreach ( $files as $file ) {
936 $urls[] = $this->getThumbUrl( $file );
938 array_shift( $urls ); // don't purge directory
941 // Give media handler a chance to filter the file purge list
942 if ( !empty( $options['forThumbRefresh'] ) ) {
943 $handler = $this->getHandler();
945 $handler->filterThumbnailPurgeList( $files, $options );
949 $dir = array_shift( $files );
950 $this->purgeThumbList( $dir, $files );
952 // Purge any custom thumbnail caches
953 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
957 SquidUpdate
::purge( $urls );
960 wfProfileOut( __METHOD__
);
964 * Delete a list of thumbnails visible at urls
965 * @param string $dir base dir of the files.
966 * @param array $files of strings: relative filenames (to $dir)
968 protected function purgeThumbList( $dir, $files ) {
969 $fileListDebug = strtr(
970 var_export( $files, true ),
973 wfDebug( __METHOD__
. ": $fileListDebug\n" );
975 $purgeList = array();
976 foreach ( $files as $file ) {
977 # Check that the base file name is part of the thumb name
978 # This is a basic sanity check to avoid erasing unrelated directories
979 if ( strpos( $file, $this->getName() ) !== false
980 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
982 $purgeList[] = "{$dir}/{$file}";
986 # Delete the thumbnails
987 $this->repo
->quickPurgeBatch( $purgeList );
988 # Clear out the thumbnail directory if empty
989 $this->repo
->quickCleanDir( $dir );
992 /** purgeDescription inherited */
993 /** purgeEverything inherited */
1002 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1003 $dbr = $this->repo
->getSlaveDB();
1004 $tables = array( 'oldimage' );
1005 $fields = OldLocalFile
::selectFields();
1006 $conds = $opts = $join_conds = array();
1007 $eq = $inc ?
'=' : '';
1008 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1011 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1015 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1019 $opts['LIMIT'] = $limit;
1022 // Search backwards for time > x queries
1023 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1024 $opts['ORDER BY'] = "oi_timestamp $order";
1025 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1027 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1028 &$conds, &$opts, &$join_conds ) );
1030 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1033 foreach ( $res as $row ) {
1034 $r[] = $this->repo
->newFileFromRow( $row );
1037 if ( $order == 'ASC' ) {
1038 $r = array_reverse( $r ); // make sure it ends up descending
1045 * Return the history of this file, line by line.
1046 * starts with current version, then old versions.
1047 * uses $this->historyLine to check which line to return:
1048 * 0 return line for current version
1049 * 1 query for old versions, return first one
1050 * 2, ... return next old version from above query
1053 public function nextHistoryLine() {
1054 # Polymorphic function name to distinguish foreign and local fetches
1055 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1057 $dbr = $this->repo
->getSlaveDB();
1059 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1060 $this->historyRes
= $dbr->select( 'image',
1063 "'' AS oi_archive_name",
1067 array( 'img_name' => $this->title
->getDBkey() ),
1071 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1072 $this->historyRes
= null;
1076 } elseif ( $this->historyLine
== 1 ) {
1077 $this->historyRes
= $dbr->select( 'oldimage', '*',
1078 array( 'oi_name' => $this->title
->getDBkey() ),
1080 array( 'ORDER BY' => 'oi_timestamp DESC' )
1083 $this->historyLine++
;
1085 return $dbr->fetchObject( $this->historyRes
);
1089 * Reset the history pointer to the first element of the history
1091 public function resetHistory() {
1092 $this->historyLine
= 0;
1094 if ( !is_null( $this->historyRes
) ) {
1095 $this->historyRes
= null;
1099 /** getHashPath inherited */
1100 /** getRel inherited */
1101 /** getUrlRel inherited */
1102 /** getArchiveRel inherited */
1103 /** getArchivePath inherited */
1104 /** getThumbPath inherited */
1105 /** getArchiveUrl inherited */
1106 /** getThumbUrl inherited */
1107 /** getArchiveVirtualUrl inherited */
1108 /** getThumbVirtualUrl inherited */
1109 /** isHashed inherited */
1112 * Upload a file and record it in the DB
1113 * @param string $srcPath source storage path, virtual URL, or filesystem path
1114 * @param string $comment upload description
1115 * @param string $pageText text to use for the new description page,
1116 * if a new description page is created
1117 * @param $flags Integer|bool: flags for publish()
1118 * @param array|bool $props File properties, if known. This can be used to reduce the
1119 * upload time when uploading virtual URLs for which the file info
1121 * @param string|bool $timestamp timestamp for img_timestamp, or false to use the current time
1122 * @param $user User|null: User object or null to use $wgUser
1124 * @return FileRepoStatus object. On success, the value member contains the
1125 * archive name, or an empty string if it was a new file.
1127 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1128 $timestamp = false, $user = null
1132 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1133 return $this->readOnlyFatalStatus();
1137 wfProfileIn( __METHOD__
. '-getProps' );
1138 if ( $this->repo
->isVirtualUrl( $srcPath )
1139 || FileBackend
::isStoragePath( $srcPath )
1141 $props = $this->repo
->getFileProps( $srcPath );
1143 $props = FSFile
::getPropsFromPath( $srcPath );
1145 wfProfileOut( __METHOD__
. '-getProps' );
1149 $handler = MediaHandler
::getHandler( $props['mime'] );
1151 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1153 $options['headers'] = array();
1156 // Trim spaces on user supplied text
1157 $comment = trim( $comment );
1159 // truncate nicely or the DB will do it for us
1160 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1161 $comment = $wgContLang->truncate( $comment, 255 );
1162 $this->lock(); // begin
1163 $status = $this->publish( $srcPath, $flags, $options );
1165 if ( $status->successCount
> 0 ) {
1166 # Essentially we are displacing any existing current file and saving
1167 # a new current file at the old location. If just the first succeeded,
1168 # we still need to displace the current DB entry and put in a new one.
1169 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1170 $status->fatal( 'filenotfound', $srcPath );
1174 $this->unlock(); // done
1180 * Record a file upload in the upload log and the image table
1182 * @param $desc string
1183 * @param $license string
1184 * @param $copyStatus string
1185 * @param $source string
1186 * @param $watch bool
1187 * @param $timestamp string|bool
1188 * @param $user User object or null to use $wgUser
1191 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1192 $watch = false, $timestamp = false, User
$user = null ) {
1198 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1200 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1205 $user->addWatch( $this->getTitle() );
1212 * Record a file upload in the upload log and the image table
1214 * @param $comment string
1215 * @param $pageText string
1216 * @param $props bool|array
1217 * @param $timestamp bool|string
1218 * @param $user null|User
1221 function recordUpload2(
1222 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1224 wfProfileIn( __METHOD__
);
1226 if ( is_null( $user ) ) {
1231 $dbw = $this->repo
->getMasterDB();
1232 $dbw->begin( __METHOD__
);
1235 wfProfileIn( __METHOD__
. '-getProps' );
1236 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1237 wfProfileOut( __METHOD__
. '-getProps' );
1240 if ( $timestamp === false ) {
1241 $timestamp = $dbw->timestamp();
1244 $props['description'] = $comment;
1245 $props['user'] = $user->getId();
1246 $props['user_text'] = $user->getName();
1247 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1248 $this->setProps( $props );
1250 # Fail now if the file isn't there
1251 if ( !$this->fileExists
) {
1252 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1253 wfProfileOut( __METHOD__
);
1260 # Test to see if the row exists using INSERT IGNORE
1261 # This avoids race conditions by locking the row until the commit, and also
1262 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1263 $dbw->insert( 'image',
1265 'img_name' => $this->getName(),
1266 'img_size' => $this->size
,
1267 'img_width' => intval( $this->width
),
1268 'img_height' => intval( $this->height
),
1269 'img_bits' => $this->bits
,
1270 'img_media_type' => $this->media_type
,
1271 'img_major_mime' => $this->major_mime
,
1272 'img_minor_mime' => $this->minor_mime
,
1273 'img_timestamp' => $timestamp,
1274 'img_description' => $comment,
1275 'img_user' => $user->getId(),
1276 'img_user_text' => $user->getName(),
1277 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1278 'img_sha1' => $this->sha1
1283 if ( $dbw->affectedRows() == 0 ) {
1284 # (bug 34993) Note: $oldver can be empty here, if the previous
1285 # version of the file was broken. Allow registration of the new
1286 # version to continue anyway, because that's better than having
1287 # an image that's not fixable by user operations.
1290 # Collision, this is an update of a file
1291 # Insert previous contents into oldimage
1292 $dbw->insertSelect( 'oldimage', 'image',
1294 'oi_name' => 'img_name',
1295 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1296 'oi_size' => 'img_size',
1297 'oi_width' => 'img_width',
1298 'oi_height' => 'img_height',
1299 'oi_bits' => 'img_bits',
1300 'oi_timestamp' => 'img_timestamp',
1301 'oi_description' => 'img_description',
1302 'oi_user' => 'img_user',
1303 'oi_user_text' => 'img_user_text',
1304 'oi_metadata' => 'img_metadata',
1305 'oi_media_type' => 'img_media_type',
1306 'oi_major_mime' => 'img_major_mime',
1307 'oi_minor_mime' => 'img_minor_mime',
1308 'oi_sha1' => 'img_sha1'
1310 array( 'img_name' => $this->getName() ),
1314 # Update the current image row
1315 $dbw->update( 'image',
1317 'img_size' => $this->size
,
1318 'img_width' => intval( $this->width
),
1319 'img_height' => intval( $this->height
),
1320 'img_bits' => $this->bits
,
1321 'img_media_type' => $this->media_type
,
1322 'img_major_mime' => $this->major_mime
,
1323 'img_minor_mime' => $this->minor_mime
,
1324 'img_timestamp' => $timestamp,
1325 'img_description' => $comment,
1326 'img_user' => $user->getId(),
1327 'img_user_text' => $user->getName(),
1328 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1329 'img_sha1' => $this->sha1
1331 array( 'img_name' => $this->getName() ),
1335 # This is a new file, so update the image count
1336 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1339 $descTitle = $this->getTitle();
1340 $wikiPage = new WikiFilePage( $descTitle );
1341 $wikiPage->setFile( $this );
1344 $action = $reupload ?
'overwrite' : 'upload';
1346 $logEntry = new ManualLogEntry( 'upload', $action );
1347 $logEntry->setPerformer( $user );
1348 $logEntry->setComment( $comment );
1349 $logEntry->setTarget( $descTitle );
1351 // Allow people using the api to associate log entries with the upload.
1352 // Log has a timestamp, but sometimes different from upload timestamp.
1353 $logEntry->setParameters(
1355 'img_sha1' => $this->sha1
,
1356 'img_timestamp' => $timestamp,
1359 // Note we keep $logId around since during new image
1360 // creation, page doesn't exist yet, so log_page = 0
1361 // but we want it to point to the page we're making,
1362 // so we later modify the log entry.
1363 // For a similar reason, we avoid making an RC entry
1364 // now and wait until the page exists.
1365 $logId = $logEntry->insert();
1367 $exists = $descTitle->exists();
1369 // Page exists, do RC entry now (otherwise we wait for later).
1370 $logEntry->publish( $logId );
1372 wfProfileIn( __METHOD__
. '-edit' );
1375 # Create a null revision
1376 $latest = $descTitle->getLatestRevID();
1377 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1379 $nullRevision = Revision
::newNullRevision(
1381 $descTitle->getArticleID(),
1385 if ( !is_null( $nullRevision ) ) {
1386 $nullRevision->insertOn( $dbw );
1388 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1389 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1393 # Commit the transaction now, in case something goes wrong later
1394 # The most important thing is that files don't get lost, especially archives
1395 # NOTE: once we have support for nested transactions, the commit may be moved
1396 # to after $wikiPage->doEdit has been called.
1397 $dbw->commit( __METHOD__
);
1400 # Invalidate the cache for the description page
1401 $descTitle->invalidateCache();
1402 $descTitle->purgeSquid();
1404 # New file; create the description page.
1405 # There's already a log entry, so don't make a second RC entry
1406 # Squid and file cache for the description page are purged by doEditContent.
1407 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1408 $status = $wikiPage->doEditContent(
1411 EDIT_NEW | EDIT_SUPPRESS_RC
,
1416 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1417 // Now that the page exists, make an RC entry.
1418 $logEntry->publish( $logId );
1419 if ( isset( $status->value
['revision'] ) ) {
1420 $dbw->update( 'logging',
1421 array( 'log_page' => $status->value
['revision']->getPage() ),
1422 array( 'log_id' => $logId ),
1426 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1429 wfProfileOut( __METHOD__
. '-edit' );
1431 # Save to cache and purge the squid
1432 # We shall not saveToCache before the commit since otherwise
1433 # in case of a rollback there is an usable file from memcached
1434 # which in fact doesn't really exist (bug 24978)
1435 $this->saveToCache();
1438 # Delete old thumbnails
1439 wfProfileIn( __METHOD__
. '-purge' );
1440 $this->purgeThumbnails();
1441 wfProfileOut( __METHOD__
. '-purge' );
1443 # Remove the old file from the squid cache
1444 SquidUpdate
::purge( array( $this->getURL() ) );
1447 # Hooks, hooks, the magic of hooks...
1448 wfProfileIn( __METHOD__
. '-hooks' );
1449 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1450 wfProfileOut( __METHOD__
. '-hooks' );
1452 # Invalidate cache for all pages using this file
1453 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1454 $update->doUpdate();
1456 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1459 # Invalidate cache for all pages that redirects on this page
1460 $redirs = $this->getTitle()->getRedirectsHere();
1462 foreach ( $redirs as $redir ) {
1463 if ( !$reupload && $redir->getNamespace() === NS_FILE
) {
1464 LinksUpdate
::queueRecursiveJobsForTable( $redir, 'imagelinks' );
1466 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1467 $update->doUpdate();
1470 wfProfileOut( __METHOD__
);
1476 * Move or copy a file to its public location. If a file exists at the
1477 * destination, move it to an archive. Returns a FileRepoStatus object with
1478 * the archive name in the "value" member on success.
1480 * The archive name should be passed through to recordUpload for database
1483 * @param string $srcPath local filesystem path to the source image
1484 * @param $flags Integer: a bitwise combination of:
1485 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1486 * @param array $options Optional additional parameters
1487 * @return FileRepoStatus object. On success, the value member contains the
1488 * archive name, or an empty string if it was a new file.
1490 function publish( $srcPath, $flags = 0, array $options = array() ) {
1491 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1495 * Move or copy a file to a specified location. Returns a FileRepoStatus
1496 * object with the archive name in the "value" member on success.
1498 * The archive name should be passed through to recordUpload for database
1501 * @param string $srcPath local filesystem path to the source image
1502 * @param string $dstRel target relative path
1503 * @param $flags Integer: a bitwise combination of:
1504 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1505 * @param array $options Optional additional parameters
1506 * @return FileRepoStatus object. On success, the value member contains the
1507 * archive name, or an empty string if it was a new file.
1509 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1510 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1511 return $this->readOnlyFatalStatus();
1514 $this->lock(); // begin
1516 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1517 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1518 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1519 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1521 if ( $status->value
== 'new' ) {
1522 $status->value
= '';
1524 $status->value
= $archiveName;
1527 $this->unlock(); // done
1532 /** getLinksTo inherited */
1533 /** getExifData inherited */
1534 /** isLocal inherited */
1535 /** wasDeleted inherited */
1538 * Move file to the new title
1540 * Move current, old version and all thumbnails
1541 * to the new filename. Old file is deleted.
1543 * Cache purging is done; checks for validity
1544 * and logging are caller's responsibility
1546 * @param $target Title New file name
1547 * @return FileRepoStatus object.
1549 function move( $target ) {
1550 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1551 return $this->readOnlyFatalStatus();
1554 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1555 $batch = new LocalFileMoveBatch( $this, $target );
1557 $this->lock(); // begin
1558 $batch->addCurrent();
1559 $archiveNames = $batch->addOlds();
1560 $status = $batch->execute();
1561 $this->unlock(); // done
1563 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1565 // Purge the source and target files...
1566 $oldTitleFile = wfLocalFile( $this->title
);
1567 $newTitleFile = wfLocalFile( $target );
1568 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1569 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1570 $this->getRepo()->getMasterDB()->onTransactionIdle(
1571 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1572 $oldTitleFile->purgeEverything();
1573 foreach ( $archiveNames as $archiveName ) {
1574 $oldTitleFile->purgeOldThumbnails( $archiveName );
1576 $newTitleFile->purgeEverything();
1580 if ( $status->isOK() ) {
1581 // Now switch the object
1582 $this->title
= $target;
1583 // Force regeneration of the name and hashpath
1584 unset( $this->name
);
1585 unset( $this->hashPath
);
1592 * Delete all versions of the file.
1594 * Moves the files into an archive directory (or deletes them)
1595 * and removes the database rows.
1597 * Cache purging is done; logging is caller's responsibility.
1601 * @return FileRepoStatus object.
1603 function delete( $reason, $suppress = false ) {
1604 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1605 return $this->readOnlyFatalStatus();
1608 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1610 $this->lock(); // begin
1611 $batch->addCurrent();
1612 # Get old version relative paths
1613 $archiveNames = $batch->addOlds();
1614 $status = $batch->execute();
1615 $this->unlock(); // done
1617 if ( $status->isOK() ) {
1618 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1621 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1622 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1624 $this->getRepo()->getMasterDB()->onTransactionIdle(
1625 function () use ( $file, $archiveNames ) {
1628 $file->purgeEverything();
1629 foreach ( $archiveNames as $archiveName ) {
1630 $file->purgeOldThumbnails( $archiveName );
1633 if ( $wgUseSquid ) {
1635 $purgeUrls = array();
1636 foreach ( $archiveNames as $archiveName ) {
1637 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1639 SquidUpdate
::purge( $purgeUrls );
1648 * Delete an old version of the file.
1650 * Moves the file into an archive directory (or deletes it)
1651 * and removes the database row.
1653 * Cache purging is done; logging is caller's responsibility.
1655 * @param $archiveName String
1656 * @param $reason String
1657 * @param $suppress Boolean
1658 * @throws MWException or FSException on database or file store failure
1659 * @return FileRepoStatus object.
1661 function deleteOld( $archiveName, $reason, $suppress = false ) {
1663 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1664 return $this->readOnlyFatalStatus();
1667 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1669 $this->lock(); // begin
1670 $batch->addOld( $archiveName );
1671 $status = $batch->execute();
1672 $this->unlock(); // done
1674 $this->purgeOldThumbnails( $archiveName );
1675 if ( $status->isOK() ) {
1676 $this->purgeDescription();
1677 $this->purgeHistory();
1680 if ( $wgUseSquid ) {
1682 SquidUpdate
::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1689 * Restore all or specified deleted revisions to the given file.
1690 * Permissions and logging are left to the caller.
1692 * May throw database exceptions on error.
1694 * @param array $versions set of record ids of deleted items to restore,
1695 * or empty to restore all revisions.
1696 * @param $unsuppress Boolean
1697 * @return FileRepoStatus
1699 function restore( $versions = array(), $unsuppress = false ) {
1700 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1701 return $this->readOnlyFatalStatus();
1704 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1706 $this->lock(); // begin
1710 $batch->addIds( $versions );
1712 $status = $batch->execute();
1713 if ( $status->isGood() ) {
1714 $cleanupStatus = $batch->cleanup();
1715 $cleanupStatus->successCount
= 0;
1716 $cleanupStatus->failCount
= 0;
1717 $status->merge( $cleanupStatus );
1719 $this->unlock(); // done
1724 /** isMultipage inherited */
1725 /** pageCount inherited */
1726 /** scaleHeight inherited */
1727 /** getImageSize inherited */
1730 * Get the URL of the file description page.
1733 function getDescriptionUrl() {
1734 return $this->title
->getLocalURL();
1738 * Get the HTML text of the description page
1739 * This is not used by ImagePage for local files, since (among other things)
1740 * it skips the parser cache.
1742 * @param $lang Language What language to get description in (Optional)
1743 * @return bool|mixed
1745 function getDescriptionText( $lang = null ) {
1746 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1750 $content = $revision->getContent();
1754 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1756 return $pout->getText();
1762 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1764 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1766 } elseif ( $audience == self
::FOR_THIS_USER
1767 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1771 return $this->description
;
1776 * @return bool|string
1778 function getTimestamp() {
1781 return $this->timestamp
;
1787 function getSha1() {
1789 // Initialise now if necessary
1790 if ( $this->sha1
== '' && $this->fileExists
) {
1791 $this->lock(); // begin
1793 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1794 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1795 $dbw = $this->repo
->getMasterDB();
1796 $dbw->update( 'image',
1797 array( 'img_sha1' => $this->sha1
),
1798 array( 'img_name' => $this->getName() ),
1800 $this->saveToCache();
1803 $this->unlock(); // done
1810 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1812 function isCacheable() {
1815 // If extra data (metadata) was not loaded then it must have been large
1816 return $this->extraDataLoaded
1817 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1821 * Start a transaction and lock the image for update
1822 * Increments a reference counter if the lock is already held
1823 * @return boolean True if the image exists, false otherwise
1826 $dbw = $this->repo
->getMasterDB();
1828 if ( !$this->locked
) {
1829 if ( !$dbw->trxLevel() ) {
1830 $dbw->begin( __METHOD__
);
1831 $this->lockedOwnTrx
= true;
1834 // Bug 54736: use simple lock to handle when the file does not exist.
1835 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1836 $cache = wfGetMainCache();
1837 $key = $this->getCacheKey();
1838 if ( !$cache->lock( $key, 60 ) ) {
1839 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1841 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1842 $cache->unlock( $key ); // release on commit
1846 return $dbw->selectField( 'image', '1',
1847 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1851 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1852 * the transaction and thereby releases the image lock.
1855 if ( $this->locked
) {
1857 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1858 $dbw = $this->repo
->getMasterDB();
1859 $dbw->commit( __METHOD__
);
1860 $this->lockedOwnTrx
= false;
1866 * Roll back the DB transaction and mark the image unlocked
1868 function unlockAndRollback() {
1869 $this->locked
= false;
1870 $dbw = $this->repo
->getMasterDB();
1871 $dbw->rollback( __METHOD__
);
1872 $this->lockedOwnTrx
= false;
1878 protected function readOnlyFatalStatus() {
1879 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1880 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1882 } // LocalFile class
1884 # ------------------------------------------------------------------------------
1887 * Helper class for file deletion
1888 * @ingroup FileAbstraction
1890 class LocalFileDeleteBatch
{
1892 /** @var LocalFile */
1899 private $srcRels = array();
1902 private $archiveUrls = array();
1904 /** @var array Items to be processed in the deletion batch */
1905 private $deletionBatch;
1907 /** @var bool Wether to suppress all suppressable fields when deleting */
1910 /** @var FileRepoStatus */
1915 * @param $reason string
1916 * @param $suppress bool
1918 function __construct( File
$file, $reason = '', $suppress = false ) {
1919 $this->file
= $file;
1920 $this->reason
= $reason;
1921 $this->suppress
= $suppress;
1922 $this->status
= $file->repo
->newGood();
1925 function addCurrent() {
1926 $this->srcRels
['.'] = $this->file
->getRel();
1930 * @param $oldName string
1932 function addOld( $oldName ) {
1933 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1934 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1938 * Add the old versions of the image to the batch
1939 * @return Array List of archive names from old versions
1941 function addOlds() {
1942 $archiveNames = array();
1944 $dbw = $this->file
->repo
->getMasterDB();
1945 $result = $dbw->select( 'oldimage',
1946 array( 'oi_archive_name' ),
1947 array( 'oi_name' => $this->file
->getName() ),
1951 foreach ( $result as $row ) {
1952 $this->addOld( $row->oi_archive_name
);
1953 $archiveNames[] = $row->oi_archive_name
;
1956 return $archiveNames;
1962 function getOldRels() {
1963 if ( !isset( $this->srcRels
['.'] ) ) {
1964 $oldRels =& $this->srcRels
;
1965 $deleteCurrent = false;
1967 $oldRels = $this->srcRels
;
1968 unset( $oldRels['.'] );
1969 $deleteCurrent = true;
1972 return array( $oldRels, $deleteCurrent );
1978 protected function getHashes() {
1980 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1982 if ( $deleteCurrent ) {
1983 $hashes['.'] = $this->file
->getSha1();
1986 if ( count( $oldRels ) ) {
1987 $dbw = $this->file
->repo
->getMasterDB();
1988 $res = $dbw->select(
1990 array( 'oi_archive_name', 'oi_sha1' ),
1991 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1995 foreach ( $res as $row ) {
1996 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1997 // Get the hash from the file
1998 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1999 $props = $this->file
->repo
->getFileProps( $oldUrl );
2001 if ( $props['fileExists'] ) {
2002 // Upgrade the oldimage row
2003 $dbw->update( 'oldimage',
2004 array( 'oi_sha1' => $props['sha1'] ),
2005 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
2007 $hashes[$row->oi_archive_name
] = $props['sha1'];
2009 $hashes[$row->oi_archive_name
] = false;
2012 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2017 $missing = array_diff_key( $this->srcRels
, $hashes );
2019 foreach ( $missing as $name => $rel ) {
2020 $this->status
->error( 'filedelete-old-unregistered', $name );
2023 foreach ( $hashes as $name => $hash ) {
2025 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2026 unset( $hashes[$name] );
2033 function doDBInserts() {
2036 $dbw = $this->file
->repo
->getMasterDB();
2037 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2038 $encUserId = $dbw->addQuotes( $wgUser->getId() );
2039 $encReason = $dbw->addQuotes( $this->reason
);
2040 $encGroup = $dbw->addQuotes( 'deleted' );
2041 $ext = $this->file
->getExtension();
2042 $dotExt = $ext === '' ?
'' : ".$ext";
2043 $encExt = $dbw->addQuotes( $dotExt );
2044 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2046 // Bitfields to further suppress the content
2047 if ( $this->suppress
) {
2049 // This should be 15...
2050 $bitfield |
= Revision
::DELETED_TEXT
;
2051 $bitfield |
= Revision
::DELETED_COMMENT
;
2052 $bitfield |
= Revision
::DELETED_USER
;
2053 $bitfield |
= Revision
::DELETED_RESTRICTED
;
2055 $bitfield = 'oi_deleted';
2058 if ( $deleteCurrent ) {
2059 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2060 $where = array( 'img_name' => $this->file
->getName() );
2061 $dbw->insertSelect( 'filearchive', 'image',
2063 'fa_storage_group' => $encGroup,
2064 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
2065 'fa_deleted_user' => $encUserId,
2066 'fa_deleted_timestamp' => $encTimestamp,
2067 'fa_deleted_reason' => $encReason,
2068 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2070 'fa_name' => 'img_name',
2071 'fa_archive_name' => 'NULL',
2072 'fa_size' => 'img_size',
2073 'fa_width' => 'img_width',
2074 'fa_height' => 'img_height',
2075 'fa_metadata' => 'img_metadata',
2076 'fa_bits' => 'img_bits',
2077 'fa_media_type' => 'img_media_type',
2078 'fa_major_mime' => 'img_major_mime',
2079 'fa_minor_mime' => 'img_minor_mime',
2080 'fa_description' => 'img_description',
2081 'fa_user' => 'img_user',
2082 'fa_user_text' => 'img_user_text',
2083 'fa_timestamp' => 'img_timestamp',
2084 'fa_sha1' => 'img_sha1',
2085 ), $where, __METHOD__
);
2088 if ( count( $oldRels ) ) {
2089 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2091 'oi_name' => $this->file
->getName(),
2092 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
2093 $dbw->insertSelect( 'filearchive', 'oldimage',
2095 'fa_storage_group' => $encGroup,
2096 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
2097 'fa_deleted_user' => $encUserId,
2098 'fa_deleted_timestamp' => $encTimestamp,
2099 'fa_deleted_reason' => $encReason,
2100 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
2102 'fa_name' => 'oi_name',
2103 'fa_archive_name' => 'oi_archive_name',
2104 'fa_size' => 'oi_size',
2105 'fa_width' => 'oi_width',
2106 'fa_height' => 'oi_height',
2107 'fa_metadata' => 'oi_metadata',
2108 'fa_bits' => 'oi_bits',
2109 'fa_media_type' => 'oi_media_type',
2110 'fa_major_mime' => 'oi_major_mime',
2111 'fa_minor_mime' => 'oi_minor_mime',
2112 'fa_description' => 'oi_description',
2113 'fa_user' => 'oi_user',
2114 'fa_user_text' => 'oi_user_text',
2115 'fa_timestamp' => 'oi_timestamp',
2116 'fa_sha1' => 'oi_sha1',
2117 ), $where, __METHOD__
);
2121 function doDBDeletes() {
2122 $dbw = $this->file
->repo
->getMasterDB();
2123 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2125 if ( count( $oldRels ) ) {
2126 $dbw->delete( 'oldimage',
2128 'oi_name' => $this->file
->getName(),
2129 'oi_archive_name' => array_keys( $oldRels )
2133 if ( $deleteCurrent ) {
2134 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2139 * Run the transaction
2140 * @return FileRepoStatus
2142 function execute() {
2143 wfProfileIn( __METHOD__
);
2145 $this->file
->lock();
2146 // Leave private files alone
2147 $privateFiles = array();
2148 list( $oldRels, ) = $this->getOldRels();
2149 $dbw = $this->file
->repo
->getMasterDB();
2151 if ( !empty( $oldRels ) ) {
2152 $res = $dbw->select( 'oldimage',
2153 array( 'oi_archive_name' ),
2154 array( 'oi_name' => $this->file
->getName(),
2155 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
2156 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2159 foreach ( $res as $row ) {
2160 $privateFiles[$row->oi_archive_name
] = 1;
2163 // Prepare deletion batch
2164 $hashes = $this->getHashes();
2165 $this->deletionBatch
= array();
2166 $ext = $this->file
->getExtension();
2167 $dotExt = $ext === '' ?
'' : ".$ext";
2169 foreach ( $this->srcRels
as $name => $srcRel ) {
2170 // Skip files that have no hash (missing source).
2171 // Keep private files where they are.
2172 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2173 $hash = $hashes[$name];
2174 $key = $hash . $dotExt;
2175 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2176 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2180 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2181 // We acquire this lock by running the inserts now, before the file operations.
2183 // This potentially has poor lock contention characteristics -- an alternative
2184 // scheme would be to insert stub filearchive entries with no fa_name and commit
2185 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2186 $this->doDBInserts();
2188 // Removes non-existent file from the batch, so we don't get errors.
2189 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2191 // Execute the file deletion batch
2192 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2194 if ( !$status->isGood() ) {
2195 $this->status
->merge( $status );
2198 if ( !$this->status
->isOK() ) {
2199 // Critical file deletion error
2200 // Roll back inserts, release lock and abort
2201 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2202 $this->file
->unlockAndRollback();
2203 wfProfileOut( __METHOD__
);
2205 return $this->status
;
2208 // Delete image/oldimage rows
2209 $this->doDBDeletes();
2211 // Commit and return
2212 $this->file
->unlock();
2213 wfProfileOut( __METHOD__
);
2215 return $this->status
;
2219 * Removes non-existent files from a deletion batch.
2220 * @param $batch array
2223 function removeNonexistentFiles( $batch ) {
2224 $files = $newBatch = array();
2226 foreach ( $batch as $batchItem ) {
2227 list( $src, ) = $batchItem;
2228 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2231 $result = $this->file
->repo
->fileExistsBatch( $files );
2233 foreach ( $batch as $batchItem ) {
2234 if ( $result[$batchItem[0]] ) {
2235 $newBatch[] = $batchItem;
2243 # ------------------------------------------------------------------------------
2246 * Helper class for file undeletion
2247 * @ingroup FileAbstraction
2249 class LocalFileRestoreBatch
{
2250 /** @var LocalFile */
2253 /** @var array List of file IDs to restore */
2254 private $cleanupBatch;
2256 /** @var array List of file IDs to restore */
2259 /** @var bool Add all revisions of the file */
2262 /** @var bool Wether to remove all settings for suppressed fields */
2263 private $unsuppress = false;
2267 * @param $unsuppress bool
2269 function __construct( File
$file, $unsuppress = false ) {
2270 $this->file
= $file;
2271 $this->cleanupBatch
= $this->ids
= array();
2272 $this->ids
= array();
2273 $this->unsuppress
= $unsuppress;
2279 function addId( $fa_id ) {
2280 $this->ids
[] = $fa_id;
2284 * Add a whole lot of files by ID
2286 function addIds( $ids ) {
2287 $this->ids
= array_merge( $this->ids
, $ids );
2291 * Add all revisions of the file
2298 * Run the transaction, except the cleanup batch.
2299 * The cleanup batch should be run in a separate transaction, because it locks different
2300 * rows and there's no need to keep the image row locked while it's acquiring those locks
2301 * The caller may have its own transaction open.
2302 * So we save the batch and let the caller call cleanup()
2303 * @return FileRepoStatus
2305 function execute() {
2308 if ( !$this->all
&& !$this->ids
) {
2310 return $this->file
->repo
->newGood();
2313 $exists = $this->file
->lock();
2314 $dbw = $this->file
->repo
->getMasterDB();
2315 $status = $this->file
->repo
->newGood();
2317 // Fetch all or selected archived revisions for the file,
2318 // sorted from the most recent to the oldest.
2319 $conditions = array( 'fa_name' => $this->file
->getName() );
2321 if ( !$this->all
) {
2322 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2325 $result = $dbw->select(
2327 ArchivedFile
::selectFields(),
2330 array( 'ORDER BY' => 'fa_timestamp DESC' )
2333 $idsPresent = array();
2334 $storeBatch = array();
2335 $insertBatch = array();
2336 $insertCurrent = false;
2337 $deleteIds = array();
2339 $archiveNames = array();
2341 foreach ( $result as $row ) {
2342 $idsPresent[] = $row->fa_id
;
2344 if ( $row->fa_name
!= $this->file
->getName() ) {
2345 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2346 $status->failCount++
;
2350 if ( $row->fa_storage_key
== '' ) {
2351 // Revision was missing pre-deletion
2352 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2353 $status->failCount++
;
2357 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) .
2358 $row->fa_storage_key
;
2359 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2361 if ( isset( $row->fa_sha1
) ) {
2362 $sha1 = $row->fa_sha1
;
2364 // old row, populate from key
2365 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2369 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2370 $sha1 = substr( $sha1, 1 );
2373 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2374 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2375 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2376 ||
is_null( $row->fa_metadata
)
2378 // Refresh our metadata
2379 // Required for a new current revision; nice for older ones too. :)
2380 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2383 'minor_mime' => $row->fa_minor_mime
,
2384 'major_mime' => $row->fa_major_mime
,
2385 'media_type' => $row->fa_media_type
,
2386 'metadata' => $row->fa_metadata
2390 if ( $first && !$exists ) {
2391 // This revision will be published as the new current version
2392 $destRel = $this->file
->getRel();
2393 $insertCurrent = array(
2394 'img_name' => $row->fa_name
,
2395 'img_size' => $row->fa_size
,
2396 'img_width' => $row->fa_width
,
2397 'img_height' => $row->fa_height
,
2398 'img_metadata' => $props['metadata'],
2399 'img_bits' => $row->fa_bits
,
2400 'img_media_type' => $props['media_type'],
2401 'img_major_mime' => $props['major_mime'],
2402 'img_minor_mime' => $props['minor_mime'],
2403 'img_description' => $row->fa_description
,
2404 'img_user' => $row->fa_user
,
2405 'img_user_text' => $row->fa_user_text
,
2406 'img_timestamp' => $row->fa_timestamp
,
2410 // The live (current) version cannot be hidden!
2411 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2412 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2413 $this->cleanupBatch
[] = $row->fa_storage_key
;
2416 $archiveName = $row->fa_archive_name
;
2418 if ( $archiveName == '' ) {
2419 // This was originally a current version; we
2420 // have to devise a new archive name for it.
2421 // Format is <timestamp of archiving>!<name>
2422 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2425 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2427 } while ( isset( $archiveNames[$archiveName] ) );
2430 $archiveNames[$archiveName] = true;
2431 $destRel = $this->file
->getArchiveRel( $archiveName );
2432 $insertBatch[] = array(
2433 'oi_name' => $row->fa_name
,
2434 'oi_archive_name' => $archiveName,
2435 'oi_size' => $row->fa_size
,
2436 'oi_width' => $row->fa_width
,
2437 'oi_height' => $row->fa_height
,
2438 'oi_bits' => $row->fa_bits
,
2439 'oi_description' => $row->fa_description
,
2440 'oi_user' => $row->fa_user
,
2441 'oi_user_text' => $row->fa_user_text
,
2442 'oi_timestamp' => $row->fa_timestamp
,
2443 'oi_metadata' => $props['metadata'],
2444 'oi_media_type' => $props['media_type'],
2445 'oi_major_mime' => $props['major_mime'],
2446 'oi_minor_mime' => $props['minor_mime'],
2447 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2448 'oi_sha1' => $sha1 );
2451 $deleteIds[] = $row->fa_id
;
2453 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2454 // private files can stay where they are
2455 $status->successCount++
;
2457 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2458 $this->cleanupBatch
[] = $row->fa_storage_key
;
2466 // Add a warning to the status object for missing IDs
2467 $missingIds = array_diff( $this->ids
, $idsPresent );
2469 foreach ( $missingIds as $id ) {
2470 $status->error( 'undelete-missing-filearchive', $id );
2473 // Remove missing files from batch, so we don't get errors when undeleting them
2474 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2476 // Run the store batch
2477 // Use the OVERWRITE_SAME flag to smooth over a common error
2478 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2479 $status->merge( $storeStatus );
2481 if ( !$status->isGood() ) {
2482 // Even if some files could be copied, fail entirely as that is the
2483 // easiest thing to do without data loss
2484 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2485 $status->ok
= false;
2486 $this->file
->unlock();
2491 // Run the DB updates
2492 // Because we have locked the image row, key conflicts should be rare.
2493 // If they do occur, we can roll back the transaction at this time with
2494 // no data loss, but leaving unregistered files scattered throughout the
2496 // This is not ideal, which is why it's important to lock the image row.
2497 if ( $insertCurrent ) {
2498 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2501 if ( $insertBatch ) {
2502 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2506 $dbw->delete( 'filearchive',
2507 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2511 // If store batch is empty (all files are missing), deletion is to be considered successful
2512 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2514 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2516 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2518 $this->file
->purgeEverything();
2520 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2521 $this->file
->purgeDescription();
2522 $this->file
->purgeHistory();
2526 $this->file
->unlock();
2532 * Removes non-existent files from a store batch.
2533 * @param $triplets array
2536 function removeNonexistentFiles( $triplets ) {
2537 $files = $filteredTriplets = array();
2538 foreach ( $triplets as $file ) {
2539 $files[$file[0]] = $file[0];
2542 $result = $this->file
->repo
->fileExistsBatch( $files );
2544 foreach ( $triplets as $file ) {
2545 if ( $result[$file[0]] ) {
2546 $filteredTriplets[] = $file;
2550 return $filteredTriplets;
2554 * Removes non-existent files from a cleanup batch.
2555 * @param $batch array
2558 function removeNonexistentFromCleanup( $batch ) {
2559 $files = $newBatch = array();
2560 $repo = $this->file
->repo
;
2562 foreach ( $batch as $file ) {
2563 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2564 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2567 $result = $repo->fileExistsBatch( $files );
2569 foreach ( $batch as $file ) {
2570 if ( $result[$file] ) {
2571 $newBatch[] = $file;
2579 * Delete unused files in the deleted zone.
2580 * This should be called from outside the transaction in which execute() was called.
2581 * @return FileRepoStatus
2583 function cleanup() {
2584 if ( !$this->cleanupBatch
) {
2585 return $this->file
->repo
->newGood();
2588 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2590 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2596 * Cleanup a failed batch. The batch was only partially successful, so
2597 * rollback by removing all items that were succesfully copied.
2599 * @param Status $storeStatus
2600 * @param array $storeBatch
2602 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2603 $cleanupBatch = array();
2605 foreach ( $storeStatus->success
as $i => $success ) {
2606 // Check if this item of the batch was successfully copied
2608 // Item was successfully copied and needs to be removed again
2609 // Extract ($dstZone, $dstRel) from the batch
2610 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2613 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2617 # ------------------------------------------------------------------------------
2620 * Helper class for file movement
2621 * @ingroup FileAbstraction
2623 class LocalFileMoveBatch
{
2624 /** @var LocalFile */
2637 protected $oldCount;
2649 * @param Title $target
2651 function __construct( File
$file, Title
$target ) {
2652 $this->file
= $file;
2653 $this->target
= $target;
2654 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2655 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2656 $this->oldName
= $this->file
->getName();
2657 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2658 $this->oldRel
= $this->oldHash
. $this->oldName
;
2659 $this->newRel
= $this->newHash
. $this->newName
;
2660 $this->db
= $file->getRepo()->getMasterDb();
2664 * Add the current image to the batch
2666 function addCurrent() {
2667 $this->cur
= array( $this->oldRel
, $this->newRel
);
2671 * Add the old versions of the image to the batch
2672 * @return Array List of archive names from old versions
2674 function addOlds() {
2675 $archiveBase = 'archive';
2676 $this->olds
= array();
2677 $this->oldCount
= 0;
2678 $archiveNames = array();
2680 $result = $this->db
->select( 'oldimage',
2681 array( 'oi_archive_name', 'oi_deleted' ),
2682 array( 'oi_name' => $this->oldName
),
2686 foreach ( $result as $row ) {
2687 $archiveNames[] = $row->oi_archive_name
;
2688 $oldName = $row->oi_archive_name
;
2689 $bits = explode( '!', $oldName, 2 );
2691 if ( count( $bits ) != 2 ) {
2692 wfDebug( "Old file name missing !: '$oldName' \n" );
2696 list( $timestamp, $filename ) = $bits;
2698 if ( $this->oldName
!= $filename ) {
2699 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2705 // Do we want to add those to oldCount?
2706 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2710 $this->olds
[] = array(
2711 "{$archiveBase}/{$this->oldHash}{$oldName}",
2712 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2716 return $archiveNames;
2721 * @return FileRepoStatus
2723 function execute() {
2724 $repo = $this->file
->repo
;
2725 $status = $repo->newGood();
2727 $triplets = $this->getMoveTriplets();
2728 $triplets = $this->removeNonexistentFiles( $triplets );
2730 $this->file
->lock(); // begin
2731 // Rename the file versions metadata in the DB.
2732 // This implicitly locks the destination file, which avoids race conditions.
2733 // If we moved the files from A -> C before DB updates, another process could
2734 // move files from B -> C at this point, causing storeBatch() to fail and thus
2735 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2736 $statusDb = $this->doDBUpdates();
2737 if ( !$statusDb->isGood() ) {
2738 $this->file
->unlockAndRollback();
2739 $statusDb->ok
= false;
2743 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2744 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2746 // Copy the files into their new location.
2747 // If a prior process fataled copying or cleaning up files we tolerate any
2748 // of the existing files if they are identical to the ones being stored.
2749 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2750 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2751 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2752 if ( !$statusMove->isGood() ) {
2753 // Delete any files copied over (while the destination is still locked)
2754 $this->cleanupTarget( $triplets );
2755 $this->file
->unlockAndRollback(); // unlocks the destination
2756 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2757 $statusMove->ok
= false;
2761 $this->file
->unlock(); // done
2763 // Everything went ok, remove the source files
2764 $this->cleanupSource( $triplets );
2766 $status->merge( $statusDb );
2767 $status->merge( $statusMove );
2773 * Do the database updates and return a new FileRepoStatus indicating how
2774 * many rows where updated.
2776 * @return FileRepoStatus
2778 function doDBUpdates() {
2779 $repo = $this->file
->repo
;
2780 $status = $repo->newGood();
2783 // Update current image
2786 array( 'img_name' => $this->newName
),
2787 array( 'img_name' => $this->oldName
),
2791 if ( $dbw->affectedRows() ) {
2792 $status->successCount++
;
2794 $status->failCount++
;
2795 $status->fatal( 'imageinvalidfilename' );
2800 // Update old images
2804 'oi_name' => $this->newName
,
2805 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2806 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2808 array( 'oi_name' => $this->oldName
),
2812 $affected = $dbw->affectedRows();
2813 $total = $this->oldCount
;
2814 $status->successCount +
= $affected;
2815 // Bug 34934: $total is based on files that actually exist.
2816 // There may be more DB rows than such files, in which case $affected
2817 // can be greater than $total. We use max() to avoid negatives here.
2818 $status->failCount +
= max( 0, $total - $affected );
2819 if ( $status->failCount
) {
2820 $status->error( 'imageinvalidfilename' );
2827 * Generate triplets for FileRepo::storeBatch().
2830 function getMoveTriplets() {
2831 $moves = array_merge( array( $this->cur
), $this->olds
);
2832 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2834 foreach ( $moves as $move ) {
2835 // $move: (oldRelativePath, newRelativePath)
2836 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2837 $triplets[] = array( $srcUrl, 'public', $move[1] );
2840 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2848 * Removes non-existent files from move batch.
2849 * @param $triplets array
2852 function removeNonexistentFiles( $triplets ) {
2855 foreach ( $triplets as $file ) {
2856 $files[$file[0]] = $file[0];
2859 $result = $this->file
->repo
->fileExistsBatch( $files );
2860 $filteredTriplets = array();
2862 foreach ( $triplets as $file ) {
2863 if ( $result[$file[0]] ) {
2864 $filteredTriplets[] = $file;
2866 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2870 return $filteredTriplets;
2874 * Cleanup a partially moved array of triplets by deleting the target
2875 * files. Called if something went wrong half way.
2877 function cleanupTarget( $triplets ) {
2878 // Create dest pairs from the triplets
2880 foreach ( $triplets as $triplet ) {
2881 // $triplet: (old source virtual URL, dst zone, dest rel)
2882 $pairs[] = array( $triplet[1], $triplet[2] );
2885 $this->file
->repo
->cleanupBatch( $pairs );
2889 * Cleanup a fully moved array of triplets by deleting the source files.
2890 * Called at the end of the move process if everything else went ok.
2892 function cleanupSource( $triplets ) {
2893 // Create source file names from the triplets
2895 foreach ( $triplets as $triplet ) {
2896 $files[] = $triplet[0];
2899 $this->file
->repo
->cleanupBatch( $files );