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() {
523 $dir = $this->getThumbPath();
525 if ( is_dir( $dir ) ) {
526 $handle = opendir( $dir );
529 while ( false !== ( $file = readdir($handle) ) ) {
530 if ( $file{0} != '.' ) {
542 * Refresh metadata in memcached, but don't touch thumbnails or squid
544 function purgeMetadataCache() {
546 $this->saveToCache();
547 $this->purgeHistory();
551 * Purge the shared history (OldLocalFile) cache
553 function purgeHistory() {
555 $hashedName = md5($this->getName());
556 $oldKey = wfMemcKey( 'oldfile', $hashedName );
557 $wgMemc->delete( $oldKey );
561 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
563 function purgeCache() {
564 // Refresh metadata cache
565 $this->purgeMetadataCache();
568 $this->purgeThumbnails();
570 // Purge squid cache for this file
571 SquidUpdate
::purge( array( $this->getURL() ) );
575 * Delete cached transformed files
577 function purgeThumbnails() {
580 $files = $this->getThumbnails();
581 $dir = $this->getThumbPath();
583 foreach ( $files as $file ) {
584 # Check that the base file name is part of the thumb name
585 # This is a basic sanity check to avoid erasing unrelated directories
586 if ( strpos( $file, $this->getName() ) !== false ) {
587 $url = $this->getThumbUrl( $file );
589 @unlink
( "$dir/$file" );
595 SquidUpdate
::purge( $urls );
599 /** purgeDescription inherited */
600 /** purgeEverything inherited */
602 function getHistory($limit = null, $start = null, $end = null) {
603 $dbr = $this->repo
->getSlaveDB();
604 $conds = $opts = array();
605 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
606 if( $start !== null ) {
607 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
609 if( $end !== null ) {
610 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
613 $opts['LIMIT'] = $limit;
615 $opts['ORDER BY'] = 'oi_timestamp DESC';
616 $res = $dbr->select('oldimage', '*', $conds, __METHOD__
, $opts);
618 while( $row = $dbr->fetchObject($res) ) {
619 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
625 * Return the history of this file, line by line.
626 * starts with current version, then old versions.
627 * uses $this->historyLine to check which line to return:
628 * 0 return line for current version
629 * 1 query for old versions, return first one
630 * 2, ... return next old version from above query
634 function nextHistoryLine() {
635 # Polymorphic function name to distinguish foreign and local fetches
636 $fname = get_class( $this ) . '::' . __FUNCTION__
;
638 $dbr = $this->repo
->getSlaveDB();
640 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
641 $this->historyRes
= $dbr->select( 'image',
644 "'' AS oi_archive_name",
648 array( 'img_name' => $this->title
->getDBkey() ),
651 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
652 $dbr->freeResult($this->historyRes
);
653 $this->historyRes
= null;
656 } else if ( $this->historyLine
== 1 ) {
657 $dbr->freeResult($this->historyRes
);
658 $this->historyRes
= $dbr->select( 'oldimage', '*',
659 array( 'oi_name' => $this->title
->getDBkey() ),
661 array( 'ORDER BY' => 'oi_timestamp DESC' )
664 $this->historyLine ++
;
666 return $dbr->fetchObject( $this->historyRes
);
670 * Reset the history pointer to the first element of the history
673 function resetHistory() {
674 $this->historyLine
= 0;
675 if (!is_null($this->historyRes
)) {
676 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
677 $this->historyRes
= null;
681 /** getFullPath inherited */
682 /** getHashPath inherited */
683 /** getRel inherited */
684 /** getUrlRel inherited */
685 /** getArchiveRel inherited */
686 /** getThumbRel inherited */
687 /** getArchivePath inherited */
688 /** getThumbPath inherited */
689 /** getArchiveUrl inherited */
690 /** getThumbUrl inherited */
691 /** getArchiveVirtualUrl inherited */
692 /** getThumbVirtualUrl inherited */
693 /** isHashed inherited */
696 * Upload a file and record it in the DB
697 * @param string $srcPath Source path or virtual URL
698 * @param string $comment Upload description
699 * @param string $pageText Text to use for the new description page, if a new description page is created
700 * @param integer $flags Flags for publish()
701 * @param array $props File properties, if known. This can be used to reduce the
702 * upload time when uploading virtual URLs for which the file info
704 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
706 * @return FileRepoStatus object. On success, the value member contains the
707 * archive name, or an empty string if it was a new file.
709 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
711 $status = $this->publish( $srcPath, $flags );
713 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
714 $status->fatal( 'filenotfound', $srcPath );
722 * Record a file upload in the upload log and the image table
723 * @deprecated use upload()
725 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
726 $watch = false, $timestamp = false )
728 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
729 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
734 $wgUser->addWatch( $this->getTitle() );
741 * Record a file upload in the upload log and the image table
743 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
747 $dbw = $this->repo
->getMasterDB();
750 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
752 $props['description'] = $comment;
753 $props['user'] = $wgUser->getID();
754 $props['user_text'] = $wgUser->getName();
755 $props['timestamp'] = wfTimestamp( TS_MW
);
756 $this->setProps( $props );
758 // Delete thumbnails and refresh the metadata cache
759 $this->purgeThumbnails();
760 $this->saveToCache();
761 SquidUpdate
::purge( array( $this->getURL() ) );
763 // Fail now if the file isn't there
764 if ( !$this->fileExists
) {
765 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
770 if ( $timestamp === false ) {
771 $timestamp = $dbw->timestamp();
774 # Test to see if the row exists using INSERT IGNORE
775 # This avoids race conditions by locking the row until the commit, and also
776 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
777 $dbw->insert( 'image',
779 'img_name' => $this->getName(),
780 'img_size'=> $this->size
,
781 'img_width' => intval( $this->width
),
782 'img_height' => intval( $this->height
),
783 'img_bits' => $this->bits
,
784 'img_media_type' => $this->media_type
,
785 'img_major_mime' => $this->major_mime
,
786 'img_minor_mime' => $this->minor_mime
,
787 'img_timestamp' => $timestamp,
788 'img_description' => $comment,
789 'img_user' => $wgUser->getID(),
790 'img_user_text' => $wgUser->getName(),
791 'img_metadata' => $this->metadata
,
792 'img_sha1' => $this->sha1
798 if( $dbw->affectedRows() == 0 ) {
801 # Collision, this is an update of a file
802 # Insert previous contents into oldimage
803 $dbw->insertSelect( 'oldimage', 'image',
805 'oi_name' => 'img_name',
806 'oi_archive_name' => $dbw->addQuotes( $oldver ),
807 'oi_size' => 'img_size',
808 'oi_width' => 'img_width',
809 'oi_height' => 'img_height',
810 'oi_bits' => 'img_bits',
811 'oi_timestamp' => 'img_timestamp',
812 'oi_description' => 'img_description',
813 'oi_user' => 'img_user',
814 'oi_user_text' => 'img_user_text',
815 'oi_metadata' => 'img_metadata',
816 'oi_media_type' => 'img_media_type',
817 'oi_major_mime' => 'img_major_mime',
818 'oi_minor_mime' => 'img_minor_mime',
819 'oi_sha1' => 'img_sha1'
820 ), array( 'img_name' => $this->getName() ), __METHOD__
823 # Update the current image row
824 $dbw->update( 'image',
826 'img_size' => $this->size
,
827 'img_width' => intval( $this->width
),
828 'img_height' => intval( $this->height
),
829 'img_bits' => $this->bits
,
830 'img_media_type' => $this->media_type
,
831 'img_major_mime' => $this->major_mime
,
832 'img_minor_mime' => $this->minor_mime
,
833 'img_timestamp' => $timestamp,
834 'img_description' => $comment,
835 'img_user' => $wgUser->getID(),
836 'img_user_text' => $wgUser->getName(),
837 'img_metadata' => $this->metadata
,
838 'img_sha1' => $this->sha1
839 ), array( /* WHERE */
840 'img_name' => $this->getName()
845 # Update the image count
846 $site_stats = $dbw->tableName( 'site_stats' );
847 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
850 $descTitle = $this->getTitle();
851 $article = new Article( $descTitle );
854 $log = new LogPage( 'upload' );
855 $action = $reupload ?
'overwrite' : 'upload';
856 $log->addEntry( $action, $descTitle, $comment );
858 if( $descTitle->exists() ) {
859 # Create a null revision
860 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
861 $nullRevision->insertOn( $dbw );
862 $article->updateRevisionOn( $dbw, $nullRevision );
864 # Invalidate the cache for the description page
865 $descTitle->invalidateCache();
866 $descTitle->purgeSquid();
868 // New file; create the description page.
869 // There's already a log entry, so don't make a second RC entry
870 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
873 # Hooks, hooks, the magic of hooks...
874 wfRunHooks( 'FileUpload', array( $this ) );
876 # Commit the transaction now, in case something goes wrong later
877 # The most important thing is that files don't get lost, especially archives
878 $dbw->immediateCommit();
880 # Invalidate cache for all pages using this file
881 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
883 # Invalidate cache for all pages that redirects on this page
884 $redirs = $this->getTitle()->getRedirectsHere();
885 foreach( $redirs as $redir ) {
886 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
894 * Move or copy a file to its public location. If a file exists at the
895 * destination, move it to an archive. Returns the archive name on success
896 * or an empty string if it was a new file, and a wikitext-formatted
897 * WikiError object on failure.
899 * The archive name should be passed through to recordUpload for database
902 * @param string $sourcePath Local filesystem path to the source image
903 * @param integer $flags A bitwise combination of:
904 * File::DELETE_SOURCE Delete the source file, i.e. move
906 * @return FileRepoStatus object. On success, the value member contains the
907 * archive name, or an empty string if it was a new file.
909 function publish( $srcPath, $flags = 0 ) {
911 $dstRel = $this->getRel();
912 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
913 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
914 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
915 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
916 if ( $status->value
== 'new' ) {
919 $status->value
= $archiveName;
925 /** getLinksTo inherited */
926 /** getExifData inherited */
927 /** isLocal inherited */
928 /** wasDeleted inherited */
931 * Move file to the new title
933 * Move current, old version and all thumbnails
934 * to the new filename. Old file is deleted.
936 * Cache purging is done; checks for validity
937 * and logging are caller's responsibility
939 * @param $target Title New file name
940 * @return FileRepoStatus object.
942 function move( $target ) {
944 $dbw = $this->repo
->getMasterDB();
945 $batch = new LocalFileMoveBatch( $this, $target, $dbw );
946 $batch->addCurrent();
948 if( !$this->repo
->canTransformVia404() ) {
952 $status = $batch->execute();
953 $this->purgeEverything();
956 if ( $status->isOk() ) {
957 // Now switch the object
958 $this->title
= $target;
959 // Force regeneration of the name and hashpath
960 unset( $this->name
);
961 unset( $this->hashPath
);
962 // Purge the new image
963 $this->purgeEverything();
970 * Delete all versions of the file.
972 * Moves the files into an archive directory (or deletes them)
973 * and removes the database rows.
975 * Cache purging is done; logging is caller's responsibility.
979 * @return FileRepoStatus object.
981 function delete( $reason, $suppress = false ) {
983 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
984 $batch->addCurrent();
986 # Get old version relative paths
987 $dbw = $this->repo
->getMasterDB();
988 $result = $dbw->select( 'oldimage',
989 array( 'oi_archive_name' ),
990 array( 'oi_name' => $this->getName() ) );
991 while ( $row = $dbw->fetchObject( $result ) ) {
992 $batch->addOld( $row->oi_archive_name
);
994 $status = $batch->execute();
998 $site_stats = $dbw->tableName( 'site_stats' );
999 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1000 $this->purgeEverything();
1008 * Delete an old version of the file.
1010 * Moves the file into an archive directory (or deletes it)
1011 * and removes the database row.
1013 * Cache purging is done; logging is caller's responsibility.
1017 * @throws MWException or FSException on database or filestore failure
1018 * @return FileRepoStatus object.
1020 function deleteOld( $archiveName, $reason, $suppress=false ) {
1022 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1023 $batch->addOld( $archiveName );
1024 $status = $batch->execute();
1026 if ( $status->ok
) {
1027 $this->purgeDescription();
1028 $this->purgeHistory();
1034 * Restore all or specified deleted revisions to the given file.
1035 * Permissions and logging are left to the caller.
1037 * May throw database exceptions on error.
1039 * @param $versions set of record ids of deleted items to restore,
1040 * or empty to restore all revisions.
1042 * @return FileRepoStatus
1044 function restore( $versions = array(), $unsuppress = false ) {
1045 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1049 $batch->addIds( $versions );
1051 $status = $batch->execute();
1052 if ( !$status->ok
) {
1056 $cleanupStatus = $batch->cleanup();
1057 $cleanupStatus->successCount
= 0;
1058 $cleanupStatus->failCount
= 0;
1059 $status->merge( $cleanupStatus );
1063 /** isMultipage inherited */
1064 /** pageCount inherited */
1065 /** scaleHeight inherited */
1066 /** getImageSize inherited */
1069 * Get the URL of the file description page.
1071 function getDescriptionUrl() {
1072 return $this->title
->getLocalUrl();
1076 * Get the HTML text of the description page
1077 * This is not used by ImagePage for local files, since (among other things)
1078 * it skips the parser cache.
1080 function getDescriptionText() {
1082 $revision = Revision
::newFromTitle( $this->title
);
1083 if ( !$revision ) return false;
1084 $text = $revision->getText();
1085 if ( !$text ) return false;
1086 $html = $wgParser->parse( $text, new ParserOptions
);
1090 function getDescription() {
1092 return $this->description
;
1095 function getTimestamp() {
1097 return $this->timestamp
;
1100 function getSha1() {
1102 // Initialise now if necessary
1103 if ( $this->sha1
== '' && $this->fileExists
) {
1104 $this->sha1
= File
::sha1Base36( $this->getPath() );
1105 if ( strval( $this->sha1
) != '' ) {
1106 $dbw = $this->repo
->getMasterDB();
1107 $dbw->update( 'image',
1108 array( 'img_sha1' => $this->sha1
),
1109 array( 'img_name' => $this->getName() ),
1111 $this->saveToCache();
1119 * Start a transaction and lock the image for update
1120 * Increments a reference counter if the lock is already held
1121 * @return boolean True if the image exists, false otherwise
1124 $dbw = $this->repo
->getMasterDB();
1125 if ( !$this->locked
) {
1129 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1133 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1134 * the transaction and thereby releases the image lock.
1137 if ( $this->locked
) {
1139 if ( !$this->locked
) {
1140 $dbw = $this->repo
->getMasterDB();
1147 * Roll back the DB transaction and mark the image unlocked
1149 function unlockAndRollback() {
1150 $this->locked
= false;
1151 $dbw = $this->repo
->getMasterDB();
1154 } // LocalFile class
1156 #------------------------------------------------------------------------------
1159 * Helper class for file deletion
1161 class LocalFileDeleteBatch
{
1162 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1165 function __construct( File
$file, $reason = '', $suppress = false ) {
1166 $this->file
= $file;
1167 $this->reason
= $reason;
1168 $this->suppress
= $suppress;
1169 $this->status
= $file->repo
->newGood();
1172 function addCurrent() {
1173 $this->srcRels
['.'] = $this->file
->getRel();
1176 function addOld( $oldName ) {
1177 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1178 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1181 function getOldRels() {
1182 if ( !isset( $this->srcRels
['.'] ) ) {
1183 $oldRels =& $this->srcRels
;
1184 $deleteCurrent = false;
1186 $oldRels = $this->srcRels
;
1187 unset( $oldRels['.'] );
1188 $deleteCurrent = true;
1190 return array( $oldRels, $deleteCurrent );
1193 /*protected*/ function getHashes() {
1195 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1196 if ( $deleteCurrent ) {
1197 $hashes['.'] = $this->file
->getSha1();
1199 if ( count( $oldRels ) ) {
1200 $dbw = $this->file
->repo
->getMasterDB();
1201 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1202 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1204 while ( $row = $dbw->fetchObject( $res ) ) {
1205 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1206 // Get the hash from the file
1207 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1208 $props = $this->file
->repo
->getFileProps( $oldUrl );
1209 if ( $props['fileExists'] ) {
1210 // Upgrade the oldimage row
1211 $dbw->update( 'oldimage',
1212 array( 'oi_sha1' => $props['sha1'] ),
1213 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1215 $hashes[$row->oi_archive_name
] = $props['sha1'];
1217 $hashes[$row->oi_archive_name
] = false;
1220 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1224 $missing = array_diff_key( $this->srcRels
, $hashes );
1225 foreach ( $missing as $name => $rel ) {
1226 $this->status
->error( 'filedelete-old-unregistered', $name );
1228 foreach ( $hashes as $name => $hash ) {
1230 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1231 unset( $hashes[$name] );
1238 function doDBInserts() {
1240 $dbw = $this->file
->repo
->getMasterDB();
1241 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1242 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1243 $encReason = $dbw->addQuotes( $this->reason
);
1244 $encGroup = $dbw->addQuotes( 'deleted' );
1245 $ext = $this->file
->getExtension();
1246 $dotExt = $ext === '' ?
'' : ".$ext";
1247 $encExt = $dbw->addQuotes( $dotExt );
1248 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1250 // Bitfields to further suppress the content
1251 if ( $this->suppress
) {
1253 // This should be 15...
1254 $bitfield |
= Revision
::DELETED_TEXT
;
1255 $bitfield |
= Revision
::DELETED_COMMENT
;
1256 $bitfield |
= Revision
::DELETED_USER
;
1257 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1259 $bitfield = 'oi_deleted';
1262 if ( $deleteCurrent ) {
1263 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1264 $where = array( 'img_name' => $this->file
->getName() );
1265 $dbw->insertSelect( 'filearchive', 'image',
1267 'fa_storage_group' => $encGroup,
1268 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1269 'fa_deleted_user' => $encUserId,
1270 'fa_deleted_timestamp' => $encTimestamp,
1271 'fa_deleted_reason' => $encReason,
1272 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1274 'fa_name' => 'img_name',
1275 'fa_archive_name' => 'NULL',
1276 'fa_size' => 'img_size',
1277 'fa_width' => 'img_width',
1278 'fa_height' => 'img_height',
1279 'fa_metadata' => 'img_metadata',
1280 'fa_bits' => 'img_bits',
1281 'fa_media_type' => 'img_media_type',
1282 'fa_major_mime' => 'img_major_mime',
1283 'fa_minor_mime' => 'img_minor_mime',
1284 'fa_description' => 'img_description',
1285 'fa_user' => 'img_user',
1286 'fa_user_text' => 'img_user_text',
1287 'fa_timestamp' => 'img_timestamp'
1288 ), $where, __METHOD__
);
1291 if ( count( $oldRels ) ) {
1292 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1294 'oi_name' => $this->file
->getName(),
1295 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1296 $dbw->insertSelect( 'filearchive', 'oldimage',
1298 'fa_storage_group' => $encGroup,
1299 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1300 'fa_deleted_user' => $encUserId,
1301 'fa_deleted_timestamp' => $encTimestamp,
1302 'fa_deleted_reason' => $encReason,
1303 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1305 'fa_name' => 'oi_name',
1306 'fa_archive_name' => 'oi_archive_name',
1307 'fa_size' => 'oi_size',
1308 'fa_width' => 'oi_width',
1309 'fa_height' => 'oi_height',
1310 'fa_metadata' => 'oi_metadata',
1311 'fa_bits' => 'oi_bits',
1312 'fa_media_type' => 'oi_media_type',
1313 'fa_major_mime' => 'oi_major_mime',
1314 'fa_minor_mime' => 'oi_minor_mime',
1315 'fa_description' => 'oi_description',
1316 'fa_user' => 'oi_user',
1317 'fa_user_text' => 'oi_user_text',
1318 'fa_timestamp' => 'oi_timestamp',
1319 'fa_deleted' => $bitfield
1320 ), $where, __METHOD__
);
1324 function doDBDeletes() {
1325 $dbw = $this->file
->repo
->getMasterDB();
1326 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1327 if ( count( $oldRels ) ) {
1328 $dbw->delete( 'oldimage',
1330 'oi_name' => $this->file
->getName(),
1331 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1334 if ( $deleteCurrent ) {
1335 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1340 * Run the transaction
1342 function execute() {
1343 global $wgUser, $wgUseSquid;
1344 wfProfileIn( __METHOD__
);
1346 $this->file
->lock();
1347 // Leave private files alone
1348 $privateFiles = array();
1349 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1350 $dbw = $this->file
->repo
->getMasterDB();
1351 if( !empty( $oldRels ) ) {
1352 $res = $dbw->select( 'oldimage',
1353 array( 'oi_archive_name' ),
1354 array( 'oi_name' => $this->file
->getName(),
1355 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1356 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1358 while( $row = $dbw->fetchObject( $res ) ) {
1359 $privateFiles[$row->oi_archive_name
] = 1;
1362 // Prepare deletion batch
1363 $hashes = $this->getHashes();
1364 $this->deletionBatch
= array();
1365 $ext = $this->file
->getExtension();
1366 $dotExt = $ext === '' ?
'' : ".$ext";
1367 foreach ( $this->srcRels
as $name => $srcRel ) {
1368 // Skip files that have no hash (missing source).
1369 // Keep private files where they are.
1370 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1371 $hash = $hashes[$name];
1372 $key = $hash . $dotExt;
1373 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1374 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1378 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1379 // We acquire this lock by running the inserts now, before the file operations.
1381 // This potentially has poor lock contention characteristics -- an alternative
1382 // scheme would be to insert stub filearchive entries with no fa_name and commit
1383 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1384 $this->doDBInserts();
1386 // Execute the file deletion batch
1387 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1388 if ( !$status->isGood() ) {
1389 $this->status
->merge( $status );
1392 if ( !$this->status
->ok
) {
1393 // Critical file deletion error
1394 // Roll back inserts, release lock and abort
1395 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1396 $this->file
->unlockAndRollback();
1397 return $this->status
;
1401 if ( $wgUseSquid ) {
1403 foreach ( $this->srcRels
as $srcRel ) {
1404 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1405 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1407 SquidUpdate
::purge( $urls );
1410 // Delete image/oldimage rows
1411 $this->doDBDeletes();
1413 // Commit and return
1414 $this->file
->unlock();
1415 wfProfileOut( __METHOD__
);
1416 return $this->status
;
1420 #------------------------------------------------------------------------------
1423 * Helper class for file undeletion
1425 class LocalFileRestoreBatch
{
1426 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1428 function __construct( File
$file, $unsuppress = false ) {
1429 $this->file
= $file;
1430 $this->cleanupBatch
= $this->ids
= array();
1431 $this->ids
= array();
1432 $this->unsuppress
= $unsuppress;
1438 function addId( $fa_id ) {
1439 $this->ids
[] = $fa_id;
1443 * Add a whole lot of files by ID
1445 function addIds( $ids ) {
1446 $this->ids
= array_merge( $this->ids
, $ids );
1450 * Add all revisions of the file
1457 * Run the transaction, except the cleanup batch.
1458 * The cleanup batch should be run in a separate transaction, because it locks different
1459 * rows and there's no need to keep the image row locked while it's acquiring those locks
1460 * The caller may have its own transaction open.
1461 * So we save the batch and let the caller call cleanup()
1463 function execute() {
1464 global $wgUser, $wgLang;
1465 if ( !$this->all
&& !$this->ids
) {
1467 return $this->file
->repo
->newGood();
1470 $exists = $this->file
->lock();
1471 $dbw = $this->file
->repo
->getMasterDB();
1472 $status = $this->file
->repo
->newGood();
1474 // Fetch all or selected archived revisions for the file,
1475 // sorted from the most recent to the oldest.
1476 $conditions = array( 'fa_name' => $this->file
->getName() );
1478 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1481 $result = $dbw->select( 'filearchive', '*',
1484 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1486 $idsPresent = array();
1487 $storeBatch = array();
1488 $insertBatch = array();
1489 $insertCurrent = false;
1490 $deleteIds = array();
1492 $archiveNames = array();
1493 while( $row = $dbw->fetchObject( $result ) ) {
1494 $idsPresent[] = $row->fa_id
;
1496 if ( $row->fa_name
!= $this->file
->getName() ) {
1497 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1498 $status->failCount++
;
1501 if ( $row->fa_storage_key
== '' ) {
1502 // Revision was missing pre-deletion
1503 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1504 $status->failCount++
;
1508 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1509 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1511 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1513 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1514 $sha1 = substr( $sha1, 1 );
1517 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1518 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1519 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1520 ||
is_null( $row->fa_metadata
) ) {
1521 // Refresh our metadata
1522 // Required for a new current revision; nice for older ones too. :)
1523 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1526 'minor_mime' => $row->fa_minor_mime
,
1527 'major_mime' => $row->fa_major_mime
,
1528 'media_type' => $row->fa_media_type
,
1529 'metadata' => $row->fa_metadata
);
1532 if ( $first && !$exists ) {
1533 // The live (current) version cannot be hidden!
1534 if( !$this->unsuppress
&& $row->fa_deleted
) {
1535 $this->file
->unlock();
1538 // This revision will be published as the new current version
1539 $destRel = $this->file
->getRel();
1540 $insertCurrent = array(
1541 'img_name' => $row->fa_name
,
1542 'img_size' => $row->fa_size
,
1543 'img_width' => $row->fa_width
,
1544 'img_height' => $row->fa_height
,
1545 'img_metadata' => $props['metadata'],
1546 'img_bits' => $row->fa_bits
,
1547 'img_media_type' => $props['media_type'],
1548 'img_major_mime' => $props['major_mime'],
1549 'img_minor_mime' => $props['minor_mime'],
1550 'img_description' => $row->fa_description
,
1551 'img_user' => $row->fa_user
,
1552 'img_user_text' => $row->fa_user_text
,
1553 'img_timestamp' => $row->fa_timestamp
,
1554 'img_sha1' => $sha1);
1556 $archiveName = $row->fa_archive_name
;
1557 if( $archiveName == '' ) {
1558 // This was originally a current version; we
1559 // have to devise a new archive name for it.
1560 // Format is <timestamp of archiving>!<name>
1561 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1563 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1565 } while ( isset( $archiveNames[$archiveName] ) );
1567 $archiveNames[$archiveName] = true;
1568 $destRel = $this->file
->getArchiveRel( $archiveName );
1569 $insertBatch[] = array(
1570 'oi_name' => $row->fa_name
,
1571 'oi_archive_name' => $archiveName,
1572 'oi_size' => $row->fa_size
,
1573 'oi_width' => $row->fa_width
,
1574 'oi_height' => $row->fa_height
,
1575 'oi_bits' => $row->fa_bits
,
1576 'oi_description' => $row->fa_description
,
1577 'oi_user' => $row->fa_user
,
1578 'oi_user_text' => $row->fa_user_text
,
1579 'oi_timestamp' => $row->fa_timestamp
,
1580 'oi_metadata' => $props['metadata'],
1581 'oi_media_type' => $props['media_type'],
1582 'oi_major_mime' => $props['major_mime'],
1583 'oi_minor_mime' => $props['minor_mime'],
1584 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1585 'oi_sha1' => $sha1 );
1588 $deleteIds[] = $row->fa_id
;
1589 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1590 // private files can stay where they are
1592 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1593 $this->cleanupBatch
[] = $row->fa_storage_key
;
1599 // Add a warning to the status object for missing IDs
1600 $missingIds = array_diff( $this->ids
, $idsPresent );
1601 foreach ( $missingIds as $id ) {
1602 $status->error( 'undelete-missing-filearchive', $id );
1605 // Run the store batch
1606 // Use the OVERWRITE_SAME flag to smooth over a common error
1607 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1608 $status->merge( $storeStatus );
1610 if ( !$status->ok
) {
1611 // Store batch returned a critical error -- this usually means nothing was stored
1612 // Stop now and return an error
1613 $this->file
->unlock();
1617 // Run the DB updates
1618 // Because we have locked the image row, key conflicts should be rare.
1619 // If they do occur, we can roll back the transaction at this time with
1620 // no data loss, but leaving unregistered files scattered throughout the
1622 // This is not ideal, which is why it's important to lock the image row.
1623 if ( $insertCurrent ) {
1624 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1626 if ( $insertBatch ) {
1627 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1630 $dbw->delete( 'filearchive',
1631 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1635 if( $status->successCount
> 0 ) {
1637 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1639 // Update site_stats
1640 $site_stats = $dbw->tableName( 'site_stats' );
1641 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1643 $this->file
->purgeEverything();
1645 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1646 $this->file
->purgeDescription();
1647 $this->file
->purgeHistory();
1650 $this->file
->unlock();
1655 * Delete unused files in the deleted zone.
1656 * This should be called from outside the transaction in which execute() was called.
1658 function cleanup() {
1659 if ( !$this->cleanupBatch
) {
1660 return $this->file
->repo
->newGood();
1662 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1667 #------------------------------------------------------------------------------
1670 * Helper class for file movement
1672 class LocalFileMoveBatch
{
1673 var $file, $cur, $olds, $oldcount, $archive, $thumbs, $target, $db;
1675 function __construct( File
$file, Title
$target, Database
$db ) {
1676 $this->file
= $file;
1677 $this->target
= $target;
1678 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1679 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDbKey() );
1680 $this->oldName
= $this->file
->getName();
1681 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1682 $this->oldRel
= $this->oldHash
. $this->oldName
;
1683 $this->newRel
= $this->newHash
. $this->newName
;
1687 function addCurrent() {
1688 $this->cur
= array( $this->oldRel
, $this->newRel
);
1691 function addThumbs() {
1692 // Thumbnails are purged, so no need to move them
1693 $this->thumbs
= array();
1696 function addOlds() {
1697 $archiveBase = 'archive';
1698 $this->olds
= array();
1699 $this->oldcount
= 0;
1701 $result = $this->db
->select( 'oldimage',
1702 array( 'oi_archive_name', 'oi_deleted' ),
1703 array( 'oi_name' => $this->oldName
),
1706 while( $row = $this->db
->fetchObject( $result ) ) {
1707 $oldname = $row->oi_archive_name
;
1708 $bits = explode( '!', $oldname, 2 );
1709 if( count( $bits ) != 2 ) {
1710 wfDebug( 'Invalid old file name: ' . $oldname );
1713 list( $timestamp, $filename ) = $bits;
1714 if( $this->oldName
!= $filename ) {
1715 wfDebug( 'Invalid old file name:' . $oldName );
1719 // Do we want to add those to oldcount?
1720 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1723 $this->olds
[] = array(
1724 "{$archiveBase}/{$this->oldHash}{$oldname}",
1725 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1728 $this->db
->freeResult( $result );
1731 function execute() {
1732 $repo = $this->file
->repo
;
1733 $status = $repo->newGood();
1734 $triplets = $this->getMoveTriplets();
1736 $statusDb = $this->doDBUpdates();
1737 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1738 if( !$statusMove->isOk() ) {
1739 $this->db
->rollback();
1741 $status->merge( $statusDb );
1742 $status->merge( $statusMove );
1746 function doDBUpdates() {
1747 $repo = $this->file
->repo
;
1748 $status = $repo->newGood();
1751 // Update current image
1754 array( 'img_name' => $this->newName
),
1755 array( 'img_name' => $this->oldName
),
1758 if( $dbw->affectedRows() ) {
1759 $status->successCount++
;
1761 $status->failCount++
;
1764 // Update old images
1768 'oi_name' => $this->newName
,
1769 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1771 array( 'oi_name' => $this->oldName
),
1774 $affected = $dbw->affectedRows();
1775 $total = $this->oldcount
;
1776 $status->successCount +
= $affected;
1777 $status->failCount +
= $total - $affected;
1782 // Generates triplets for FSRepo::storeBatch()
1783 function getMoveTriplets() {
1784 $moves = array_merge( array( $this->cur
), $this->olds
, $this->thumbs
);
1785 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1786 foreach( $moves as $move ) {
1787 // $move: (oldRelativePath, newRelativePath)
1788 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1789 $triplets[] = array( $srcUrl, 'public', $move[1] );