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
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 $tables = array('oldimage');
625 $join_conds = array();
626 $fields = OldLocalFile
::selectFields();
627 $conds = $opts = array();
628 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
629 if( $start !== null ) {
630 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
632 if( $end !== null ) {
633 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
636 $opts['LIMIT'] = $limit;
638 $opts['ORDER BY'] = 'oi_timestamp DESC';
640 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields, &$conds, &$opts, &$join_conds ) );
642 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
644 while( $row = $dbr->fetchObject($res) ) {
645 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
651 * Return the history of this file, line by line.
652 * starts with current version, then old versions.
653 * uses $this->historyLine to check which line to return:
654 * 0 return line for current version
655 * 1 query for old versions, return first one
656 * 2, ... return next old version from above query
660 function nextHistoryLine() {
661 # Polymorphic function name to distinguish foreign and local fetches
662 $fname = get_class( $this ) . '::' . __FUNCTION__
;
664 $dbr = $this->repo
->getSlaveDB();
666 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
667 $this->historyRes
= $dbr->select( 'image',
670 "'' AS oi_archive_name",
674 array( 'img_name' => $this->title
->getDBkey() ),
677 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
678 $dbr->freeResult($this->historyRes
);
679 $this->historyRes
= null;
682 } else if ( $this->historyLine
== 1 ) {
683 $dbr->freeResult($this->historyRes
);
684 $this->historyRes
= $dbr->select( 'oldimage', '*',
685 array( 'oi_name' => $this->title
->getDBkey() ),
687 array( 'ORDER BY' => 'oi_timestamp DESC' )
690 $this->historyLine ++
;
692 return $dbr->fetchObject( $this->historyRes
);
696 * Reset the history pointer to the first element of the history
699 function resetHistory() {
700 $this->historyLine
= 0;
701 if (!is_null($this->historyRes
)) {
702 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
703 $this->historyRes
= null;
707 /** getFullPath inherited */
708 /** getHashPath inherited */
709 /** getRel inherited */
710 /** getUrlRel inherited */
711 /** getArchiveRel inherited */
712 /** getThumbRel inherited */
713 /** getArchivePath inherited */
714 /** getThumbPath inherited */
715 /** getArchiveUrl inherited */
716 /** getThumbUrl inherited */
717 /** getArchiveVirtualUrl inherited */
718 /** getThumbVirtualUrl inherited */
719 /** isHashed inherited */
722 * Upload a file and record it in the DB
723 * @param string $srcPath Source path or virtual URL
724 * @param string $comment Upload description
725 * @param string $pageText Text to use for the new description page, if a new description page is created
726 * @param integer $flags Flags for publish()
727 * @param array $props File properties, if known. This can be used to reduce the
728 * upload time when uploading virtual URLs for which the file info
730 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
732 * @return FileRepoStatus object. On success, the value member contains the
733 * archive name, or an empty string if it was a new file.
735 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
737 $status = $this->publish( $srcPath, $flags );
739 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
740 $status->fatal( 'filenotfound', $srcPath );
748 * Record a file upload in the upload log and the image table
749 * @deprecated use upload()
751 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
752 $watch = false, $timestamp = false )
754 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
755 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
760 $wgUser->addWatch( $this->getTitle() );
767 * Record a file upload in the upload log and the image table
769 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
773 $dbw = $this->repo
->getMasterDB();
776 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
778 $props['description'] = $comment;
779 $props['user'] = $wgUser->getId();
780 $props['user_text'] = $wgUser->getName();
781 $props['timestamp'] = wfTimestamp( TS_MW
);
782 $this->setProps( $props );
784 // Delete thumbnails and refresh the metadata cache
785 $this->purgeThumbnails();
786 $this->saveToCache();
787 SquidUpdate
::purge( array( $this->getURL() ) );
789 // Fail now if the file isn't there
790 if ( !$this->fileExists
) {
791 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
796 if ( $timestamp === false ) {
797 $timestamp = $dbw->timestamp();
800 # Test to see if the row exists using INSERT IGNORE
801 # This avoids race conditions by locking the row until the commit, and also
802 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
803 $dbw->insert( 'image',
805 'img_name' => $this->getName(),
806 'img_size'=> $this->size
,
807 'img_width' => intval( $this->width
),
808 'img_height' => intval( $this->height
),
809 'img_bits' => $this->bits
,
810 'img_media_type' => $this->media_type
,
811 'img_major_mime' => $this->major_mime
,
812 'img_minor_mime' => $this->minor_mime
,
813 'img_timestamp' => $timestamp,
814 'img_description' => $comment,
815 'img_user' => $wgUser->getId(),
816 'img_user_text' => $wgUser->getName(),
817 'img_metadata' => $this->metadata
,
818 'img_sha1' => $this->sha1
824 if( $dbw->affectedRows() == 0 ) {
827 # Collision, this is an update of a file
828 # Insert previous contents into oldimage
829 $dbw->insertSelect( 'oldimage', 'image',
831 'oi_name' => 'img_name',
832 'oi_archive_name' => $dbw->addQuotes( $oldver ),
833 'oi_size' => 'img_size',
834 'oi_width' => 'img_width',
835 'oi_height' => 'img_height',
836 'oi_bits' => 'img_bits',
837 'oi_timestamp' => 'img_timestamp',
838 'oi_description' => 'img_description',
839 'oi_user' => 'img_user',
840 'oi_user_text' => 'img_user_text',
841 'oi_metadata' => 'img_metadata',
842 'oi_media_type' => 'img_media_type',
843 'oi_major_mime' => 'img_major_mime',
844 'oi_minor_mime' => 'img_minor_mime',
845 'oi_sha1' => 'img_sha1'
846 ), array( 'img_name' => $this->getName() ), __METHOD__
849 # Update the current image row
850 $dbw->update( 'image',
852 'img_size' => $this->size
,
853 'img_width' => intval( $this->width
),
854 'img_height' => intval( $this->height
),
855 'img_bits' => $this->bits
,
856 'img_media_type' => $this->media_type
,
857 'img_major_mime' => $this->major_mime
,
858 'img_minor_mime' => $this->minor_mime
,
859 'img_timestamp' => $timestamp,
860 'img_description' => $comment,
861 'img_user' => $wgUser->getId(),
862 'img_user_text' => $wgUser->getName(),
863 'img_metadata' => $this->metadata
,
864 'img_sha1' => $this->sha1
865 ), array( /* WHERE */
866 'img_name' => $this->getName()
871 # Update the image count
872 $site_stats = $dbw->tableName( 'site_stats' );
873 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
876 $descTitle = $this->getTitle();
877 $article = new Article( $descTitle );
880 $log = new LogPage( 'upload' );
881 $action = $reupload ?
'overwrite' : 'upload';
882 $log->addEntry( $action, $descTitle, $comment );
884 if( $descTitle->exists() ) {
885 # Create a null revision
886 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
887 $nullRevision->insertOn( $dbw );
889 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, false) );
890 $article->updateRevisionOn( $dbw, $nullRevision );
892 # Invalidate the cache for the description page
893 $descTitle->invalidateCache();
894 $descTitle->purgeSquid();
896 // New file; create the description page.
897 // There's already a log entry, so don't make a second RC entry
898 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
901 # Hooks, hooks, the magic of hooks...
902 wfRunHooks( 'FileUpload', array( $this ) );
904 # Commit the transaction now, in case something goes wrong later
905 # The most important thing is that files don't get lost, especially archives
906 $dbw->immediateCommit();
908 # Invalidate cache for all pages using this file
909 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
911 # Invalidate cache for all pages that redirects on this page
912 $redirs = $this->getTitle()->getRedirectsHere();
913 foreach( $redirs as $redir ) {
914 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
922 * Move or copy a file to its public location. If a file exists at the
923 * destination, move it to an archive. Returns the archive name on success
924 * or an empty string if it was a new file, and a wikitext-formatted
925 * WikiError object on failure.
927 * The archive name should be passed through to recordUpload for database
930 * @param string $sourcePath Local filesystem path to the source image
931 * @param integer $flags A bitwise combination of:
932 * File::DELETE_SOURCE Delete the source file, i.e. move
934 * @return FileRepoStatus object. On success, the value member contains the
935 * archive name, or an empty string if it was a new file.
937 function publish( $srcPath, $flags = 0 ) {
939 $dstRel = $this->getRel();
940 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
941 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
942 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
943 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
944 if ( $status->value
== 'new' ) {
947 $status->value
= $archiveName;
953 /** getLinksTo inherited */
954 /** getExifData inherited */
955 /** isLocal inherited */
956 /** wasDeleted inherited */
959 * Move file to the new title
961 * Move current, old version and all thumbnails
962 * to the new filename. Old file is deleted.
964 * Cache purging is done; checks for validity
965 * and logging are caller's responsibility
967 * @param $target Title New file name
968 * @return FileRepoStatus object.
970 function move( $target ) {
972 $dbw = $this->repo
->getMasterDB();
973 $batch = new LocalFileMoveBatch( $this, $target, $dbw );
974 $batch->addCurrent();
976 if( !$this->repo
->canTransformVia404() ) {
980 $status = $batch->execute();
981 $this->purgeEverything();
984 if ( $status->isOk() ) {
985 // Now switch the object
986 $this->title
= $target;
987 // Force regeneration of the name and hashpath
988 unset( $this->name
);
989 unset( $this->hashPath
);
990 // Purge the new image
991 $this->purgeEverything();
998 * Delete all versions of the file.
1000 * Moves the files into an archive directory (or deletes them)
1001 * and removes the database rows.
1003 * Cache purging is done; logging is caller's responsibility.
1007 * @return FileRepoStatus object.
1009 function delete( $reason, $suppress = false ) {
1011 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1012 $batch->addCurrent();
1014 # Get old version relative paths
1015 $dbw = $this->repo
->getMasterDB();
1016 $result = $dbw->select( 'oldimage',
1017 array( 'oi_archive_name' ),
1018 array( 'oi_name' => $this->getName() ) );
1019 while ( $row = $dbw->fetchObject( $result ) ) {
1020 $batch->addOld( $row->oi_archive_name
);
1022 $status = $batch->execute();
1024 if ( $status->ok
) {
1025 // Update site_stats
1026 $site_stats = $dbw->tableName( 'site_stats' );
1027 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1028 $this->purgeEverything();
1036 * Delete an old version of the file.
1038 * Moves the file into an archive directory (or deletes it)
1039 * and removes the database row.
1041 * Cache purging is done; logging is caller's responsibility.
1045 * @throws MWException or FSException on database or filestore failure
1046 * @return FileRepoStatus object.
1048 function deleteOld( $archiveName, $reason, $suppress=false ) {
1050 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1051 $batch->addOld( $archiveName );
1052 $status = $batch->execute();
1054 if ( $status->ok
) {
1055 $this->purgeDescription();
1056 $this->purgeHistory();
1062 * Restore all or specified deleted revisions to the given file.
1063 * Permissions and logging are left to the caller.
1065 * May throw database exceptions on error.
1067 * @param $versions set of record ids of deleted items to restore,
1068 * or empty to restore all revisions.
1070 * @return FileRepoStatus
1072 function restore( $versions = array(), $unsuppress = false ) {
1073 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1077 $batch->addIds( $versions );
1079 $status = $batch->execute();
1080 if ( !$status->ok
) {
1084 $cleanupStatus = $batch->cleanup();
1085 $cleanupStatus->successCount
= 0;
1086 $cleanupStatus->failCount
= 0;
1087 $status->merge( $cleanupStatus );
1091 /** isMultipage inherited */
1092 /** pageCount inherited */
1093 /** scaleHeight inherited */
1094 /** getImageSize inherited */
1097 * Get the URL of the file description page.
1099 function getDescriptionUrl() {
1100 return $this->title
->getLocalUrl();
1104 * Get the HTML text of the description page
1105 * This is not used by ImagePage for local files, since (among other things)
1106 * it skips the parser cache.
1108 function getDescriptionText() {
1110 $revision = Revision
::newFromTitle( $this->title
);
1111 if ( !$revision ) return false;
1112 $text = $revision->getText();
1113 if ( !$text ) return false;
1114 $html = $wgParser->parse( $text, new ParserOptions
);
1118 function getDescription() {
1120 return $this->description
;
1123 function getTimestamp() {
1125 return $this->timestamp
;
1128 function getSha1() {
1130 // Initialise now if necessary
1131 if ( $this->sha1
== '' && $this->fileExists
) {
1132 $this->sha1
= File
::sha1Base36( $this->getPath() );
1133 if ( strval( $this->sha1
) != '' ) {
1134 $dbw = $this->repo
->getMasterDB();
1135 $dbw->update( 'image',
1136 array( 'img_sha1' => $this->sha1
),
1137 array( 'img_name' => $this->getName() ),
1139 $this->saveToCache();
1147 * Start a transaction and lock the image for update
1148 * Increments a reference counter if the lock is already held
1149 * @return boolean True if the image exists, false otherwise
1152 $dbw = $this->repo
->getMasterDB();
1153 if ( !$this->locked
) {
1157 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1161 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1162 * the transaction and thereby releases the image lock.
1165 if ( $this->locked
) {
1167 if ( !$this->locked
) {
1168 $dbw = $this->repo
->getMasterDB();
1175 * Roll back the DB transaction and mark the image unlocked
1177 function unlockAndRollback() {
1178 $this->locked
= false;
1179 $dbw = $this->repo
->getMasterDB();
1182 } // LocalFile class
1184 #------------------------------------------------------------------------------
1187 * Helper class for file deletion
1190 class LocalFileDeleteBatch
{
1191 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1194 function __construct( File
$file, $reason = '', $suppress = false ) {
1195 $this->file
= $file;
1196 $this->reason
= $reason;
1197 $this->suppress
= $suppress;
1198 $this->status
= $file->repo
->newGood();
1201 function addCurrent() {
1202 $this->srcRels
['.'] = $this->file
->getRel();
1205 function addOld( $oldName ) {
1206 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1207 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1210 function getOldRels() {
1211 if ( !isset( $this->srcRels
['.'] ) ) {
1212 $oldRels =& $this->srcRels
;
1213 $deleteCurrent = false;
1215 $oldRels = $this->srcRels
;
1216 unset( $oldRels['.'] );
1217 $deleteCurrent = true;
1219 return array( $oldRels, $deleteCurrent );
1222 /*protected*/ function getHashes() {
1224 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1225 if ( $deleteCurrent ) {
1226 $hashes['.'] = $this->file
->getSha1();
1228 if ( count( $oldRels ) ) {
1229 $dbw = $this->file
->repo
->getMasterDB();
1230 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1231 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1233 while ( $row = $dbw->fetchObject( $res ) ) {
1234 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1235 // Get the hash from the file
1236 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1237 $props = $this->file
->repo
->getFileProps( $oldUrl );
1238 if ( $props['fileExists'] ) {
1239 // Upgrade the oldimage row
1240 $dbw->update( 'oldimage',
1241 array( 'oi_sha1' => $props['sha1'] ),
1242 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1244 $hashes[$row->oi_archive_name
] = $props['sha1'];
1246 $hashes[$row->oi_archive_name
] = false;
1249 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1253 $missing = array_diff_key( $this->srcRels
, $hashes );
1254 foreach ( $missing as $name => $rel ) {
1255 $this->status
->error( 'filedelete-old-unregistered', $name );
1257 foreach ( $hashes as $name => $hash ) {
1259 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1260 unset( $hashes[$name] );
1267 function doDBInserts() {
1269 $dbw = $this->file
->repo
->getMasterDB();
1270 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1271 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1272 $encReason = $dbw->addQuotes( $this->reason
);
1273 $encGroup = $dbw->addQuotes( 'deleted' );
1274 $ext = $this->file
->getExtension();
1275 $dotExt = $ext === '' ?
'' : ".$ext";
1276 $encExt = $dbw->addQuotes( $dotExt );
1277 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1279 // Bitfields to further suppress the content
1280 if ( $this->suppress
) {
1282 // This should be 15...
1283 $bitfield |
= Revision
::DELETED_TEXT
;
1284 $bitfield |
= Revision
::DELETED_COMMENT
;
1285 $bitfield |
= Revision
::DELETED_USER
;
1286 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1288 $bitfield = 'oi_deleted';
1291 if ( $deleteCurrent ) {
1292 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1293 $where = array( 'img_name' => $this->file
->getName() );
1294 $dbw->insertSelect( 'filearchive', 'image',
1296 'fa_storage_group' => $encGroup,
1297 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1298 'fa_deleted_user' => $encUserId,
1299 'fa_deleted_timestamp' => $encTimestamp,
1300 'fa_deleted_reason' => $encReason,
1301 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1303 'fa_name' => 'img_name',
1304 'fa_archive_name' => 'NULL',
1305 'fa_size' => 'img_size',
1306 'fa_width' => 'img_width',
1307 'fa_height' => 'img_height',
1308 'fa_metadata' => 'img_metadata',
1309 'fa_bits' => 'img_bits',
1310 'fa_media_type' => 'img_media_type',
1311 'fa_major_mime' => 'img_major_mime',
1312 'fa_minor_mime' => 'img_minor_mime',
1313 'fa_description' => 'img_description',
1314 'fa_user' => 'img_user',
1315 'fa_user_text' => 'img_user_text',
1316 'fa_timestamp' => 'img_timestamp'
1317 ), $where, __METHOD__
);
1320 if ( count( $oldRels ) ) {
1321 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1323 'oi_name' => $this->file
->getName(),
1324 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1325 $dbw->insertSelect( 'filearchive', 'oldimage',
1327 'fa_storage_group' => $encGroup,
1328 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1329 'fa_deleted_user' => $encUserId,
1330 'fa_deleted_timestamp' => $encTimestamp,
1331 'fa_deleted_reason' => $encReason,
1332 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1334 'fa_name' => 'oi_name',
1335 'fa_archive_name' => 'oi_archive_name',
1336 'fa_size' => 'oi_size',
1337 'fa_width' => 'oi_width',
1338 'fa_height' => 'oi_height',
1339 'fa_metadata' => 'oi_metadata',
1340 'fa_bits' => 'oi_bits',
1341 'fa_media_type' => 'oi_media_type',
1342 'fa_major_mime' => 'oi_major_mime',
1343 'fa_minor_mime' => 'oi_minor_mime',
1344 'fa_description' => 'oi_description',
1345 'fa_user' => 'oi_user',
1346 'fa_user_text' => 'oi_user_text',
1347 'fa_timestamp' => 'oi_timestamp',
1348 'fa_deleted' => $bitfield
1349 ), $where, __METHOD__
);
1353 function doDBDeletes() {
1354 $dbw = $this->file
->repo
->getMasterDB();
1355 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1356 if ( count( $oldRels ) ) {
1357 $dbw->delete( 'oldimage',
1359 'oi_name' => $this->file
->getName(),
1360 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1363 if ( $deleteCurrent ) {
1364 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1369 * Run the transaction
1371 function execute() {
1372 global $wgUser, $wgUseSquid;
1373 wfProfileIn( __METHOD__
);
1375 $this->file
->lock();
1376 // Leave private files alone
1377 $privateFiles = array();
1378 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1379 $dbw = $this->file
->repo
->getMasterDB();
1380 if( !empty( $oldRels ) ) {
1381 $res = $dbw->select( 'oldimage',
1382 array( 'oi_archive_name' ),
1383 array( 'oi_name' => $this->file
->getName(),
1384 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1385 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1387 while( $row = $dbw->fetchObject( $res ) ) {
1388 $privateFiles[$row->oi_archive_name
] = 1;
1391 // Prepare deletion batch
1392 $hashes = $this->getHashes();
1393 $this->deletionBatch
= array();
1394 $ext = $this->file
->getExtension();
1395 $dotExt = $ext === '' ?
'' : ".$ext";
1396 foreach ( $this->srcRels
as $name => $srcRel ) {
1397 // Skip files that have no hash (missing source).
1398 // Keep private files where they are.
1399 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1400 $hash = $hashes[$name];
1401 $key = $hash . $dotExt;
1402 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1403 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1407 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1408 // We acquire this lock by running the inserts now, before the file operations.
1410 // This potentially has poor lock contention characteristics -- an alternative
1411 // scheme would be to insert stub filearchive entries with no fa_name and commit
1412 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1413 $this->doDBInserts();
1415 // Execute the file deletion batch
1416 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1417 if ( !$status->isGood() ) {
1418 $this->status
->merge( $status );
1421 if ( !$this->status
->ok
) {
1422 // Critical file deletion error
1423 // Roll back inserts, release lock and abort
1424 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1425 $this->file
->unlockAndRollback();
1426 return $this->status
;
1430 if ( $wgUseSquid ) {
1432 foreach ( $this->srcRels
as $srcRel ) {
1433 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1434 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1436 SquidUpdate
::purge( $urls );
1439 // Delete image/oldimage rows
1440 $this->doDBDeletes();
1442 // Commit and return
1443 $this->file
->unlock();
1444 wfProfileOut( __METHOD__
);
1445 return $this->status
;
1449 #------------------------------------------------------------------------------
1452 * Helper class for file undeletion
1455 class LocalFileRestoreBatch
{
1456 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1458 function __construct( File
$file, $unsuppress = false ) {
1459 $this->file
= $file;
1460 $this->cleanupBatch
= $this->ids
= array();
1461 $this->ids
= array();
1462 $this->unsuppress
= $unsuppress;
1468 function addId( $fa_id ) {
1469 $this->ids
[] = $fa_id;
1473 * Add a whole lot of files by ID
1475 function addIds( $ids ) {
1476 $this->ids
= array_merge( $this->ids
, $ids );
1480 * Add all revisions of the file
1487 * Run the transaction, except the cleanup batch.
1488 * The cleanup batch should be run in a separate transaction, because it locks different
1489 * rows and there's no need to keep the image row locked while it's acquiring those locks
1490 * The caller may have its own transaction open.
1491 * So we save the batch and let the caller call cleanup()
1493 function execute() {
1494 global $wgUser, $wgLang;
1495 if ( !$this->all
&& !$this->ids
) {
1497 return $this->file
->repo
->newGood();
1500 $exists = $this->file
->lock();
1501 $dbw = $this->file
->repo
->getMasterDB();
1502 $status = $this->file
->repo
->newGood();
1504 // Fetch all or selected archived revisions for the file,
1505 // sorted from the most recent to the oldest.
1506 $conditions = array( 'fa_name' => $this->file
->getName() );
1508 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1511 $result = $dbw->select( 'filearchive', '*',
1514 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1516 $idsPresent = array();
1517 $storeBatch = array();
1518 $insertBatch = array();
1519 $insertCurrent = false;
1520 $deleteIds = array();
1522 $archiveNames = array();
1523 while( $row = $dbw->fetchObject( $result ) ) {
1524 $idsPresent[] = $row->fa_id
;
1526 if ( $row->fa_name
!= $this->file
->getName() ) {
1527 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1528 $status->failCount++
;
1531 if ( $row->fa_storage_key
== '' ) {
1532 // Revision was missing pre-deletion
1533 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1534 $status->failCount++
;
1538 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1539 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1541 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1543 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1544 $sha1 = substr( $sha1, 1 );
1547 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1548 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1549 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1550 ||
is_null( $row->fa_metadata
) ) {
1551 // Refresh our metadata
1552 // Required for a new current revision; nice for older ones too. :)
1553 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1556 'minor_mime' => $row->fa_minor_mime
,
1557 'major_mime' => $row->fa_major_mime
,
1558 'media_type' => $row->fa_media_type
,
1559 'metadata' => $row->fa_metadata
);
1562 if ( $first && !$exists ) {
1563 // The live (current) version cannot be hidden!
1564 if( !$this->unsuppress
&& $row->fa_deleted
) {
1565 $this->file
->unlock();
1568 // This revision will be published as the new current version
1569 $destRel = $this->file
->getRel();
1570 $insertCurrent = array(
1571 'img_name' => $row->fa_name
,
1572 'img_size' => $row->fa_size
,
1573 'img_width' => $row->fa_width
,
1574 'img_height' => $row->fa_height
,
1575 'img_metadata' => $props['metadata'],
1576 'img_bits' => $row->fa_bits
,
1577 'img_media_type' => $props['media_type'],
1578 'img_major_mime' => $props['major_mime'],
1579 'img_minor_mime' => $props['minor_mime'],
1580 'img_description' => $row->fa_description
,
1581 'img_user' => $row->fa_user
,
1582 'img_user_text' => $row->fa_user_text
,
1583 'img_timestamp' => $row->fa_timestamp
,
1584 'img_sha1' => $sha1);
1586 $archiveName = $row->fa_archive_name
;
1587 if( $archiveName == '' ) {
1588 // This was originally a current version; we
1589 // have to devise a new archive name for it.
1590 // Format is <timestamp of archiving>!<name>
1591 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1593 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1595 } while ( isset( $archiveNames[$archiveName] ) );
1597 $archiveNames[$archiveName] = true;
1598 $destRel = $this->file
->getArchiveRel( $archiveName );
1599 $insertBatch[] = array(
1600 'oi_name' => $row->fa_name
,
1601 'oi_archive_name' => $archiveName,
1602 'oi_size' => $row->fa_size
,
1603 'oi_width' => $row->fa_width
,
1604 'oi_height' => $row->fa_height
,
1605 'oi_bits' => $row->fa_bits
,
1606 'oi_description' => $row->fa_description
,
1607 'oi_user' => $row->fa_user
,
1608 'oi_user_text' => $row->fa_user_text
,
1609 'oi_timestamp' => $row->fa_timestamp
,
1610 'oi_metadata' => $props['metadata'],
1611 'oi_media_type' => $props['media_type'],
1612 'oi_major_mime' => $props['major_mime'],
1613 'oi_minor_mime' => $props['minor_mime'],
1614 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1615 'oi_sha1' => $sha1 );
1618 $deleteIds[] = $row->fa_id
;
1619 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1620 // private files can stay where they are
1622 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1623 $this->cleanupBatch
[] = $row->fa_storage_key
;
1629 // Add a warning to the status object for missing IDs
1630 $missingIds = array_diff( $this->ids
, $idsPresent );
1631 foreach ( $missingIds as $id ) {
1632 $status->error( 'undelete-missing-filearchive', $id );
1635 // Run the store batch
1636 // Use the OVERWRITE_SAME flag to smooth over a common error
1637 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1638 $status->merge( $storeStatus );
1640 if ( !$status->ok
) {
1641 // Store batch returned a critical error -- this usually means nothing was stored
1642 // Stop now and return an error
1643 $this->file
->unlock();
1647 // Run the DB updates
1648 // Because we have locked the image row, key conflicts should be rare.
1649 // If they do occur, we can roll back the transaction at this time with
1650 // no data loss, but leaving unregistered files scattered throughout the
1652 // This is not ideal, which is why it's important to lock the image row.
1653 if ( $insertCurrent ) {
1654 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1656 if ( $insertBatch ) {
1657 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1660 $dbw->delete( 'filearchive',
1661 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1665 if( $status->successCount
> 0 ) {
1667 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1669 // Update site_stats
1670 $site_stats = $dbw->tableName( 'site_stats' );
1671 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1673 $this->file
->purgeEverything();
1675 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1676 $this->file
->purgeDescription();
1677 $this->file
->purgeHistory();
1680 $this->file
->unlock();
1685 * Delete unused files in the deleted zone.
1686 * This should be called from outside the transaction in which execute() was called.
1688 function cleanup() {
1689 if ( !$this->cleanupBatch
) {
1690 return $this->file
->repo
->newGood();
1692 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1697 #------------------------------------------------------------------------------
1700 * Helper class for file movement
1703 class LocalFileMoveBatch
{
1704 var $file, $cur, $olds, $oldcount, $archive, $thumbs, $target, $db;
1706 function __construct( File
$file, Title
$target, Database
$db ) {
1707 $this->file
= $file;
1708 $this->target
= $target;
1709 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1710 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDbKey() );
1711 $this->oldName
= $this->file
->getName();
1712 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1713 $this->oldRel
= $this->oldHash
. $this->oldName
;
1714 $this->newRel
= $this->newHash
. $this->newName
;
1718 function addCurrent() {
1719 $this->cur
= array( $this->oldRel
, $this->newRel
);
1722 function addThumbs() {
1723 // Thumbnails are purged, so no need to move them
1724 $this->thumbs
= array();
1727 function addOlds() {
1728 $archiveBase = 'archive';
1729 $this->olds
= array();
1730 $this->oldcount
= 0;
1732 $result = $this->db
->select( 'oldimage',
1733 array( 'oi_archive_name', 'oi_deleted' ),
1734 array( 'oi_name' => $this->oldName
),
1737 while( $row = $this->db
->fetchObject( $result ) ) {
1738 $oldname = $row->oi_archive_name
;
1739 $bits = explode( '!', $oldname, 2 );
1740 if( count( $bits ) != 2 ) {
1741 wfDebug( 'Invalid old file name: ' . $oldname );
1744 list( $timestamp, $filename ) = $bits;
1745 if( $this->oldName
!= $filename ) {
1746 wfDebug( 'Invalid old file name:' . $oldName );
1750 // Do we want to add those to oldcount?
1751 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1754 $this->olds
[] = array(
1755 "{$archiveBase}/{$this->oldHash}{$oldname}",
1756 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1759 $this->db
->freeResult( $result );
1762 function execute() {
1763 $repo = $this->file
->repo
;
1764 $status = $repo->newGood();
1765 $triplets = $this->getMoveTriplets();
1767 $statusDb = $this->doDBUpdates();
1768 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1769 if( !$statusMove->isOk() ) {
1770 $this->db
->rollback();
1772 $status->merge( $statusDb );
1773 $status->merge( $statusMove );
1777 function doDBUpdates() {
1778 $repo = $this->file
->repo
;
1779 $status = $repo->newGood();
1782 // Update current image
1785 array( 'img_name' => $this->newName
),
1786 array( 'img_name' => $this->oldName
),
1789 if( $dbw->affectedRows() ) {
1790 $status->successCount++
;
1792 $status->failCount++
;
1795 // Update old images
1799 'oi_name' => $this->newName
,
1800 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1802 array( 'oi_name' => $this->oldName
),
1805 $affected = $dbw->affectedRows();
1806 $total = $this->oldcount
;
1807 $status->successCount +
= $affected;
1808 $status->failCount +
= $total - $affected;
1813 // Generates triplets for FSRepo::storeBatch()
1814 function getMoveTriplets() {
1815 $moves = array_merge( array( $this->cur
), $this->olds
, $this->thumbs
);
1816 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1817 foreach( $moves as $move ) {
1818 // $move: (oldRelativePath, newRelativePath)
1819 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1820 $triplets[] = array( $srcUrl, 'public', $move[1] );