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__
);
216 $cachedValues = $wgMemc->get( $key );
218 // Check if the key existed and belongs to this version of MediaWiki
219 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION
) {
220 wfDebug( "Pulling file metadata from cache key $key\n" );
221 $this->fileExists
= $cachedValues['fileExists'];
222 if ( $this->fileExists
) {
223 $this->setProps( $cachedValues );
225 $this->dataLoaded
= true;
226 $this->extraDataLoaded
= true;
227 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
228 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
232 if ( $this->dataLoaded
) {
233 wfIncrStats( 'image_cache_hit' );
235 wfIncrStats( 'image_cache_miss' );
238 wfProfileOut( __METHOD__
);
239 return $this->dataLoaded
;
243 * Save the file metadata to memcached
245 function saveToCache() {
249 $key = $this->getCacheKey();
255 $fields = $this->getCacheFields( '' );
256 $cache = array( 'version' => MW_FILE_VERSION
);
257 $cache['fileExists'] = $this->fileExists
;
259 if ( $this->fileExists
) {
260 foreach ( $fields as $field ) {
261 $cache[$field] = $this->$field;
265 // Strip off excessive entries from the subset of fields that can become large.
266 // If the cache value gets to large it will not fit in memcached and nothing will
267 // get cached at all, causing master queries for any file access.
268 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
269 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
270 unset( $cache[$field] ); // don't let the value get too big
274 // Cache presence for 1 week and negatives for 1 day
275 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
279 * Load metadata from the file itself
281 function loadFromFile() {
282 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
283 $this->setProps( $props );
287 * @param $prefix string
290 function getCacheFields( $prefix = 'img_' ) {
291 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
292 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
293 static $results = array();
295 if ( $prefix == '' ) {
299 if ( !isset( $results[$prefix] ) ) {
300 $prefixedFields = array();
301 foreach ( $fields as $field ) {
302 $prefixedFields[] = $prefix . $field;
304 $results[$prefix] = $prefixedFields;
307 return $results[$prefix];
313 function getLazyCacheFields( $prefix = 'img_' ) {
314 static $fields = array( 'metadata' );
315 static $results = array();
317 if ( $prefix == '' ) {
321 if ( !isset( $results[$prefix] ) ) {
322 $prefixedFields = array();
323 foreach ( $fields as $field ) {
324 $prefixedFields[] = $prefix . $field;
326 $results[$prefix] = $prefixedFields;
329 return $results[$prefix];
333 * Load file metadata from the DB
335 function loadFromDB() {
336 # Polymorphic function name to distinguish foreign and local fetches
337 $fname = get_class( $this ) . '::' . __FUNCTION__
;
338 wfProfileIn( $fname );
340 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
341 $this->dataLoaded
= true;
342 $this->extraDataLoaded
= true;
344 $dbr = $this->repo
->getMasterDB();
345 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
346 array( 'img_name' => $this->getName() ), $fname );
349 $this->loadFromRow( $row );
351 $this->fileExists
= false;
354 wfProfileOut( $fname );
358 * Load lazy file metadata from the DB.
359 * This covers fields that are sometimes not cached.
361 protected function loadExtraFromDB() {
362 # Polymorphic function name to distinguish foreign and local fetches
363 $fname = get_class( $this ) . '::' . __FUNCTION__
;
364 wfProfileIn( $fname );
366 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
367 $this->extraDataLoaded
= true;
369 $dbr = $this->repo
->getSlaveDB();
370 // In theory the file could have just been renamed/deleted...oh well
371 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
372 array( 'img_name' => $this->getName() ), $fname );
374 if ( !$row ) { // fallback to master
375 $dbr = $this->repo
->getMasterDB();
376 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
377 array( 'img_name' => $this->getName() ), $fname );
381 foreach ( $this->unprefixRow( $row, 'img_' ) as $name => $value ) {
382 $this->$name = $value;
385 wfProfileOut( $fname );
386 throw new MWException( "Could not find data for image '{$this->getName()}'." );
389 wfProfileOut( $fname );
394 * @param $prefix string
397 protected function unprefixRow( $row, $prefix = 'img_' ) {
398 $array = (array)$row;
399 $prefixLength = strlen( $prefix );
401 // Sanity check prefix once
402 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
403 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
407 foreach ( $array as $name => $value ) {
408 $decoded[substr( $name, $prefixLength )] = $value;
414 * Decode a row from the database (either object or array) to an array
415 * with timestamps and MIME types decoded, and the field prefix removed.
417 * @param $prefix string
418 * @throws MWException
421 function decodeRow( $row, $prefix = 'img_' ) {
422 $decoded = $this->unprefixRow( $row, $prefix );
424 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
426 if ( empty( $decoded['major_mime'] ) ) {
427 $decoded['mime'] = 'unknown/unknown';
429 if ( !$decoded['minor_mime'] ) {
430 $decoded['minor_mime'] = 'unknown';
432 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
435 # Trim zero padding from char/binary field
436 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
442 * Load file metadata from a DB result row
444 function loadFromRow( $row, $prefix = 'img_' ) {
445 $this->dataLoaded
= true;
446 $this->extraDataLoaded
= true;
448 $array = $this->decodeRow( $row, $prefix );
450 foreach ( $array as $name => $value ) {
451 $this->$name = $value;
454 $this->fileExists
= true;
455 $this->maybeUpgradeRow();
459 * Load file metadata from cache or DB, unless already loaded
460 * @param integer $flags
462 function load( $flags = 0 ) {
463 if ( !$this->dataLoaded
) {
464 if ( !$this->loadFromCache() ) {
466 $this->saveToCache();
468 $this->dataLoaded
= true;
470 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
471 $this->loadExtraFromDB();
476 * Upgrade a row if it needs it
478 function maybeUpgradeRow() {
479 global $wgUpdateCompatibleMetadata;
480 if ( wfReadOnly() ) {
484 if ( is_null( $this->media_type
) ||
485 $this->mime
== 'image/svg'
488 $this->upgraded
= true;
490 $handler = $this->getHandler();
492 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
493 if ( $validity === MediaHandler
::METADATA_BAD
494 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
497 $this->upgraded
= true;
503 function getUpgraded() {
504 return $this->upgraded
;
508 * Fix assorted version-related problems with the image row by reloading it from the file
510 function upgradeRow() {
511 wfProfileIn( __METHOD__
);
513 $this->lock(); // begin
515 $this->loadFromFile();
517 # Don't destroy file info of missing files
518 if ( !$this->fileExists
) {
519 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
520 wfProfileOut( __METHOD__
);
524 $dbw = $this->repo
->getMasterDB();
525 list( $major, $minor ) = self
::splitMime( $this->mime
);
527 if ( wfReadOnly() ) {
528 wfProfileOut( __METHOD__
);
531 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
533 $dbw->update( 'image',
535 'img_size' => $this->size
, // sanity
536 'img_width' => $this->width
,
537 'img_height' => $this->height
,
538 'img_bits' => $this->bits
,
539 'img_media_type' => $this->media_type
,
540 'img_major_mime' => $major,
541 'img_minor_mime' => $minor,
542 'img_metadata' => $this->metadata
,
543 'img_sha1' => $this->sha1
,
545 array( 'img_name' => $this->getName() ),
549 $this->saveToCache();
551 $this->unlock(); // done
553 wfProfileOut( __METHOD__
);
557 * Set properties in this object to be equal to those given in the
558 * associative array $info. Only cacheable fields can be set.
559 * All fields *must* be set in $info except for getLazyCacheFields().
561 * If 'mime' is given, it will be split into major_mime/minor_mime.
562 * If major_mime/minor_mime are given, $this->mime will also be set.
564 function setProps( $info ) {
565 $this->dataLoaded
= true;
566 $fields = $this->getCacheFields( '' );
567 $fields[] = 'fileExists';
569 foreach ( $fields as $field ) {
570 if ( isset( $info[$field] ) ) {
571 $this->$field = $info[$field];
575 // Fix up mime fields
576 if ( isset( $info['major_mime'] ) ) {
577 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
578 } elseif ( isset( $info['mime'] ) ) {
579 $this->mime
= $info['mime'];
580 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
584 /** splitMime inherited */
585 /** getName inherited */
586 /** getTitle inherited */
587 /** getURL inherited */
588 /** getViewURL inherited */
589 /** getPath inherited */
590 /** isVisible inhereted */
595 function isMissing() {
596 if ( $this->missing
=== null ) {
597 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
598 $this->missing
= !$fileExists;
600 return $this->missing
;
604 * Return the width of the image
609 public function getWidth( $page = 1 ) {
612 if ( $this->isMultipage() ) {
613 $dim = $this->getHandler()->getPageDimensions( $this, $page );
615 return $dim['width'];
617 // For non-paged media, the false goes through an
618 // intval, turning failure into 0, so do same here.
627 * Return the height of the image
632 public function getHeight( $page = 1 ) {
635 if ( $this->isMultipage() ) {
636 $dim = $this->getHandler()->getPageDimensions( $this, $page );
638 return $dim['height'];
640 // For non-paged media, the false goes through an
641 // intval, turning failure into 0, so do same here.
645 return $this->height
;
650 * Returns ID or name of user who uploaded the file
652 * @param string $type 'text' or 'id'
655 function getUser( $type = 'text' ) {
658 if ( $type == 'text' ) {
659 return $this->user_text
;
660 } elseif ( $type == 'id' ) {
666 * Get handler-specific metadata
669 function getMetadata() {
670 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
671 return $this->metadata
;
677 function getBitDepth() {
683 * Return the size of the image file, in bytes
686 public function getSize() {
692 * Returns the mime type of the file.
695 function getMimeType() {
701 * Return the type of the media in the file.
702 * Use the value returned by this function with the MEDIATYPE_xxx constants.
705 function getMediaType() {
707 return $this->media_type
;
710 /** canRender inherited */
711 /** mustRender inherited */
712 /** allowInlineDisplay inherited */
713 /** isSafeFile inherited */
714 /** isTrustedFile inherited */
717 * Returns true if the file exists on disk.
718 * @return boolean Whether file exist on disk.
720 public function exists() {
722 return $this->fileExists
;
725 /** getTransformScript inherited */
726 /** getUnscaledThumb inherited */
727 /** thumbName inherited */
728 /** createThumb inherited */
729 /** transform inherited */
732 * Fix thumbnail files from 1.4 or before, with extreme prejudice
733 * @todo : do we still care about this? Perhaps a maintenance script
734 * can be made instead. Enabling this code results in a serious
735 * RTT regression for wikis without 404 handling.
737 function migrateThumbFile( $thumbName ) {
738 /* Old code for bug 2532
739 $thumbDir = $this->getThumbPath();
740 $thumbPath = "$thumbDir/$thumbName";
741 if ( is_dir( $thumbPath ) ) {
742 // Directory where file should be
743 // This happened occasionally due to broken migration code in 1.5
744 // Rename to broken-*
745 for ( $i = 0; $i < 100; $i++ ) {
746 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
747 if ( !file_exists( $broken ) ) {
748 rename( $thumbPath, $broken );
752 // Doesn't exist anymore
758 if ( $this->repo->fileExists( $thumbDir ) ) {
759 // Delete file where directory should be
760 $this->repo->cleanupBatch( array( $thumbDir ) );
765 /** getHandler inherited */
766 /** iconThumb inherited */
767 /** getLastError inherited */
770 * Get all thumbnail names previously generated for this file
771 * @param string|bool $archiveName Name of an archive file, default false
772 * @return array first element is the base dir, then files in that base dir.
774 function getThumbnails( $archiveName = false ) {
775 if ( $archiveName ) {
776 $dir = $this->getArchiveThumbPath( $archiveName );
778 $dir = $this->getThumbPath();
781 $backend = $this->repo
->getBackend();
782 $files = array( $dir );
783 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
784 foreach ( $iterator as $file ) {
792 * Refresh metadata in memcached, but don't touch thumbnails or squid
794 function purgeMetadataCache() {
796 $this->saveToCache();
797 $this->purgeHistory();
801 * Purge the shared history (OldLocalFile) cache.
803 * @note This used to purge old thumbnails as well.
805 function purgeHistory() {
808 $hashedName = md5( $this->getName() );
809 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
812 $wgMemc->delete( $oldKey );
817 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
819 * @param Array $options An array potentially with the key forThumbRefresh.
821 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
823 function purgeCache( $options = array() ) {
824 wfProfileIn( __METHOD__
);
825 // Refresh metadata cache
826 $this->purgeMetadataCache();
829 $this->purgeThumbnails( $options );
831 // Purge squid cache for this file
832 SquidUpdate
::purge( array( $this->getURL() ) );
833 wfProfileOut( __METHOD__
);
837 * Delete cached transformed files for an archived version only.
838 * @param string $archiveName name of the archived file
840 function purgeOldThumbnails( $archiveName ) {
842 wfProfileIn( __METHOD__
);
844 // Get a list of old thumbnails and URLs
845 $files = $this->getThumbnails( $archiveName );
846 $dir = array_shift( $files );
847 $this->purgeThumbList( $dir, $files );
849 // Purge any custom thumbnail caches
850 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
855 foreach ( $files as $file ) {
856 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
858 SquidUpdate
::purge( $urls );
861 wfProfileOut( __METHOD__
);
865 * Delete cached transformed files for the current version only.
867 function purgeThumbnails( $options = array() ) {
869 wfProfileIn( __METHOD__
);
872 $files = $this->getThumbnails();
873 // Always purge all files from squid regardless of handler filters
876 foreach ( $files as $file ) {
877 $urls[] = $this->getThumbUrl( $file );
879 array_shift( $urls ); // don't purge directory
882 // Give media handler a chance to filter the file purge list
883 if ( !empty( $options['forThumbRefresh'] ) ) {
884 $handler = $this->getHandler();
886 $handler->filterThumbnailPurgeList( $files, $options );
890 $dir = array_shift( $files );
891 $this->purgeThumbList( $dir, $files );
893 // Purge any custom thumbnail caches
894 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
898 SquidUpdate
::purge( $urls );
901 wfProfileOut( __METHOD__
);
905 * Delete a list of thumbnails visible at urls
906 * @param string $dir base dir of the files.
907 * @param array $files of strings: relative filenames (to $dir)
909 protected function purgeThumbList( $dir, $files ) {
910 $fileListDebug = strtr(
911 var_export( $files, true ),
914 wfDebug( __METHOD__
. ": $fileListDebug\n" );
916 $purgeList = array();
917 foreach ( $files as $file ) {
918 # Check that the base file name is part of the thumb name
919 # This is a basic sanity check to avoid erasing unrelated directories
920 if ( strpos( $file, $this->getName() ) !== false
921 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
923 $purgeList[] = "{$dir}/{$file}";
927 # Delete the thumbnails
928 $this->repo
->quickPurgeBatch( $purgeList );
929 # Clear out the thumbnail directory if empty
930 $this->repo
->quickCleanDir( $dir );
933 /** purgeDescription inherited */
934 /** purgeEverything inherited */
943 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
944 $dbr = $this->repo
->getSlaveDB();
945 $tables = array( 'oldimage' );
946 $fields = OldLocalFile
::selectFields();
947 $conds = $opts = $join_conds = array();
948 $eq = $inc ?
'=' : '';
949 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
952 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
956 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
960 $opts['LIMIT'] = $limit;
963 // Search backwards for time > x queries
964 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
965 $opts['ORDER BY'] = "oi_timestamp $order";
966 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
968 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
969 &$conds, &$opts, &$join_conds ) );
971 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
974 foreach ( $res as $row ) {
975 if ( $this->repo
->oldFileFromRowFactory
) {
976 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
978 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
982 if ( $order == 'ASC' ) {
983 $r = array_reverse( $r ); // make sure it ends up descending
990 * Return the history of this file, line by line.
991 * starts with current version, then old versions.
992 * uses $this->historyLine to check which line to return:
993 * 0 return line for current version
994 * 1 query for old versions, return first one
995 * 2, ... return next old version from above query
998 public function nextHistoryLine() {
999 # Polymorphic function name to distinguish foreign and local fetches
1000 $fname = get_class( $this ) . '::' . __FUNCTION__
;
1002 $dbr = $this->repo
->getSlaveDB();
1004 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1005 $this->historyRes
= $dbr->select( 'image',
1008 "'' AS oi_archive_name",
1012 array( 'img_name' => $this->title
->getDBkey() ),
1016 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1017 $this->historyRes
= null;
1020 } elseif ( $this->historyLine
== 1 ) {
1021 $this->historyRes
= $dbr->select( 'oldimage', '*',
1022 array( 'oi_name' => $this->title
->getDBkey() ),
1024 array( 'ORDER BY' => 'oi_timestamp DESC' )
1027 $this->historyLine ++
;
1029 return $dbr->fetchObject( $this->historyRes
);
1033 * Reset the history pointer to the first element of the history
1035 public function resetHistory() {
1036 $this->historyLine
= 0;
1038 if ( !is_null( $this->historyRes
) ) {
1039 $this->historyRes
= null;
1043 /** getHashPath inherited */
1044 /** getRel inherited */
1045 /** getUrlRel inherited */
1046 /** getArchiveRel inherited */
1047 /** getArchivePath inherited */
1048 /** getThumbPath inherited */
1049 /** getArchiveUrl inherited */
1050 /** getThumbUrl inherited */
1051 /** getArchiveVirtualUrl inherited */
1052 /** getThumbVirtualUrl inherited */
1053 /** isHashed inherited */
1056 * Upload a file and record it in the DB
1057 * @param string $srcPath source storage path, virtual URL, or filesystem path
1058 * @param string $comment upload description
1059 * @param string $pageText text to use for the new description page,
1060 * if a new description page is created
1061 * @param $flags Integer|bool: flags for publish()
1062 * @param array|bool $props File properties, if known. This can be used to reduce the
1063 * upload time when uploading virtual URLs for which the file info
1065 * @param string|bool $timestamp timestamp for img_timestamp, or false to use the current time
1066 * @param $user User|null: User object or null to use $wgUser
1068 * @return FileRepoStatus object. On success, the value member contains the
1069 * archive name, or an empty string if it was a new file.
1071 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
1074 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1075 return $this->readOnlyFatalStatus();
1079 wfProfileIn( __METHOD__
. '-getProps' );
1080 if ( $this->repo
->isVirtualUrl( $srcPath )
1081 || FileBackend
::isStoragePath( $srcPath ) )
1083 $props = $this->repo
->getFileProps( $srcPath );
1085 $props = FSFile
::getPropsFromPath( $srcPath );
1087 wfProfileOut( __METHOD__
. '-getProps' );
1091 $handler = MediaHandler
::getHandler( $props['mime'] );
1093 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1095 $options['headers'] = array();
1098 // Trim spaces on user supplied text
1099 $comment = trim( $comment );
1101 // truncate nicely or the DB will do it for us
1102 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1103 $comment = $wgContLang->truncate( $comment, 255 );
1104 $this->lock(); // begin
1105 $status = $this->publish( $srcPath, $flags, $options );
1107 if ( $status->successCount
> 0 ) {
1108 # Essentially we are displacing any existing current file and saving
1109 # a new current file at the old location. If just the first succeeded,
1110 # we still need to displace the current DB entry and put in a new one.
1111 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1112 $status->fatal( 'filenotfound', $srcPath );
1116 $this->unlock(); // done
1122 * Record a file upload in the upload log and the image table
1124 * @param $desc string
1125 * @param $license string
1126 * @param $copyStatus string
1127 * @param $source string
1128 * @param $watch bool
1129 * @param $timestamp string|bool
1130 * @param $user User object or null to use $wgUser
1133 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1134 $watch = false, $timestamp = false, User
$user = null )
1141 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1143 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1148 $user->addWatch( $this->getTitle() );
1154 * Record a file upload in the upload log and the image table
1156 * @param $comment string
1157 * @param $pageText string
1158 * @param $props bool|array
1159 * @param $timestamp bool|string
1160 * @param $user null|User
1163 function recordUpload2(
1164 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1166 wfProfileIn( __METHOD__
);
1168 if ( is_null( $user ) ) {
1173 $dbw = $this->repo
->getMasterDB();
1174 $dbw->begin( __METHOD__
);
1177 wfProfileIn( __METHOD__
. '-getProps' );
1178 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1179 wfProfileOut( __METHOD__
. '-getProps' );
1182 if ( $timestamp === false ) {
1183 $timestamp = $dbw->timestamp();
1186 $props['description'] = $comment;
1187 $props['user'] = $user->getId();
1188 $props['user_text'] = $user->getName();
1189 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1190 $this->setProps( $props );
1192 # Fail now if the file isn't there
1193 if ( !$this->fileExists
) {
1194 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1195 wfProfileOut( __METHOD__
);
1201 # Test to see if the row exists using INSERT IGNORE
1202 # This avoids race conditions by locking the row until the commit, and also
1203 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1204 $dbw->insert( 'image',
1206 'img_name' => $this->getName(),
1207 'img_size' => $this->size
,
1208 'img_width' => intval( $this->width
),
1209 'img_height' => intval( $this->height
),
1210 'img_bits' => $this->bits
,
1211 'img_media_type' => $this->media_type
,
1212 'img_major_mime' => $this->major_mime
,
1213 'img_minor_mime' => $this->minor_mime
,
1214 'img_timestamp' => $timestamp,
1215 'img_description' => $comment,
1216 'img_user' => $user->getId(),
1217 'img_user_text' => $user->getName(),
1218 'img_metadata' => $this->metadata
,
1219 'img_sha1' => $this->sha1
1224 if ( $dbw->affectedRows() == 0 ) {
1225 # (bug 34993) Note: $oldver can be empty here, if the previous
1226 # version of the file was broken. Allow registration of the new
1227 # version to continue anyway, because that's better than having
1228 # an image that's not fixable by user operations.
1231 # Collision, this is an update of a file
1232 # Insert previous contents into oldimage
1233 $dbw->insertSelect( 'oldimage', 'image',
1235 'oi_name' => 'img_name',
1236 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1237 'oi_size' => 'img_size',
1238 'oi_width' => 'img_width',
1239 'oi_height' => 'img_height',
1240 'oi_bits' => 'img_bits',
1241 'oi_timestamp' => 'img_timestamp',
1242 'oi_description' => 'img_description',
1243 'oi_user' => 'img_user',
1244 'oi_user_text' => 'img_user_text',
1245 'oi_metadata' => 'img_metadata',
1246 'oi_media_type' => 'img_media_type',
1247 'oi_major_mime' => 'img_major_mime',
1248 'oi_minor_mime' => 'img_minor_mime',
1249 'oi_sha1' => 'img_sha1'
1251 array( 'img_name' => $this->getName() ),
1255 # Update the current image row
1256 $dbw->update( 'image',
1258 'img_size' => $this->size
,
1259 'img_width' => intval( $this->width
),
1260 'img_height' => intval( $this->height
),
1261 'img_bits' => $this->bits
,
1262 'img_media_type' => $this->media_type
,
1263 'img_major_mime' => $this->major_mime
,
1264 'img_minor_mime' => $this->minor_mime
,
1265 'img_timestamp' => $timestamp,
1266 'img_description' => $comment,
1267 'img_user' => $user->getId(),
1268 'img_user_text' => $user->getName(),
1269 'img_metadata' => $this->metadata
,
1270 'img_sha1' => $this->sha1
1272 array( 'img_name' => $this->getName() ),
1276 # This is a new file, so update the image count
1277 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1280 $descTitle = $this->getTitle();
1281 $wikiPage = new WikiFilePage( $descTitle );
1282 $wikiPage->setFile( $this );
1285 $action = $reupload ?
'overwrite' : 'upload';
1287 $logEntry = new ManualLogEntry( 'upload', $action );
1288 $logEntry->setPerformer( $user );
1289 $logEntry->setComment( $comment );
1290 $logEntry->setTarget( $descTitle );
1292 // Allow people using the api to associate log entries with the upload.
1293 // Log has a timestamp, but sometimes different from upload timestamp.
1294 $logEntry->setParameters(
1296 'img_sha1' => $this->sha1
,
1297 'img_timestamp' => $timestamp,
1300 // Note we keep $logId around since during new image
1301 // creation, page doesn't exist yet, so log_page = 0
1302 // but we want it to point to the page we're making,
1303 // so we later modify the log entry.
1304 // For a similar reason, we avoid making an RC entry
1305 // now and wait until the page exists.
1306 $logId = $logEntry->insert();
1308 $exists = $descTitle->exists();
1310 // Page exists, do RC entry now (otherwise we wait for later).
1311 $logEntry->publish( $logId );
1313 wfProfileIn( __METHOD__
. '-edit' );
1316 # Create a null revision
1317 $latest = $descTitle->getLatestRevID();
1318 $editSummary = LogFormatter
::newFromEntry( $logEntry )->getPlainActionText();
1320 $nullRevision = Revision
::newNullRevision(
1322 $descTitle->getArticleID(),
1326 if ( !is_null( $nullRevision ) ) {
1327 $nullRevision->insertOn( $dbw );
1329 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1330 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1334 # Commit the transaction now, in case something goes wrong later
1335 # The most important thing is that files don't get lost, especially archives
1336 # NOTE: once we have support for nested transactions, the commit may be moved
1337 # to after $wikiPage->doEdit has been called.
1338 $dbw->commit( __METHOD__
);
1341 # Invalidate the cache for the description page
1342 $descTitle->invalidateCache();
1343 $descTitle->purgeSquid();
1345 # New file; create the description page.
1346 # There's already a log entry, so don't make a second RC entry
1347 # Squid and file cache for the description page are purged by doEditContent.
1348 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1349 $status = $wikiPage->doEditContent( $content, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1351 $dbw->begin( __METHOD__
); // XXX; doEdit() uses a transaction
1352 // Now that the page exists, make an RC entry.
1353 $logEntry->publish( $logId );
1354 if ( isset( $status->value
['revision'] ) ) {
1355 $dbw->update( 'logging',
1356 array( 'log_page' => $status->value
['revision']->getPage() ),
1357 array( 'log_id' => $logId ),
1361 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1365 wfProfileOut( __METHOD__
. '-edit' );
1367 # Save to cache and purge the squid
1368 # We shall not saveToCache before the commit since otherwise
1369 # in case of a rollback there is an usable file from memcached
1370 # which in fact doesn't really exist (bug 24978)
1371 $this->saveToCache();
1374 # Delete old thumbnails
1375 wfProfileIn( __METHOD__
. '-purge' );
1376 $this->purgeThumbnails();
1377 wfProfileOut( __METHOD__
. '-purge' );
1379 # Remove the old file from the squid cache
1380 SquidUpdate
::purge( array( $this->getURL() ) );
1383 # Hooks, hooks, the magic of hooks...
1384 wfProfileIn( __METHOD__
. '-hooks' );
1385 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1386 wfProfileOut( __METHOD__
. '-hooks' );
1388 # Invalidate cache for all pages using this file
1389 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1390 $update->doUpdate();
1392 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1395 # Invalidate cache for all pages that redirects on this page
1396 $redirs = $this->getTitle()->getRedirectsHere();
1398 foreach ( $redirs as $redir ) {
1399 if ( !$reupload && $redir->getNamespace() === NS_FILE
) {
1400 LinksUpdate
::queueRecursiveJobsForTable( $redir, 'imagelinks' );
1402 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1403 $update->doUpdate();
1406 wfProfileOut( __METHOD__
);
1411 * Move or copy a file to its public location. If a file exists at the
1412 * destination, move it to an archive. Returns a FileRepoStatus object with
1413 * the archive name in the "value" member on success.
1415 * The archive name should be passed through to recordUpload for database
1418 * @param string $srcPath local filesystem path to the source image
1419 * @param $flags Integer: a bitwise combination of:
1420 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1421 * @param array $options Optional additional parameters
1422 * @return FileRepoStatus object. On success, the value member contains the
1423 * archive name, or an empty string if it was a new file.
1425 function publish( $srcPath, $flags = 0, array $options = array() ) {
1426 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1430 * Move or copy a file to a specified location. Returns a FileRepoStatus
1431 * object with the archive name in the "value" member on success.
1433 * The archive name should be passed through to recordUpload for database
1436 * @param string $srcPath local filesystem path to the source image
1437 * @param string $dstRel target relative path
1438 * @param $flags Integer: a bitwise combination of:
1439 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1440 * @param array $options Optional additional parameters
1441 * @return FileRepoStatus object. On success, the value member contains the
1442 * archive name, or an empty string if it was a new file.
1444 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1445 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1446 return $this->readOnlyFatalStatus();
1449 $this->lock(); // begin
1451 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1452 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1453 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1454 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1456 if ( $status->value
== 'new' ) {
1457 $status->value
= '';
1459 $status->value
= $archiveName;
1462 $this->unlock(); // done
1467 /** getLinksTo inherited */
1468 /** getExifData inherited */
1469 /** isLocal inherited */
1470 /** wasDeleted inherited */
1473 * Move file to the new title
1475 * Move current, old version and all thumbnails
1476 * to the new filename. Old file is deleted.
1478 * Cache purging is done; checks for validity
1479 * and logging are caller's responsibility
1481 * @param $target Title New file name
1482 * @return FileRepoStatus object.
1484 function move( $target ) {
1485 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1486 return $this->readOnlyFatalStatus();
1489 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1490 $batch = new LocalFileMoveBatch( $this, $target );
1492 $this->lock(); // begin
1493 $batch->addCurrent();
1494 $archiveNames = $batch->addOlds();
1495 $status = $batch->execute();
1496 $this->unlock(); // done
1498 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1500 $this->purgeEverything();
1501 foreach ( $archiveNames as $archiveName ) {
1502 $this->purgeOldThumbnails( $archiveName );
1504 if ( $status->isOK() ) {
1505 // Now switch the object
1506 $this->title
= $target;
1507 // Force regeneration of the name and hashpath
1508 unset( $this->name
);
1509 unset( $this->hashPath
);
1510 // Purge the new image
1511 $this->purgeEverything();
1518 * Delete all versions of the file.
1520 * Moves the files into an archive directory (or deletes them)
1521 * and removes the database rows.
1523 * Cache purging is done; logging is caller's responsibility.
1527 * @return FileRepoStatus object.
1529 function delete( $reason, $suppress = false ) {
1530 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1531 return $this->readOnlyFatalStatus();
1534 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1536 $this->lock(); // begin
1537 $batch->addCurrent();
1538 # Get old version relative paths
1539 $archiveNames = $batch->addOlds();
1540 $status = $batch->execute();
1541 $this->unlock(); // done
1543 if ( $status->isOK() ) {
1544 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1547 $this->purgeEverything();
1548 foreach ( $archiveNames as $archiveName ) {
1549 $this->purgeOldThumbnails( $archiveName );
1556 * Delete an old version of the file.
1558 * Moves the file into an archive directory (or deletes it)
1559 * and removes the database row.
1561 * Cache purging is done; logging is caller's responsibility.
1563 * @param $archiveName String
1564 * @param $reason String
1565 * @param $suppress Boolean
1566 * @throws MWException or FSException on database or file store failure
1567 * @return FileRepoStatus object.
1569 function deleteOld( $archiveName, $reason, $suppress = false ) {
1570 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1571 return $this->readOnlyFatalStatus();
1574 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1576 $this->lock(); // begin
1577 $batch->addOld( $archiveName );
1578 $status = $batch->execute();
1579 $this->unlock(); // done
1581 $this->purgeOldThumbnails( $archiveName );
1582 if ( $status->isOK() ) {
1583 $this->purgeDescription();
1584 $this->purgeHistory();
1591 * Restore all or specified deleted revisions to the given file.
1592 * Permissions and logging are left to the caller.
1594 * May throw database exceptions on error.
1596 * @param array $versions set of record ids of deleted items to restore,
1597 * or empty to restore all revisions.
1598 * @param $unsuppress Boolean
1599 * @return FileRepoStatus
1601 function restore( $versions = array(), $unsuppress = false ) {
1602 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1603 return $this->readOnlyFatalStatus();
1606 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1608 $this->lock(); // begin
1612 $batch->addIds( $versions );
1614 $status = $batch->execute();
1615 if ( $status->isGood() ) {
1616 $cleanupStatus = $batch->cleanup();
1617 $cleanupStatus->successCount
= 0;
1618 $cleanupStatus->failCount
= 0;
1619 $status->merge( $cleanupStatus );
1621 $this->unlock(); // done
1626 /** isMultipage inherited */
1627 /** pageCount inherited */
1628 /** scaleHeight inherited */
1629 /** getImageSize inherited */
1632 * Get the URL of the file description page.
1635 function getDescriptionUrl() {
1636 return $this->title
->getLocalURL();
1640 * Get the HTML text of the description page
1641 * This is not used by ImagePage for local files, since (among other things)
1642 * it skips the parser cache.
1643 * @return bool|mixed
1645 function getDescriptionText() {
1646 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1650 $content = $revision->getContent();
1654 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions() );
1655 return $pout->getText();
1661 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1663 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1665 } elseif ( $audience == self
::FOR_THIS_USER
1666 && !$this->userCan( self
::DELETED_COMMENT
, $user ) )
1670 return $this->description
;
1675 * @return bool|string
1677 function getTimestamp() {
1679 return $this->timestamp
;
1685 function getSha1() {
1687 // Initialise now if necessary
1688 if ( $this->sha1
== '' && $this->fileExists
) {
1689 $this->lock(); // begin
1691 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1692 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1693 $dbw = $this->repo
->getMasterDB();
1694 $dbw->update( 'image',
1695 array( 'img_sha1' => $this->sha1
),
1696 array( 'img_name' => $this->getName() ),
1698 $this->saveToCache();
1701 $this->unlock(); // done
1708 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1710 function isCacheable() {
1712 // If extra data (metadata) was not loaded then it must have been large
1713 return $this->extraDataLoaded
1714 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1718 * Start a transaction and lock the image for update
1719 * Increments a reference counter if the lock is already held
1720 * @return boolean True if the image exists, false otherwise
1723 $dbw = $this->repo
->getMasterDB();
1725 if ( !$this->locked
) {
1726 if ( !$dbw->trxLevel() ) {
1727 $dbw->begin( __METHOD__
);
1728 $this->lockedOwnTrx
= true;
1733 return $dbw->selectField( 'image', '1',
1734 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1738 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1739 * the transaction and thereby releases the image lock.
1742 if ( $this->locked
) {
1744 if ( !$this->locked
&& $this->lockedOwnTrx
) {
1745 $dbw = $this->repo
->getMasterDB();
1746 $dbw->commit( __METHOD__
);
1747 $this->lockedOwnTrx
= false;
1753 * Roll back the DB transaction and mark the image unlocked
1755 function unlockAndRollback() {
1756 $this->locked
= false;
1757 $dbw = $this->repo
->getMasterDB();
1758 $dbw->rollback( __METHOD__
);
1759 $this->lockedOwnTrx
= false;
1765 protected function readOnlyFatalStatus() {
1766 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1767 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1769 } // LocalFile class
1771 # ------------------------------------------------------------------------------
1774 * Helper class for file deletion
1775 * @ingroup FileAbstraction
1777 class LocalFileDeleteBatch
{
1784 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1789 * @param $reason string
1790 * @param $suppress bool
1792 function __construct( File
$file, $reason = '', $suppress = false ) {
1793 $this->file
= $file;
1794 $this->reason
= $reason;
1795 $this->suppress
= $suppress;
1796 $this->status
= $file->repo
->newGood();
1799 function addCurrent() {
1800 $this->srcRels
['.'] = $this->file
->getRel();
1804 * @param $oldName string
1806 function addOld( $oldName ) {
1807 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1808 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1812 * Add the old versions of the image to the batch
1813 * @return Array List of archive names from old versions
1815 function addOlds() {
1816 $archiveNames = array();
1818 $dbw = $this->file
->repo
->getMasterDB();
1819 $result = $dbw->select( 'oldimage',
1820 array( 'oi_archive_name' ),
1821 array( 'oi_name' => $this->file
->getName() ),
1825 foreach ( $result as $row ) {
1826 $this->addOld( $row->oi_archive_name
);
1827 $archiveNames[] = $row->oi_archive_name
;
1830 return $archiveNames;
1836 function getOldRels() {
1837 if ( !isset( $this->srcRels
['.'] ) ) {
1838 $oldRels =& $this->srcRels
;
1839 $deleteCurrent = false;
1841 $oldRels = $this->srcRels
;
1842 unset( $oldRels['.'] );
1843 $deleteCurrent = true;
1846 return array( $oldRels, $deleteCurrent );
1852 protected function getHashes() {
1854 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1856 if ( $deleteCurrent ) {
1857 $hashes['.'] = $this->file
->getSha1();
1860 if ( count( $oldRels ) ) {
1861 $dbw = $this->file
->repo
->getMasterDB();
1862 $res = $dbw->select(
1864 array( 'oi_archive_name', 'oi_sha1' ),
1865 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1869 foreach ( $res as $row ) {
1870 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1871 // Get the hash from the file
1872 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1873 $props = $this->file
->repo
->getFileProps( $oldUrl );
1875 if ( $props['fileExists'] ) {
1876 // Upgrade the oldimage row
1877 $dbw->update( 'oldimage',
1878 array( 'oi_sha1' => $props['sha1'] ),
1879 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1881 $hashes[$row->oi_archive_name
] = $props['sha1'];
1883 $hashes[$row->oi_archive_name
] = false;
1886 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1891 $missing = array_diff_key( $this->srcRels
, $hashes );
1893 foreach ( $missing as $name => $rel ) {
1894 $this->status
->error( 'filedelete-old-unregistered', $name );
1897 foreach ( $hashes as $name => $hash ) {
1899 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1900 unset( $hashes[$name] );
1907 function doDBInserts() {
1910 $dbw = $this->file
->repo
->getMasterDB();
1911 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1912 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1913 $encReason = $dbw->addQuotes( $this->reason
);
1914 $encGroup = $dbw->addQuotes( 'deleted' );
1915 $ext = $this->file
->getExtension();
1916 $dotExt = $ext === '' ?
'' : ".$ext";
1917 $encExt = $dbw->addQuotes( $dotExt );
1918 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1920 // Bitfields to further suppress the content
1921 if ( $this->suppress
) {
1923 // This should be 15...
1924 $bitfield |
= Revision
::DELETED_TEXT
;
1925 $bitfield |
= Revision
::DELETED_COMMENT
;
1926 $bitfield |
= Revision
::DELETED_USER
;
1927 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1929 $bitfield = 'oi_deleted';
1932 if ( $deleteCurrent ) {
1933 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1934 $where = array( 'img_name' => $this->file
->getName() );
1935 $dbw->insertSelect( 'filearchive', 'image',
1937 'fa_storage_group' => $encGroup,
1938 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1939 'fa_deleted_user' => $encUserId,
1940 'fa_deleted_timestamp' => $encTimestamp,
1941 'fa_deleted_reason' => $encReason,
1942 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1944 'fa_name' => 'img_name',
1945 'fa_archive_name' => 'NULL',
1946 'fa_size' => 'img_size',
1947 'fa_width' => 'img_width',
1948 'fa_height' => 'img_height',
1949 'fa_metadata' => 'img_metadata',
1950 'fa_bits' => 'img_bits',
1951 'fa_media_type' => 'img_media_type',
1952 'fa_major_mime' => 'img_major_mime',
1953 'fa_minor_mime' => 'img_minor_mime',
1954 'fa_description' => 'img_description',
1955 'fa_user' => 'img_user',
1956 'fa_user_text' => 'img_user_text',
1957 'fa_timestamp' => 'img_timestamp',
1958 'fa_sha1' => 'img_sha1',
1959 ), $where, __METHOD__
);
1962 if ( count( $oldRels ) ) {
1963 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1965 'oi_name' => $this->file
->getName(),
1966 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1967 $dbw->insertSelect( 'filearchive', 'oldimage',
1969 'fa_storage_group' => $encGroup,
1970 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1971 'fa_deleted_user' => $encUserId,
1972 'fa_deleted_timestamp' => $encTimestamp,
1973 'fa_deleted_reason' => $encReason,
1974 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1976 'fa_name' => 'oi_name',
1977 'fa_archive_name' => 'oi_archive_name',
1978 'fa_size' => 'oi_size',
1979 'fa_width' => 'oi_width',
1980 'fa_height' => 'oi_height',
1981 'fa_metadata' => 'oi_metadata',
1982 'fa_bits' => 'oi_bits',
1983 'fa_media_type' => 'oi_media_type',
1984 'fa_major_mime' => 'oi_major_mime',
1985 'fa_minor_mime' => 'oi_minor_mime',
1986 'fa_description' => 'oi_description',
1987 'fa_user' => 'oi_user',
1988 'fa_user_text' => 'oi_user_text',
1989 'fa_timestamp' => 'oi_timestamp',
1990 'fa_sha1' => 'oi_sha1',
1991 ), $where, __METHOD__
);
1995 function doDBDeletes() {
1996 $dbw = $this->file
->repo
->getMasterDB();
1997 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1999 if ( count( $oldRels ) ) {
2000 $dbw->delete( 'oldimage',
2002 'oi_name' => $this->file
->getName(),
2003 'oi_archive_name' => array_keys( $oldRels )
2007 if ( $deleteCurrent ) {
2008 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
2013 * Run the transaction
2014 * @return FileRepoStatus
2016 function execute() {
2017 wfProfileIn( __METHOD__
);
2019 $this->file
->lock();
2020 // Leave private files alone
2021 $privateFiles = array();
2022 list( $oldRels, ) = $this->getOldRels();
2023 $dbw = $this->file
->repo
->getMasterDB();
2025 if ( !empty( $oldRels ) ) {
2026 $res = $dbw->select( 'oldimage',
2027 array( 'oi_archive_name' ),
2028 array( 'oi_name' => $this->file
->getName(),
2029 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
2030 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
2033 foreach ( $res as $row ) {
2034 $privateFiles[$row->oi_archive_name
] = 1;
2037 // Prepare deletion batch
2038 $hashes = $this->getHashes();
2039 $this->deletionBatch
= array();
2040 $ext = $this->file
->getExtension();
2041 $dotExt = $ext === '' ?
'' : ".$ext";
2043 foreach ( $this->srcRels
as $name => $srcRel ) {
2044 // Skip files that have no hash (missing source).
2045 // Keep private files where they are.
2046 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2047 $hash = $hashes[$name];
2048 $key = $hash . $dotExt;
2049 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
2050 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
2054 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2055 // We acquire this lock by running the inserts now, before the file operations.
2057 // This potentially has poor lock contention characteristics -- an alternative
2058 // scheme would be to insert stub filearchive entries with no fa_name and commit
2059 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2060 $this->doDBInserts();
2062 // Removes non-existent file from the batch, so we don't get errors.
2063 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
2065 // Execute the file deletion batch
2066 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2068 if ( !$status->isGood() ) {
2069 $this->status
->merge( $status );
2072 if ( !$this->status
->isOK() ) {
2073 // Critical file deletion error
2074 // Roll back inserts, release lock and abort
2075 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2076 $this->file
->unlockAndRollback();
2077 wfProfileOut( __METHOD__
);
2078 return $this->status
;
2081 // Delete image/oldimage rows
2082 $this->doDBDeletes();
2084 // Commit and return
2085 $this->file
->unlock();
2086 wfProfileOut( __METHOD__
);
2088 return $this->status
;
2092 * Removes non-existent files from a deletion batch.
2093 * @param $batch array
2096 function removeNonexistentFiles( $batch ) {
2097 $files = $newBatch = array();
2099 foreach ( $batch as $batchItem ) {
2100 list( $src, ) = $batchItem;
2101 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2104 $result = $this->file
->repo
->fileExistsBatch( $files );
2106 foreach ( $batch as $batchItem ) {
2107 if ( $result[$batchItem[0]] ) {
2108 $newBatch[] = $batchItem;
2116 # ------------------------------------------------------------------------------
2119 * Helper class for file undeletion
2120 * @ingroup FileAbstraction
2122 class LocalFileRestoreBatch
{
2128 var $cleanupBatch, $ids, $all, $unsuppress = false;
2132 * @param $unsuppress bool
2134 function __construct( File
$file, $unsuppress = false ) {
2135 $this->file
= $file;
2136 $this->cleanupBatch
= $this->ids
= array();
2137 $this->ids
= array();
2138 $this->unsuppress
= $unsuppress;
2144 function addId( $fa_id ) {
2145 $this->ids
[] = $fa_id;
2149 * Add a whole lot of files by ID
2151 function addIds( $ids ) {
2152 $this->ids
= array_merge( $this->ids
, $ids );
2156 * Add all revisions of the file
2163 * Run the transaction, except the cleanup batch.
2164 * The cleanup batch should be run in a separate transaction, because it locks different
2165 * rows and there's no need to keep the image row locked while it's acquiring those locks
2166 * The caller may have its own transaction open.
2167 * So we save the batch and let the caller call cleanup()
2168 * @return FileRepoStatus
2170 function execute() {
2173 if ( !$this->all
&& !$this->ids
) {
2175 return $this->file
->repo
->newGood();
2178 $exists = $this->file
->lock();
2179 $dbw = $this->file
->repo
->getMasterDB();
2180 $status = $this->file
->repo
->newGood();
2182 // Fetch all or selected archived revisions for the file,
2183 // sorted from the most recent to the oldest.
2184 $conditions = array( 'fa_name' => $this->file
->getName() );
2186 if ( !$this->all
) {
2187 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2190 $result = $dbw->select(
2192 ArchivedFile
::selectFields(),
2195 array( 'ORDER BY' => 'fa_timestamp DESC' )
2198 $idsPresent = array();
2199 $storeBatch = array();
2200 $insertBatch = array();
2201 $insertCurrent = false;
2202 $deleteIds = array();
2204 $archiveNames = array();
2206 foreach ( $result as $row ) {
2207 $idsPresent[] = $row->fa_id
;
2209 if ( $row->fa_name
!= $this->file
->getName() ) {
2210 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2211 $status->failCount++
;
2215 if ( $row->fa_storage_key
== '' ) {
2216 // Revision was missing pre-deletion
2217 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2218 $status->failCount++
;
2222 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
2223 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2225 if ( isset( $row->fa_sha1
) ) {
2226 $sha1 = $row->fa_sha1
;
2228 // old row, populate from key
2229 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2233 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2234 $sha1 = substr( $sha1, 1 );
2237 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2238 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2239 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2240 ||
is_null( $row->fa_metadata
) ) {
2241 // Refresh our metadata
2242 // Required for a new current revision; nice for older ones too. :)
2243 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2246 'minor_mime' => $row->fa_minor_mime
,
2247 'major_mime' => $row->fa_major_mime
,
2248 'media_type' => $row->fa_media_type
,
2249 'metadata' => $row->fa_metadata
2253 if ( $first && !$exists ) {
2254 // This revision will be published as the new current version
2255 $destRel = $this->file
->getRel();
2256 $insertCurrent = array(
2257 'img_name' => $row->fa_name
,
2258 'img_size' => $row->fa_size
,
2259 'img_width' => $row->fa_width
,
2260 'img_height' => $row->fa_height
,
2261 'img_metadata' => $props['metadata'],
2262 'img_bits' => $row->fa_bits
,
2263 'img_media_type' => $props['media_type'],
2264 'img_major_mime' => $props['major_mime'],
2265 'img_minor_mime' => $props['minor_mime'],
2266 'img_description' => $row->fa_description
,
2267 'img_user' => $row->fa_user
,
2268 'img_user_text' => $row->fa_user_text
,
2269 'img_timestamp' => $row->fa_timestamp
,
2273 // The live (current) version cannot be hidden!
2274 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2275 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2276 $this->cleanupBatch
[] = $row->fa_storage_key
;
2279 $archiveName = $row->fa_archive_name
;
2281 if ( $archiveName == '' ) {
2282 // This was originally a current version; we
2283 // have to devise a new archive name for it.
2284 // Format is <timestamp of archiving>!<name>
2285 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2288 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2290 } while ( isset( $archiveNames[$archiveName] ) );
2293 $archiveNames[$archiveName] = true;
2294 $destRel = $this->file
->getArchiveRel( $archiveName );
2295 $insertBatch[] = array(
2296 'oi_name' => $row->fa_name
,
2297 'oi_archive_name' => $archiveName,
2298 'oi_size' => $row->fa_size
,
2299 'oi_width' => $row->fa_width
,
2300 'oi_height' => $row->fa_height
,
2301 'oi_bits' => $row->fa_bits
,
2302 'oi_description' => $row->fa_description
,
2303 'oi_user' => $row->fa_user
,
2304 'oi_user_text' => $row->fa_user_text
,
2305 'oi_timestamp' => $row->fa_timestamp
,
2306 'oi_metadata' => $props['metadata'],
2307 'oi_media_type' => $props['media_type'],
2308 'oi_major_mime' => $props['major_mime'],
2309 'oi_minor_mime' => $props['minor_mime'],
2310 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2311 'oi_sha1' => $sha1 );
2314 $deleteIds[] = $row->fa_id
;
2316 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2317 // private files can stay where they are
2318 $status->successCount++
;
2320 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2321 $this->cleanupBatch
[] = $row->fa_storage_key
;
2329 // Add a warning to the status object for missing IDs
2330 $missingIds = array_diff( $this->ids
, $idsPresent );
2332 foreach ( $missingIds as $id ) {
2333 $status->error( 'undelete-missing-filearchive', $id );
2336 // Remove missing files from batch, so we don't get errors when undeleting them
2337 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2339 // Run the store batch
2340 // Use the OVERWRITE_SAME flag to smooth over a common error
2341 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2342 $status->merge( $storeStatus );
2344 if ( !$status->isGood() ) {
2345 // Even if some files could be copied, fail entirely as that is the
2346 // easiest thing to do without data loss
2347 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2348 $status->ok
= false;
2349 $this->file
->unlock();
2354 // Run the DB updates
2355 // Because we have locked the image row, key conflicts should be rare.
2356 // If they do occur, we can roll back the transaction at this time with
2357 // no data loss, but leaving unregistered files scattered throughout the
2359 // This is not ideal, which is why it's important to lock the image row.
2360 if ( $insertCurrent ) {
2361 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2364 if ( $insertBatch ) {
2365 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2369 $dbw->delete( 'filearchive',
2370 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2374 // If store batch is empty (all files are missing), deletion is to be considered successful
2375 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2377 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2379 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2381 $this->file
->purgeEverything();
2383 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2384 $this->file
->purgeDescription();
2385 $this->file
->purgeHistory();
2389 $this->file
->unlock();
2395 * Removes non-existent files from a store batch.
2396 * @param $triplets array
2399 function removeNonexistentFiles( $triplets ) {
2400 $files = $filteredTriplets = array();
2401 foreach ( $triplets as $file ) {
2402 $files[$file[0]] = $file[0];
2405 $result = $this->file
->repo
->fileExistsBatch( $files );
2407 foreach ( $triplets as $file ) {
2408 if ( $result[$file[0]] ) {
2409 $filteredTriplets[] = $file;
2413 return $filteredTriplets;
2417 * Removes non-existent files from a cleanup batch.
2418 * @param $batch array
2421 function removeNonexistentFromCleanup( $batch ) {
2422 $files = $newBatch = array();
2423 $repo = $this->file
->repo
;
2425 foreach ( $batch as $file ) {
2426 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2427 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2430 $result = $repo->fileExistsBatch( $files );
2432 foreach ( $batch as $file ) {
2433 if ( $result[$file] ) {
2434 $newBatch[] = $file;
2442 * Delete unused files in the deleted zone.
2443 * This should be called from outside the transaction in which execute() was called.
2444 * @return FileRepoStatus
2446 function cleanup() {
2447 if ( !$this->cleanupBatch
) {
2448 return $this->file
->repo
->newGood();
2451 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2453 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2459 * Cleanup a failed batch. The batch was only partially successful, so
2460 * rollback by removing all items that were succesfully copied.
2462 * @param Status $storeStatus
2463 * @param array $storeBatch
2465 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2466 $cleanupBatch = array();
2468 foreach ( $storeStatus->success
as $i => $success ) {
2469 // Check if this item of the batch was successfully copied
2471 // Item was successfully copied and needs to be removed again
2472 // Extract ($dstZone, $dstRel) from the batch
2473 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2476 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2480 # ------------------------------------------------------------------------------
2483 * Helper class for file movement
2484 * @ingroup FileAbstraction
2486 class LocalFileMoveBatch
{
2498 var $cur, $olds, $oldCount, $archive;
2507 * @param Title $target
2509 function __construct( File
$file, Title
$target ) {
2510 $this->file
= $file;
2511 $this->target
= $target;
2512 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2513 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2514 $this->oldName
= $this->file
->getName();
2515 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2516 $this->oldRel
= $this->oldHash
. $this->oldName
;
2517 $this->newRel
= $this->newHash
. $this->newName
;
2518 $this->db
= $file->getRepo()->getMasterDb();
2522 * Add the current image to the batch
2524 function addCurrent() {
2525 $this->cur
= array( $this->oldRel
, $this->newRel
);
2529 * Add the old versions of the image to the batch
2530 * @return Array List of archive names from old versions
2532 function addOlds() {
2533 $archiveBase = 'archive';
2534 $this->olds
= array();
2535 $this->oldCount
= 0;
2536 $archiveNames = array();
2538 $result = $this->db
->select( 'oldimage',
2539 array( 'oi_archive_name', 'oi_deleted' ),
2540 array( 'oi_name' => $this->oldName
),
2544 foreach ( $result as $row ) {
2545 $archiveNames[] = $row->oi_archive_name
;
2546 $oldName = $row->oi_archive_name
;
2547 $bits = explode( '!', $oldName, 2 );
2549 if ( count( $bits ) != 2 ) {
2550 wfDebug( "Old file name missing !: '$oldName' \n" );
2554 list( $timestamp, $filename ) = $bits;
2556 if ( $this->oldName
!= $filename ) {
2557 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2563 // Do we want to add those to oldCount?
2564 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2568 $this->olds
[] = array(
2569 "{$archiveBase}/{$this->oldHash}{$oldName}",
2570 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2574 return $archiveNames;
2579 * @return FileRepoStatus
2581 function execute() {
2582 $repo = $this->file
->repo
;
2583 $status = $repo->newGood();
2585 $triplets = $this->getMoveTriplets();
2586 $triplets = $this->removeNonexistentFiles( $triplets );
2588 $this->file
->lock(); // begin
2589 // Rename the file versions metadata in the DB.
2590 // This implicitly locks the destination file, which avoids race conditions.
2591 // If we moved the files from A -> C before DB updates, another process could
2592 // move files from B -> C at this point, causing storeBatch() to fail and thus
2593 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2594 $statusDb = $this->doDBUpdates();
2595 if ( !$statusDb->isGood() ) {
2596 $this->file
->unlockAndRollback();
2597 $statusDb->ok
= false;
2600 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2602 // Copy the files into their new location.
2603 // If a prior process fataled copying or cleaning up files we tolerate any
2604 // of the existing files if they are identical to the ones being stored.
2605 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2606 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2607 if ( !$statusMove->isGood() ) {
2608 // Delete any files copied over (while the destination is still locked)
2609 $this->cleanupTarget( $triplets );
2610 $this->file
->unlockAndRollback(); // unlocks the destination
2611 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2612 $statusMove->ok
= false;
2615 $this->file
->unlock(); // done
2617 // Everything went ok, remove the source files
2618 $this->cleanupSource( $triplets );
2620 $status->merge( $statusDb );
2621 $status->merge( $statusMove );
2627 * Do the database updates and return a new FileRepoStatus indicating how
2628 * many rows where updated.
2630 * @return FileRepoStatus
2632 function doDBUpdates() {
2633 $repo = $this->file
->repo
;
2634 $status = $repo->newGood();
2637 // Update current image
2640 array( 'img_name' => $this->newName
),
2641 array( 'img_name' => $this->oldName
),
2645 if ( $dbw->affectedRows() ) {
2646 $status->successCount++
;
2648 $status->failCount++
;
2649 $status->fatal( 'imageinvalidfilename' );
2653 // Update old images
2657 'oi_name' => $this->newName
,
2658 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2659 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2661 array( 'oi_name' => $this->oldName
),
2665 $affected = $dbw->affectedRows();
2666 $total = $this->oldCount
;
2667 $status->successCount +
= $affected;
2668 // Bug 34934: $total is based on files that actually exist.
2669 // There may be more DB rows than such files, in which case $affected
2670 // can be greater than $total. We use max() to avoid negatives here.
2671 $status->failCount +
= max( 0, $total - $affected );
2672 if ( $status->failCount
) {
2673 $status->error( 'imageinvalidfilename' );
2680 * Generate triplets for FileRepo::storeBatch().
2683 function getMoveTriplets() {
2684 $moves = array_merge( array( $this->cur
), $this->olds
);
2685 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2687 foreach ( $moves as $move ) {
2688 // $move: (oldRelativePath, newRelativePath)
2689 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2690 $triplets[] = array( $srcUrl, 'public', $move[1] );
2691 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2698 * Removes non-existent files from move batch.
2699 * @param $triplets array
2702 function removeNonexistentFiles( $triplets ) {
2705 foreach ( $triplets as $file ) {
2706 $files[$file[0]] = $file[0];
2709 $result = $this->file
->repo
->fileExistsBatch( $files );
2710 $filteredTriplets = array();
2712 foreach ( $triplets as $file ) {
2713 if ( $result[$file[0]] ) {
2714 $filteredTriplets[] = $file;
2716 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2720 return $filteredTriplets;
2724 * Cleanup a partially moved array of triplets by deleting the target
2725 * files. Called if something went wrong half way.
2727 function cleanupTarget( $triplets ) {
2728 // Create dest pairs from the triplets
2730 foreach ( $triplets as $triplet ) {
2731 // $triplet: (old source virtual URL, dst zone, dest rel)
2732 $pairs[] = array( $triplet[1], $triplet[2] );
2735 $this->file
->repo
->cleanupBatch( $pairs );
2739 * Cleanup a fully moved array of triplets by deleting the source files.
2740 * Called at the end of the move process if everything else went ok.
2742 function cleanupSource( $triplets ) {
2743 // Create source file names from the triplets
2745 foreach ( $triplets as $triplet ) {
2746 $files[] = $triplet[0];
2749 $this->file
->repo
->cleanupBatch( $files );