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
;
456 function getBitDepth() {
462 * Return the size of the image file, in bytes
471 * Returns the mime type of the file.
473 function getMimeType() {
479 * Return the type of the media in the file.
480 * Use the value returned by this function with the MEDIATYPE_xxx constants.
482 function getMediaType() {
484 return $this->media_type
;
487 /** canRender inherited */
488 /** mustRender inherited */
489 /** allowInlineDisplay inherited */
490 /** isSafeFile inherited */
491 /** isTrustedFile inherited */
494 * Returns true if the file file exists on disk.
495 * @return boolean Whether file file exist on disk.
500 return $this->fileExists
;
503 /** getTransformScript inherited */
504 /** getUnscaledThumb inherited */
505 /** thumbName inherited */
506 /** createThumb inherited */
507 /** getThumbnail inherited */
508 /** transform inherited */
511 * Fix thumbnail files from 1.4 or before, with extreme prejudice
513 function migrateThumbFile( $thumbName ) {
514 $thumbDir = $this->getThumbPath();
515 $thumbPath = "$thumbDir/$thumbName";
516 if ( is_dir( $thumbPath ) ) {
517 // Directory where file should be
518 // This happened occasionally due to broken migration code in 1.5
519 // Rename to broken-*
520 for ( $i = 0; $i < 100 ; $i++
) {
521 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
522 if ( !file_exists( $broken ) ) {
523 rename( $thumbPath, $broken );
527 // Doesn't exist anymore
530 if ( is_file( $thumbDir ) ) {
531 // File where directory should be
533 // Doesn't exist anymore
538 /** getHandler inherited */
539 /** iconThumb inherited */
540 /** getLastError inherited */
543 * Get all thumbnail names previously generated for this file
545 function getThumbnails() {
548 $dir = $this->getThumbPath();
550 if ( is_dir( $dir ) ) {
551 $handle = opendir( $dir );
554 while ( false !== ( $file = readdir($handle) ) ) {
555 if ( $file{0} != '.' ) {
567 * Refresh metadata in memcached, but don't touch thumbnails or squid
569 function purgeMetadataCache() {
571 $this->saveToCache();
572 $this->purgeHistory();
576 * Purge the shared history (OldLocalFile) cache
578 function purgeHistory() {
580 $hashedName = md5($this->getName());
581 $oldKey = wfMemcKey( 'oldfile', $hashedName );
582 $wgMemc->delete( $oldKey );
586 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
588 function purgeCache() {
589 // Refresh metadata cache
590 $this->purgeMetadataCache();
593 $this->purgeThumbnails();
595 // Purge squid cache for this file
596 SquidUpdate
::purge( array( $this->getURL() ) );
600 * Delete cached transformed files
602 function purgeThumbnails() {
605 $files = $this->getThumbnails();
606 $dir = $this->getThumbPath();
608 foreach ( $files as $file ) {
609 # Check that the base file name is part of the thumb name
610 # This is a basic sanity check to avoid erasing unrelated directories
611 if ( strpos( $file, $this->getName() ) !== false ) {
612 $url = $this->getThumbUrl( $file );
614 @unlink
( "$dir/$file" );
620 SquidUpdate
::purge( $urls );
624 /** purgeDescription inherited */
625 /** purgeEverything inherited */
627 function getHistory($limit = null, $start = null, $end = null) {
628 $dbr = $this->repo
->getSlaveDB();
629 $tables = array('oldimage');
630 $join_conds = array();
631 $fields = OldLocalFile
::selectFields();
632 $conds = $opts = array();
633 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
634 if( $start !== null ) {
635 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
637 if( $end !== null ) {
638 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
641 $opts['LIMIT'] = $limit;
643 $opts['ORDER BY'] = 'oi_timestamp DESC';
645 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields, &$conds, &$opts, &$join_conds ) );
647 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
649 while( $row = $dbr->fetchObject($res) ) {
650 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
656 * Return the history of this file, line by line.
657 * starts with current version, then old versions.
658 * uses $this->historyLine to check which line to return:
659 * 0 return line for current version
660 * 1 query for old versions, return first one
661 * 2, ... return next old version from above query
665 function nextHistoryLine() {
666 # Polymorphic function name to distinguish foreign and local fetches
667 $fname = get_class( $this ) . '::' . __FUNCTION__
;
669 $dbr = $this->repo
->getSlaveDB();
671 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
672 $this->historyRes
= $dbr->select( 'image',
675 "'' AS oi_archive_name",
679 array( 'img_name' => $this->title
->getDBkey() ),
682 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
683 $dbr->freeResult($this->historyRes
);
684 $this->historyRes
= null;
687 } else if ( $this->historyLine
== 1 ) {
688 $dbr->freeResult($this->historyRes
);
689 $this->historyRes
= $dbr->select( 'oldimage', '*',
690 array( 'oi_name' => $this->title
->getDBkey() ),
692 array( 'ORDER BY' => 'oi_timestamp DESC' )
695 $this->historyLine ++
;
697 return $dbr->fetchObject( $this->historyRes
);
701 * Reset the history pointer to the first element of the history
704 function resetHistory() {
705 $this->historyLine
= 0;
706 if (!is_null($this->historyRes
)) {
707 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
708 $this->historyRes
= null;
712 /** getFullPath inherited */
713 /** getHashPath inherited */
714 /** getRel inherited */
715 /** getUrlRel inherited */
716 /** getArchiveRel inherited */
717 /** getThumbRel inherited */
718 /** getArchivePath inherited */
719 /** getThumbPath inherited */
720 /** getArchiveUrl inherited */
721 /** getThumbUrl inherited */
722 /** getArchiveVirtualUrl inherited */
723 /** getThumbVirtualUrl inherited */
724 /** isHashed inherited */
727 * Upload a file and record it in the DB
728 * @param string $srcPath Source path or virtual URL
729 * @param string $comment Upload description
730 * @param string $pageText Text to use for the new description page, if a new description page is created
731 * @param integer $flags Flags for publish()
732 * @param array $props File properties, if known. This can be used to reduce the
733 * upload time when uploading virtual URLs for which the file info
735 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
737 * @return FileRepoStatus object. On success, the value member contains the
738 * archive name, or an empty string if it was a new file.
740 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
742 $status = $this->publish( $srcPath, $flags );
744 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
745 $status->fatal( 'filenotfound', $srcPath );
753 * Record a file upload in the upload log and the image table
754 * @deprecated use upload()
756 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
757 $watch = false, $timestamp = false )
759 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
760 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
765 $wgUser->addWatch( $this->getTitle() );
772 * Record a file upload in the upload log and the image table
774 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
778 $dbw = $this->repo
->getMasterDB();
781 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
783 $props['description'] = $comment;
784 $props['user'] = $wgUser->getId();
785 $props['user_text'] = $wgUser->getName();
786 $props['timestamp'] = wfTimestamp( TS_MW
);
787 $this->setProps( $props );
789 // Delete thumbnails and refresh the metadata cache
790 $this->purgeThumbnails();
791 $this->saveToCache();
792 SquidUpdate
::purge( array( $this->getURL() ) );
794 // Fail now if the file isn't there
795 if ( !$this->fileExists
) {
796 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
801 if ( $timestamp === false ) {
802 $timestamp = $dbw->timestamp();
805 # Test to see if the row exists using INSERT IGNORE
806 # This avoids race conditions by locking the row until the commit, and also
807 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
808 $dbw->insert( 'image',
810 'img_name' => $this->getName(),
811 'img_size'=> $this->size
,
812 'img_width' => intval( $this->width
),
813 'img_height' => intval( $this->height
),
814 'img_bits' => $this->bits
,
815 'img_media_type' => $this->media_type
,
816 'img_major_mime' => $this->major_mime
,
817 'img_minor_mime' => $this->minor_mime
,
818 'img_timestamp' => $timestamp,
819 'img_description' => $comment,
820 'img_user' => $wgUser->getId(),
821 'img_user_text' => $wgUser->getName(),
822 'img_metadata' => $this->metadata
,
823 'img_sha1' => $this->sha1
829 if( $dbw->affectedRows() == 0 ) {
832 # Collision, this is an update of a file
833 # Insert previous contents into oldimage
834 $dbw->insertSelect( 'oldimage', 'image',
836 'oi_name' => 'img_name',
837 'oi_archive_name' => $dbw->addQuotes( $oldver ),
838 'oi_size' => 'img_size',
839 'oi_width' => 'img_width',
840 'oi_height' => 'img_height',
841 'oi_bits' => 'img_bits',
842 'oi_timestamp' => 'img_timestamp',
843 'oi_description' => 'img_description',
844 'oi_user' => 'img_user',
845 'oi_user_text' => 'img_user_text',
846 'oi_metadata' => 'img_metadata',
847 'oi_media_type' => 'img_media_type',
848 'oi_major_mime' => 'img_major_mime',
849 'oi_minor_mime' => 'img_minor_mime',
850 'oi_sha1' => 'img_sha1'
851 ), array( 'img_name' => $this->getName() ), __METHOD__
854 # Update the current image row
855 $dbw->update( 'image',
857 'img_size' => $this->size
,
858 'img_width' => intval( $this->width
),
859 'img_height' => intval( $this->height
),
860 'img_bits' => $this->bits
,
861 'img_media_type' => $this->media_type
,
862 'img_major_mime' => $this->major_mime
,
863 'img_minor_mime' => $this->minor_mime
,
864 'img_timestamp' => $timestamp,
865 'img_description' => $comment,
866 'img_user' => $wgUser->getId(),
867 'img_user_text' => $wgUser->getName(),
868 'img_metadata' => $this->metadata
,
869 'img_sha1' => $this->sha1
870 ), array( /* WHERE */
871 'img_name' => $this->getName()
876 # Update the image count
877 $site_stats = $dbw->tableName( 'site_stats' );
878 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
881 $descTitle = $this->getTitle();
882 $article = new Article( $descTitle );
885 $log = new LogPage( 'upload' );
886 $action = $reupload ?
'overwrite' : 'upload';
887 $log->addEntry( $action, $descTitle, $comment );
889 if( $descTitle->exists() ) {
890 # Create a null revision
891 $latest = $descTitle->getLatestRevID();
892 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
893 $nullRevision->insertOn( $dbw );
895 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
896 $article->updateRevisionOn( $dbw, $nullRevision );
898 # Invalidate the cache for the description page
899 $descTitle->invalidateCache();
900 $descTitle->purgeSquid();
902 // New file; create the description page.
903 // There's already a log entry, so don't make a second RC entry
904 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
907 # Hooks, hooks, the magic of hooks...
908 wfRunHooks( 'FileUpload', array( $this ) );
910 # Commit the transaction now, in case something goes wrong later
911 # The most important thing is that files don't get lost, especially archives
912 $dbw->immediateCommit();
914 # Invalidate cache for all pages using this file
915 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
917 # Invalidate cache for all pages that redirects on this page
918 $redirs = $this->getTitle()->getRedirectsHere();
919 foreach( $redirs as $redir ) {
920 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
928 * Move or copy a file to its public location. If a file exists at the
929 * destination, move it to an archive. Returns the archive name on success
930 * or an empty string if it was a new file, and a wikitext-formatted
931 * WikiError object on failure.
933 * The archive name should be passed through to recordUpload for database
936 * @param string $sourcePath Local filesystem path to the source image
937 * @param integer $flags A bitwise combination of:
938 * File::DELETE_SOURCE Delete the source file, i.e. move
940 * @return FileRepoStatus object. On success, the value member contains the
941 * archive name, or an empty string if it was a new file.
943 function publish( $srcPath, $flags = 0 ) {
945 $dstRel = $this->getRel();
946 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
947 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
948 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
949 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
950 if ( $status->value
== 'new' ) {
953 $status->value
= $archiveName;
959 /** getLinksTo inherited */
960 /** getExifData inherited */
961 /** isLocal inherited */
962 /** wasDeleted inherited */
965 * Move file to the new title
967 * Move current, old version and all thumbnails
968 * to the new filename. Old file is deleted.
970 * Cache purging is done; checks for validity
971 * and logging are caller's responsibility
973 * @param $target Title New file name
974 * @return FileRepoStatus object.
976 function move( $target ) {
977 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
979 $batch = new LocalFileMoveBatch( $this, $target );
980 $batch->addCurrent();
983 $status = $batch->execute();
984 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
985 $this->purgeEverything();
988 if ( $status->isOk() ) {
989 // Now switch the object
990 $this->title
= $target;
991 // Force regeneration of the name and hashpath
992 unset( $this->name
);
993 unset( $this->hashPath
);
994 // Purge the new image
995 $this->purgeEverything();
1002 * Delete all versions of the file.
1004 * Moves the files into an archive directory (or deletes them)
1005 * and removes the database rows.
1007 * Cache purging is done; logging is caller's responsibility.
1011 * @return FileRepoStatus object.
1013 function delete( $reason, $suppress = false ) {
1015 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1016 $batch->addCurrent();
1018 # Get old version relative paths
1019 $dbw = $this->repo
->getMasterDB();
1020 $result = $dbw->select( 'oldimage',
1021 array( 'oi_archive_name' ),
1022 array( 'oi_name' => $this->getName() ) );
1023 while ( $row = $dbw->fetchObject( $result ) ) {
1024 $batch->addOld( $row->oi_archive_name
);
1026 $status = $batch->execute();
1028 if ( $status->ok
) {
1029 // Update site_stats
1030 $site_stats = $dbw->tableName( 'site_stats' );
1031 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1032 $this->purgeEverything();
1040 * Delete an old version of the file.
1042 * Moves the file into an archive directory (or deletes it)
1043 * and removes the database row.
1045 * Cache purging is done; logging is caller's responsibility.
1049 * @throws MWException or FSException on database or filestore failure
1050 * @return FileRepoStatus object.
1052 function deleteOld( $archiveName, $reason, $suppress=false ) {
1054 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1055 $batch->addOld( $archiveName );
1056 $status = $batch->execute();
1058 if ( $status->ok
) {
1059 $this->purgeDescription();
1060 $this->purgeHistory();
1066 * Restore all or specified deleted revisions to the given file.
1067 * Permissions and logging are left to the caller.
1069 * May throw database exceptions on error.
1071 * @param $versions set of record ids of deleted items to restore,
1072 * or empty to restore all revisions.
1074 * @return FileRepoStatus
1076 function restore( $versions = array(), $unsuppress = false ) {
1077 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1081 $batch->addIds( $versions );
1083 $status = $batch->execute();
1084 if ( !$status->ok
) {
1088 $cleanupStatus = $batch->cleanup();
1089 $cleanupStatus->successCount
= 0;
1090 $cleanupStatus->failCount
= 0;
1091 $status->merge( $cleanupStatus );
1095 /** isMultipage inherited */
1096 /** pageCount inherited */
1097 /** scaleHeight inherited */
1098 /** getImageSize inherited */
1101 * Get the URL of the file description page.
1103 function getDescriptionUrl() {
1104 return $this->title
->getLocalUrl();
1108 * Get the HTML text of the description page
1109 * This is not used by ImagePage for local files, since (among other things)
1110 * it skips the parser cache.
1112 function getDescriptionText() {
1114 $revision = Revision
::newFromTitle( $this->title
);
1115 if ( !$revision ) return false;
1116 $text = $revision->getText();
1117 if ( !$text ) return false;
1118 $html = $wgParser->parse( $text, new ParserOptions
);
1122 function getDescription() {
1124 return $this->description
;
1127 function getTimestamp() {
1129 return $this->timestamp
;
1132 function getSha1() {
1134 // Initialise now if necessary
1135 if ( $this->sha1
== '' && $this->fileExists
) {
1136 $this->sha1
= File
::sha1Base36( $this->getPath() );
1137 if ( strval( $this->sha1
) != '' ) {
1138 $dbw = $this->repo
->getMasterDB();
1139 $dbw->update( 'image',
1140 array( 'img_sha1' => $this->sha1
),
1141 array( 'img_name' => $this->getName() ),
1143 $this->saveToCache();
1151 * Start a transaction and lock the image for update
1152 * Increments a reference counter if the lock is already held
1153 * @return boolean True if the image exists, false otherwise
1156 $dbw = $this->repo
->getMasterDB();
1157 if ( !$this->locked
) {
1161 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1165 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1166 * the transaction and thereby releases the image lock.
1169 if ( $this->locked
) {
1171 if ( !$this->locked
) {
1172 $dbw = $this->repo
->getMasterDB();
1179 * Roll back the DB transaction and mark the image unlocked
1181 function unlockAndRollback() {
1182 $this->locked
= false;
1183 $dbw = $this->repo
->getMasterDB();
1186 } // LocalFile class
1188 #------------------------------------------------------------------------------
1191 * Helper class for file deletion
1194 class LocalFileDeleteBatch
{
1195 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1198 function __construct( File
$file, $reason = '', $suppress = false ) {
1199 $this->file
= $file;
1200 $this->reason
= $reason;
1201 $this->suppress
= $suppress;
1202 $this->status
= $file->repo
->newGood();
1205 function addCurrent() {
1206 $this->srcRels
['.'] = $this->file
->getRel();
1209 function addOld( $oldName ) {
1210 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1211 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1214 function getOldRels() {
1215 if ( !isset( $this->srcRels
['.'] ) ) {
1216 $oldRels =& $this->srcRels
;
1217 $deleteCurrent = false;
1219 $oldRels = $this->srcRels
;
1220 unset( $oldRels['.'] );
1221 $deleteCurrent = true;
1223 return array( $oldRels, $deleteCurrent );
1226 /*protected*/ function getHashes() {
1228 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1229 if ( $deleteCurrent ) {
1230 $hashes['.'] = $this->file
->getSha1();
1232 if ( count( $oldRels ) ) {
1233 $dbw = $this->file
->repo
->getMasterDB();
1234 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1235 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1237 while ( $row = $dbw->fetchObject( $res ) ) {
1238 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1239 // Get the hash from the file
1240 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1241 $props = $this->file
->repo
->getFileProps( $oldUrl );
1242 if ( $props['fileExists'] ) {
1243 // Upgrade the oldimage row
1244 $dbw->update( 'oldimage',
1245 array( 'oi_sha1' => $props['sha1'] ),
1246 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1248 $hashes[$row->oi_archive_name
] = $props['sha1'];
1250 $hashes[$row->oi_archive_name
] = false;
1253 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1257 $missing = array_diff_key( $this->srcRels
, $hashes );
1258 foreach ( $missing as $name => $rel ) {
1259 $this->status
->error( 'filedelete-old-unregistered', $name );
1261 foreach ( $hashes as $name => $hash ) {
1263 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1264 unset( $hashes[$name] );
1271 function doDBInserts() {
1273 $dbw = $this->file
->repo
->getMasterDB();
1274 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1275 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1276 $encReason = $dbw->addQuotes( $this->reason
);
1277 $encGroup = $dbw->addQuotes( 'deleted' );
1278 $ext = $this->file
->getExtension();
1279 $dotExt = $ext === '' ?
'' : ".$ext";
1280 $encExt = $dbw->addQuotes( $dotExt );
1281 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1283 // Bitfields to further suppress the content
1284 if ( $this->suppress
) {
1286 // This should be 15...
1287 $bitfield |
= Revision
::DELETED_TEXT
;
1288 $bitfield |
= Revision
::DELETED_COMMENT
;
1289 $bitfield |
= Revision
::DELETED_USER
;
1290 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1292 $bitfield = 'oi_deleted';
1295 if ( $deleteCurrent ) {
1296 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1297 $where = array( 'img_name' => $this->file
->getName() );
1298 $dbw->insertSelect( 'filearchive', 'image',
1300 'fa_storage_group' => $encGroup,
1301 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1302 'fa_deleted_user' => $encUserId,
1303 'fa_deleted_timestamp' => $encTimestamp,
1304 'fa_deleted_reason' => $encReason,
1305 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1307 'fa_name' => 'img_name',
1308 'fa_archive_name' => 'NULL',
1309 'fa_size' => 'img_size',
1310 'fa_width' => 'img_width',
1311 'fa_height' => 'img_height',
1312 'fa_metadata' => 'img_metadata',
1313 'fa_bits' => 'img_bits',
1314 'fa_media_type' => 'img_media_type',
1315 'fa_major_mime' => 'img_major_mime',
1316 'fa_minor_mime' => 'img_minor_mime',
1317 'fa_description' => 'img_description',
1318 'fa_user' => 'img_user',
1319 'fa_user_text' => 'img_user_text',
1320 'fa_timestamp' => 'img_timestamp'
1321 ), $where, __METHOD__
);
1324 if ( count( $oldRels ) ) {
1325 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1327 'oi_name' => $this->file
->getName(),
1328 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1329 $dbw->insertSelect( 'filearchive', 'oldimage',
1331 'fa_storage_group' => $encGroup,
1332 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1333 'fa_deleted_user' => $encUserId,
1334 'fa_deleted_timestamp' => $encTimestamp,
1335 'fa_deleted_reason' => $encReason,
1336 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1338 'fa_name' => 'oi_name',
1339 'fa_archive_name' => 'oi_archive_name',
1340 'fa_size' => 'oi_size',
1341 'fa_width' => 'oi_width',
1342 'fa_height' => 'oi_height',
1343 'fa_metadata' => 'oi_metadata',
1344 'fa_bits' => 'oi_bits',
1345 'fa_media_type' => 'oi_media_type',
1346 'fa_major_mime' => 'oi_major_mime',
1347 'fa_minor_mime' => 'oi_minor_mime',
1348 'fa_description' => 'oi_description',
1349 'fa_user' => 'oi_user',
1350 'fa_user_text' => 'oi_user_text',
1351 'fa_timestamp' => 'oi_timestamp',
1352 'fa_deleted' => $bitfield
1353 ), $where, __METHOD__
);
1357 function doDBDeletes() {
1358 $dbw = $this->file
->repo
->getMasterDB();
1359 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1360 if ( count( $oldRels ) ) {
1361 $dbw->delete( 'oldimage',
1363 'oi_name' => $this->file
->getName(),
1364 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1367 if ( $deleteCurrent ) {
1368 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1373 * Run the transaction
1375 function execute() {
1376 global $wgUser, $wgUseSquid;
1377 wfProfileIn( __METHOD__
);
1379 $this->file
->lock();
1380 // Leave private files alone
1381 $privateFiles = array();
1382 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1383 $dbw = $this->file
->repo
->getMasterDB();
1384 if( !empty( $oldRels ) ) {
1385 $res = $dbw->select( 'oldimage',
1386 array( 'oi_archive_name' ),
1387 array( 'oi_name' => $this->file
->getName(),
1388 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1389 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1391 while( $row = $dbw->fetchObject( $res ) ) {
1392 $privateFiles[$row->oi_archive_name
] = 1;
1395 // Prepare deletion batch
1396 $hashes = $this->getHashes();
1397 $this->deletionBatch
= array();
1398 $ext = $this->file
->getExtension();
1399 $dotExt = $ext === '' ?
'' : ".$ext";
1400 foreach ( $this->srcRels
as $name => $srcRel ) {
1401 // Skip files that have no hash (missing source).
1402 // Keep private files where they are.
1403 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1404 $hash = $hashes[$name];
1405 $key = $hash . $dotExt;
1406 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1407 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1411 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1412 // We acquire this lock by running the inserts now, before the file operations.
1414 // This potentially has poor lock contention characteristics -- an alternative
1415 // scheme would be to insert stub filearchive entries with no fa_name and commit
1416 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1417 $this->doDBInserts();
1419 // Execute the file deletion batch
1420 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1421 if ( !$status->isGood() ) {
1422 $this->status
->merge( $status );
1425 if ( !$this->status
->ok
) {
1426 // Critical file deletion error
1427 // Roll back inserts, release lock and abort
1428 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1429 $this->file
->unlockAndRollback();
1430 return $this->status
;
1434 if ( $wgUseSquid ) {
1436 foreach ( $this->srcRels
as $srcRel ) {
1437 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1438 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1440 SquidUpdate
::purge( $urls );
1443 // Delete image/oldimage rows
1444 $this->doDBDeletes();
1446 // Commit and return
1447 $this->file
->unlock();
1448 wfProfileOut( __METHOD__
);
1449 return $this->status
;
1453 #------------------------------------------------------------------------------
1456 * Helper class for file undeletion
1459 class LocalFileRestoreBatch
{
1460 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1462 function __construct( File
$file, $unsuppress = false ) {
1463 $this->file
= $file;
1464 $this->cleanupBatch
= $this->ids
= array();
1465 $this->ids
= array();
1466 $this->unsuppress
= $unsuppress;
1472 function addId( $fa_id ) {
1473 $this->ids
[] = $fa_id;
1477 * Add a whole lot of files by ID
1479 function addIds( $ids ) {
1480 $this->ids
= array_merge( $this->ids
, $ids );
1484 * Add all revisions of the file
1491 * Run the transaction, except the cleanup batch.
1492 * The cleanup batch should be run in a separate transaction, because it locks different
1493 * rows and there's no need to keep the image row locked while it's acquiring those locks
1494 * The caller may have its own transaction open.
1495 * So we save the batch and let the caller call cleanup()
1497 function execute() {
1498 global $wgUser, $wgLang;
1499 if ( !$this->all
&& !$this->ids
) {
1501 return $this->file
->repo
->newGood();
1504 $exists = $this->file
->lock();
1505 $dbw = $this->file
->repo
->getMasterDB();
1506 $status = $this->file
->repo
->newGood();
1508 // Fetch all or selected archived revisions for the file,
1509 // sorted from the most recent to the oldest.
1510 $conditions = array( 'fa_name' => $this->file
->getName() );
1512 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1515 $result = $dbw->select( 'filearchive', '*',
1518 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1520 $idsPresent = array();
1521 $storeBatch = array();
1522 $insertBatch = array();
1523 $insertCurrent = false;
1524 $deleteIds = array();
1526 $archiveNames = array();
1527 while( $row = $dbw->fetchObject( $result ) ) {
1528 $idsPresent[] = $row->fa_id
;
1530 if ( $row->fa_name
!= $this->file
->getName() ) {
1531 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1532 $status->failCount++
;
1535 if ( $row->fa_storage_key
== '' ) {
1536 // Revision was missing pre-deletion
1537 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1538 $status->failCount++
;
1542 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1543 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1545 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1547 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1548 $sha1 = substr( $sha1, 1 );
1551 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1552 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1553 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1554 ||
is_null( $row->fa_metadata
) ) {
1555 // Refresh our metadata
1556 // Required for a new current revision; nice for older ones too. :)
1557 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1560 'minor_mime' => $row->fa_minor_mime
,
1561 'major_mime' => $row->fa_major_mime
,
1562 'media_type' => $row->fa_media_type
,
1563 'metadata' => $row->fa_metadata
);
1566 if ( $first && !$exists ) {
1567 // The live (current) version cannot be hidden!
1568 if( !$this->unsuppress
&& $row->fa_deleted
) {
1569 $this->file
->unlock();
1572 // This revision will be published as the new current version
1573 $destRel = $this->file
->getRel();
1574 $insertCurrent = array(
1575 'img_name' => $row->fa_name
,
1576 'img_size' => $row->fa_size
,
1577 'img_width' => $row->fa_width
,
1578 'img_height' => $row->fa_height
,
1579 'img_metadata' => $props['metadata'],
1580 'img_bits' => $row->fa_bits
,
1581 'img_media_type' => $props['media_type'],
1582 'img_major_mime' => $props['major_mime'],
1583 'img_minor_mime' => $props['minor_mime'],
1584 'img_description' => $row->fa_description
,
1585 'img_user' => $row->fa_user
,
1586 'img_user_text' => $row->fa_user_text
,
1587 'img_timestamp' => $row->fa_timestamp
,
1588 'img_sha1' => $sha1);
1590 $archiveName = $row->fa_archive_name
;
1591 if( $archiveName == '' ) {
1592 // This was originally a current version; we
1593 // have to devise a new archive name for it.
1594 // Format is <timestamp of archiving>!<name>
1595 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1597 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1599 } while ( isset( $archiveNames[$archiveName] ) );
1601 $archiveNames[$archiveName] = true;
1602 $destRel = $this->file
->getArchiveRel( $archiveName );
1603 $insertBatch[] = array(
1604 'oi_name' => $row->fa_name
,
1605 'oi_archive_name' => $archiveName,
1606 'oi_size' => $row->fa_size
,
1607 'oi_width' => $row->fa_width
,
1608 'oi_height' => $row->fa_height
,
1609 'oi_bits' => $row->fa_bits
,
1610 'oi_description' => $row->fa_description
,
1611 'oi_user' => $row->fa_user
,
1612 'oi_user_text' => $row->fa_user_text
,
1613 'oi_timestamp' => $row->fa_timestamp
,
1614 'oi_metadata' => $props['metadata'],
1615 'oi_media_type' => $props['media_type'],
1616 'oi_major_mime' => $props['major_mime'],
1617 'oi_minor_mime' => $props['minor_mime'],
1618 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1619 'oi_sha1' => $sha1 );
1622 $deleteIds[] = $row->fa_id
;
1623 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1624 // private files can stay where they are
1626 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1627 $this->cleanupBatch
[] = $row->fa_storage_key
;
1633 // Add a warning to the status object for missing IDs
1634 $missingIds = array_diff( $this->ids
, $idsPresent );
1635 foreach ( $missingIds as $id ) {
1636 $status->error( 'undelete-missing-filearchive', $id );
1639 // Run the store batch
1640 // Use the OVERWRITE_SAME flag to smooth over a common error
1641 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1642 $status->merge( $storeStatus );
1644 if ( !$status->ok
) {
1645 // Store batch returned a critical error -- this usually means nothing was stored
1646 // Stop now and return an error
1647 $this->file
->unlock();
1651 // Run the DB updates
1652 // Because we have locked the image row, key conflicts should be rare.
1653 // If they do occur, we can roll back the transaction at this time with
1654 // no data loss, but leaving unregistered files scattered throughout the
1656 // This is not ideal, which is why it's important to lock the image row.
1657 if ( $insertCurrent ) {
1658 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1660 if ( $insertBatch ) {
1661 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1664 $dbw->delete( 'filearchive',
1665 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1669 if( $status->successCount
> 0 ) {
1671 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1673 // Update site_stats
1674 $site_stats = $dbw->tableName( 'site_stats' );
1675 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1677 $this->file
->purgeEverything();
1679 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1680 $this->file
->purgeDescription();
1681 $this->file
->purgeHistory();
1684 $this->file
->unlock();
1689 * Delete unused files in the deleted zone.
1690 * This should be called from outside the transaction in which execute() was called.
1692 function cleanup() {
1693 if ( !$this->cleanupBatch
) {
1694 return $this->file
->repo
->newGood();
1696 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1701 #------------------------------------------------------------------------------
1704 * Helper class for file movement
1707 class LocalFileMoveBatch
{
1708 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1710 function __construct( File
$file, Title
$target ) {
1711 $this->file
= $file;
1712 $this->target
= $target;
1713 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1714 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDbKey() );
1715 $this->oldName
= $this->file
->getName();
1716 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1717 $this->oldRel
= $this->oldHash
. $this->oldName
;
1718 $this->newRel
= $this->newHash
. $this->newName
;
1719 $this->db
= $file->repo
->getMasterDb();
1723 * Add the current image to the batch
1725 function addCurrent() {
1726 $this->cur
= array( $this->oldRel
, $this->newRel
);
1730 * Add the old versions of the image to the batch
1732 function addOlds() {
1733 $archiveBase = 'archive';
1734 $this->olds
= array();
1735 $this->oldCount
= 0;
1737 $result = $this->db
->select( 'oldimage',
1738 array( 'oi_archive_name', 'oi_deleted' ),
1739 array( 'oi_name' => $this->oldName
),
1742 while( $row = $this->db
->fetchObject( $result ) ) {
1743 $oldName = $row->oi_archive_name
;
1744 $bits = explode( '!', $oldName, 2 );
1745 if( count( $bits ) != 2 ) {
1746 wfDebug( 'Invalid old file name: ' . $oldName );
1749 list( $timestamp, $filename ) = $bits;
1750 if( $this->oldName
!= $filename ) {
1751 wfDebug( 'Invalid old file name:' . $oldName );
1755 // Do we want to add those to oldCount?
1756 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1759 $this->olds
[] = array(
1760 "{$archiveBase}/{$this->oldHash}{$oldname}",
1761 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1764 $this->db
->freeResult( $result );
1770 function execute() {
1771 $repo = $this->file
->repo
;
1772 $status = $repo->newGood();
1773 $triplets = $this->getMoveTriplets();
1775 $statusDb = $this->doDBUpdates();
1776 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1777 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1778 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1779 if( !$statusMove->isOk() ) {
1780 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1781 $this->db
->rollback();
1783 $status->merge( $statusDb );
1784 $status->merge( $statusMove );
1789 * Do the database updates and return a new WikiError indicating how many
1790 * rows where updated.
1792 function doDBUpdates() {
1793 $repo = $this->file
->repo
;
1794 $status = $repo->newGood();
1797 // Update current image
1800 array( 'img_name' => $this->newName
),
1801 array( 'img_name' => $this->oldName
),
1804 if( $dbw->affectedRows() ) {
1805 $status->successCount++
;
1807 $status->failCount++
;
1810 // Update old images
1814 'oi_name' => $this->newName
,
1815 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1817 array( 'oi_name' => $this->oldName
),
1820 $affected = $dbw->affectedRows();
1821 $total = $this->oldCount
;
1822 $status->successCount +
= $affected;
1823 $status->failCount +
= $total - $affected;
1829 * Generate triplets for FSRepo::storeBatch().
1831 function getMoveTriplets() {
1832 $moves = array_merge( array( $this->cur
), $this->olds
);
1833 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1834 foreach( $moves as $move ) {
1835 // $move: (oldRelativePath, newRelativePath)
1836 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1837 $triplets[] = array( $srcUrl, 'public', $move[1] );
1838 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );