6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 7 );
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 );
79 * Do not call this except from inside a repo class.
81 function __construct( $title, $repo ) {
82 if( !is_object( $title ) ) {
83 throw new MWException( __CLASS__
.' constructor given bogus title.' );
85 parent
::__construct( $title, $repo );
87 $this->historyLine
= 0;
88 $this->historyRes
= null;
89 $this->dataLoaded
= false;
93 * Get the memcached key
95 function getCacheKey() {
96 $hashedName = md5($this->getName());
97 return wfMemcKey( 'file', $hashedName );
101 * Try to load file metadata from memcached. Returns true on success.
103 function loadFromCache() {
105 wfProfileIn( __METHOD__
);
106 $this->dataLoaded
= false;
107 $key = $this->getCacheKey();
111 $cachedValues = $wgMemc->get( $key );
113 // Check if the key existed and belongs to this version of MediaWiki
114 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
115 wfDebug( "Pulling file metadata from cache key $key\n" );
116 $this->fileExists
= $cachedValues['fileExists'];
117 if ( $this->fileExists
) {
118 $this->setProps( $cachedValues );
120 $this->dataLoaded
= true;
122 if ( $this->dataLoaded
) {
123 wfIncrStats( 'image_cache_hit' );
125 wfIncrStats( 'image_cache_miss' );
128 wfProfileOut( __METHOD__
);
129 return $this->dataLoaded
;
133 * Save the file metadata to memcached
135 function saveToCache() {
138 $key = $this->getCacheKey();
142 $fields = $this->getCacheFields( '' );
143 $cache = array( 'version' => MW_FILE_VERSION
);
144 $cache['fileExists'] = $this->fileExists
;
145 if ( $this->fileExists
) {
146 foreach ( $fields as $field ) {
147 $cache[$field] = $this->$field;
151 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
155 * Load metadata from the file itself
157 function loadFromFile() {
158 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
161 function getCacheFields( $prefix = 'img_' ) {
162 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
163 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
164 static $results = array();
165 if ( $prefix == '' ) {
168 if ( !isset( $results[$prefix] ) ) {
169 $prefixedFields = array();
170 foreach ( $fields as $field ) {
171 $prefixedFields[] = $prefix . $field;
173 $results[$prefix] = $prefixedFields;
175 return $results[$prefix];
179 * Load file metadata from the DB
181 function loadFromDB() {
182 # Polymorphic function name to distinguish foreign and local fetches
183 $fname = get_class( $this ) . '::' . __FUNCTION__
;
184 wfProfileIn( $fname );
186 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
187 $this->dataLoaded
= true;
189 $dbr = $this->repo
->getMasterDB();
191 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
192 array( 'img_name' => $this->getName() ), $fname );
194 $this->loadFromRow( $row );
196 $this->fileExists
= false;
199 wfProfileOut( $fname );
203 * Decode a row from the database (either object or array) to an array
204 * with timestamps and MIME types decoded, and the field prefix removed.
206 function decodeRow( $row, $prefix = 'img_' ) {
207 $array = (array)$row;
208 $prefixLength = strlen( $prefix );
209 // Sanity check prefix once
210 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
211 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
214 foreach ( $array as $name => $value ) {
215 $decoded[substr( $name, $prefixLength )] = $value;
217 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
218 if ( empty( $decoded['major_mime'] ) ) {
219 $decoded['mime'] = "unknown/unknown";
221 if (!$decoded['minor_mime']) {
222 $decoded['minor_mime'] = "unknown";
224 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
226 # Trim zero padding from char/binary field
227 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
232 * Load file metadata from a DB result row
234 function loadFromRow( $row, $prefix = 'img_' ) {
235 $this->dataLoaded
= true;
236 $array = $this->decodeRow( $row, $prefix );
237 foreach ( $array as $name => $value ) {
238 $this->$name = $value;
240 $this->fileExists
= true;
241 $this->maybeUpgradeRow();
245 * Load file metadata from cache or DB, unless already loaded
248 if ( !$this->dataLoaded
) {
249 if ( !$this->loadFromCache() ) {
251 $this->saveToCache();
253 $this->dataLoaded
= true;
258 * Upgrade a row if it needs it
260 function maybeUpgradeRow() {
261 if ( wfReadOnly() ) {
264 if ( is_null($this->media_type
) ||
265 $this->mime
== 'image/svg'
268 $this->upgraded
= true;
270 $handler = $this->getHandler();
271 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
273 $this->upgraded
= true;
278 function getUpgraded() {
279 return $this->upgraded
;
283 * Fix assorted version-related problems with the image row by reloading it from the file
285 function upgradeRow() {
286 wfProfileIn( __METHOD__
);
288 $this->loadFromFile();
290 # Don't destroy file info of missing files
291 if ( !$this->fileExists
) {
292 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
295 $dbw = $this->repo
->getMasterDB();
296 list( $major, $minor ) = self
::splitMime( $this->mime
);
298 if ( wfReadOnly() ) {
301 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
303 $dbw->update( 'image',
305 'img_width' => $this->width
,
306 'img_height' => $this->height
,
307 'img_bits' => $this->bits
,
308 'img_media_type' => $this->media_type
,
309 'img_major_mime' => $major,
310 'img_minor_mime' => $minor,
311 'img_metadata' => $this->metadata
,
312 'img_sha1' => $this->sha1
,
313 ), array( 'img_name' => $this->getName() ),
316 $this->saveToCache();
317 wfProfileOut( __METHOD__
);
321 * Set properties in this object to be equal to those given in the
322 * associative array $info. Only cacheable fields can be set.
324 * If 'mime' is given, it will be split into major_mime/minor_mime.
325 * If major_mime/minor_mime are given, $this->mime will also be set.
327 function setProps( $info ) {
328 $this->dataLoaded
= true;
329 $fields = $this->getCacheFields( '' );
330 $fields[] = 'fileExists';
331 foreach ( $fields as $field ) {
332 if ( isset( $info[$field] ) ) {
333 $this->$field = $info[$field];
336 // Fix up mime fields
337 if ( isset( $info['major_mime'] ) ) {
338 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
339 } elseif ( isset( $info['mime'] ) ) {
340 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
344 /** splitMime inherited */
345 /** getName inherited */
346 /** getTitle inherited */
347 /** getURL inherited */
348 /** getViewURL inherited */
349 /** getPath inherited */
350 /** isVisible inhereted */
353 * Return the width of the image
355 * Returns false on error
358 function getWidth( $page = 1 ) {
360 if ( $this->isMultipage() ) {
361 $dim = $this->getHandler()->getPageDimensions( $this, $page );
363 return $dim['width'];
373 * Return the height of the image
375 * Returns false on error
378 function getHeight( $page = 1 ) {
380 if ( $this->isMultipage() ) {
381 $dim = $this->getHandler()->getPageDimensions( $this, $page );
383 return $dim['height'];
388 return $this->height
;
393 * Returns ID or name of user who uploaded the file
395 * @param $type string 'text' or 'id'
397 function getUser($type='text') {
399 if( $type == 'text' ) {
400 return $this->user_text
;
401 } elseif( $type == 'id' ) {
407 * Get handler-specific metadata
409 function getMetadata() {
411 return $this->metadata
;
415 * Return the size of the image file, in bytes
424 * Returns the mime type of the file.
426 function getMimeType() {
432 * Return the type of the media in the file.
433 * Use the value returned by this function with the MEDIATYPE_xxx constants.
435 function getMediaType() {
437 return $this->media_type
;
440 /** canRender inherited */
441 /** mustRender inherited */
442 /** allowInlineDisplay inherited */
443 /** isSafeFile inherited */
444 /** isTrustedFile inherited */
447 * Returns true if the file file exists on disk.
448 * @return boolean Whether file file exist on disk.
453 return $this->fileExists
;
456 /** getTransformScript inherited */
457 /** getUnscaledThumb inherited */
458 /** thumbName inherited */
459 /** createThumb inherited */
460 /** getThumbnail inherited */
461 /** transform inherited */
464 * Fix thumbnail files from 1.4 or before, with extreme prejudice
466 function migrateThumbFile( $thumbName ) {
467 $thumbDir = $this->getThumbPath();
468 $thumbPath = "$thumbDir/$thumbName";
469 if ( is_dir( $thumbPath ) ) {
470 // Directory where file should be
471 // This happened occasionally due to broken migration code in 1.5
472 // Rename to broken-*
473 for ( $i = 0; $i < 100 ; $i++
) {
474 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
475 if ( !file_exists( $broken ) ) {
476 rename( $thumbPath, $broken );
480 // Doesn't exist anymore
483 if ( is_file( $thumbDir ) ) {
484 // File where directory should be
486 // Doesn't exist anymore
491 /** getHandler inherited */
492 /** iconThumb inherited */
493 /** getLastError inherited */
496 * Get all thumbnail names previously generated for this file
498 function getThumbnails() {
499 if ( $this->isHashed() ) {
502 $dir = $this->getThumbPath();
504 if ( is_dir( $dir ) ) {
505 $handle = opendir( $dir );
508 while ( false !== ( $file = readdir($handle) ) ) {
509 if ( $file{0} != '.' ) {
524 * Refresh metadata in memcached, but don't touch thumbnails or squid
526 function purgeMetadataCache() {
528 $this->saveToCache();
529 $this->purgeHistory();
533 * Purge the shared history (OldLocalFile) cache
535 function purgeHistory() {
537 $hashedName = md5($this->getName());
538 $oldKey = wfMemcKey( 'oldfile', $hashedName );
539 $wgMemc->delete( $oldKey );
543 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
545 function purgeCache() {
546 // Refresh metadata cache
547 $this->purgeMetadataCache();
550 $this->purgeThumbnails();
552 // Purge squid cache for this file
553 SquidUpdate
::purge( array( $this->getURL() ) );
557 * Delete cached transformed files
559 function purgeThumbnails() {
562 $files = $this->getThumbnails();
563 $dir = $this->getThumbPath();
565 foreach ( $files as $file ) {
566 # Check that the base file name is part of the thumb name
567 # This is a basic sanity check to avoid erasing unrelated directories
568 if ( strpos( $file, $this->getName() ) !== false ) {
569 $url = $this->getThumbUrl( $file );
571 @unlink
( "$dir/$file" );
577 SquidUpdate
::purge( $urls );
581 /** purgeDescription inherited */
582 /** purgeEverything inherited */
584 function getHistory($limit = null, $start = null, $end = null) {
585 $dbr = $this->repo
->getSlaveDB();
586 $conds = $opts = array();
587 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
588 if( $start !== null ) {
589 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
591 if( $end !== null ) {
592 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
595 $opts['LIMIT'] = $limit;
597 $opts['ORDER BY'] = 'oi_timestamp DESC';
598 $res = $dbr->select('oldimage', '*', $conds, __METHOD__
, $opts);
600 while( $row = $dbr->fetchObject($res) ) {
601 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
607 * Return the history of this file, line by line.
608 * starts with current version, then old versions.
609 * uses $this->historyLine to check which line to return:
610 * 0 return line for current version
611 * 1 query for old versions, return first one
612 * 2, ... return next old version from above query
616 function nextHistoryLine() {
617 # Polymorphic function name to distinguish foreign and local fetches
618 $fname = get_class( $this ) . '::' . __FUNCTION__
;
620 $dbr = $this->repo
->getSlaveDB();
622 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
623 $this->historyRes
= $dbr->select( 'image',
626 "'' AS oi_archive_name",
630 array( 'img_name' => $this->title
->getDBkey() ),
633 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
634 $dbr->freeResult($this->historyRes
);
635 $this->historyRes
= null;
638 } else if ( $this->historyLine
== 1 ) {
639 $dbr->freeResult($this->historyRes
);
640 $this->historyRes
= $dbr->select( 'oldimage', '*',
641 array( 'oi_name' => $this->title
->getDBkey() ),
643 array( 'ORDER BY' => 'oi_timestamp DESC' )
646 $this->historyLine ++
;
648 return $dbr->fetchObject( $this->historyRes
);
652 * Reset the history pointer to the first element of the history
655 function resetHistory() {
656 $this->historyLine
= 0;
657 if (!is_null($this->historyRes
)) {
658 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
659 $this->historyRes
= null;
663 /** getFullPath inherited */
664 /** getHashPath inherited */
665 /** getRel inherited */
666 /** getUrlRel inherited */
667 /** getArchiveRel inherited */
668 /** getThumbRel inherited */
669 /** getArchivePath inherited */
670 /** getThumbPath inherited */
671 /** getArchiveUrl inherited */
672 /** getThumbUrl inherited */
673 /** getArchiveVirtualUrl inherited */
674 /** getThumbVirtualUrl inherited */
675 /** isHashed inherited */
678 * Upload a file and record it in the DB
679 * @param string $srcPath Source path or virtual URL
680 * @param string $comment Upload description
681 * @param string $pageText Text to use for the new description page, if a new description page is created
682 * @param integer $flags Flags for publish()
683 * @param array $props File properties, if known. This can be used to reduce the
684 * upload time when uploading virtual URLs for which the file info
686 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
688 * @return FileRepoStatus object. On success, the value member contains the
689 * archive name, or an empty string if it was a new file.
691 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
693 $status = $this->publish( $srcPath, $flags );
695 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
696 $status->fatal( 'filenotfound', $srcPath );
704 * Record a file upload in the upload log and the image table
705 * @deprecated use upload()
707 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
708 $watch = false, $timestamp = false )
710 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
711 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
716 $wgUser->addWatch( $this->getTitle() );
723 * Record a file upload in the upload log and the image table
725 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
729 $dbw = $this->repo
->getMasterDB();
732 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
734 $props['description'] = $comment;
735 $props['user'] = $wgUser->getID();
736 $props['user_text'] = $wgUser->getName();
737 $props['timestamp'] = wfTimestamp( TS_MW
);
738 $this->setProps( $props );
740 // Delete thumbnails and refresh the metadata cache
741 $this->purgeThumbnails();
742 $this->saveToCache();
743 SquidUpdate
::purge( array( $this->getURL() ) );
745 // Fail now if the file isn't there
746 if ( !$this->fileExists
) {
747 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
752 if ( $timestamp === false ) {
753 $timestamp = $dbw->timestamp();
756 # Test to see if the row exists using INSERT IGNORE
757 # This avoids race conditions by locking the row until the commit, and also
758 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
759 $dbw->insert( 'image',
761 'img_name' => $this->getName(),
762 'img_size'=> $this->size
,
763 'img_width' => intval( $this->width
),
764 'img_height' => intval( $this->height
),
765 'img_bits' => $this->bits
,
766 'img_media_type' => $this->media_type
,
767 'img_major_mime' => $this->major_mime
,
768 'img_minor_mime' => $this->minor_mime
,
769 'img_timestamp' => $timestamp,
770 'img_description' => $comment,
771 'img_user' => $wgUser->getID(),
772 'img_user_text' => $wgUser->getName(),
773 'img_metadata' => $this->metadata
,
774 'img_sha1' => $this->sha1
780 if( $dbw->affectedRows() == 0 ) {
783 # Collision, this is an update of a file
784 # Insert previous contents into oldimage
785 $dbw->insertSelect( 'oldimage', 'image',
787 'oi_name' => 'img_name',
788 'oi_archive_name' => $dbw->addQuotes( $oldver ),
789 'oi_size' => 'img_size',
790 'oi_width' => 'img_width',
791 'oi_height' => 'img_height',
792 'oi_bits' => 'img_bits',
793 'oi_timestamp' => 'img_timestamp',
794 'oi_description' => 'img_description',
795 'oi_user' => 'img_user',
796 'oi_user_text' => 'img_user_text',
797 'oi_metadata' => 'img_metadata',
798 'oi_media_type' => 'img_media_type',
799 'oi_major_mime' => 'img_major_mime',
800 'oi_minor_mime' => 'img_minor_mime',
801 'oi_sha1' => 'img_sha1'
802 ), array( 'img_name' => $this->getName() ), __METHOD__
805 # Update the current image row
806 $dbw->update( 'image',
808 'img_size' => $this->size
,
809 'img_width' => intval( $this->width
),
810 'img_height' => intval( $this->height
),
811 'img_bits' => $this->bits
,
812 'img_media_type' => $this->media_type
,
813 'img_major_mime' => $this->major_mime
,
814 'img_minor_mime' => $this->minor_mime
,
815 'img_timestamp' => $timestamp,
816 'img_description' => $comment,
817 'img_user' => $wgUser->getID(),
818 'img_user_text' => $wgUser->getName(),
819 'img_metadata' => $this->metadata
,
820 'img_sha1' => $this->sha1
821 ), array( /* WHERE */
822 'img_name' => $this->getName()
827 # Update the image count
828 $site_stats = $dbw->tableName( 'site_stats' );
829 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
832 $descTitle = $this->getTitle();
833 $article = new Article( $descTitle );
836 $log = new LogPage( 'upload' );
837 $action = $reupload ?
'overwrite' : 'upload';
838 $log->addEntry( $action, $descTitle, $comment );
840 if( $descTitle->exists() ) {
841 # Create a null revision
842 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
843 $nullRevision->insertOn( $dbw );
844 $article->updateRevisionOn( $dbw, $nullRevision );
846 # Invalidate the cache for the description page
847 $descTitle->invalidateCache();
848 $descTitle->purgeSquid();
850 // New file; create the description page.
851 // There's already a log entry, so don't make a second RC entry
852 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
855 # Hooks, hooks, the magic of hooks...
856 wfRunHooks( 'FileUpload', array( $this ) );
858 # Commit the transaction now, in case something goes wrong later
859 # The most important thing is that files don't get lost, especially archives
860 $dbw->immediateCommit();
862 # Invalidate cache for all pages using this file
863 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
865 # Invalidate cache for all pages that redirects on this page
866 $redirs = $this->getTitle()->getRedirectsHere();
867 foreach( $redirs as $redir ) {
868 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
876 * Move or copy a file to its public location. If a file exists at the
877 * destination, move it to an archive. Returns the archive name on success
878 * or an empty string if it was a new file, and a wikitext-formatted
879 * WikiError object on failure.
881 * The archive name should be passed through to recordUpload for database
884 * @param string $sourcePath Local filesystem path to the source image
885 * @param integer $flags A bitwise combination of:
886 * File::DELETE_SOURCE Delete the source file, i.e. move
888 * @return FileRepoStatus object. On success, the value member contains the
889 * archive name, or an empty string if it was a new file.
891 function publish( $srcPath, $flags = 0 ) {
893 $dstRel = $this->getRel();
894 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
895 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
896 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
897 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
898 if ( $status->value
== 'new' ) {
901 $status->value
= $archiveName;
907 /** getLinksTo inherited */
908 /** getExifData inherited */
909 /** isLocal inherited */
910 /** wasDeleted inherited */
913 * Move file to the new title
915 * Move current, old version and all thumbnails
916 * to the new filename. Old file is deleted.
918 * Cache purging is done; checks for validity
919 * and logging are caller's responsibility
921 * @param $target Title New file name
922 * @return FileRepoStatus object.
924 function move( $target ) {
926 $dbw = $this->repo
->getMasterDB();
927 $batch = new LocalFileMoveBatch( $this, $target, $dbw );
928 $batch->addCurrent();
930 if( !$this->repo
->canTransformVia404() ) {
934 $status = $batch->execute();
935 $this->purgeEverything();
938 // Now switch the object and repurge
939 $this->title
= $target;
940 unset( $this->name
);
941 $this->purgeEverything();
946 * Delete all versions of the file.
948 * Moves the files into an archive directory (or deletes them)
949 * and removes the database rows.
951 * Cache purging is done; logging is caller's responsibility.
955 * @return FileRepoStatus object.
957 function delete( $reason, $suppress = false ) {
959 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
960 $batch->addCurrent();
962 # Get old version relative paths
963 $dbw = $this->repo
->getMasterDB();
964 $result = $dbw->select( 'oldimage',
965 array( 'oi_archive_name' ),
966 array( 'oi_name' => $this->getName() ) );
967 while ( $row = $dbw->fetchObject( $result ) ) {
968 $batch->addOld( $row->oi_archive_name
);
970 $status = $batch->execute();
974 $site_stats = $dbw->tableName( 'site_stats' );
975 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
976 $this->purgeEverything();
984 * Delete an old version of the file.
986 * Moves the file into an archive directory (or deletes it)
987 * and removes the database row.
989 * Cache purging is done; logging is caller's responsibility.
993 * @throws MWException or FSException on database or filestore failure
994 * @return FileRepoStatus object.
996 function deleteOld( $archiveName, $reason, $suppress=false ) {
998 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
999 $batch->addOld( $archiveName );
1000 $status = $batch->execute();
1002 if ( $status->ok
) {
1003 $this->purgeDescription();
1004 $this->purgeHistory();
1010 * Restore all or specified deleted revisions to the given file.
1011 * Permissions and logging are left to the caller.
1013 * May throw database exceptions on error.
1015 * @param $versions set of record ids of deleted items to restore,
1016 * or empty to restore all revisions.
1018 * @return FileRepoStatus
1020 function restore( $versions = array(), $unsuppress = false ) {
1021 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1025 $batch->addIds( $versions );
1027 $status = $batch->execute();
1028 if ( !$status->ok
) {
1032 $cleanupStatus = $batch->cleanup();
1033 $cleanupStatus->successCount
= 0;
1034 $cleanupStatus->failCount
= 0;
1035 $status->merge( $cleanupStatus );
1039 /** isMultipage inherited */
1040 /** pageCount inherited */
1041 /** scaleHeight inherited */
1042 /** getImageSize inherited */
1045 * Get the URL of the file description page.
1047 function getDescriptionUrl() {
1048 return $this->title
->getLocalUrl();
1052 * Get the HTML text of the description page
1053 * This is not used by ImagePage for local files, since (among other things)
1054 * it skips the parser cache.
1056 function getDescriptionText() {
1058 $revision = Revision
::newFromTitle( $this->title
);
1059 if ( !$revision ) return false;
1060 $text = $revision->getText();
1061 if ( !$text ) return false;
1062 $html = $wgParser->parse( $text, new ParserOptions
);
1066 function getDescription() {
1068 return $this->description
;
1071 function getTimestamp() {
1073 return $this->timestamp
;
1076 function getSha1() {
1078 // Initialise now if necessary
1079 if ( $this->sha1
== '' && $this->fileExists
) {
1080 $this->sha1
= File
::sha1Base36( $this->getPath() );
1081 if ( strval( $this->sha1
) != '' ) {
1082 $dbw = $this->repo
->getMasterDB();
1083 $dbw->update( 'image',
1084 array( 'img_sha1' => $this->sha1
),
1085 array( 'img_name' => $this->getName() ),
1087 $this->saveToCache();
1095 * Start a transaction and lock the image for update
1096 * Increments a reference counter if the lock is already held
1097 * @return boolean True if the image exists, false otherwise
1100 $dbw = $this->repo
->getMasterDB();
1101 if ( !$this->locked
) {
1105 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1109 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1110 * the transaction and thereby releases the image lock.
1113 if ( $this->locked
) {
1115 if ( !$this->locked
) {
1116 $dbw = $this->repo
->getMasterDB();
1123 * Roll back the DB transaction and mark the image unlocked
1125 function unlockAndRollback() {
1126 $this->locked
= false;
1127 $dbw = $this->repo
->getMasterDB();
1130 } // LocalFile class
1132 #------------------------------------------------------------------------------
1135 * Helper class for file deletion
1137 class LocalFileDeleteBatch
{
1138 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1141 function __construct( File
$file, $reason = '', $suppress = false ) {
1142 $this->file
= $file;
1143 $this->reason
= $reason;
1144 $this->suppress
= $suppress;
1145 $this->status
= $file->repo
->newGood();
1148 function addCurrent() {
1149 $this->srcRels
['.'] = $this->file
->getRel();
1152 function addOld( $oldName ) {
1153 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1154 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1157 function getOldRels() {
1158 if ( !isset( $this->srcRels
['.'] ) ) {
1159 $oldRels =& $this->srcRels
;
1160 $deleteCurrent = false;
1162 $oldRels = $this->srcRels
;
1163 unset( $oldRels['.'] );
1164 $deleteCurrent = true;
1166 return array( $oldRels, $deleteCurrent );
1169 /*protected*/ function getHashes() {
1171 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1172 if ( $deleteCurrent ) {
1173 $hashes['.'] = $this->file
->getSha1();
1175 if ( count( $oldRels ) ) {
1176 $dbw = $this->file
->repo
->getMasterDB();
1177 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1178 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1180 while ( $row = $dbw->fetchObject( $res ) ) {
1181 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1182 // Get the hash from the file
1183 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1184 $props = $this->file
->repo
->getFileProps( $oldUrl );
1185 if ( $props['fileExists'] ) {
1186 // Upgrade the oldimage row
1187 $dbw->update( 'oldimage',
1188 array( 'oi_sha1' => $props['sha1'] ),
1189 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1191 $hashes[$row->oi_archive_name
] = $props['sha1'];
1193 $hashes[$row->oi_archive_name
] = false;
1196 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1200 $missing = array_diff_key( $this->srcRels
, $hashes );
1201 foreach ( $missing as $name => $rel ) {
1202 $this->status
->error( 'filedelete-old-unregistered', $name );
1204 foreach ( $hashes as $name => $hash ) {
1206 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1207 unset( $hashes[$name] );
1214 function doDBInserts() {
1216 $dbw = $this->file
->repo
->getMasterDB();
1217 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1218 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1219 $encReason = $dbw->addQuotes( $this->reason
);
1220 $encGroup = $dbw->addQuotes( 'deleted' );
1221 $ext = $this->file
->getExtension();
1222 $dotExt = $ext === '' ?
'' : ".$ext";
1223 $encExt = $dbw->addQuotes( $dotExt );
1224 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1226 // Bitfields to further suppress the content
1227 if ( $this->suppress
) {
1229 // This should be 15...
1230 $bitfield |
= Revision
::DELETED_TEXT
;
1231 $bitfield |
= Revision
::DELETED_COMMENT
;
1232 $bitfield |
= Revision
::DELETED_USER
;
1233 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1235 $bitfield = 'oi_deleted';
1238 if ( $deleteCurrent ) {
1239 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1240 $where = array( 'img_name' => $this->file
->getName() );
1241 $dbw->insertSelect( 'filearchive', 'image',
1243 'fa_storage_group' => $encGroup,
1244 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1245 'fa_deleted_user' => $encUserId,
1246 'fa_deleted_timestamp' => $encTimestamp,
1247 'fa_deleted_reason' => $encReason,
1248 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1250 'fa_name' => 'img_name',
1251 'fa_archive_name' => 'NULL',
1252 'fa_size' => 'img_size',
1253 'fa_width' => 'img_width',
1254 'fa_height' => 'img_height',
1255 'fa_metadata' => 'img_metadata',
1256 'fa_bits' => 'img_bits',
1257 'fa_media_type' => 'img_media_type',
1258 'fa_major_mime' => 'img_major_mime',
1259 'fa_minor_mime' => 'img_minor_mime',
1260 'fa_description' => 'img_description',
1261 'fa_user' => 'img_user',
1262 'fa_user_text' => 'img_user_text',
1263 'fa_timestamp' => 'img_timestamp'
1264 ), $where, __METHOD__
);
1267 if ( count( $oldRels ) ) {
1268 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1270 'oi_name' => $this->file
->getName(),
1271 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1272 $dbw->insertSelect( 'filearchive', 'oldimage',
1274 'fa_storage_group' => $encGroup,
1275 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1276 'fa_deleted_user' => $encUserId,
1277 'fa_deleted_timestamp' => $encTimestamp,
1278 'fa_deleted_reason' => $encReason,
1279 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1281 'fa_name' => 'oi_name',
1282 'fa_archive_name' => 'oi_archive_name',
1283 'fa_size' => 'oi_size',
1284 'fa_width' => 'oi_width',
1285 'fa_height' => 'oi_height',
1286 'fa_metadata' => 'oi_metadata',
1287 'fa_bits' => 'oi_bits',
1288 'fa_media_type' => 'oi_media_type',
1289 'fa_major_mime' => 'oi_major_mime',
1290 'fa_minor_mime' => 'oi_minor_mime',
1291 'fa_description' => 'oi_description',
1292 'fa_user' => 'oi_user',
1293 'fa_user_text' => 'oi_user_text',
1294 'fa_timestamp' => 'oi_timestamp',
1295 'fa_deleted' => $bitfield
1296 ), $where, __METHOD__
);
1300 function doDBDeletes() {
1301 $dbw = $this->file
->repo
->getMasterDB();
1302 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1303 if ( count( $oldRels ) ) {
1304 $dbw->delete( 'oldimage',
1306 'oi_name' => $this->file
->getName(),
1307 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1310 if ( $deleteCurrent ) {
1311 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1316 * Run the transaction
1318 function execute() {
1319 global $wgUser, $wgUseSquid;
1320 wfProfileIn( __METHOD__
);
1322 $this->file
->lock();
1323 // Leave private files alone
1324 $privateFiles = array();
1325 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1326 $dbw = $this->file
->repo
->getMasterDB();
1327 if( !empty( $oldRels ) ) {
1328 $res = $dbw->select( 'oldimage',
1329 array( 'oi_archive_name' ),
1330 array( 'oi_name' => $this->file
->getName(),
1331 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1332 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1334 while( $row = $dbw->fetchObject( $res ) ) {
1335 $privateFiles[$row->oi_archive_name
] = 1;
1338 // Prepare deletion batch
1339 $hashes = $this->getHashes();
1340 $this->deletionBatch
= array();
1341 $ext = $this->file
->getExtension();
1342 $dotExt = $ext === '' ?
'' : ".$ext";
1343 foreach ( $this->srcRels
as $name => $srcRel ) {
1344 // Skip files that have no hash (missing source).
1345 // Keep private files where they are.
1346 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1347 $hash = $hashes[$name];
1348 $key = $hash . $dotExt;
1349 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1350 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1354 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1355 // We acquire this lock by running the inserts now, before the file operations.
1357 // This potentially has poor lock contention characteristics -- an alternative
1358 // scheme would be to insert stub filearchive entries with no fa_name and commit
1359 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1360 $this->doDBInserts();
1362 // Execute the file deletion batch
1363 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1364 if ( !$status->isGood() ) {
1365 $this->status
->merge( $status );
1368 if ( !$this->status
->ok
) {
1369 // Critical file deletion error
1370 // Roll back inserts, release lock and abort
1371 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1372 $this->file
->unlockAndRollback();
1373 return $this->status
;
1377 if ( $wgUseSquid ) {
1379 foreach ( $this->srcRels
as $srcRel ) {
1380 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1381 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1383 SquidUpdate
::purge( $urls );
1386 // Delete image/oldimage rows
1387 $this->doDBDeletes();
1389 // Commit and return
1390 $this->file
->unlock();
1391 wfProfileOut( __METHOD__
);
1392 return $this->status
;
1396 #------------------------------------------------------------------------------
1399 * Helper class for file undeletion
1401 class LocalFileRestoreBatch
{
1402 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1404 function __construct( File
$file, $unsuppress = false ) {
1405 $this->file
= $file;
1406 $this->cleanupBatch
= $this->ids
= array();
1407 $this->ids
= array();
1408 $this->unsuppress
= $unsuppress;
1414 function addId( $fa_id ) {
1415 $this->ids
[] = $fa_id;
1419 * Add a whole lot of files by ID
1421 function addIds( $ids ) {
1422 $this->ids
= array_merge( $this->ids
, $ids );
1426 * Add all revisions of the file
1433 * Run the transaction, except the cleanup batch.
1434 * The cleanup batch should be run in a separate transaction, because it locks different
1435 * rows and there's no need to keep the image row locked while it's acquiring those locks
1436 * The caller may have its own transaction open.
1437 * So we save the batch and let the caller call cleanup()
1439 function execute() {
1440 global $wgUser, $wgLang;
1441 if ( !$this->all
&& !$this->ids
) {
1443 return $this->file
->repo
->newGood();
1446 $exists = $this->file
->lock();
1447 $dbw = $this->file
->repo
->getMasterDB();
1448 $status = $this->file
->repo
->newGood();
1450 // Fetch all or selected archived revisions for the file,
1451 // sorted from the most recent to the oldest.
1452 $conditions = array( 'fa_name' => $this->file
->getName() );
1454 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1457 $result = $dbw->select( 'filearchive', '*',
1460 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1462 $idsPresent = array();
1463 $storeBatch = array();
1464 $insertBatch = array();
1465 $insertCurrent = false;
1466 $deleteIds = array();
1468 $archiveNames = array();
1469 while( $row = $dbw->fetchObject( $result ) ) {
1470 $idsPresent[] = $row->fa_id
;
1472 if ( $row->fa_name
!= $this->file
->getName() ) {
1473 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1474 $status->failCount++
;
1477 if ( $row->fa_storage_key
== '' ) {
1478 // Revision was missing pre-deletion
1479 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1480 $status->failCount++
;
1484 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1485 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1487 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1489 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1490 $sha1 = substr( $sha1, 1 );
1493 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1494 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1495 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1496 ||
is_null( $row->fa_metadata
) ) {
1497 // Refresh our metadata
1498 // Required for a new current revision; nice for older ones too. :)
1499 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1502 'minor_mime' => $row->fa_minor_mime
,
1503 'major_mime' => $row->fa_major_mime
,
1504 'media_type' => $row->fa_media_type
,
1505 'metadata' => $row->fa_metadata
);
1508 if ( $first && !$exists ) {
1509 // The live (current) version cannot be hidden!
1510 if( !$this->unsuppress
&& $row->fa_deleted
) {
1511 $this->file
->unlock();
1514 // This revision will be published as the new current version
1515 $destRel = $this->file
->getRel();
1516 $insertCurrent = array(
1517 'img_name' => $row->fa_name
,
1518 'img_size' => $row->fa_size
,
1519 'img_width' => $row->fa_width
,
1520 'img_height' => $row->fa_height
,
1521 'img_metadata' => $props['metadata'],
1522 'img_bits' => $row->fa_bits
,
1523 'img_media_type' => $props['media_type'],
1524 'img_major_mime' => $props['major_mime'],
1525 'img_minor_mime' => $props['minor_mime'],
1526 'img_description' => $row->fa_description
,
1527 'img_user' => $row->fa_user
,
1528 'img_user_text' => $row->fa_user_text
,
1529 'img_timestamp' => $row->fa_timestamp
,
1530 'img_sha1' => $sha1);
1532 $archiveName = $row->fa_archive_name
;
1533 if( $archiveName == '' ) {
1534 // This was originally a current version; we
1535 // have to devise a new archive name for it.
1536 // Format is <timestamp of archiving>!<name>
1537 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1539 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1541 } while ( isset( $archiveNames[$archiveName] ) );
1543 $archiveNames[$archiveName] = true;
1544 $destRel = $this->file
->getArchiveRel( $archiveName );
1545 $insertBatch[] = array(
1546 'oi_name' => $row->fa_name
,
1547 'oi_archive_name' => $archiveName,
1548 'oi_size' => $row->fa_size
,
1549 'oi_width' => $row->fa_width
,
1550 'oi_height' => $row->fa_height
,
1551 'oi_bits' => $row->fa_bits
,
1552 'oi_description' => $row->fa_description
,
1553 'oi_user' => $row->fa_user
,
1554 'oi_user_text' => $row->fa_user_text
,
1555 'oi_timestamp' => $row->fa_timestamp
,
1556 'oi_metadata' => $props['metadata'],
1557 'oi_media_type' => $props['media_type'],
1558 'oi_major_mime' => $props['major_mime'],
1559 'oi_minor_mime' => $props['minor_mime'],
1560 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1561 'oi_sha1' => $sha1 );
1564 $deleteIds[] = $row->fa_id
;
1565 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1566 // private files can stay where they are
1568 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1569 $this->cleanupBatch
[] = $row->fa_storage_key
;
1575 // Add a warning to the status object for missing IDs
1576 $missingIds = array_diff( $this->ids
, $idsPresent );
1577 foreach ( $missingIds as $id ) {
1578 $status->error( 'undelete-missing-filearchive', $id );
1581 // Run the store batch
1582 // Use the OVERWRITE_SAME flag to smooth over a common error
1583 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1584 $status->merge( $storeStatus );
1586 if ( !$status->ok
) {
1587 // Store batch returned a critical error -- this usually means nothing was stored
1588 // Stop now and return an error
1589 $this->file
->unlock();
1593 // Run the DB updates
1594 // Because we have locked the image row, key conflicts should be rare.
1595 // If they do occur, we can roll back the transaction at this time with
1596 // no data loss, but leaving unregistered files scattered throughout the
1598 // This is not ideal, which is why it's important to lock the image row.
1599 if ( $insertCurrent ) {
1600 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1602 if ( $insertBatch ) {
1603 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1606 $dbw->delete( 'filearchive',
1607 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1611 if( $status->successCount
> 0 ) {
1613 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1615 // Update site_stats
1616 $site_stats = $dbw->tableName( 'site_stats' );
1617 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1619 $this->file
->purgeEverything();
1621 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1622 $this->file
->purgeDescription();
1623 $this->file
->purgeHistory();
1626 $this->file
->unlock();
1631 * Delete unused files in the deleted zone.
1632 * This should be called from outside the transaction in which execute() was called.
1634 function cleanup() {
1635 if ( !$this->cleanupBatch
) {
1636 return $this->file
->repo
->newGood();
1638 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1643 #------------------------------------------------------------------------------
1646 * Helper class for file movement
1648 class LocalFileMoveBatch
{
1649 var $file, $cur, $olds, $archive, $thumbs, $target, $db;
1651 function __construct( File
$file, Title
$target, Database
$db ) {
1652 $this->file
= $file;
1653 $this->target
= $target;
1654 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1655 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDbKey() );
1656 $this->oldName
= $this->file
->getName();
1657 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1658 $this->oldRel
= $this->oldHash
. $this->oldName
;
1659 $this->newRel
= $this->newHash
. $this->newName
;
1663 function addCurrent() {
1664 $this->cur
= array( $this->oldRel
, $this->newRel
);
1667 function addThumbs() {
1668 $this->thumbs
= array();
1669 $repo = $this->file
->repo
;
1670 $thumbDirRel = 'thumb/' . $this->oldRel
;
1671 $thumbDir = $repo->getZonePath( 'public' ) . '/' . $thumbDirRel;
1672 $newThumbDirRel = 'thumb/' . $this->newRel
;
1673 if( !is_dir( $thumbDir ) ||
!is_readable( $thumbDir ) ) {
1674 $this->thumbs
= array();
1677 $files = scandir( $thumbDir );
1678 foreach( $files as $file ) {
1679 if( $file == '.' ||
$file == '..' ) continue;
1680 if( preg_match( '/^(\d+)px-/', $file, $matches ) ) {
1681 list( $unused, $width ) = $matches;
1682 $this->thumbs
[] = array(
1683 $thumbDirRel . '/' . $file,
1684 $newThumbDirRel . '/' . $width . 'px-' . $this->newName
1687 wfDebug( 'Strange file in thumbnail directory: ' . $thumbDirRel . '/' . $file );
1693 function addOlds() {
1694 $archiveBase = 'archive';
1695 $this->olds
= array();
1697 $result = $this->db
->select( 'oldimage',
1698 array( 'oi_archive_name' ),
1699 array( 'oi_name' => $this->oldName
),
1702 while( $row = $this->db
->fetchObject( $result ) ) {
1703 $oldname = $row->oi_archive_name
;
1704 $bits = explode( '!', $oldname, 2 );
1705 if( count( $bits ) != 2 ) {
1706 wfDebug( 'Invalid old file name: ' . $oldname );
1709 list( $timestamp, $filename ) = $bits;
1710 if( $this->oldName
!= $filename ) {
1711 wfDebug( 'Invalid old file name:' . $oldName );
1714 $this->olds
[] = array(
1715 "{$archiveBase}/{$this->oldHash}{$oldname}",
1716 "{$archiveBase}/{$this->oldHash}{$timestamp}!{$this->newName}"
1719 $this->db
->freeResult( $result );
1722 function execute() {
1723 $repo = $this->file
->repo
;
1724 $status = $repo->newGood();
1725 $triplets = $this->getMoveTriplets();
1727 $statusDb = $this->doDBUpdates();
1728 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1729 if( !$statusMove->isOk() ) {
1730 $this->db
->rollback();
1732 $status->merge( $statusDb );
1733 $status->merge( $statusMove );
1737 function doDBUpdates() {
1738 $repo = $this->file
->repo
;
1739 $status = $repo->newGood();
1742 // Update current image
1745 array( 'img_name' => $this->newName
),
1746 array( 'img_name' => $this->oldName
),
1749 if( $dbw->affectedRows() ) {
1750 $status->successCount++
;
1752 $status->failCount++
;
1755 // Update old images
1759 'oi_name' => $this->newName
,
1760 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1762 array( 'oi_name' => $this->oldName
),
1765 $affected = $dbw->affectedRows();
1766 $total = count( $this->olds
);
1767 $status->successCount +
= $affected;
1768 $status->failCount +
= $total - $affected;
1770 // Update deleted images
1774 'fa_name' => $this->newName
,
1775 'fa_archive_name = ' . $dbw->strreplace( 'fa_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1777 array( 'fa_name' => $this->oldName
),
1780 $affected = $dbw->affectedRows();
1781 $total = count( $this->olds
);
1782 $status->successCount +
= $affected;
1783 $status->failCount +
= $total - $affected;
1788 // Generates triplets for FSRepo::storeBatch()
1789 function getMoveTriplets() {
1790 $moves = array_merge( array( $this->cur
), $this->olds
, $this->thumbs
);
1791 $triplets = array(); // The format is: (srcUrl,destZone,desrUrl)
1792 foreach( $moves as $move ) {
1793 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1794 $triplets[] = array( $srcUrl, 'public', $move[1] );