6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 8 );
11 * Class to represent a local file in the wiki's own database
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate image thumbnails or for uploading.
16 * Note that only the repo object knows what its file class is called. You should
17 * never name a file class explictly outside of the repo class. Instead use the
18 * repo's factory functions to generate file objects, for example:
20 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
25 * @addtogroup FileRepo
27 class LocalFile
extends File
32 var $fileExists, # does the file file exist on disk? (loadFromXxx)
33 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
34 $historyRes, # result of the query for the file's history (nextHistoryLine)
37 $bits, # --- returned by getimagesize (loadFromXxx)
39 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
40 $mime, # MIME type, determined by MimeMagic::guessMimeType
41 $major_mime, # Major mime type
42 $minor_mime, # Minor mime type
43 $size, # Size in bytes (loadFromXxx)
44 $metadata, # Handler-specific metadata
45 $timestamp, # Upload timestamp
46 $sha1, # SHA-1 base 36 content hash
47 $user, $user_text, # User, who uploaded the file
48 $description, # Description of current revision of the file
49 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
50 $upgraded, # Whether the row was upgraded on load
51 $locked, # True if the image row is locked
52 $deleted; # Bitfield akin to rev_deleted
57 * Create a LocalFile from a title
58 * Do not call this except from inside a repo class.
60 * Note: $unused param is only here to avoid an E_STRICT
62 static function newFromTitle( $title, $repo, $unused = null ) {
63 return new self( $title, $repo );
67 * Create a LocalFile from a title
68 * Do not call this except from inside a repo class.
70 static function newFromRow( $row, $repo ) {
71 $title = Title
::makeTitle( NS_IMAGE
, $row->img_name
);
72 $file = new self( $title, $repo );
73 $file->loadFromRow( $row );
78 * Fields in the image table
80 static function selectFields() {
101 * Do not call this except from inside a repo class.
103 function __construct( $title, $repo ) {
104 if( !is_object( $title ) ) {
105 throw new MWException( __CLASS__
.' constructor given bogus title.' );
107 parent
::__construct( $title, $repo );
108 $this->metadata
= '';
109 $this->historyLine
= 0;
110 $this->historyRes
= null;
111 $this->dataLoaded
= false;
115 * Get the memcached key
117 function getCacheKey() {
118 $hashedName = md5($this->getName());
119 return wfMemcKey( 'file', $hashedName );
123 * Try to load file metadata from memcached. Returns true on success.
125 function loadFromCache() {
127 wfProfileIn( __METHOD__
);
128 $this->dataLoaded
= false;
129 $key = $this->getCacheKey();
133 $cachedValues = $wgMemc->get( $key );
135 // Check if the key existed and belongs to this version of MediaWiki
136 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
137 wfDebug( "Pulling file metadata from cache key $key\n" );
138 $this->fileExists
= $cachedValues['fileExists'];
139 if ( $this->fileExists
) {
140 $this->setProps( $cachedValues );
142 $this->dataLoaded
= true;
144 if ( $this->dataLoaded
) {
145 wfIncrStats( 'image_cache_hit' );
147 wfIncrStats( 'image_cache_miss' );
150 wfProfileOut( __METHOD__
);
151 return $this->dataLoaded
;
155 * Save the file metadata to memcached
157 function saveToCache() {
160 $key = $this->getCacheKey();
164 $fields = $this->getCacheFields( '' );
165 $cache = array( 'version' => MW_FILE_VERSION
);
166 $cache['fileExists'] = $this->fileExists
;
167 if ( $this->fileExists
) {
168 foreach ( $fields as $field ) {
169 $cache[$field] = $this->$field;
173 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
177 * Load metadata from the file itself
179 function loadFromFile() {
180 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
183 function getCacheFields( $prefix = 'img_' ) {
184 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
185 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
186 static $results = array();
187 if ( $prefix == '' ) {
190 if ( !isset( $results[$prefix] ) ) {
191 $prefixedFields = array();
192 foreach ( $fields as $field ) {
193 $prefixedFields[] = $prefix . $field;
195 $results[$prefix] = $prefixedFields;
197 return $results[$prefix];
201 * Load file metadata from the DB
203 function loadFromDB() {
204 # Polymorphic function name to distinguish foreign and local fetches
205 $fname = get_class( $this ) . '::' . __FUNCTION__
;
206 wfProfileIn( $fname );
208 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
209 $this->dataLoaded
= true;
211 $dbr = $this->repo
->getMasterDB();
213 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
214 array( 'img_name' => $this->getName() ), $fname );
216 $this->loadFromRow( $row );
218 $this->fileExists
= false;
221 wfProfileOut( $fname );
225 * Decode a row from the database (either object or array) to an array
226 * with timestamps and MIME types decoded, and the field prefix removed.
228 function decodeRow( $row, $prefix = 'img_' ) {
229 $array = (array)$row;
230 $prefixLength = strlen( $prefix );
231 // Sanity check prefix once
232 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
233 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
236 foreach ( $array as $name => $value ) {
237 $decoded[substr( $name, $prefixLength )] = $value;
239 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
240 if ( empty( $decoded['major_mime'] ) ) {
241 $decoded['mime'] = "unknown/unknown";
243 if (!$decoded['minor_mime']) {
244 $decoded['minor_mime'] = "unknown";
246 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
248 # Trim zero padding from char/binary field
249 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
254 * Load file metadata from a DB result row
256 function loadFromRow( $row, $prefix = 'img_' ) {
257 $this->dataLoaded
= true;
258 $array = $this->decodeRow( $row, $prefix );
259 foreach ( $array as $name => $value ) {
260 $this->$name = $value;
262 $this->fileExists
= true;
263 $this->maybeUpgradeRow();
267 * Load file metadata from cache or DB, unless already loaded
270 if ( !$this->dataLoaded
) {
271 if ( !$this->loadFromCache() ) {
273 $this->saveToCache();
275 $this->dataLoaded
= true;
280 * Upgrade a row if it needs it
282 function maybeUpgradeRow() {
283 if ( wfReadOnly() ) {
286 if ( is_null($this->media_type
) ||
287 $this->mime
== 'image/svg'
290 $this->upgraded
= true;
292 $handler = $this->getHandler();
293 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
295 $this->upgraded
= true;
300 function getUpgraded() {
301 return $this->upgraded
;
305 * Fix assorted version-related problems with the image row by reloading it from the file
307 function upgradeRow() {
308 wfProfileIn( __METHOD__
);
310 $this->loadFromFile();
312 # Don't destroy file info of missing files
313 if ( !$this->fileExists
) {
314 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
317 $dbw = $this->repo
->getMasterDB();
318 list( $major, $minor ) = self
::splitMime( $this->mime
);
320 if ( wfReadOnly() ) {
323 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
325 $dbw->update( 'image',
327 'img_width' => $this->width
,
328 'img_height' => $this->height
,
329 'img_bits' => $this->bits
,
330 'img_media_type' => $this->media_type
,
331 'img_major_mime' => $major,
332 'img_minor_mime' => $minor,
333 'img_metadata' => $this->metadata
,
334 'img_sha1' => $this->sha1
,
335 ), array( 'img_name' => $this->getName() ),
338 $this->saveToCache();
339 wfProfileOut( __METHOD__
);
343 * Set properties in this object to be equal to those given in the
344 * associative array $info. Only cacheable fields can be set.
346 * If 'mime' is given, it will be split into major_mime/minor_mime.
347 * If major_mime/minor_mime are given, $this->mime will also be set.
349 function setProps( $info ) {
350 $this->dataLoaded
= true;
351 $fields = $this->getCacheFields( '' );
352 $fields[] = 'fileExists';
353 foreach ( $fields as $field ) {
354 if ( isset( $info[$field] ) ) {
355 $this->$field = $info[$field];
358 // Fix up mime fields
359 if ( isset( $info['major_mime'] ) ) {
360 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
361 } elseif ( isset( $info['mime'] ) ) {
362 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
366 /** splitMime inherited */
367 /** getName inherited */
368 /** getTitle inherited */
369 /** getURL inherited */
370 /** getViewURL inherited */
371 /** getPath inherited */
372 /** isVisible inhereted */
375 * Return the width of the image
377 * Returns false on error
380 function getWidth( $page = 1 ) {
382 if ( $this->isMultipage() ) {
383 $dim = $this->getHandler()->getPageDimensions( $this, $page );
385 return $dim['width'];
395 * Return the height of the image
397 * Returns false on error
400 function getHeight( $page = 1 ) {
402 if ( $this->isMultipage() ) {
403 $dim = $this->getHandler()->getPageDimensions( $this, $page );
405 return $dim['height'];
410 return $this->height
;
415 * Returns ID or name of user who uploaded the file
417 * @param $type string 'text' or 'id'
419 function getUser($type='text') {
421 if( $type == 'text' ) {
422 return $this->user_text
;
423 } elseif( $type == 'id' ) {
429 * Get handler-specific metadata
431 function getMetadata() {
433 return $this->metadata
;
437 * Return the size of the image file, in bytes
446 * Returns the mime type of the file.
448 function getMimeType() {
454 * Return the type of the media in the file.
455 * Use the value returned by this function with the MEDIATYPE_xxx constants.
457 function getMediaType() {
459 return $this->media_type
;
462 /** canRender inherited */
463 /** mustRender inherited */
464 /** allowInlineDisplay inherited */
465 /** isSafeFile inherited */
466 /** isTrustedFile inherited */
469 * Returns true if the file file exists on disk.
470 * @return boolean Whether file file exist on disk.
475 return $this->fileExists
;
478 /** getTransformScript inherited */
479 /** getUnscaledThumb inherited */
480 /** thumbName inherited */
481 /** createThumb inherited */
482 /** getThumbnail inherited */
483 /** transform inherited */
486 * Fix thumbnail files from 1.4 or before, with extreme prejudice
488 function migrateThumbFile( $thumbName ) {
489 $thumbDir = $this->getThumbPath();
490 $thumbPath = "$thumbDir/$thumbName";
491 if ( is_dir( $thumbPath ) ) {
492 // Directory where file should be
493 // This happened occasionally due to broken migration code in 1.5
494 // Rename to broken-*
495 for ( $i = 0; $i < 100 ; $i++
) {
496 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
497 if ( !file_exists( $broken ) ) {
498 rename( $thumbPath, $broken );
502 // Doesn't exist anymore
505 if ( is_file( $thumbDir ) ) {
506 // File where directory should be
508 // Doesn't exist anymore
513 /** getHandler inherited */
514 /** iconThumb inherited */
515 /** getLastError inherited */
518 * Get all thumbnail names previously generated for this file
520 function getThumbnails() {
521 if ( $this->isHashed() ) {
524 $dir = $this->getThumbPath();
526 if ( is_dir( $dir ) ) {
527 $handle = opendir( $dir );
530 while ( false !== ( $file = readdir($handle) ) ) {
531 if ( $file{0} != '.' ) {
546 * Refresh metadata in memcached, but don't touch thumbnails or squid
548 function purgeMetadataCache() {
550 $this->saveToCache();
551 $this->purgeHistory();
555 * Purge the shared history (OldLocalFile) cache
557 function purgeHistory() {
559 $hashedName = md5($this->getName());
560 $oldKey = wfMemcKey( 'oldfile', $hashedName );
561 $wgMemc->delete( $oldKey );
565 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
567 function purgeCache() {
568 // Refresh metadata cache
569 $this->purgeMetadataCache();
572 $this->purgeThumbnails();
574 // Purge squid cache for this file
575 SquidUpdate
::purge( array( $this->getURL() ) );
579 * Delete cached transformed files
581 function purgeThumbnails() {
584 $files = $this->getThumbnails();
585 $dir = $this->getThumbPath();
587 foreach ( $files as $file ) {
588 # Check that the base file name is part of the thumb name
589 # This is a basic sanity check to avoid erasing unrelated directories
590 if ( strpos( $file, $this->getName() ) !== false ) {
591 $url = $this->getThumbUrl( $file );
593 @unlink
( "$dir/$file" );
599 SquidUpdate
::purge( $urls );
603 /** purgeDescription inherited */
604 /** purgeEverything inherited */
606 function getHistory($limit = null, $start = null, $end = null) {
607 $dbr = $this->repo
->getSlaveDB();
608 $conds = $opts = array();
609 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
610 if( $start !== null ) {
611 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
613 if( $end !== null ) {
614 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
617 $opts['LIMIT'] = $limit;
619 $opts['ORDER BY'] = 'oi_timestamp DESC';
620 $res = $dbr->select('oldimage', '*', $conds, __METHOD__
, $opts);
622 while( $row = $dbr->fetchObject($res) ) {
623 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
629 * Return the history of this file, line by line.
630 * starts with current version, then old versions.
631 * uses $this->historyLine to check which line to return:
632 * 0 return line for current version
633 * 1 query for old versions, return first one
634 * 2, ... return next old version from above query
638 function nextHistoryLine() {
639 # Polymorphic function name to distinguish foreign and local fetches
640 $fname = get_class( $this ) . '::' . __FUNCTION__
;
642 $dbr = $this->repo
->getSlaveDB();
644 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
645 $this->historyRes
= $dbr->select( 'image',
648 "'' AS oi_archive_name",
652 array( 'img_name' => $this->title
->getDBkey() ),
655 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
656 $dbr->freeResult($this->historyRes
);
657 $this->historyRes
= null;
660 } else if ( $this->historyLine
== 1 ) {
661 $dbr->freeResult($this->historyRes
);
662 $this->historyRes
= $dbr->select( 'oldimage', '*',
663 array( 'oi_name' => $this->title
->getDBkey() ),
665 array( 'ORDER BY' => 'oi_timestamp DESC' )
668 $this->historyLine ++
;
670 return $dbr->fetchObject( $this->historyRes
);
674 * Reset the history pointer to the first element of the history
677 function resetHistory() {
678 $this->historyLine
= 0;
679 if (!is_null($this->historyRes
)) {
680 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
681 $this->historyRes
= null;
685 /** getFullPath inherited */
686 /** getHashPath inherited */
687 /** getRel inherited */
688 /** getUrlRel inherited */
689 /** getArchiveRel inherited */
690 /** getThumbRel inherited */
691 /** getArchivePath inherited */
692 /** getThumbPath inherited */
693 /** getArchiveUrl inherited */
694 /** getThumbUrl inherited */
695 /** getArchiveVirtualUrl inherited */
696 /** getThumbVirtualUrl inherited */
697 /** isHashed inherited */
700 * Upload a file and record it in the DB
701 * @param string $srcPath Source path or virtual URL
702 * @param string $comment Upload description
703 * @param string $pageText Text to use for the new description page, if a new description page is created
704 * @param integer $flags Flags for publish()
705 * @param array $props File properties, if known. This can be used to reduce the
706 * upload time when uploading virtual URLs for which the file info
708 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
710 * @return FileRepoStatus object. On success, the value member contains the
711 * archive name, or an empty string if it was a new file.
713 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
715 $status = $this->publish( $srcPath, $flags );
717 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
718 $status->fatal( 'filenotfound', $srcPath );
726 * Record a file upload in the upload log and the image table
727 * @deprecated use upload()
729 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
730 $watch = false, $timestamp = false )
732 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
733 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
738 $wgUser->addWatch( $this->getTitle() );
745 * Record a file upload in the upload log and the image table
747 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
751 $dbw = $this->repo
->getMasterDB();
754 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
756 $props['description'] = $comment;
757 $props['user'] = $wgUser->getID();
758 $props['user_text'] = $wgUser->getName();
759 $props['timestamp'] = wfTimestamp( TS_MW
);
760 $this->setProps( $props );
762 // Delete thumbnails and refresh the metadata cache
763 $this->purgeThumbnails();
764 $this->saveToCache();
765 SquidUpdate
::purge( array( $this->getURL() ) );
767 // Fail now if the file isn't there
768 if ( !$this->fileExists
) {
769 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
774 if ( $timestamp === false ) {
775 $timestamp = $dbw->timestamp();
778 # Test to see if the row exists using INSERT IGNORE
779 # This avoids race conditions by locking the row until the commit, and also
780 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
781 $dbw->insert( 'image',
783 'img_name' => $this->getName(),
784 'img_size'=> $this->size
,
785 'img_width' => intval( $this->width
),
786 'img_height' => intval( $this->height
),
787 'img_bits' => $this->bits
,
788 'img_media_type' => $this->media_type
,
789 'img_major_mime' => $this->major_mime
,
790 'img_minor_mime' => $this->minor_mime
,
791 'img_timestamp' => $timestamp,
792 'img_description' => $comment,
793 'img_user' => $wgUser->getID(),
794 'img_user_text' => $wgUser->getName(),
795 'img_metadata' => $this->metadata
,
796 'img_sha1' => $this->sha1
802 if( $dbw->affectedRows() == 0 ) {
805 # Collision, this is an update of a file
806 # Insert previous contents into oldimage
807 $dbw->insertSelect( 'oldimage', 'image',
809 'oi_name' => 'img_name',
810 'oi_archive_name' => $dbw->addQuotes( $oldver ),
811 'oi_size' => 'img_size',
812 'oi_width' => 'img_width',
813 'oi_height' => 'img_height',
814 'oi_bits' => 'img_bits',
815 'oi_timestamp' => 'img_timestamp',
816 'oi_description' => 'img_description',
817 'oi_user' => 'img_user',
818 'oi_user_text' => 'img_user_text',
819 'oi_metadata' => 'img_metadata',
820 'oi_media_type' => 'img_media_type',
821 'oi_major_mime' => 'img_major_mime',
822 'oi_minor_mime' => 'img_minor_mime',
823 'oi_sha1' => 'img_sha1'
824 ), array( 'img_name' => $this->getName() ), __METHOD__
827 # Update the current image row
828 $dbw->update( 'image',
830 'img_size' => $this->size
,
831 'img_width' => intval( $this->width
),
832 'img_height' => intval( $this->height
),
833 'img_bits' => $this->bits
,
834 'img_media_type' => $this->media_type
,
835 'img_major_mime' => $this->major_mime
,
836 'img_minor_mime' => $this->minor_mime
,
837 'img_timestamp' => $timestamp,
838 'img_description' => $comment,
839 'img_user' => $wgUser->getID(),
840 'img_user_text' => $wgUser->getName(),
841 'img_metadata' => $this->metadata
,
842 'img_sha1' => $this->sha1
843 ), array( /* WHERE */
844 'img_name' => $this->getName()
849 # Update the image count
850 $site_stats = $dbw->tableName( 'site_stats' );
851 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
854 $descTitle = $this->getTitle();
855 $article = new Article( $descTitle );
858 $log = new LogPage( 'upload' );
859 $action = $reupload ?
'overwrite' : 'upload';
860 $log->addEntry( $action, $descTitle, $comment );
862 if( $descTitle->exists() ) {
863 # Create a null revision
864 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
865 $nullRevision->insertOn( $dbw );
866 $article->updateRevisionOn( $dbw, $nullRevision );
868 # Invalidate the cache for the description page
869 $descTitle->invalidateCache();
870 $descTitle->purgeSquid();
872 // New file; create the description page.
873 // There's already a log entry, so don't make a second RC entry
874 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
877 # Hooks, hooks, the magic of hooks...
878 wfRunHooks( 'FileUpload', array( $this ) );
880 # Commit the transaction now, in case something goes wrong later
881 # The most important thing is that files don't get lost, especially archives
882 $dbw->immediateCommit();
884 # Invalidate cache for all pages using this file
885 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
887 # Invalidate cache for all pages that redirects on this page
888 $redirs = $this->getTitle()->getRedirectsHere();
889 foreach( $redirs as $redir ) {
890 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
898 * Move or copy a file to its public location. If a file exists at the
899 * destination, move it to an archive. Returns the archive name on success
900 * or an empty string if it was a new file, and a wikitext-formatted
901 * WikiError object on failure.
903 * The archive name should be passed through to recordUpload for database
906 * @param string $sourcePath Local filesystem path to the source image
907 * @param integer $flags A bitwise combination of:
908 * File::DELETE_SOURCE Delete the source file, i.e. move
910 * @return FileRepoStatus object. On success, the value member contains the
911 * archive name, or an empty string if it was a new file.
913 function publish( $srcPath, $flags = 0 ) {
915 $dstRel = $this->getRel();
916 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
917 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
918 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
919 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
920 if ( $status->value
== 'new' ) {
923 $status->value
= $archiveName;
929 /** getLinksTo inherited */
930 /** getExifData inherited */
931 /** isLocal inherited */
932 /** wasDeleted inherited */
935 * Move file to the new title
937 * Move current, old version and all thumbnails
938 * to the new filename. Old file is deleted.
940 * Cache purging is done; checks for validity
941 * and logging are caller's responsibility
943 * @param $target Title New file name
944 * @return FileRepoStatus object.
946 function move( $target ) {
948 $dbw = $this->repo
->getMasterDB();
949 $batch = new LocalFileMoveBatch( $this, $target, $dbw );
950 $batch->addCurrent();
952 if( !$this->repo
->canTransformVia404() ) {
956 $status = $batch->execute();
957 $this->purgeEverything();
960 if ( $status->isOk() ) {
961 // Now switch the object
962 $this->title
= $target;
963 // Force regeneration of the name and hashpath
964 unset( $this->name
);
965 unset( $this->hashPath
);
966 // Purge the new image
967 $this->purgeEverything();
974 * Delete all versions of the file.
976 * Moves the files into an archive directory (or deletes them)
977 * and removes the database rows.
979 * Cache purging is done; logging is caller's responsibility.
983 * @return FileRepoStatus object.
985 function delete( $reason, $suppress = false ) {
987 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
988 $batch->addCurrent();
990 # Get old version relative paths
991 $dbw = $this->repo
->getMasterDB();
992 $result = $dbw->select( 'oldimage',
993 array( 'oi_archive_name' ),
994 array( 'oi_name' => $this->getName() ) );
995 while ( $row = $dbw->fetchObject( $result ) ) {
996 $batch->addOld( $row->oi_archive_name
);
998 $status = $batch->execute();
1000 if ( $status->ok
) {
1001 // Update site_stats
1002 $site_stats = $dbw->tableName( 'site_stats' );
1003 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1004 $this->purgeEverything();
1012 * Delete an old version of the file.
1014 * Moves the file into an archive directory (or deletes it)
1015 * and removes the database row.
1017 * Cache purging is done; logging is caller's responsibility.
1021 * @throws MWException or FSException on database or filestore failure
1022 * @return FileRepoStatus object.
1024 function deleteOld( $archiveName, $reason, $suppress=false ) {
1026 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1027 $batch->addOld( $archiveName );
1028 $status = $batch->execute();
1030 if ( $status->ok
) {
1031 $this->purgeDescription();
1032 $this->purgeHistory();
1038 * Restore all or specified deleted revisions to the given file.
1039 * Permissions and logging are left to the caller.
1041 * May throw database exceptions on error.
1043 * @param $versions set of record ids of deleted items to restore,
1044 * or empty to restore all revisions.
1046 * @return FileRepoStatus
1048 function restore( $versions = array(), $unsuppress = false ) {
1049 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1053 $batch->addIds( $versions );
1055 $status = $batch->execute();
1056 if ( !$status->ok
) {
1060 $cleanupStatus = $batch->cleanup();
1061 $cleanupStatus->successCount
= 0;
1062 $cleanupStatus->failCount
= 0;
1063 $status->merge( $cleanupStatus );
1067 /** isMultipage inherited */
1068 /** pageCount inherited */
1069 /** scaleHeight inherited */
1070 /** getImageSize inherited */
1073 * Get the URL of the file description page.
1075 function getDescriptionUrl() {
1076 return $this->title
->getLocalUrl();
1080 * Get the HTML text of the description page
1081 * This is not used by ImagePage for local files, since (among other things)
1082 * it skips the parser cache.
1084 function getDescriptionText() {
1086 $revision = Revision
::newFromTitle( $this->title
);
1087 if ( !$revision ) return false;
1088 $text = $revision->getText();
1089 if ( !$text ) return false;
1090 $html = $wgParser->parse( $text, new ParserOptions
);
1094 function getDescription() {
1096 return $this->description
;
1099 function getTimestamp() {
1101 return $this->timestamp
;
1104 function getSha1() {
1106 // Initialise now if necessary
1107 if ( $this->sha1
== '' && $this->fileExists
) {
1108 $this->sha1
= File
::sha1Base36( $this->getPath() );
1109 if ( strval( $this->sha1
) != '' ) {
1110 $dbw = $this->repo
->getMasterDB();
1111 $dbw->update( 'image',
1112 array( 'img_sha1' => $this->sha1
),
1113 array( 'img_name' => $this->getName() ),
1115 $this->saveToCache();
1123 * Start a transaction and lock the image for update
1124 * Increments a reference counter if the lock is already held
1125 * @return boolean True if the image exists, false otherwise
1128 $dbw = $this->repo
->getMasterDB();
1129 if ( !$this->locked
) {
1133 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1137 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1138 * the transaction and thereby releases the image lock.
1141 if ( $this->locked
) {
1143 if ( !$this->locked
) {
1144 $dbw = $this->repo
->getMasterDB();
1151 * Roll back the DB transaction and mark the image unlocked
1153 function unlockAndRollback() {
1154 $this->locked
= false;
1155 $dbw = $this->repo
->getMasterDB();
1158 } // LocalFile class
1160 #------------------------------------------------------------------------------
1163 * Helper class for file deletion
1165 class LocalFileDeleteBatch
{
1166 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1169 function __construct( File
$file, $reason = '', $suppress = false ) {
1170 $this->file
= $file;
1171 $this->reason
= $reason;
1172 $this->suppress
= $suppress;
1173 $this->status
= $file->repo
->newGood();
1176 function addCurrent() {
1177 $this->srcRels
['.'] = $this->file
->getRel();
1180 function addOld( $oldName ) {
1181 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1182 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1185 function getOldRels() {
1186 if ( !isset( $this->srcRels
['.'] ) ) {
1187 $oldRels =& $this->srcRels
;
1188 $deleteCurrent = false;
1190 $oldRels = $this->srcRels
;
1191 unset( $oldRels['.'] );
1192 $deleteCurrent = true;
1194 return array( $oldRels, $deleteCurrent );
1197 /*protected*/ function getHashes() {
1199 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1200 if ( $deleteCurrent ) {
1201 $hashes['.'] = $this->file
->getSha1();
1203 if ( count( $oldRels ) ) {
1204 $dbw = $this->file
->repo
->getMasterDB();
1205 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1206 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1208 while ( $row = $dbw->fetchObject( $res ) ) {
1209 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1210 // Get the hash from the file
1211 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1212 $props = $this->file
->repo
->getFileProps( $oldUrl );
1213 if ( $props['fileExists'] ) {
1214 // Upgrade the oldimage row
1215 $dbw->update( 'oldimage',
1216 array( 'oi_sha1' => $props['sha1'] ),
1217 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1219 $hashes[$row->oi_archive_name
] = $props['sha1'];
1221 $hashes[$row->oi_archive_name
] = false;
1224 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1228 $missing = array_diff_key( $this->srcRels
, $hashes );
1229 foreach ( $missing as $name => $rel ) {
1230 $this->status
->error( 'filedelete-old-unregistered', $name );
1232 foreach ( $hashes as $name => $hash ) {
1234 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1235 unset( $hashes[$name] );
1242 function doDBInserts() {
1244 $dbw = $this->file
->repo
->getMasterDB();
1245 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1246 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1247 $encReason = $dbw->addQuotes( $this->reason
);
1248 $encGroup = $dbw->addQuotes( 'deleted' );
1249 $ext = $this->file
->getExtension();
1250 $dotExt = $ext === '' ?
'' : ".$ext";
1251 $encExt = $dbw->addQuotes( $dotExt );
1252 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1254 // Bitfields to further suppress the content
1255 if ( $this->suppress
) {
1257 // This should be 15...
1258 $bitfield |
= Revision
::DELETED_TEXT
;
1259 $bitfield |
= Revision
::DELETED_COMMENT
;
1260 $bitfield |
= Revision
::DELETED_USER
;
1261 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1263 $bitfield = 'oi_deleted';
1266 if ( $deleteCurrent ) {
1267 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1268 $where = array( 'img_name' => $this->file
->getName() );
1269 $dbw->insertSelect( 'filearchive', 'image',
1271 'fa_storage_group' => $encGroup,
1272 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1273 'fa_deleted_user' => $encUserId,
1274 'fa_deleted_timestamp' => $encTimestamp,
1275 'fa_deleted_reason' => $encReason,
1276 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1278 'fa_name' => 'img_name',
1279 'fa_archive_name' => 'NULL',
1280 'fa_size' => 'img_size',
1281 'fa_width' => 'img_width',
1282 'fa_height' => 'img_height',
1283 'fa_metadata' => 'img_metadata',
1284 'fa_bits' => 'img_bits',
1285 'fa_media_type' => 'img_media_type',
1286 'fa_major_mime' => 'img_major_mime',
1287 'fa_minor_mime' => 'img_minor_mime',
1288 'fa_description' => 'img_description',
1289 'fa_user' => 'img_user',
1290 'fa_user_text' => 'img_user_text',
1291 'fa_timestamp' => 'img_timestamp'
1292 ), $where, __METHOD__
);
1295 if ( count( $oldRels ) ) {
1296 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1298 'oi_name' => $this->file
->getName(),
1299 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1300 $dbw->insertSelect( 'filearchive', 'oldimage',
1302 'fa_storage_group' => $encGroup,
1303 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1304 'fa_deleted_user' => $encUserId,
1305 'fa_deleted_timestamp' => $encTimestamp,
1306 'fa_deleted_reason' => $encReason,
1307 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1309 'fa_name' => 'oi_name',
1310 'fa_archive_name' => 'oi_archive_name',
1311 'fa_size' => 'oi_size',
1312 'fa_width' => 'oi_width',
1313 'fa_height' => 'oi_height',
1314 'fa_metadata' => 'oi_metadata',
1315 'fa_bits' => 'oi_bits',
1316 'fa_media_type' => 'oi_media_type',
1317 'fa_major_mime' => 'oi_major_mime',
1318 'fa_minor_mime' => 'oi_minor_mime',
1319 'fa_description' => 'oi_description',
1320 'fa_user' => 'oi_user',
1321 'fa_user_text' => 'oi_user_text',
1322 'fa_timestamp' => 'oi_timestamp',
1323 'fa_deleted' => $bitfield
1324 ), $where, __METHOD__
);
1328 function doDBDeletes() {
1329 $dbw = $this->file
->repo
->getMasterDB();
1330 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1331 if ( count( $oldRels ) ) {
1332 $dbw->delete( 'oldimage',
1334 'oi_name' => $this->file
->getName(),
1335 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1338 if ( $deleteCurrent ) {
1339 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1344 * Run the transaction
1346 function execute() {
1347 global $wgUser, $wgUseSquid;
1348 wfProfileIn( __METHOD__
);
1350 $this->file
->lock();
1351 // Leave private files alone
1352 $privateFiles = array();
1353 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1354 $dbw = $this->file
->repo
->getMasterDB();
1355 if( !empty( $oldRels ) ) {
1356 $res = $dbw->select( 'oldimage',
1357 array( 'oi_archive_name' ),
1358 array( 'oi_name' => $this->file
->getName(),
1359 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1360 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1362 while( $row = $dbw->fetchObject( $res ) ) {
1363 $privateFiles[$row->oi_archive_name
] = 1;
1366 // Prepare deletion batch
1367 $hashes = $this->getHashes();
1368 $this->deletionBatch
= array();
1369 $ext = $this->file
->getExtension();
1370 $dotExt = $ext === '' ?
'' : ".$ext";
1371 foreach ( $this->srcRels
as $name => $srcRel ) {
1372 // Skip files that have no hash (missing source).
1373 // Keep private files where they are.
1374 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1375 $hash = $hashes[$name];
1376 $key = $hash . $dotExt;
1377 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1378 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1382 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1383 // We acquire this lock by running the inserts now, before the file operations.
1385 // This potentially has poor lock contention characteristics -- an alternative
1386 // scheme would be to insert stub filearchive entries with no fa_name and commit
1387 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1388 $this->doDBInserts();
1390 // Execute the file deletion batch
1391 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1392 if ( !$status->isGood() ) {
1393 $this->status
->merge( $status );
1396 if ( !$this->status
->ok
) {
1397 // Critical file deletion error
1398 // Roll back inserts, release lock and abort
1399 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1400 $this->file
->unlockAndRollback();
1401 return $this->status
;
1405 if ( $wgUseSquid ) {
1407 foreach ( $this->srcRels
as $srcRel ) {
1408 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1409 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1411 SquidUpdate
::purge( $urls );
1414 // Delete image/oldimage rows
1415 $this->doDBDeletes();
1417 // Commit and return
1418 $this->file
->unlock();
1419 wfProfileOut( __METHOD__
);
1420 return $this->status
;
1424 #------------------------------------------------------------------------------
1427 * Helper class for file undeletion
1429 class LocalFileRestoreBatch
{
1430 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1432 function __construct( File
$file, $unsuppress = false ) {
1433 $this->file
= $file;
1434 $this->cleanupBatch
= $this->ids
= array();
1435 $this->ids
= array();
1436 $this->unsuppress
= $unsuppress;
1442 function addId( $fa_id ) {
1443 $this->ids
[] = $fa_id;
1447 * Add a whole lot of files by ID
1449 function addIds( $ids ) {
1450 $this->ids
= array_merge( $this->ids
, $ids );
1454 * Add all revisions of the file
1461 * Run the transaction, except the cleanup batch.
1462 * The cleanup batch should be run in a separate transaction, because it locks different
1463 * rows and there's no need to keep the image row locked while it's acquiring those locks
1464 * The caller may have its own transaction open.
1465 * So we save the batch and let the caller call cleanup()
1467 function execute() {
1468 global $wgUser, $wgLang;
1469 if ( !$this->all
&& !$this->ids
) {
1471 return $this->file
->repo
->newGood();
1474 $exists = $this->file
->lock();
1475 $dbw = $this->file
->repo
->getMasterDB();
1476 $status = $this->file
->repo
->newGood();
1478 // Fetch all or selected archived revisions for the file,
1479 // sorted from the most recent to the oldest.
1480 $conditions = array( 'fa_name' => $this->file
->getName() );
1482 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1485 $result = $dbw->select( 'filearchive', '*',
1488 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1490 $idsPresent = array();
1491 $storeBatch = array();
1492 $insertBatch = array();
1493 $insertCurrent = false;
1494 $deleteIds = array();
1496 $archiveNames = array();
1497 while( $row = $dbw->fetchObject( $result ) ) {
1498 $idsPresent[] = $row->fa_id
;
1500 if ( $row->fa_name
!= $this->file
->getName() ) {
1501 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1502 $status->failCount++
;
1505 if ( $row->fa_storage_key
== '' ) {
1506 // Revision was missing pre-deletion
1507 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1508 $status->failCount++
;
1512 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1513 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1515 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1517 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1518 $sha1 = substr( $sha1, 1 );
1521 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1522 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1523 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1524 ||
is_null( $row->fa_metadata
) ) {
1525 // Refresh our metadata
1526 // Required for a new current revision; nice for older ones too. :)
1527 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1530 'minor_mime' => $row->fa_minor_mime
,
1531 'major_mime' => $row->fa_major_mime
,
1532 'media_type' => $row->fa_media_type
,
1533 'metadata' => $row->fa_metadata
);
1536 if ( $first && !$exists ) {
1537 // The live (current) version cannot be hidden!
1538 if( !$this->unsuppress
&& $row->fa_deleted
) {
1539 $this->file
->unlock();
1542 // This revision will be published as the new current version
1543 $destRel = $this->file
->getRel();
1544 $insertCurrent = array(
1545 'img_name' => $row->fa_name
,
1546 'img_size' => $row->fa_size
,
1547 'img_width' => $row->fa_width
,
1548 'img_height' => $row->fa_height
,
1549 'img_metadata' => $props['metadata'],
1550 'img_bits' => $row->fa_bits
,
1551 'img_media_type' => $props['media_type'],
1552 'img_major_mime' => $props['major_mime'],
1553 'img_minor_mime' => $props['minor_mime'],
1554 'img_description' => $row->fa_description
,
1555 'img_user' => $row->fa_user
,
1556 'img_user_text' => $row->fa_user_text
,
1557 'img_timestamp' => $row->fa_timestamp
,
1558 'img_sha1' => $sha1);
1560 $archiveName = $row->fa_archive_name
;
1561 if( $archiveName == '' ) {
1562 // This was originally a current version; we
1563 // have to devise a new archive name for it.
1564 // Format is <timestamp of archiving>!<name>
1565 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1567 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1569 } while ( isset( $archiveNames[$archiveName] ) );
1571 $archiveNames[$archiveName] = true;
1572 $destRel = $this->file
->getArchiveRel( $archiveName );
1573 $insertBatch[] = array(
1574 'oi_name' => $row->fa_name
,
1575 'oi_archive_name' => $archiveName,
1576 'oi_size' => $row->fa_size
,
1577 'oi_width' => $row->fa_width
,
1578 'oi_height' => $row->fa_height
,
1579 'oi_bits' => $row->fa_bits
,
1580 'oi_description' => $row->fa_description
,
1581 'oi_user' => $row->fa_user
,
1582 'oi_user_text' => $row->fa_user_text
,
1583 'oi_timestamp' => $row->fa_timestamp
,
1584 'oi_metadata' => $props['metadata'],
1585 'oi_media_type' => $props['media_type'],
1586 'oi_major_mime' => $props['major_mime'],
1587 'oi_minor_mime' => $props['minor_mime'],
1588 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1589 'oi_sha1' => $sha1 );
1592 $deleteIds[] = $row->fa_id
;
1593 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1594 // private files can stay where they are
1596 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1597 $this->cleanupBatch
[] = $row->fa_storage_key
;
1603 // Add a warning to the status object for missing IDs
1604 $missingIds = array_diff( $this->ids
, $idsPresent );
1605 foreach ( $missingIds as $id ) {
1606 $status->error( 'undelete-missing-filearchive', $id );
1609 // Run the store batch
1610 // Use the OVERWRITE_SAME flag to smooth over a common error
1611 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1612 $status->merge( $storeStatus );
1614 if ( !$status->ok
) {
1615 // Store batch returned a critical error -- this usually means nothing was stored
1616 // Stop now and return an error
1617 $this->file
->unlock();
1621 // Run the DB updates
1622 // Because we have locked the image row, key conflicts should be rare.
1623 // If they do occur, we can roll back the transaction at this time with
1624 // no data loss, but leaving unregistered files scattered throughout the
1626 // This is not ideal, which is why it's important to lock the image row.
1627 if ( $insertCurrent ) {
1628 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1630 if ( $insertBatch ) {
1631 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1634 $dbw->delete( 'filearchive',
1635 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1639 if( $status->successCount
> 0 ) {
1641 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1643 // Update site_stats
1644 $site_stats = $dbw->tableName( 'site_stats' );
1645 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1647 $this->file
->purgeEverything();
1649 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1650 $this->file
->purgeDescription();
1651 $this->file
->purgeHistory();
1654 $this->file
->unlock();
1659 * Delete unused files in the deleted zone.
1660 * This should be called from outside the transaction in which execute() was called.
1662 function cleanup() {
1663 if ( !$this->cleanupBatch
) {
1664 return $this->file
->repo
->newGood();
1666 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1671 #------------------------------------------------------------------------------
1674 * Helper class for file movement
1676 class LocalFileMoveBatch
{
1677 var $file, $cur, $olds, $oldcount, $archive, $thumbs, $target, $db;
1679 function __construct( File
$file, Title
$target, Database
$db ) {
1680 $this->file
= $file;
1681 $this->target
= $target;
1682 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1683 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDbKey() );
1684 $this->oldName
= $this->file
->getName();
1685 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1686 $this->oldRel
= $this->oldHash
. $this->oldName
;
1687 $this->newRel
= $this->newHash
. $this->newName
;
1691 function addCurrent() {
1692 $this->cur
= array( $this->oldRel
, $this->newRel
);
1695 function addThumbs() {
1696 // Thumbnails are purged, so no need to move them
1697 $this->thumbs
= array();
1700 function addOlds() {
1701 $archiveBase = 'archive';
1702 $this->olds
= array();
1703 $this->oldcount
= 0;
1705 $result = $this->db
->select( 'oldimage',
1706 array( 'oi_archive_name', 'oi_deleted' ),
1707 array( 'oi_name' => $this->oldName
),
1710 while( $row = $this->db
->fetchObject( $result ) ) {
1711 $oldname = $row->oi_archive_name
;
1712 $bits = explode( '!', $oldname, 2 );
1713 if( count( $bits ) != 2 ) {
1714 wfDebug( 'Invalid old file name: ' . $oldname );
1717 list( $timestamp, $filename ) = $bits;
1718 if( $this->oldName
!= $filename ) {
1719 wfDebug( 'Invalid old file name:' . $oldName );
1723 // Do we want to add those to oldcount?
1724 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1727 $this->olds
[] = array(
1728 "{$archiveBase}/{$this->oldHash}{$oldname}",
1729 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1732 $this->db
->freeResult( $result );
1735 function execute() {
1736 $repo = $this->file
->repo
;
1737 $status = $repo->newGood();
1738 $triplets = $this->getMoveTriplets();
1740 $statusDb = $this->doDBUpdates();
1741 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1742 if( !$statusMove->isOk() ) {
1743 $this->db
->rollback();
1745 $status->merge( $statusDb );
1746 $status->merge( $statusMove );
1750 function doDBUpdates() {
1751 $repo = $this->file
->repo
;
1752 $status = $repo->newGood();
1755 // Update current image
1758 array( 'img_name' => $this->newName
),
1759 array( 'img_name' => $this->oldName
),
1762 if( $dbw->affectedRows() ) {
1763 $status->successCount++
;
1765 $status->failCount++
;
1768 // Update old images
1772 'oi_name' => $this->newName
,
1773 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1775 array( 'oi_name' => $this->oldName
),
1778 $affected = $dbw->affectedRows();
1779 $total = $this->oldcount
;
1780 $status->successCount +
= $affected;
1781 $status->failCount +
= $total - $affected;
1786 // Generates triplets for FSRepo::storeBatch()
1787 function getMoveTriplets() {
1788 $moves = array_merge( array( $this->cur
), $this->olds
, $this->thumbs
);
1789 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1790 foreach( $moves as $move ) {
1791 // $move: (oldRelativePath, newRelativePath)
1792 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1793 $triplets[] = array( $srcUrl, 'public', $move[1] );