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 * Create a LocalFile from a SHA-1 key
79 * Do not call this except from inside a repo class.
81 static function newFromKey( $sha1, $repo, $timestamp = false ) {
82 # Polymorphic function name to distinguish foreign and local fetches
83 $fname = get_class( $this ) . '::' . __FUNCTION__
;
85 $conds = array( 'img_sha1' => $sha1 );
87 $conds['img_timestamp'] = $timestamp;
89 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), $conds, $fname );
91 return self
::newFromRow( $row, $repo );
98 * Fields in the image table
100 static function selectFields() {
121 * Do not call this except from inside a repo class.
123 function __construct( $title, $repo ) {
124 if( !is_object( $title ) ) {
125 throw new MWException( __CLASS__
.' constructor given bogus title.' );
127 parent
::__construct( $title, $repo );
128 $this->metadata
= '';
129 $this->historyLine
= 0;
130 $this->historyRes
= null;
131 $this->dataLoaded
= false;
135 * Get the memcached key
137 function getCacheKey() {
138 $hashedName = md5($this->getName());
139 return wfMemcKey( 'file', $hashedName );
143 * Try to load file metadata from memcached. Returns true on success.
145 function loadFromCache() {
147 wfProfileIn( __METHOD__
);
148 $this->dataLoaded
= false;
149 $key = $this->getCacheKey();
153 $cachedValues = $wgMemc->get( $key );
155 // Check if the key existed and belongs to this version of MediaWiki
156 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
157 wfDebug( "Pulling file metadata from cache key $key\n" );
158 $this->fileExists
= $cachedValues['fileExists'];
159 if ( $this->fileExists
) {
160 $this->setProps( $cachedValues );
162 $this->dataLoaded
= true;
164 if ( $this->dataLoaded
) {
165 wfIncrStats( 'image_cache_hit' );
167 wfIncrStats( 'image_cache_miss' );
170 wfProfileOut( __METHOD__
);
171 return $this->dataLoaded
;
175 * Save the file metadata to memcached
177 function saveToCache() {
180 $key = $this->getCacheKey();
184 $fields = $this->getCacheFields( '' );
185 $cache = array( 'version' => MW_FILE_VERSION
);
186 $cache['fileExists'] = $this->fileExists
;
187 if ( $this->fileExists
) {
188 foreach ( $fields as $field ) {
189 $cache[$field] = $this->$field;
193 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
197 * Load metadata from the file itself
199 function loadFromFile() {
200 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
203 function getCacheFields( $prefix = 'img_' ) {
204 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
205 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
206 static $results = array();
207 if ( $prefix == '' ) {
210 if ( !isset( $results[$prefix] ) ) {
211 $prefixedFields = array();
212 foreach ( $fields as $field ) {
213 $prefixedFields[] = $prefix . $field;
215 $results[$prefix] = $prefixedFields;
217 return $results[$prefix];
221 * Load file metadata from the DB
223 function loadFromDB() {
224 # Polymorphic function name to distinguish foreign and local fetches
225 $fname = get_class( $this ) . '::' . __FUNCTION__
;
226 wfProfileIn( $fname );
228 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
229 $this->dataLoaded
= true;
231 $dbr = $this->repo
->getMasterDB();
233 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
234 array( 'img_name' => $this->getName() ), $fname );
236 $this->loadFromRow( $row );
238 $this->fileExists
= false;
241 wfProfileOut( $fname );
245 * Decode a row from the database (either object or array) to an array
246 * with timestamps and MIME types decoded, and the field prefix removed.
248 function decodeRow( $row, $prefix = 'img_' ) {
249 $array = (array)$row;
250 $prefixLength = strlen( $prefix );
251 // Sanity check prefix once
252 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
253 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
256 foreach ( $array as $name => $value ) {
257 $decoded[substr( $name, $prefixLength )] = $value;
259 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
260 if ( empty( $decoded['major_mime'] ) ) {
261 $decoded['mime'] = "unknown/unknown";
263 if (!$decoded['minor_mime']) {
264 $decoded['minor_mime'] = "unknown";
266 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
268 # Trim zero padding from char/binary field
269 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
274 * Load file metadata from a DB result row
276 function loadFromRow( $row, $prefix = 'img_' ) {
277 $this->dataLoaded
= true;
278 $array = $this->decodeRow( $row, $prefix );
279 foreach ( $array as $name => $value ) {
280 $this->$name = $value;
282 $this->fileExists
= true;
283 $this->maybeUpgradeRow();
287 * Load file metadata from cache or DB, unless already loaded
290 if ( !$this->dataLoaded
) {
291 if ( !$this->loadFromCache() ) {
293 $this->saveToCache();
295 $this->dataLoaded
= true;
300 * Upgrade a row if it needs it
302 function maybeUpgradeRow() {
303 if ( wfReadOnly() ) {
306 if ( is_null($this->media_type
) ||
307 $this->mime
== 'image/svg'
310 $this->upgraded
= true;
312 $handler = $this->getHandler();
313 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
315 $this->upgraded
= true;
320 function getUpgraded() {
321 return $this->upgraded
;
325 * Fix assorted version-related problems with the image row by reloading it from the file
327 function upgradeRow() {
328 wfProfileIn( __METHOD__
);
330 $this->loadFromFile();
332 # Don't destroy file info of missing files
333 if ( !$this->fileExists
) {
334 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
337 $dbw = $this->repo
->getMasterDB();
338 list( $major, $minor ) = self
::splitMime( $this->mime
);
340 if ( wfReadOnly() ) {
343 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
345 $dbw->update( 'image',
347 'img_width' => $this->width
,
348 'img_height' => $this->height
,
349 'img_bits' => $this->bits
,
350 'img_media_type' => $this->media_type
,
351 'img_major_mime' => $major,
352 'img_minor_mime' => $minor,
353 'img_metadata' => $this->metadata
,
354 'img_sha1' => $this->sha1
,
355 ), array( 'img_name' => $this->getName() ),
358 $this->saveToCache();
359 wfProfileOut( __METHOD__
);
363 * Set properties in this object to be equal to those given in the
364 * associative array $info. Only cacheable fields can be set.
366 * If 'mime' is given, it will be split into major_mime/minor_mime.
367 * If major_mime/minor_mime are given, $this->mime will also be set.
369 function setProps( $info ) {
370 $this->dataLoaded
= true;
371 $fields = $this->getCacheFields( '' );
372 $fields[] = 'fileExists';
373 foreach ( $fields as $field ) {
374 if ( isset( $info[$field] ) ) {
375 $this->$field = $info[$field];
378 // Fix up mime fields
379 if ( isset( $info['major_mime'] ) ) {
380 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
381 } elseif ( isset( $info['mime'] ) ) {
382 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
386 /** splitMime inherited */
387 /** getName inherited */
388 /** getTitle inherited */
389 /** getURL inherited */
390 /** getViewURL inherited */
391 /** getPath inherited */
392 /** isVisible inhereted */
395 * Return the width of the image
397 * Returns false on error
400 function getWidth( $page = 1 ) {
402 if ( $this->isMultipage() ) {
403 $dim = $this->getHandler()->getPageDimensions( $this, $page );
405 return $dim['width'];
415 * Return the height of the image
417 * Returns false on error
420 function getHeight( $page = 1 ) {
422 if ( $this->isMultipage() ) {
423 $dim = $this->getHandler()->getPageDimensions( $this, $page );
425 return $dim['height'];
430 return $this->height
;
435 * Returns ID or name of user who uploaded the file
437 * @param $type string 'text' or 'id'
439 function getUser($type='text') {
441 if( $type == 'text' ) {
442 return $this->user_text
;
443 } elseif( $type == 'id' ) {
449 * Get handler-specific metadata
451 function getMetadata() {
453 return $this->metadata
;
457 * Return the size of the image file, in bytes
466 * Returns the mime type of the file.
468 function getMimeType() {
474 * Return the type of the media in the file.
475 * Use the value returned by this function with the MEDIATYPE_xxx constants.
477 function getMediaType() {
479 return $this->media_type
;
482 /** canRender inherited */
483 /** mustRender inherited */
484 /** allowInlineDisplay inherited */
485 /** isSafeFile inherited */
486 /** isTrustedFile inherited */
489 * Returns true if the file file exists on disk.
490 * @return boolean Whether file file exist on disk.
495 return $this->fileExists
;
498 /** getTransformScript inherited */
499 /** getUnscaledThumb inherited */
500 /** thumbName inherited */
501 /** createThumb inherited */
502 /** getThumbnail inherited */
503 /** transform inherited */
506 * Fix thumbnail files from 1.4 or before, with extreme prejudice
508 function migrateThumbFile( $thumbName ) {
509 $thumbDir = $this->getThumbPath();
510 $thumbPath = "$thumbDir/$thumbName";
511 if ( is_dir( $thumbPath ) ) {
512 // Directory where file should be
513 // This happened occasionally due to broken migration code in 1.5
514 // Rename to broken-*
515 for ( $i = 0; $i < 100 ; $i++
) {
516 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
517 if ( !file_exists( $broken ) ) {
518 rename( $thumbPath, $broken );
522 // Doesn't exist anymore
525 if ( is_file( $thumbDir ) ) {
526 // File where directory should be
528 // Doesn't exist anymore
533 /** getHandler inherited */
534 /** iconThumb inherited */
535 /** getLastError inherited */
538 * Get all thumbnail names previously generated for this file
540 function getThumbnails() {
543 $dir = $this->getThumbPath();
545 if ( is_dir( $dir ) ) {
546 $handle = opendir( $dir );
549 while ( false !== ( $file = readdir($handle) ) ) {
550 if ( $file{0} != '.' ) {
562 * Refresh metadata in memcached, but don't touch thumbnails or squid
564 function purgeMetadataCache() {
566 $this->saveToCache();
567 $this->purgeHistory();
571 * Purge the shared history (OldLocalFile) cache
573 function purgeHistory() {
575 $hashedName = md5($this->getName());
576 $oldKey = wfMemcKey( 'oldfile', $hashedName );
577 $wgMemc->delete( $oldKey );
581 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
583 function purgeCache() {
584 // Refresh metadata cache
585 $this->purgeMetadataCache();
588 $this->purgeThumbnails();
590 // Purge squid cache for this file
591 SquidUpdate
::purge( array( $this->getURL() ) );
595 * Delete cached transformed files
597 function purgeThumbnails() {
600 $files = $this->getThumbnails();
601 $dir = $this->getThumbPath();
603 foreach ( $files as $file ) {
604 # Check that the base file name is part of the thumb name
605 # This is a basic sanity check to avoid erasing unrelated directories
606 if ( strpos( $file, $this->getName() ) !== false ) {
607 $url = $this->getThumbUrl( $file );
609 @unlink
( "$dir/$file" );
615 SquidUpdate
::purge( $urls );
619 /** purgeDescription inherited */
620 /** purgeEverything inherited */
622 function getHistory($limit = null, $start = null, $end = null) {
623 $dbr = $this->repo
->getSlaveDB();
624 $conds = $opts = array();
625 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
626 if( $start !== null ) {
627 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
629 if( $end !== null ) {
630 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
633 $opts['LIMIT'] = $limit;
635 $opts['ORDER BY'] = 'oi_timestamp DESC';
636 $res = $dbr->select('oldimage', '*', $conds, __METHOD__
, $opts);
638 while( $row = $dbr->fetchObject($res) ) {
639 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
645 * Return the history of this file, line by line.
646 * starts with current version, then old versions.
647 * uses $this->historyLine to check which line to return:
648 * 0 return line for current version
649 * 1 query for old versions, return first one
650 * 2, ... return next old version from above query
654 function nextHistoryLine() {
655 # Polymorphic function name to distinguish foreign and local fetches
656 $fname = get_class( $this ) . '::' . __FUNCTION__
;
658 $dbr = $this->repo
->getSlaveDB();
660 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
661 $this->historyRes
= $dbr->select( 'image',
664 "'' AS oi_archive_name",
668 array( 'img_name' => $this->title
->getDBkey() ),
671 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
672 $dbr->freeResult($this->historyRes
);
673 $this->historyRes
= null;
676 } else if ( $this->historyLine
== 1 ) {
677 $dbr->freeResult($this->historyRes
);
678 $this->historyRes
= $dbr->select( 'oldimage', '*',
679 array( 'oi_name' => $this->title
->getDBkey() ),
681 array( 'ORDER BY' => 'oi_timestamp DESC' )
684 $this->historyLine ++
;
686 return $dbr->fetchObject( $this->historyRes
);
690 * Reset the history pointer to the first element of the history
693 function resetHistory() {
694 $this->historyLine
= 0;
695 if (!is_null($this->historyRes
)) {
696 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
697 $this->historyRes
= null;
701 /** getFullPath inherited */
702 /** getHashPath inherited */
703 /** getRel inherited */
704 /** getUrlRel inherited */
705 /** getArchiveRel inherited */
706 /** getThumbRel inherited */
707 /** getArchivePath inherited */
708 /** getThumbPath inherited */
709 /** getArchiveUrl inherited */
710 /** getThumbUrl inherited */
711 /** getArchiveVirtualUrl inherited */
712 /** getThumbVirtualUrl inherited */
713 /** isHashed inherited */
716 * Upload a file and record it in the DB
717 * @param string $srcPath Source path or virtual URL
718 * @param string $comment Upload description
719 * @param string $pageText Text to use for the new description page, if a new description page is created
720 * @param integer $flags Flags for publish()
721 * @param array $props File properties, if known. This can be used to reduce the
722 * upload time when uploading virtual URLs for which the file info
724 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
726 * @return FileRepoStatus object. On success, the value member contains the
727 * archive name, or an empty string if it was a new file.
729 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
731 $status = $this->publish( $srcPath, $flags );
733 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
734 $status->fatal( 'filenotfound', $srcPath );
742 * Record a file upload in the upload log and the image table
743 * @deprecated use upload()
745 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
746 $watch = false, $timestamp = false )
748 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
749 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
754 $wgUser->addWatch( $this->getTitle() );
761 * Record a file upload in the upload log and the image table
763 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
767 $dbw = $this->repo
->getMasterDB();
770 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
772 $props['description'] = $comment;
773 $props['user'] = $wgUser->getID();
774 $props['user_text'] = $wgUser->getName();
775 $props['timestamp'] = wfTimestamp( TS_MW
);
776 $this->setProps( $props );
778 // Delete thumbnails and refresh the metadata cache
779 $this->purgeThumbnails();
780 $this->saveToCache();
781 SquidUpdate
::purge( array( $this->getURL() ) );
783 // Fail now if the file isn't there
784 if ( !$this->fileExists
) {
785 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
790 if ( $timestamp === false ) {
791 $timestamp = $dbw->timestamp();
794 # Test to see if the row exists using INSERT IGNORE
795 # This avoids race conditions by locking the row until the commit, and also
796 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
797 $dbw->insert( 'image',
799 'img_name' => $this->getName(),
800 'img_size'=> $this->size
,
801 'img_width' => intval( $this->width
),
802 'img_height' => intval( $this->height
),
803 'img_bits' => $this->bits
,
804 'img_media_type' => $this->media_type
,
805 'img_major_mime' => $this->major_mime
,
806 'img_minor_mime' => $this->minor_mime
,
807 'img_timestamp' => $timestamp,
808 'img_description' => $comment,
809 'img_user' => $wgUser->getID(),
810 'img_user_text' => $wgUser->getName(),
811 'img_metadata' => $this->metadata
,
812 'img_sha1' => $this->sha1
818 if( $dbw->affectedRows() == 0 ) {
821 # Collision, this is an update of a file
822 # Insert previous contents into oldimage
823 $dbw->insertSelect( 'oldimage', 'image',
825 'oi_name' => 'img_name',
826 'oi_archive_name' => $dbw->addQuotes( $oldver ),
827 'oi_size' => 'img_size',
828 'oi_width' => 'img_width',
829 'oi_height' => 'img_height',
830 'oi_bits' => 'img_bits',
831 'oi_timestamp' => 'img_timestamp',
832 'oi_description' => 'img_description',
833 'oi_user' => 'img_user',
834 'oi_user_text' => 'img_user_text',
835 'oi_metadata' => 'img_metadata',
836 'oi_media_type' => 'img_media_type',
837 'oi_major_mime' => 'img_major_mime',
838 'oi_minor_mime' => 'img_minor_mime',
839 'oi_sha1' => 'img_sha1'
840 ), array( 'img_name' => $this->getName() ), __METHOD__
843 # Update the current image row
844 $dbw->update( 'image',
846 'img_size' => $this->size
,
847 'img_width' => intval( $this->width
),
848 'img_height' => intval( $this->height
),
849 'img_bits' => $this->bits
,
850 'img_media_type' => $this->media_type
,
851 'img_major_mime' => $this->major_mime
,
852 'img_minor_mime' => $this->minor_mime
,
853 'img_timestamp' => $timestamp,
854 'img_description' => $comment,
855 'img_user' => $wgUser->getID(),
856 'img_user_text' => $wgUser->getName(),
857 'img_metadata' => $this->metadata
,
858 'img_sha1' => $this->sha1
859 ), array( /* WHERE */
860 'img_name' => $this->getName()
865 # Update the image count
866 $site_stats = $dbw->tableName( 'site_stats' );
867 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
870 $descTitle = $this->getTitle();
871 $article = new Article( $descTitle );
874 $log = new LogPage( 'upload' );
875 $action = $reupload ?
'overwrite' : 'upload';
876 $log->addEntry( $action, $descTitle, $comment );
878 if( $descTitle->exists() ) {
879 # Create a null revision
880 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
881 $nullRevision->insertOn( $dbw );
882 wfRunHooks( 'newRevisionFromEditComplete', array($descTitle, $nullRevision, false) );
883 $article->updateRevisionOn( $dbw, $nullRevision );
885 # Invalidate the cache for the description page
886 $descTitle->invalidateCache();
887 $descTitle->purgeSquid();
889 // New file; create the description page.
890 // There's already a log entry, so don't make a second RC entry
891 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
894 # Hooks, hooks, the magic of hooks...
895 wfRunHooks( 'FileUpload', array( $this ) );
897 # Commit the transaction now, in case something goes wrong later
898 # The most important thing is that files don't get lost, especially archives
899 $dbw->immediateCommit();
901 # Invalidate cache for all pages using this file
902 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
904 # Invalidate cache for all pages that redirects on this page
905 $redirs = $this->getTitle()->getRedirectsHere();
906 foreach( $redirs as $redir ) {
907 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
915 * Move or copy a file to its public location. If a file exists at the
916 * destination, move it to an archive. Returns the archive name on success
917 * or an empty string if it was a new file, and a wikitext-formatted
918 * WikiError object on failure.
920 * The archive name should be passed through to recordUpload for database
923 * @param string $sourcePath Local filesystem path to the source image
924 * @param integer $flags A bitwise combination of:
925 * File::DELETE_SOURCE Delete the source file, i.e. move
927 * @return FileRepoStatus object. On success, the value member contains the
928 * archive name, or an empty string if it was a new file.
930 function publish( $srcPath, $flags = 0 ) {
932 $dstRel = $this->getRel();
933 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
934 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
935 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
936 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
937 if ( $status->value
== 'new' ) {
940 $status->value
= $archiveName;
946 /** getLinksTo inherited */
947 /** getExifData inherited */
948 /** isLocal inherited */
949 /** wasDeleted inherited */
952 * Move file to the new title
954 * Move current, old version and all thumbnails
955 * to the new filename. Old file is deleted.
957 * Cache purging is done; checks for validity
958 * and logging are caller's responsibility
960 * @param $target Title New file name
961 * @return FileRepoStatus object.
963 function move( $target ) {
965 $dbw = $this->repo
->getMasterDB();
966 $batch = new LocalFileMoveBatch( $this, $target, $dbw );
967 $batch->addCurrent();
969 if( !$this->repo
->canTransformVia404() ) {
973 $status = $batch->execute();
974 $this->purgeEverything();
977 if ( $status->isOk() ) {
978 // Now switch the object
979 $this->title
= $target;
980 // Force regeneration of the name and hashpath
981 unset( $this->name
);
982 unset( $this->hashPath
);
983 // Purge the new image
984 $this->purgeEverything();
991 * Delete all versions of the file.
993 * Moves the files into an archive directory (or deletes them)
994 * and removes the database rows.
996 * Cache purging is done; logging is caller's responsibility.
1000 * @return FileRepoStatus object.
1002 function delete( $reason, $suppress = false ) {
1004 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1005 $batch->addCurrent();
1007 # Get old version relative paths
1008 $dbw = $this->repo
->getMasterDB();
1009 $result = $dbw->select( 'oldimage',
1010 array( 'oi_archive_name' ),
1011 array( 'oi_name' => $this->getName() ) );
1012 while ( $row = $dbw->fetchObject( $result ) ) {
1013 $batch->addOld( $row->oi_archive_name
);
1015 $status = $batch->execute();
1017 if ( $status->ok
) {
1018 // Update site_stats
1019 $site_stats = $dbw->tableName( 'site_stats' );
1020 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1021 $this->purgeEverything();
1029 * Delete an old version of the file.
1031 * Moves the file into an archive directory (or deletes it)
1032 * and removes the database row.
1034 * Cache purging is done; logging is caller's responsibility.
1038 * @throws MWException or FSException on database or filestore failure
1039 * @return FileRepoStatus object.
1041 function deleteOld( $archiveName, $reason, $suppress=false ) {
1043 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1044 $batch->addOld( $archiveName );
1045 $status = $batch->execute();
1047 if ( $status->ok
) {
1048 $this->purgeDescription();
1049 $this->purgeHistory();
1055 * Restore all or specified deleted revisions to the given file.
1056 * Permissions and logging are left to the caller.
1058 * May throw database exceptions on error.
1060 * @param $versions set of record ids of deleted items to restore,
1061 * or empty to restore all revisions.
1063 * @return FileRepoStatus
1065 function restore( $versions = array(), $unsuppress = false ) {
1066 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1070 $batch->addIds( $versions );
1072 $status = $batch->execute();
1073 if ( !$status->ok
) {
1077 $cleanupStatus = $batch->cleanup();
1078 $cleanupStatus->successCount
= 0;
1079 $cleanupStatus->failCount
= 0;
1080 $status->merge( $cleanupStatus );
1084 /** isMultipage inherited */
1085 /** pageCount inherited */
1086 /** scaleHeight inherited */
1087 /** getImageSize inherited */
1090 * Get the URL of the file description page.
1092 function getDescriptionUrl() {
1093 return $this->title
->getLocalUrl();
1097 * Get the HTML text of the description page
1098 * This is not used by ImagePage for local files, since (among other things)
1099 * it skips the parser cache.
1101 function getDescriptionText() {
1103 $revision = Revision
::newFromTitle( $this->title
);
1104 if ( !$revision ) return false;
1105 $text = $revision->getText();
1106 if ( !$text ) return false;
1107 $html = $wgParser->parse( $text, new ParserOptions
);
1111 function getDescription() {
1113 return $this->description
;
1116 function getTimestamp() {
1118 return $this->timestamp
;
1121 function getSha1() {
1123 // Initialise now if necessary
1124 if ( $this->sha1
== '' && $this->fileExists
) {
1125 $this->sha1
= File
::sha1Base36( $this->getPath() );
1126 if ( strval( $this->sha1
) != '' ) {
1127 $dbw = $this->repo
->getMasterDB();
1128 $dbw->update( 'image',
1129 array( 'img_sha1' => $this->sha1
),
1130 array( 'img_name' => $this->getName() ),
1132 $this->saveToCache();
1140 * Start a transaction and lock the image for update
1141 * Increments a reference counter if the lock is already held
1142 * @return boolean True if the image exists, false otherwise
1145 $dbw = $this->repo
->getMasterDB();
1146 if ( !$this->locked
) {
1150 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1154 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1155 * the transaction and thereby releases the image lock.
1158 if ( $this->locked
) {
1160 if ( !$this->locked
) {
1161 $dbw = $this->repo
->getMasterDB();
1168 * Roll back the DB transaction and mark the image unlocked
1170 function unlockAndRollback() {
1171 $this->locked
= false;
1172 $dbw = $this->repo
->getMasterDB();
1175 } // LocalFile class
1177 #------------------------------------------------------------------------------
1180 * Helper class for file deletion
1182 class LocalFileDeleteBatch
{
1183 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1186 function __construct( File
$file, $reason = '', $suppress = false ) {
1187 $this->file
= $file;
1188 $this->reason
= $reason;
1189 $this->suppress
= $suppress;
1190 $this->status
= $file->repo
->newGood();
1193 function addCurrent() {
1194 $this->srcRels
['.'] = $this->file
->getRel();
1197 function addOld( $oldName ) {
1198 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1199 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1202 function getOldRels() {
1203 if ( !isset( $this->srcRels
['.'] ) ) {
1204 $oldRels =& $this->srcRels
;
1205 $deleteCurrent = false;
1207 $oldRels = $this->srcRels
;
1208 unset( $oldRels['.'] );
1209 $deleteCurrent = true;
1211 return array( $oldRels, $deleteCurrent );
1214 /*protected*/ function getHashes() {
1216 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1217 if ( $deleteCurrent ) {
1218 $hashes['.'] = $this->file
->getSha1();
1220 if ( count( $oldRels ) ) {
1221 $dbw = $this->file
->repo
->getMasterDB();
1222 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1223 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1225 while ( $row = $dbw->fetchObject( $res ) ) {
1226 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1227 // Get the hash from the file
1228 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1229 $props = $this->file
->repo
->getFileProps( $oldUrl );
1230 if ( $props['fileExists'] ) {
1231 // Upgrade the oldimage row
1232 $dbw->update( 'oldimage',
1233 array( 'oi_sha1' => $props['sha1'] ),
1234 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1236 $hashes[$row->oi_archive_name
] = $props['sha1'];
1238 $hashes[$row->oi_archive_name
] = false;
1241 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1245 $missing = array_diff_key( $this->srcRels
, $hashes );
1246 foreach ( $missing as $name => $rel ) {
1247 $this->status
->error( 'filedelete-old-unregistered', $name );
1249 foreach ( $hashes as $name => $hash ) {
1251 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1252 unset( $hashes[$name] );
1259 function doDBInserts() {
1261 $dbw = $this->file
->repo
->getMasterDB();
1262 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1263 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1264 $encReason = $dbw->addQuotes( $this->reason
);
1265 $encGroup = $dbw->addQuotes( 'deleted' );
1266 $ext = $this->file
->getExtension();
1267 $dotExt = $ext === '' ?
'' : ".$ext";
1268 $encExt = $dbw->addQuotes( $dotExt );
1269 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1271 // Bitfields to further suppress the content
1272 if ( $this->suppress
) {
1274 // This should be 15...
1275 $bitfield |
= Revision
::DELETED_TEXT
;
1276 $bitfield |
= Revision
::DELETED_COMMENT
;
1277 $bitfield |
= Revision
::DELETED_USER
;
1278 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1280 $bitfield = 'oi_deleted';
1283 if ( $deleteCurrent ) {
1284 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1285 $where = array( 'img_name' => $this->file
->getName() );
1286 $dbw->insertSelect( 'filearchive', 'image',
1288 'fa_storage_group' => $encGroup,
1289 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1290 'fa_deleted_user' => $encUserId,
1291 'fa_deleted_timestamp' => $encTimestamp,
1292 'fa_deleted_reason' => $encReason,
1293 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1295 'fa_name' => 'img_name',
1296 'fa_archive_name' => 'NULL',
1297 'fa_size' => 'img_size',
1298 'fa_width' => 'img_width',
1299 'fa_height' => 'img_height',
1300 'fa_metadata' => 'img_metadata',
1301 'fa_bits' => 'img_bits',
1302 'fa_media_type' => 'img_media_type',
1303 'fa_major_mime' => 'img_major_mime',
1304 'fa_minor_mime' => 'img_minor_mime',
1305 'fa_description' => 'img_description',
1306 'fa_user' => 'img_user',
1307 'fa_user_text' => 'img_user_text',
1308 'fa_timestamp' => 'img_timestamp'
1309 ), $where, __METHOD__
);
1312 if ( count( $oldRels ) ) {
1313 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1315 'oi_name' => $this->file
->getName(),
1316 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1317 $dbw->insertSelect( 'filearchive', 'oldimage',
1319 'fa_storage_group' => $encGroup,
1320 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1321 'fa_deleted_user' => $encUserId,
1322 'fa_deleted_timestamp' => $encTimestamp,
1323 'fa_deleted_reason' => $encReason,
1324 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1326 'fa_name' => 'oi_name',
1327 'fa_archive_name' => 'oi_archive_name',
1328 'fa_size' => 'oi_size',
1329 'fa_width' => 'oi_width',
1330 'fa_height' => 'oi_height',
1331 'fa_metadata' => 'oi_metadata',
1332 'fa_bits' => 'oi_bits',
1333 'fa_media_type' => 'oi_media_type',
1334 'fa_major_mime' => 'oi_major_mime',
1335 'fa_minor_mime' => 'oi_minor_mime',
1336 'fa_description' => 'oi_description',
1337 'fa_user' => 'oi_user',
1338 'fa_user_text' => 'oi_user_text',
1339 'fa_timestamp' => 'oi_timestamp',
1340 'fa_deleted' => $bitfield
1341 ), $where, __METHOD__
);
1345 function doDBDeletes() {
1346 $dbw = $this->file
->repo
->getMasterDB();
1347 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1348 if ( count( $oldRels ) ) {
1349 $dbw->delete( 'oldimage',
1351 'oi_name' => $this->file
->getName(),
1352 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1355 if ( $deleteCurrent ) {
1356 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1361 * Run the transaction
1363 function execute() {
1364 global $wgUser, $wgUseSquid;
1365 wfProfileIn( __METHOD__
);
1367 $this->file
->lock();
1368 // Leave private files alone
1369 $privateFiles = array();
1370 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1371 $dbw = $this->file
->repo
->getMasterDB();
1372 if( !empty( $oldRels ) ) {
1373 $res = $dbw->select( 'oldimage',
1374 array( 'oi_archive_name' ),
1375 array( 'oi_name' => $this->file
->getName(),
1376 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1377 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1379 while( $row = $dbw->fetchObject( $res ) ) {
1380 $privateFiles[$row->oi_archive_name
] = 1;
1383 // Prepare deletion batch
1384 $hashes = $this->getHashes();
1385 $this->deletionBatch
= array();
1386 $ext = $this->file
->getExtension();
1387 $dotExt = $ext === '' ?
'' : ".$ext";
1388 foreach ( $this->srcRels
as $name => $srcRel ) {
1389 // Skip files that have no hash (missing source).
1390 // Keep private files where they are.
1391 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1392 $hash = $hashes[$name];
1393 $key = $hash . $dotExt;
1394 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1395 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1399 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1400 // We acquire this lock by running the inserts now, before the file operations.
1402 // This potentially has poor lock contention characteristics -- an alternative
1403 // scheme would be to insert stub filearchive entries with no fa_name and commit
1404 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1405 $this->doDBInserts();
1407 // Execute the file deletion batch
1408 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1409 if ( !$status->isGood() ) {
1410 $this->status
->merge( $status );
1413 if ( !$this->status
->ok
) {
1414 // Critical file deletion error
1415 // Roll back inserts, release lock and abort
1416 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1417 $this->file
->unlockAndRollback();
1418 return $this->status
;
1422 if ( $wgUseSquid ) {
1424 foreach ( $this->srcRels
as $srcRel ) {
1425 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1426 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1428 SquidUpdate
::purge( $urls );
1431 // Delete image/oldimage rows
1432 $this->doDBDeletes();
1434 // Commit and return
1435 $this->file
->unlock();
1436 wfProfileOut( __METHOD__
);
1437 return $this->status
;
1441 #------------------------------------------------------------------------------
1444 * Helper class for file undeletion
1446 class LocalFileRestoreBatch
{
1447 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1449 function __construct( File
$file, $unsuppress = false ) {
1450 $this->file
= $file;
1451 $this->cleanupBatch
= $this->ids
= array();
1452 $this->ids
= array();
1453 $this->unsuppress
= $unsuppress;
1459 function addId( $fa_id ) {
1460 $this->ids
[] = $fa_id;
1464 * Add a whole lot of files by ID
1466 function addIds( $ids ) {
1467 $this->ids
= array_merge( $this->ids
, $ids );
1471 * Add all revisions of the file
1478 * Run the transaction, except the cleanup batch.
1479 * The cleanup batch should be run in a separate transaction, because it locks different
1480 * rows and there's no need to keep the image row locked while it's acquiring those locks
1481 * The caller may have its own transaction open.
1482 * So we save the batch and let the caller call cleanup()
1484 function execute() {
1485 global $wgUser, $wgLang;
1486 if ( !$this->all
&& !$this->ids
) {
1488 return $this->file
->repo
->newGood();
1491 $exists = $this->file
->lock();
1492 $dbw = $this->file
->repo
->getMasterDB();
1493 $status = $this->file
->repo
->newGood();
1495 // Fetch all or selected archived revisions for the file,
1496 // sorted from the most recent to the oldest.
1497 $conditions = array( 'fa_name' => $this->file
->getName() );
1499 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1502 $result = $dbw->select( 'filearchive', '*',
1505 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1507 $idsPresent = array();
1508 $storeBatch = array();
1509 $insertBatch = array();
1510 $insertCurrent = false;
1511 $deleteIds = array();
1513 $archiveNames = array();
1514 while( $row = $dbw->fetchObject( $result ) ) {
1515 $idsPresent[] = $row->fa_id
;
1517 if ( $row->fa_name
!= $this->file
->getName() ) {
1518 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1519 $status->failCount++
;
1522 if ( $row->fa_storage_key
== '' ) {
1523 // Revision was missing pre-deletion
1524 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1525 $status->failCount++
;
1529 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1530 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1532 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1534 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1535 $sha1 = substr( $sha1, 1 );
1538 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1539 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1540 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1541 ||
is_null( $row->fa_metadata
) ) {
1542 // Refresh our metadata
1543 // Required for a new current revision; nice for older ones too. :)
1544 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1547 'minor_mime' => $row->fa_minor_mime
,
1548 'major_mime' => $row->fa_major_mime
,
1549 'media_type' => $row->fa_media_type
,
1550 'metadata' => $row->fa_metadata
);
1553 if ( $first && !$exists ) {
1554 // The live (current) version cannot be hidden!
1555 if( !$this->unsuppress
&& $row->fa_deleted
) {
1556 $this->file
->unlock();
1559 // This revision will be published as the new current version
1560 $destRel = $this->file
->getRel();
1561 $insertCurrent = array(
1562 'img_name' => $row->fa_name
,
1563 'img_size' => $row->fa_size
,
1564 'img_width' => $row->fa_width
,
1565 'img_height' => $row->fa_height
,
1566 'img_metadata' => $props['metadata'],
1567 'img_bits' => $row->fa_bits
,
1568 'img_media_type' => $props['media_type'],
1569 'img_major_mime' => $props['major_mime'],
1570 'img_minor_mime' => $props['minor_mime'],
1571 'img_description' => $row->fa_description
,
1572 'img_user' => $row->fa_user
,
1573 'img_user_text' => $row->fa_user_text
,
1574 'img_timestamp' => $row->fa_timestamp
,
1575 'img_sha1' => $sha1);
1577 $archiveName = $row->fa_archive_name
;
1578 if( $archiveName == '' ) {
1579 // This was originally a current version; we
1580 // have to devise a new archive name for it.
1581 // Format is <timestamp of archiving>!<name>
1582 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1584 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1586 } while ( isset( $archiveNames[$archiveName] ) );
1588 $archiveNames[$archiveName] = true;
1589 $destRel = $this->file
->getArchiveRel( $archiveName );
1590 $insertBatch[] = array(
1591 'oi_name' => $row->fa_name
,
1592 'oi_archive_name' => $archiveName,
1593 'oi_size' => $row->fa_size
,
1594 'oi_width' => $row->fa_width
,
1595 'oi_height' => $row->fa_height
,
1596 'oi_bits' => $row->fa_bits
,
1597 'oi_description' => $row->fa_description
,
1598 'oi_user' => $row->fa_user
,
1599 'oi_user_text' => $row->fa_user_text
,
1600 'oi_timestamp' => $row->fa_timestamp
,
1601 'oi_metadata' => $props['metadata'],
1602 'oi_media_type' => $props['media_type'],
1603 'oi_major_mime' => $props['major_mime'],
1604 'oi_minor_mime' => $props['minor_mime'],
1605 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1606 'oi_sha1' => $sha1 );
1609 $deleteIds[] = $row->fa_id
;
1610 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1611 // private files can stay where they are
1613 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1614 $this->cleanupBatch
[] = $row->fa_storage_key
;
1620 // Add a warning to the status object for missing IDs
1621 $missingIds = array_diff( $this->ids
, $idsPresent );
1622 foreach ( $missingIds as $id ) {
1623 $status->error( 'undelete-missing-filearchive', $id );
1626 // Run the store batch
1627 // Use the OVERWRITE_SAME flag to smooth over a common error
1628 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1629 $status->merge( $storeStatus );
1631 if ( !$status->ok
) {
1632 // Store batch returned a critical error -- this usually means nothing was stored
1633 // Stop now and return an error
1634 $this->file
->unlock();
1638 // Run the DB updates
1639 // Because we have locked the image row, key conflicts should be rare.
1640 // If they do occur, we can roll back the transaction at this time with
1641 // no data loss, but leaving unregistered files scattered throughout the
1643 // This is not ideal, which is why it's important to lock the image row.
1644 if ( $insertCurrent ) {
1645 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1647 if ( $insertBatch ) {
1648 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1651 $dbw->delete( 'filearchive',
1652 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1656 if( $status->successCount
> 0 ) {
1658 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1660 // Update site_stats
1661 $site_stats = $dbw->tableName( 'site_stats' );
1662 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1664 $this->file
->purgeEverything();
1666 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1667 $this->file
->purgeDescription();
1668 $this->file
->purgeHistory();
1671 $this->file
->unlock();
1676 * Delete unused files in the deleted zone.
1677 * This should be called from outside the transaction in which execute() was called.
1679 function cleanup() {
1680 if ( !$this->cleanupBatch
) {
1681 return $this->file
->repo
->newGood();
1683 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1688 #------------------------------------------------------------------------------
1691 * Helper class for file movement
1693 class LocalFileMoveBatch
{
1694 var $file, $cur, $olds, $oldcount, $archive, $thumbs, $target, $db;
1696 function __construct( File
$file, Title
$target, Database
$db ) {
1697 $this->file
= $file;
1698 $this->target
= $target;
1699 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1700 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDbKey() );
1701 $this->oldName
= $this->file
->getName();
1702 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1703 $this->oldRel
= $this->oldHash
. $this->oldName
;
1704 $this->newRel
= $this->newHash
. $this->newName
;
1708 function addCurrent() {
1709 $this->cur
= array( $this->oldRel
, $this->newRel
);
1712 function addThumbs() {
1713 // Thumbnails are purged, so no need to move them
1714 $this->thumbs
= array();
1717 function addOlds() {
1718 $archiveBase = 'archive';
1719 $this->olds
= array();
1720 $this->oldcount
= 0;
1722 $result = $this->db
->select( 'oldimage',
1723 array( 'oi_archive_name', 'oi_deleted' ),
1724 array( 'oi_name' => $this->oldName
),
1727 while( $row = $this->db
->fetchObject( $result ) ) {
1728 $oldname = $row->oi_archive_name
;
1729 $bits = explode( '!', $oldname, 2 );
1730 if( count( $bits ) != 2 ) {
1731 wfDebug( 'Invalid old file name: ' . $oldname );
1734 list( $timestamp, $filename ) = $bits;
1735 if( $this->oldName
!= $filename ) {
1736 wfDebug( 'Invalid old file name:' . $oldName );
1740 // Do we want to add those to oldcount?
1741 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1744 $this->olds
[] = array(
1745 "{$archiveBase}/{$this->oldHash}{$oldname}",
1746 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1749 $this->db
->freeResult( $result );
1752 function execute() {
1753 $repo = $this->file
->repo
;
1754 $status = $repo->newGood();
1755 $triplets = $this->getMoveTriplets();
1757 $statusDb = $this->doDBUpdates();
1758 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1759 if( !$statusMove->isOk() ) {
1760 $this->db
->rollback();
1762 $status->merge( $statusDb );
1763 $status->merge( $statusMove );
1767 function doDBUpdates() {
1768 $repo = $this->file
->repo
;
1769 $status = $repo->newGood();
1772 // Update current image
1775 array( 'img_name' => $this->newName
),
1776 array( 'img_name' => $this->oldName
),
1779 if( $dbw->affectedRows() ) {
1780 $status->successCount++
;
1782 $status->failCount++
;
1785 // Update old images
1789 'oi_name' => $this->newName
,
1790 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1792 array( 'oi_name' => $this->oldName
),
1795 $affected = $dbw->affectedRows();
1796 $total = $this->oldcount
;
1797 $status->successCount +
= $affected;
1798 $status->failCount +
= $total - $affected;
1803 // Generates triplets for FSRepo::storeBatch()
1804 function getMoveTriplets() {
1805 $moves = array_merge( array( $this->cur
), $this->olds
, $this->thumbs
);
1806 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1807 foreach( $moves as $move ) {
1808 // $move: (oldRelativePath, newRelativePath)
1809 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1810 $triplets[] = array( $srcUrl, 'public', $move[1] );