*Tweak rev_deleted message
[mediawiki.git] / includes / filerepo / LocalFile.php
blob06f7b0d2642e8a0c001ee9a237a5608f14fd2d0e
1 <?php
2 /**
3 */
5 /**
6 * Bump this number when serialized cache records may be incompatible.
7 */
8 define( 'MW_FILE_VERSION', 4 );
10 /**
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
23 * in most cases.
25 * @addtogroup FileRepo
27 class LocalFile extends File
29 /**#@+
30 * @private
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)
35 $width, # \
36 $height, # |
37 $bits, # --- returned by getimagesize (loadFromXxx)
38 $attr, # /
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 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
48 $upgraded, # Whether the row was upgraded on load
49 $locked; # True if the image row is locked
51 /**#@-*/
53 /**
54 * Create a LocalFile from a title
55 * Do not call this except from inside a repo class.
57 static function newFromTitle( $title, $repo ) {
58 return new self( $title, $repo );
61 /**
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 static function newFromRow( $row, $repo ) {
66 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
67 $file = new self( $title, $repo );
68 $file->loadFromRow( $row );
69 return $file;
72 /**
73 * Constructor.
74 * Do not call this except from inside a repo class.
76 function __construct( $title, $repo ) {
77 if( !is_object( $title ) ) {
78 throw new MWException( __CLASS__.' constructor given bogus title.' );
80 parent::__construct( $title, $repo );
81 $this->metadata = '';
82 $this->historyLine = 0;
83 $this->historyRes = null;
84 $this->dataLoaded = false;
87 /**
88 * Get the memcached key
90 function getCacheKey() {
91 $hashedName = md5($this->getName());
92 return wfMemcKey( 'file', $hashedName );
95 /**
96 * Try to load file metadata from memcached. Returns true on success.
98 function loadFromCache() {
99 global $wgMemc;
100 wfProfileIn( __METHOD__ );
101 $this->dataLoaded = false;
102 $key = $this->getCacheKey();
103 if ( !$key ) {
104 return false;
106 $cachedValues = $wgMemc->get( $key );
108 // Check if the key existed and belongs to this version of MediaWiki
109 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
110 wfDebug( "Pulling file metadata from cache key $key\n" );
111 $this->fileExists = $cachedValues['fileExists'];
112 if ( $this->fileExists ) {
113 $this->setProps( $cachedValues );
115 $this->dataLoaded = true;
117 if ( $this->dataLoaded ) {
118 wfIncrStats( 'image_cache_hit' );
119 } else {
120 wfIncrStats( 'image_cache_miss' );
123 wfProfileOut( __METHOD__ );
124 return $this->dataLoaded;
128 * Save the file metadata to memcached
130 function saveToCache() {
131 global $wgMemc;
132 $this->load();
133 $key = $this->getCacheKey();
134 if ( !$key ) {
135 return;
137 $fields = $this->getCacheFields( '' );
138 $cache = array( 'version' => MW_FILE_VERSION );
139 $cache['fileExists'] = $this->fileExists;
140 if ( $this->fileExists ) {
141 foreach ( $fields as $field ) {
142 $cache[$field] = $this->$field;
146 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
150 * Load metadata from the file itself
152 function loadFromFile() {
153 $this->setProps( self::getPropsFromPath( $this->getPath() ) );
156 function getCacheFields( $prefix = 'img_' ) {
157 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
158 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1' );
159 static $results = array();
160 if ( $prefix == '' ) {
161 return $fields;
163 if ( !isset( $results[$prefix] ) ) {
164 $prefixedFields = array();
165 foreach ( $fields as $field ) {
166 $prefixedFields[] = $prefix . $field;
168 $results[$prefix] = $prefixedFields;
170 return $results[$prefix];
174 * Load file metadata from the DB
176 function loadFromDB() {
177 # Polymorphic function name to distinguish foreign and local fetches
178 $fname = get_class( $this ) . '::' . __FUNCTION__;
179 wfProfileIn( $fname );
181 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
182 $this->dataLoaded = true;
184 $dbr = $this->repo->getSlaveDB();
186 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
187 array( 'img_name' => $this->getName() ), $fname );
188 if ( $row ) {
189 $this->loadFromRow( $row );
190 } else {
191 $this->fileExists = false;
194 wfProfileOut( $fname );
198 * Decode a row from the database (either object or array) to an array
199 * with timestamps and MIME types decoded, and the field prefix removed.
201 function decodeRow( $row, $prefix = 'img_' ) {
202 $array = (array)$row;
203 $prefixLength = strlen( $prefix );
204 // Sanity check prefix once
205 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
206 throw new MWException( __METHOD__. ': incorrect $prefix parameter' );
208 $decoded = array();
209 foreach ( $array as $name => $value ) {
210 $decoded[substr( $name, $prefixLength )] = $value;
212 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
213 if ( empty( $decoded['major_mime'] ) ) {
214 $decoded['mime'] = "unknown/unknown";
215 } else {
216 if (!$decoded['minor_mime']) {
217 $decoded['minor_mime'] = "unknown";
219 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
221 # Trim zero padding from char/binary field
222 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
223 return $decoded;
227 * Load file metadata from a DB result row
229 function loadFromRow( $row, $prefix = 'img_' ) {
230 $this->dataLoaded = true;
231 $array = $this->decodeRow( $row, $prefix );
232 foreach ( $array as $name => $value ) {
233 $this->$name = $value;
235 $this->fileExists = true;
236 // Check for rows from a previous schema, quietly upgrade them
237 $this->maybeUpgradeRow();
241 * Load file metadata from cache or DB, unless already loaded
243 function load() {
244 if ( !$this->dataLoaded ) {
245 if ( !$this->loadFromCache() ) {
246 $this->loadFromDB();
247 $this->saveToCache();
249 $this->dataLoaded = true;
254 * Upgrade a row if it needs it
256 function maybeUpgradeRow() {
257 if ( wfReadOnly() ) {
258 return;
260 if ( is_null($this->media_type) ||
261 $this->mime == 'image/svg'
263 $this->upgradeRow();
264 $this->upgraded = true;
265 } else {
266 $handler = $this->getHandler();
267 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
268 $this->upgradeRow();
269 $this->upgraded = true;
274 function getUpgraded() {
275 return $this->upgraded;
279 * Fix assorted version-related problems with the image row by reloading it from the file
281 function upgradeRow() {
282 wfProfileIn( __METHOD__ );
284 $this->loadFromFile();
286 # Don't destroy file info of missing files
287 if ( !$this->fileExists ) {
288 wfDebug( __METHOD__.": file does not exist, aborting\n" );
289 return;
291 $dbw = $this->repo->getMasterDB();
292 list( $major, $minor ) = self::splitMime( $this->mime );
294 wfDebug(__METHOD__.': upgrading '.$this->getName()." to the current schema\n");
296 $dbw->update( 'image',
297 array(
298 'img_width' => $this->width,
299 'img_height' => $this->height,
300 'img_bits' => $this->bits,
301 'img_media_type' => $this->media_type,
302 'img_major_mime' => $major,
303 'img_minor_mime' => $minor,
304 'img_metadata' => $this->metadata,
305 'img_sha1' => $this->sha1,
306 ), array( 'img_name' => $this->getName() ),
307 __METHOD__
309 $this->saveToCache();
310 wfProfileOut( __METHOD__ );
314 * Set properties in this object to be equal to those given in the
315 * associative array $info. Only cacheable fields can be set.
317 * If 'mime' is given, it will be split into major_mime/minor_mime.
318 * If major_mime/minor_mime are given, $this->mime will also be set.
320 function setProps( $info ) {
321 $this->dataLoaded = true;
322 $fields = $this->getCacheFields( '' );
323 $fields[] = 'fileExists';
324 foreach ( $fields as $field ) {
325 if ( isset( $info[$field] ) ) {
326 $this->$field = $info[$field];
329 // Fix up mime fields
330 if ( isset( $info['major_mime'] ) ) {
331 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
332 } elseif ( isset( $info['mime'] ) ) {
333 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
337 /** splitMime inherited */
338 /** getName inherited */
339 /** getTitle inherited */
340 /** getURL inherited */
341 /** getViewURL inherited */
342 /** getPath inherited */
345 * Return the width of the image
347 * Returns false on error
348 * @public
350 function getWidth( $page = 1 ) {
351 $this->load();
352 if ( $this->isMultipage() ) {
353 $dim = $this->getHandler()->getPageDimensions( $this, $page );
354 if ( $dim ) {
355 return $dim['width'];
356 } else {
357 return false;
359 } else {
360 return $this->width;
365 * Return the height of the image
367 * Returns false on error
368 * @public
370 function getHeight( $page = 1 ) {
371 $this->load();
372 if ( $this->isMultipage() ) {
373 $dim = $this->getHandler()->getPageDimensions( $this, $page );
374 if ( $dim ) {
375 return $dim['height'];
376 } else {
377 return false;
379 } else {
380 return $this->height;
385 * Get handler-specific metadata
387 function getMetadata() {
388 $this->load();
389 return $this->metadata;
393 * Return the size of the image file, in bytes
394 * @public
396 function getSize() {
397 $this->load();
398 return $this->size;
402 * Returns the mime type of the file.
404 function getMimeType() {
405 $this->load();
406 return $this->mime;
410 * Return the type of the media in the file.
411 * Use the value returned by this function with the MEDIATYPE_xxx constants.
413 function getMediaType() {
414 $this->load();
415 return $this->media_type;
418 /** canRender inherited */
419 /** mustRender inherited */
420 /** allowInlineDisplay inherited */
421 /** isSafeFile inherited */
422 /** isTrustedFile inherited */
425 * Returns true if the file file exists on disk.
426 * @return boolean Whether file file exist on disk.
427 * @public
429 function exists() {
430 $this->load();
431 return $this->fileExists;
434 /** getTransformScript inherited */
435 /** getUnscaledThumb inherited */
436 /** thumbName inherited */
437 /** createThumb inherited */
438 /** getThumbnail inherited */
439 /** transform inherited */
442 * Fix thumbnail files from 1.4 or before, with extreme prejudice
444 function migrateThumbFile( $thumbName ) {
445 $thumbDir = $this->getThumbPath();
446 $thumbPath = "$thumbDir/$thumbName";
447 if ( is_dir( $thumbPath ) ) {
448 // Directory where file should be
449 // This happened occasionally due to broken migration code in 1.5
450 // Rename to broken-*
451 for ( $i = 0; $i < 100 ; $i++ ) {
452 $broken = $this->repo->getZonePath('public') . "/broken-$i-$thumbName";
453 if ( !file_exists( $broken ) ) {
454 rename( $thumbPath, $broken );
455 break;
458 // Doesn't exist anymore
459 clearstatcache();
461 if ( is_file( $thumbDir ) ) {
462 // File where directory should be
463 unlink( $thumbDir );
464 // Doesn't exist anymore
465 clearstatcache();
469 /** getHandler inherited */
470 /** iconThumb inherited */
471 /** getLastError inherited */
474 * Get all thumbnail names previously generated for this file
476 function getThumbnails() {
477 if ( $this->isHashed() ) {
478 $this->load();
479 $files = array();
480 $dir = $this->getThumbPath();
482 if ( is_dir( $dir ) ) {
483 $handle = opendir( $dir );
485 if ( $handle ) {
486 while ( false !== ( $file = readdir($handle) ) ) {
487 if ( $file{0} != '.' ) {
488 $files[] = $file;
491 closedir( $handle );
494 } else {
495 $files = array();
498 return $files;
502 * Refresh metadata in memcached, but don't touch thumbnails or squid
504 function purgeMetadataCache() {
505 $this->loadFromDB();
506 $this->saveToCache();
507 $this->purgeHistory();
511 * Purge the shared history (OldLocalFile) cache
513 function purgeHistory() {
514 global $wgMemc;
515 $hashedName = md5($this->getName());
516 $oldKey = wfMemcKey( 'oldfile', $hashedName );
517 $wgMemc->delete( $oldKey );
521 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
523 function purgeCache() {
524 // Refresh metadata cache
525 $this->purgeMetadataCache();
527 // Delete thumbnails
528 $this->purgeThumbnails();
530 // Purge squid cache for this file
531 wfPurgeSquidServers( array( $this->getURL() ) );
535 * Delete cached transformed files
537 function purgeThumbnails() {
538 global $wgUseSquid;
539 // Delete thumbnails
540 $files = $this->getThumbnails();
541 $dir = $this->getThumbPath();
542 $urls = array();
543 foreach ( $files as $file ) {
544 # Check that the base file name is part of the thumb name
545 # This is a basic sanity check to avoid erasing unrelated directories
546 if ( strpos( $file, $this->getName() ) !== false ) {
547 $url = $this->getThumbUrl( $file );
548 $urls[] = $url;
549 @unlink( "$dir/$file" );
553 // Purge the squid
554 if ( $wgUseSquid ) {
555 wfPurgeSquidServers( $urls );
559 /** purgeDescription inherited */
560 /** purgeEverything inherited */
563 * Return the history of this file, line by line.
564 * starts with current version, then old versions.
565 * uses $this->historyLine to check which line to return:
566 * 0 return line for current version
567 * 1 query for old versions, return first one
568 * 2, ... return next old version from above query
570 * @public
572 function nextHistoryLine() {
573 $dbr = $this->repo->getSlaveDB();
575 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
576 $this->historyRes = $dbr->select( 'image',
577 array(
578 '*',
579 "'' AS oi_archive_name"
581 array( 'img_name' => $this->title->getDBkey() ),
582 __METHOD__
584 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
585 $dbr->freeResult($this->historyRes);
586 $this->historyRes = null;
587 return FALSE;
589 } else if ( $this->historyLine == 1 ) {
590 $dbr->freeResult($this->historyRes);
591 $this->historyRes = $dbr->select( 'oldimage', '*',
592 array( 'oi_name' => $this->title->getDBkey() ),
593 __METHOD__,
594 array( 'ORDER BY' => 'oi_timestamp DESC' )
597 $this->historyLine ++;
599 return $dbr->fetchObject( $this->historyRes );
603 * Reset the history pointer to the first element of the history
604 * @public
606 function resetHistory() {
607 $this->historyLine = 0;
608 if (!is_null($this->historyRes)) {
609 $this->repo->getSlaveDB()->freeResult($this->historyRes);
610 $this->historyRes = null;
614 /** getFullPath inherited */
615 /** getHashPath inherited */
616 /** getRel inherited */
617 /** getUrlRel inherited */
618 /** getArchiveRel inherited */
619 /** getThumbRel inherited */
620 /** getArchivePath inherited */
621 /** getThumbPath inherited */
622 /** getArchiveUrl inherited */
623 /** getThumbUrl inherited */
624 /** getArchiveVirtualUrl inherited */
625 /** getThumbVirtualUrl inherited */
626 /** isHashed inherited */
629 * Upload a file and record it in the DB
630 * @param string $srcPath Source path or virtual URL
631 * @param string $comment Upload description
632 * @param string $pageText Text to use for the new description page, if a new description page is created
633 * @param integer $flags Flags for publish()
634 * @param array $props File properties, if known. This can be used to reduce the
635 * upload time when uploading virtual URLs for which the file info
636 * is already known
637 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
639 * @return FileRepoStatus object. On success, the value member contains the
640 * archive name, or an empty string if it was a new file.
642 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
643 $this->lock();
644 $status = $this->publish( $srcPath, $flags );
645 if ( $status->ok ) {
646 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp ) ) {
647 $status->fatal( 'filenotfound', $srcPath );
650 $this->unlock();
651 return $status;
655 * Record a file upload in the upload log and the image table
656 * @deprecated use upload()
658 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
659 $watch = false, $timestamp = false )
661 $pageText = UploadForm::getInitialPageText( $desc, $license, $copyStatus, $source );
662 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
663 return false;
665 if ( $watch ) {
666 global $wgUser;
667 $wgUser->addWatch( $this->getTitle() );
669 return true;
674 * Record a file upload in the upload log and the image table
676 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
678 global $wgUser;
680 $dbw = $this->repo->getMasterDB();
682 if ( !$props ) {
683 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
685 $this->setProps( $props );
687 // Delete thumbnails and refresh the metadata cache
688 $this->purgeThumbnails();
689 $this->saveToCache();
690 wfPurgeSquidServers( array( $this->getURL() ) );
692 // Fail now if the file isn't there
693 if ( !$this->fileExists ) {
694 wfDebug( __METHOD__.": File ".$this->getPath()." went missing!\n" );
695 return false;
698 $reupload = false;
699 if ( $timestamp === false ) {
700 $timestamp = $dbw->timestamp();
703 # Test to see if the row exists using INSERT IGNORE
704 # This avoids race conditions by locking the row until the commit, and also
705 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
706 $dbw->insert( 'image',
707 array(
708 'img_name' => $this->getName(),
709 'img_size'=> $this->size,
710 'img_width' => intval( $this->width ),
711 'img_height' => intval( $this->height ),
712 'img_bits' => $this->bits,
713 'img_media_type' => $this->media_type,
714 'img_major_mime' => $this->major_mime,
715 'img_minor_mime' => $this->minor_mime,
716 'img_timestamp' => $timestamp,
717 'img_description' => $comment,
718 'img_user' => $wgUser->getID(),
719 'img_user_text' => $wgUser->getName(),
720 'img_metadata' => $this->metadata,
721 'img_sha1' => $this->sha1
723 __METHOD__,
724 'IGNORE'
727 if( $dbw->affectedRows() == 0 ) {
728 $reupload = true;
730 # Collision, this is an update of a file
731 # Insert previous contents into oldimage
732 $dbw->insertSelect( 'oldimage', 'image',
733 array(
734 'oi_name' => 'img_name',
735 'oi_archive_name' => $dbw->addQuotes( $oldver ),
736 'oi_size' => 'img_size',
737 'oi_width' => 'img_width',
738 'oi_height' => 'img_height',
739 'oi_bits' => 'img_bits',
740 'oi_timestamp' => 'img_timestamp',
741 'oi_description' => 'img_description',
742 'oi_user' => 'img_user',
743 'oi_user_text' => 'img_user_text',
744 'oi_metadata' => 'img_metadata',
745 'oi_media_type' => 'img_media_type',
746 'oi_major_mime' => 'img_major_mime',
747 'oi_minor_mime' => 'img_minor_mime',
748 'oi_sha1' => 'img_sha1',
749 ), array( 'img_name' => $this->getName() ), __METHOD__
752 # Update the current image row
753 $dbw->update( 'image',
754 array( /* SET */
755 'img_size' => $this->size,
756 'img_width' => intval( $this->width ),
757 'img_height' => intval( $this->height ),
758 'img_bits' => $this->bits,
759 'img_media_type' => $this->media_type,
760 'img_major_mime' => $this->major_mime,
761 'img_minor_mime' => $this->minor_mime,
762 'img_timestamp' => $timestamp,
763 'img_description' => $comment,
764 'img_user' => $wgUser->getID(),
765 'img_user_text' => $wgUser->getName(),
766 'img_metadata' => $this->metadata,
767 'img_sha1' => $this->sha1
768 ), array( /* WHERE */
769 'img_name' => $this->getName()
770 ), __METHOD__
772 } else {
773 # This is a new file
774 # Update the image count
775 $site_stats = $dbw->tableName( 'site_stats' );
776 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
779 $descTitle = $this->getTitle();
780 $article = new Article( $descTitle );
782 # Add the log entry
783 $log = new LogPage( 'upload' );
784 $action = $reupload ? 'overwrite' : 'upload';
785 $log->addEntry( $action, $descTitle, $comment );
787 if( $descTitle->exists() ) {
788 # Create a null revision
789 $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
790 $nullRevision->insertOn( $dbw );
791 $article->updateRevisionOn( $dbw, $nullRevision );
793 # Invalidate the cache for the description page
794 $descTitle->invalidateCache();
795 $descTitle->purgeSquid();
796 } else {
797 // New file; create the description page.
798 // There's already a log entry, so don't make a second RC entry
799 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
802 # Hooks, hooks, the magic of hooks...
803 wfRunHooks( 'FileUpload', array( $this ) );
805 # Commit the transaction now, in case something goes wrong later
806 # The most important thing is that files don't get lost, especially archives
807 $dbw->immediateCommit();
809 # Invalidate cache for all pages using this file
810 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
811 $update->doUpdate();
813 return true;
817 * Move or copy a file to its public location. If a file exists at the
818 * destination, move it to an archive. Returns the archive name on success
819 * or an empty string if it was a new file, and a wikitext-formatted
820 * WikiError object on failure.
822 * The archive name should be passed through to recordUpload for database
823 * registration.
825 * @param string $sourcePath Local filesystem path to the source image
826 * @param integer $flags A bitwise combination of:
827 * File::DELETE_SOURCE Delete the source file, i.e. move
828 * rather than copy
829 * @return FileRepoStatus object. On success, the value member contains the
830 * archive name, or an empty string if it was a new file.
832 function publish( $srcPath, $flags = 0 ) {
833 $this->lock();
834 $dstRel = $this->getRel();
835 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
836 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
837 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
838 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
839 if ( $status->value == 'new' ) {
840 $status->value = '';
841 } else {
842 $status->value = $archiveName;
844 $this->unlock();
845 return $status;
848 /** getLinksTo inherited */
849 /** getExifData inherited */
850 /** isLocal inherited */
851 /** wasDeleted inherited */
854 * Delete all versions of the file.
856 * Moves the files into an archive directory (or deletes them)
857 * and removes the database rows.
859 * Cache purging is done; logging is caller's responsibility.
861 * @param $reason
862 * @return FileRepoStatus object.
864 function delete( $reason ) {
865 $this->lock();
866 $batch = new LocalFileDeleteBatch( $this, $reason );
867 $batch->addCurrent();
869 # Get old version relative paths
870 $dbw = $this->repo->getMasterDB();
871 $result = $dbw->select( 'oldimage',
872 array( 'oi_archive_name' ),
873 array( 'oi_name' => $this->getName() ) );
874 while ( $row = $dbw->fetchObject( $result ) ) {
875 $batch->addOld( $row->oi_archive_name );
877 $status = $batch->execute();
879 if ( $status->ok ) {
880 // Update site_stats
881 $site_stats = $dbw->tableName( 'site_stats' );
882 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
883 $this->purgeEverything();
886 $this->unlock();
887 return $status;
891 * Delete an old version of the file.
893 * Moves the file into an archive directory (or deletes it)
894 * and removes the database row.
896 * Cache purging is done; logging is caller's responsibility.
898 * @param $reason
899 * @throws MWException or FSException on database or filestore failure
900 * @return FileRepoStatus object.
902 function deleteOld( $archiveName, $reason ) {
903 $this->lock();
904 $batch = new LocalFileDeleteBatch( $this, $reason );
905 $batch->addOld( $archiveName );
906 $status = $batch->execute();
907 $this->unlock();
908 if ( $status->ok ) {
909 $this->purgeDescription();
910 $this->purgeHistory();
912 return $status;
916 * Restore all or specified deleted revisions to the given file.
917 * Permissions and logging are left to the caller.
919 * May throw database exceptions on error.
921 * @param $versions set of record ids of deleted items to restore,
922 * or empty to restore all revisions.
923 * @return FileRepoStatus
925 function restore( $versions = array(), $unsuppress = false ) {
926 $batch = new LocalFileRestoreBatch( $this );
927 if ( !$versions ) {
928 $batch->addAll();
929 } else {
930 $batch->addIds( $versions );
932 $status = $batch->execute();
933 if ( !$status->ok ) {
934 return $status;
937 $cleanupStatus = $batch->cleanup();
938 $cleanupStatus->successCount = 0;
939 $cleanupStatus->failCount = 0;
940 $status->merge( $cleanupStatus );
941 return $status;
944 /** isMultipage inherited */
945 /** pageCount inherited */
946 /** scaleHeight inherited */
947 /** getImageSize inherited */
950 * Get the URL of the file description page.
952 function getDescriptionUrl() {
953 return $this->title->getLocalUrl();
957 * Get the HTML text of the description page
958 * This is not used by ImagePage for local files, since (among other things)
959 * it skips the parser cache.
961 function getDescriptionText() {
962 global $wgParser;
963 $revision = Revision::newFromTitle( $this->title );
964 if ( !$revision ) return false;
965 $text = $revision->getText();
966 if ( !$text ) return false;
967 $html = $wgParser->parse( $text, new ParserOptions );
968 return $html;
971 function getTimestamp() {
972 $this->load();
973 return $this->timestamp;
976 function getSha1() {
977 $this->load();
978 // Initialise now if necessary
979 if ( $this->sha1 == '' && $this->fileExists ) {
980 $this->sha1 = File::sha1Base36( $this->getPath() );
981 if ( strval( $this->sha1 ) != '' ) {
982 $dbw = $this->repo->getMasterDB();
983 $dbw->update( 'image',
984 array( 'img_sha1' => $this->sha1 ),
985 array( 'img_name' => $this->getName() ),
986 __METHOD__ );
987 $this->saveToCache();
991 return $this->sha1;
995 * Start a transaction and lock the image for update
996 * Increments a reference counter if the lock is already held
997 * @return boolean True if the image exists, false otherwise
999 function lock() {
1000 $dbw = $this->repo->getMasterDB();
1001 if ( !$this->locked ) {
1002 $dbw->begin();
1003 $this->locked++;
1005 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1009 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1010 * the transaction and thereby releases the image lock.
1012 function unlock() {
1013 if ( $this->locked ) {
1014 --$this->locked;
1015 if ( !$this->locked ) {
1016 $dbw = $this->repo->getMasterDB();
1017 $dbw->commit();
1023 * Roll back the DB transaction and mark the image unlocked
1025 function unlockAndRollback() {
1026 $this->locked = false;
1027 $dbw = $this->repo->getMasterDB();
1028 $dbw->rollback();
1030 } // LocalFile class
1032 #------------------------------------------------------------------------------
1035 * Backwards compatibility class
1037 class Image extends LocalFile {
1038 function __construct( $title ) {
1039 $repo = RepoGroup::singleton()->getLocalRepo();
1040 parent::__construct( $title, $repo );
1044 * Wrapper for wfFindFile(), for backwards-compatibility only
1045 * Do not use in core code.
1046 * @deprecated
1048 static function newFromTitle( $title, $time = false ) {
1049 $img = wfFindFile( $title, $time );
1050 if ( !$img ) {
1051 $img = wfLocalFile( $title );
1053 return $img;
1057 * Wrapper for wfFindFile(), for backwards-compatibility only.
1058 * Do not use in core code.
1060 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1061 * @return image object or null if invalid title
1062 * @deprecated
1064 static function newFromName( $name ) {
1065 $title = Title::makeTitleSafe( NS_IMAGE, $name );
1066 if ( is_object( $title ) ) {
1067 $img = wfFindFile( $title );
1068 if ( !$img ) {
1069 $img = wfLocalFile( $title );
1071 return $img;
1072 } else {
1073 return NULL;
1078 * Return the URL of an image, provided its name.
1080 * Backwards-compatibility for extensions.
1081 * Note that fromSharedDirectory will only use the shared path for files
1082 * that actually exist there now, and will return local paths otherwise.
1084 * @param string $name Name of the image, without the leading "Image:"
1085 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1086 * @return string URL of $name image
1087 * @deprecated
1089 static function imageUrl( $name, $fromSharedDirectory = false ) {
1090 $image = null;
1091 if( $fromSharedDirectory ) {
1092 $image = wfFindFile( $name );
1094 if( !$image ) {
1095 $image = wfLocalFile( $name );
1097 return $image->getUrl();
1101 #------------------------------------------------------------------------------
1104 * Helper class for file deletion
1106 class LocalFileDeleteBatch {
1107 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
1108 var $status;
1110 function __construct( File $file, $reason = '' ) {
1111 $this->file = $file;
1112 $this->reason = $reason;
1113 $this->status = $file->repo->newGood();
1116 function addCurrent() {
1117 $this->srcRels['.'] = $this->file->getRel();
1120 function addOld( $oldName ) {
1121 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1122 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1125 function getOldRels() {
1126 if ( !isset( $this->srcRels['.'] ) ) {
1127 $oldRels =& $this->srcRels;
1128 $deleteCurrent = false;
1129 } else {
1130 $oldRels = $this->srcRels;
1131 unset( $oldRels['.'] );
1132 $deleteCurrent = true;
1134 return array( $oldRels, $deleteCurrent );
1137 /*protected*/ function getHashes() {
1138 $hashes = array();
1139 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1140 if ( $deleteCurrent ) {
1141 $hashes['.'] = $this->file->getSha1();
1143 if ( count( $oldRels ) ) {
1144 $dbw = $this->file->repo->getMasterDB();
1145 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1146 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1147 __METHOD__ );
1148 while ( $row = $dbw->fetchObject( $res ) ) {
1149 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1150 // Get the hash from the file
1151 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1152 $props = $this->file->repo->getFileProps( $oldUrl );
1153 if ( $props['fileExists'] ) {
1154 // Upgrade the oldimage row
1155 $dbw->update( 'oldimage',
1156 array( 'oi_sha1' => $props['sha1'] ),
1157 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1158 __METHOD__ );
1159 $hashes[$row->oi_archive_name] = $props['sha1'];
1160 } else {
1161 $hashes[$row->oi_archive_name] = false;
1163 } else {
1164 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1168 $missing = array_diff_key( $this->srcRels, $hashes );
1169 foreach ( $missing as $name => $rel ) {
1170 $this->status->error( 'filedelete-old-unregistered', $name );
1172 foreach ( $hashes as $name => $hash ) {
1173 if ( !$hash ) {
1174 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1175 unset( $hashes[$name] );
1179 return $hashes;
1182 function doDBInserts() {
1183 global $wgUser;
1184 $dbw = $this->file->repo->getMasterDB();
1185 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1186 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1187 $encReason = $dbw->addQuotes( $this->reason );
1188 $encGroup = $dbw->addQuotes( 'deleted' );
1189 $ext = $this->file->getExtension();
1190 $dotExt = $ext === '' ? '' : ".$ext";
1191 $encExt = $dbw->addQuotes( $dotExt );
1192 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1194 if ( $deleteCurrent ) {
1195 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1196 $where = array( 'img_name' => $this->file->getName() );
1197 $dbw->insertSelect( 'filearchive', 'image',
1198 array(
1199 'fa_storage_group' => $encGroup,
1200 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1201 'fa_deleted_user' => $encUserId,
1202 'fa_deleted_timestamp' => $encTimestamp,
1203 'fa_deleted_reason' => $encReason,
1204 'fa_deleted' => 0,
1206 'fa_name' => 'img_name',
1207 'fa_archive_name' => 'NULL',
1208 'fa_size' => 'img_size',
1209 'fa_width' => 'img_width',
1210 'fa_height' => 'img_height',
1211 'fa_metadata' => 'img_metadata',
1212 'fa_bits' => 'img_bits',
1213 'fa_media_type' => 'img_media_type',
1214 'fa_major_mime' => 'img_major_mime',
1215 'fa_minor_mime' => 'img_minor_mime',
1216 'fa_description' => 'img_description',
1217 'fa_user' => 'img_user',
1218 'fa_user_text' => 'img_user_text',
1219 'fa_timestamp' => 'img_timestamp'
1220 ), $where, __METHOD__ );
1223 if ( count( $oldRels ) ) {
1224 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1225 $where = array(
1226 'oi_name' => $this->file->getName(),
1227 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1228 $dbw->insertSelect( 'filearchive', 'oldimage',
1229 array(
1230 'fa_storage_group' => $encGroup,
1231 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1232 'fa_deleted_user' => $encUserId,
1233 'fa_deleted_timestamp' => $encTimestamp,
1234 'fa_deleted_reason' => $encReason,
1235 'fa_deleted' => 0,
1237 'fa_name' => 'oi_name',
1238 'fa_archive_name' => 'oi_archive_name',
1239 'fa_size' => 'oi_size',
1240 'fa_width' => 'oi_width',
1241 'fa_height' => 'oi_height',
1242 'fa_metadata' => 'oi_metadata',
1243 'fa_bits' => 'oi_bits',
1244 'fa_media_type' => 'oi_media_type',
1245 'fa_major_mime' => 'oi_major_mime',
1246 'fa_minor_mime' => 'oi_minor_mime',
1247 'fa_description' => 'oi_description',
1248 'fa_user' => 'oi_user',
1249 'fa_user_text' => 'oi_user_text',
1250 'fa_timestamp' => 'oi_timestamp'
1251 ), $where, __METHOD__ );
1255 function doDBDeletes() {
1256 $dbw = $this->file->repo->getMasterDB();
1257 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1258 if ( $deleteCurrent ) {
1259 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1261 if ( count( $oldRels ) ) {
1262 $dbw->delete( 'oldimage',
1263 array(
1264 'oi_name' => $this->file->getName(),
1265 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1266 ), __METHOD__ );
1271 * Run the transaction
1273 function execute() {
1274 global $wgUser, $wgUseSquid;
1275 wfProfileIn( __METHOD__ );
1277 $this->file->lock();
1279 // Prepare deletion batch
1280 $hashes = $this->getHashes();
1281 $this->deletionBatch = array();
1282 $ext = $this->file->getExtension();
1283 $dotExt = $ext === '' ? '' : ".$ext";
1284 foreach ( $this->srcRels as $name => $srcRel ) {
1285 // Skip files that have no hash (missing source)
1286 if ( isset( $hashes[$name] ) ) {
1287 $hash = $hashes[$name];
1288 $key = $hash . $dotExt;
1289 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1290 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1294 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1295 // We acquire this lock by running the inserts now, before the file operations.
1297 // This potentially has poor lock contention characteristics -- an alternative
1298 // scheme would be to insert stub filearchive entries with no fa_name and commit
1299 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1300 $this->doDBInserts();
1302 // Execute the file deletion batch
1303 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1304 if ( !$status->isGood() ) {
1305 $this->status->merge( $status );
1308 if ( !$this->status->ok ) {
1309 // Critical file deletion error
1310 // Roll back inserts, release lock and abort
1311 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1312 $this->file->unlockAndRollback();
1313 return $this->status;
1316 // Purge squid
1317 if ( $wgUseSquid ) {
1318 $urls = array();
1319 foreach ( $this->srcRels as $srcRel ) {
1320 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1321 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1323 SquidUpdate::purge( $urls );
1326 // Delete image/oldimage rows
1327 $this->doDBDeletes();
1329 // Commit and return
1330 $this->file->unlock();
1331 wfProfileOut( __METHOD__ );
1332 return $this->status;
1336 #------------------------------------------------------------------------------
1339 * Helper class for file undeletion
1341 class LocalFileRestoreBatch {
1342 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1344 function __construct( File $file ) {
1345 $this->file = $file;
1346 $this->cleanupBatch = $this->ids = array();
1347 $this->ids = array();
1351 * Add a file by ID
1353 function addId( $fa_id ) {
1354 $this->ids[] = $fa_id;
1358 * Add a whole lot of files by ID
1360 function addIds( $ids ) {
1361 $this->ids = array_merge( $this->ids, $ids );
1365 * Add all revisions of the file
1367 function addAll() {
1368 $this->all = true;
1372 * Run the transaction, except the cleanup batch.
1373 * The cleanup batch should be run in a separate transaction, because it locks different
1374 * rows and there's no need to keep the image row locked while it's acquiring those locks
1375 * The caller may have its own transaction open.
1376 * So we save the batch and let the caller call cleanup()
1378 function execute() {
1379 global $wgUser, $wgLang;
1380 if ( !$this->all && !$this->ids ) {
1381 // Do nothing
1382 return $this->file->repo->newGood();
1385 $exists = $this->file->lock();
1386 $dbw = $this->file->repo->getMasterDB();
1387 $status = $this->file->repo->newGood();
1389 // Fetch all or selected archived revisions for the file,
1390 // sorted from the most recent to the oldest.
1391 $conditions = array( 'fa_name' => $this->file->getName() );
1392 if( !$this->all ) {
1393 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1396 $result = $dbw->select( 'filearchive', '*',
1397 $conditions,
1398 __METHOD__,
1399 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1401 $idsPresent = array();
1402 $storeBatch = array();
1403 $insertBatch = array();
1404 $insertCurrent = false;
1405 $deleteIds = array();
1406 $first = true;
1407 $archiveNames = array();
1408 while( $row = $dbw->fetchObject( $result ) ) {
1409 $idsPresent[] = $row->fa_id;
1410 if ( $this->unsuppress ) {
1411 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1412 } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
1413 // Skip restoring file revisions that the user cannot restore
1414 continue;
1416 if ( $row->fa_name != $this->file->getName() ) {
1417 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1418 $status->failCount++;
1419 continue;
1421 if ( $row->fa_storage_key == '' ) {
1422 // Revision was missing pre-deletion
1423 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1424 $status->failCount++;
1425 continue;
1428 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1429 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1431 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1432 # Fix leading zero
1433 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1434 $sha1 = substr( $sha1, 1 );
1437 if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1438 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1439 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1440 || is_null( $row->fa_metadata ) ) {
1441 // Refresh our metadata
1442 // Required for a new current revision; nice for older ones too. :)
1443 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1444 } else {
1445 $props = array(
1446 'minor_mime' => $row->fa_minor_mime,
1447 'major_mime' => $row->fa_major_mime,
1448 'media_type' => $row->fa_media_type,
1449 'metadata' => $row->fa_metadata );
1452 if ( $first && !$exists ) {
1453 // This revision will be published as the new current version
1454 $destRel = $this->file->getRel();
1455 $insertCurrent = array(
1456 'img_name' => $row->fa_name,
1457 'img_size' => $row->fa_size,
1458 'img_width' => $row->fa_width,
1459 'img_height' => $row->fa_height,
1460 'img_metadata' => $props['metadata'],
1461 'img_bits' => $row->fa_bits,
1462 'img_media_type' => $props['media_type'],
1463 'img_major_mime' => $props['major_mime'],
1464 'img_minor_mime' => $props['minor_mime'],
1465 'img_description' => $row->fa_description,
1466 'img_user' => $row->fa_user,
1467 'img_user_text' => $row->fa_user_text,
1468 'img_timestamp' => $row->fa_timestamp,
1469 'img_sha1' => $sha1);
1470 } else {
1471 $archiveName = $row->fa_archive_name;
1472 if( $archiveName == '' ) {
1473 // This was originally a current version; we
1474 // have to devise a new archive name for it.
1475 // Format is <timestamp of archiving>!<name>
1476 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1477 do {
1478 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1479 $timestamp++;
1480 } while ( isset( $archiveNames[$archiveName] ) );
1482 $archiveNames[$archiveName] = true;
1483 $destRel = $this->file->getArchiveRel( $archiveName );
1484 $insertBatch[] = array(
1485 'oi_name' => $row->fa_name,
1486 'oi_archive_name' => $archiveName,
1487 'oi_size' => $row->fa_size,
1488 'oi_width' => $row->fa_width,
1489 'oi_height' => $row->fa_height,
1490 'oi_bits' => $row->fa_bits,
1491 'oi_description' => $row->fa_description,
1492 'oi_user' => $row->fa_user,
1493 'oi_user_text' => $row->fa_user_text,
1494 'oi_timestamp' => $row->fa_timestamp,
1495 'oi_metadata' => $props['metadata'],
1496 'oi_media_type' => $props['media_type'],
1497 'oi_major_mime' => $props['major_mime'],
1498 'oi_minor_mime' => $props['minor_mime'],
1499 'oi_deleted' => $row->fa_deleted,
1500 'oi_sha1' => $sha1 );
1503 $deleteIds[] = $row->fa_id;
1504 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1505 $this->cleanupBatch[] = $row->fa_storage_key;
1506 $first = false;
1508 unset( $result );
1510 // Add a warning to the status object for missing IDs
1511 $missingIds = array_diff( $this->ids, $idsPresent );
1512 foreach ( $missingIds as $id ) {
1513 $status->error( 'undelete-missing-filearchive', $id );
1516 // Run the store batch
1517 // Use the OVERWRITE_SAME flag to smooth over a common error
1518 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1519 $status->merge( $storeStatus );
1521 if ( !$status->ok ) {
1522 // Store batch returned a critical error -- this usually means nothing was stored
1523 // Stop now and return an error
1524 $this->file->unlock();
1525 return $status;
1528 // Run the DB updates
1529 // Because we have locked the image row, key conflicts should be rare.
1530 // If they do occur, we can roll back the transaction at this time with
1531 // no data loss, but leaving unregistered files scattered throughout the
1532 // public zone.
1533 // This is not ideal, which is why it's important to lock the image row.
1534 if ( $insertCurrent ) {
1535 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1537 if ( $insertBatch ) {
1538 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1540 if ( $deleteIds ) {
1541 $dbw->delete( 'filearchive',
1542 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1543 __METHOD__ );
1546 if( $status->successCount > 0 ) {
1547 if( !$exists ) {
1548 wfDebug( __METHOD__." restored {$status->successCount} items, creating a new current\n" );
1550 // Update site_stats
1551 $site_stats = $dbw->tableName( 'site_stats' );
1552 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1554 $this->file->purgeEverything();
1555 } else {
1556 wfDebug( __METHOD__." restored {$status->successCount} as archived versions\n" );
1557 $this->file->purgeDescription();
1558 $this->file->purgeHistory();
1561 $this->file->unlock();
1562 return $status;
1566 * Delete unused files in the deleted zone.
1567 * This should be called from outside the transaction in which execute() was called.
1569 function cleanup() {
1570 if ( !$this->cleanupBatch ) {
1571 return $this->file->repo->newGood();
1573 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1574 return $status;