6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 4 );
11 * Class to represent a local file in the wiki's own database
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate image thumbnails or for uploading.
16 * Note that only the repo object knows what its file class is called. You should
17 * never name a file class explictly outside of the repo class. Instead use the
18 * repo's factory functions to generate file objects, for example:
20 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
25 * @addtogroup FileRepo
27 class LocalFile
extends File
32 var $fileExists, # does the file file exist on disk? (loadFromXxx)
33 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
34 $historyRes, # result of the query for the file's history (nextHistoryLine)
37 $bits, # --- returned by getimagesize (loadFromXxx)
39 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
40 $mime, # MIME type, determined by MimeMagic::guessMimeType
41 $major_mime, # Major mime type
42 $minor_mine, # Minor mime type
43 $size, # Size in bytes (loadFromXxx)
45 $timestamp, # Upload timestamp
46 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
47 $upgraded; # Whether the row was upgraded on load
52 * Create a LocalFile from a title
53 * Do not call this except from inside a repo class.
55 function newFromTitle( $title, $repo ) {
56 return new self( $title, $repo );
60 * Create a LocalFile from a title
61 * Do not call this except from inside a repo class.
63 function newFromRow( $row, $repo ) {
64 $title = Title
::makeTitle( NS_IMAGE
, $row->img_name
);
65 $file = new self( $title, $repo );
66 $file->loadFromRow( $row );
72 * Do not call this except from inside a repo class.
74 function __construct( $title, $repo ) {
75 if( !is_object( $title ) ) {
76 throw new MWException( __CLASS__
.' constructor given bogus title.' );
78 parent
::__construct( $title, $repo );
80 $this->historyLine
= 0;
81 $this->dataLoaded
= false;
85 * Get the memcached key
87 function getCacheKey() {
88 $hashedName = md5($this->getName());
89 return wfMemcKey( 'file', $hashedName );
93 * Try to load file metadata from memcached. Returns true on success.
95 function loadFromCache() {
97 wfProfileIn( __METHOD__
);
98 $this->dataLoaded
= false;
99 $key = $this->getCacheKey();
103 $cachedValues = $wgMemc->get( $key );
105 // Check if the key existed and belongs to this version of MediaWiki
106 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
107 wfDebug( "Pulling file metadata from cache key $key\n" );
108 $this->fileExists
= $cachedValues['fileExists'];
109 if ( $this->fileExists
) {
110 unset( $cachedValues['version'] );
111 unset( $cachedValues['fileExists'] );
112 foreach ( $cachedValues as $name => $value ) {
113 $this->$name = $value;
117 if ( $this->dataLoaded
) {
118 wfIncrStats( 'image_cache_hit' );
120 wfIncrStats( 'image_cache_miss' );
123 wfProfileOut( __METHOD__
);
124 return $this->dataLoaded
;
128 * Save the file metadata to memcached
130 function saveToCache() {
133 $key = $this->getCacheKey();
137 $fields = $this->getCacheFields( '' );
138 $cache = array( 'version' => MW_FILE_VERSION
);
139 $cache['fileExists'] = $this->fileExists
;
140 if ( $this->fileExists
) {
141 foreach ( $fields as $field ) {
142 $cache[$field] = $this->$field;
146 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
150 * Load metadata from the file itself
152 function loadFromFile() {
153 wfProfileIn( __METHOD__
);
154 $path = $this->getPath();
155 $this->fileExists
= file_exists( $path );
158 if ( $this->fileExists
) {
159 $magic=& MimeMagic
::singleton();
161 $this->mime
= $magic->guessMimeType($path,true);
162 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
163 $this->media_type
= $magic->getMediaType($path,$this->mime
);
164 $handler = MediaHandler
::getHandler( $this->mime
);
167 $this->size
= filesize( $path );
169 # Height, width and metadata
171 $gis = $handler->getImageSize( $this, $path );
172 $this->metadata
= $handler->getMetadata( $this, $path );
175 $this->metadata
= '';
178 wfDebug(__METHOD__
.": $path loaded, {$this->size} bytes, {$this->mime}.\n");
181 $this->media_type
= MEDIATYPE_UNKNOWN
;
182 $this->metadata
= '';
183 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
187 $this->width
= $gis[0];
188 $this->height
= $gis[1];
194 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
196 #NOTE: we have to set this flag early to avoid load() to be called
197 # be some of the functions below. This may lead to recursion or other bad things!
198 # as ther's only one thread of execution, this should be safe anyway.
199 $this->dataLoaded
= true;
201 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
202 else $this->bits
= 0;
204 wfProfileOut( __METHOD__
);
207 function getCacheFields( $prefix = 'img_' ) {
208 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
209 'major_mime', 'minor_mime', 'metadata', 'timestamp' );
210 static $results = array();
211 if ( $prefix == '' ) {
214 if ( !isset( $results[$prefix] ) ) {
215 $prefixedFields = array();
216 foreach ( $fields as $field ) {
217 $prefixedFields[] = $prefix . $field;
219 $results[$prefix] = $prefixedFields;
221 return $results[$prefix];
225 * Load file metadata from the DB
227 function loadFromDB() {
228 wfProfileIn( __METHOD__
);
230 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
231 $this->dataLoaded
= true;
233 $dbr = $this->repo
->getSlaveDB();
235 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
236 array( 'img_name' => $this->getName() ), __METHOD__
);
238 $this->loadFromRow( $row );
240 $this->fileExists
= false;
243 wfProfileOut( __METHOD__
);
247 * Decode a row from the database (either object or array) to an array
248 * with timestamps and MIME types decoded, and the field prefix removed.
250 function decodeRow( $row, $prefix = 'img_' ) {
251 $array = (array)$row;
252 $prefixLength = strlen( $prefix );
253 // Sanity check prefix once
254 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
255 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
258 foreach ( $array as $name => $value ) {
259 $deprefixedName = substr( $name, $prefixLength );
260 $decoded[substr( $name, $prefixLength )] = $value;
262 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
263 if ( empty( $decoded['major_mime'] ) ) {
264 $decoded['mime'] = "unknown/unknown";
266 if (!$decoded['minor_mime']) {
267 $decoded['minor_mime'] = "unknown";
269 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
275 * Load file metadata from a DB result row
277 function loadFromRow( $row, $prefix = 'img_' ) {
278 $array = $this->decodeRow( $row, $prefix );
279 foreach ( $array as $name => $value ) {
280 $this->$name = $value;
282 $this->fileExists
= true;
283 // Check for rows from a previous schema, quietly upgrade them
284 $this->maybeUpgradeRow();
288 * Load file metadata from cache or DB, unless already loaded
291 if ( !$this->dataLoaded
) {
292 if ( !$this->loadFromCache() ) {
294 $this->saveToCache();
296 $this->dataLoaded
= true;
301 * Upgrade a row if it needs it
303 function maybeUpgradeRow() {
304 if ( wfReadOnly() ) {
307 if ( is_null($this->media_type
) ||
$this->mime
== 'image/svg' ) {
309 $this->upgraded
= true;
311 $handler = $this->getHandler();
312 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
314 $this->upgraded
= true;
319 function getUpgraded() {
320 return $this->upgraded
;
324 * Fix assorted version-related problems with the image row by reloading it from the file
326 function upgradeRow() {
327 wfProfileIn( __METHOD__
);
329 $this->loadFromFile();
331 $dbw = $this->repo
->getMasterDB();
332 list( $major, $minor ) = self
::splitMime( $this->mime
);
334 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
336 $dbw->update( 'image',
338 'img_width' => $this->width
,
339 'img_height' => $this->height
,
340 'img_bits' => $this->bits
,
341 'img_media_type' => $this->media_type
,
342 'img_major_mime' => $major,
343 'img_minor_mime' => $minor,
344 'img_metadata' => $this->metadata
,
345 ), array( 'img_name' => $this->getName() ),
348 $this->saveToCache();
349 wfProfileOut( __METHOD__
);
352 /** splitMime inherited */
353 /** getName inherited */
354 /** getTitle inherited */
355 /** getURL inherited */
356 /** getViewURL inherited */
357 /** getPath inherited */
360 * Return the width of the image
362 * Returns false on error
365 function getWidth( $page = 1 ) {
367 if ( $this->isMultipage() ) {
368 $dim = $this->getHandler()->getPageDimensions( $this, $page );
370 return $dim['width'];
380 * Return the height of the image
382 * Returns false on error
385 function getHeight( $page = 1 ) {
387 if ( $this->isMultipage() ) {
388 $dim = $this->getHandler()->getPageDimensions( $this, $page );
390 return $dim['height'];
395 return $this->height
;
400 * Get handler-specific metadata
402 function getMetadata() {
404 return $this->metadata
;
408 * Return the size of the image file, in bytes
417 * Returns the mime type of the file.
419 function getMimeType() {
425 * Return the type of the media in the file.
426 * Use the value returned by this function with the MEDIATYPE_xxx constants.
428 function getMediaType() {
430 return $this->media_type
;
433 /** canRender inherited */
434 /** mustRender inherited */
435 /** allowInlineDisplay inherited */
436 /** isSafeFile inherited */
437 /** isTrustedFile inherited */
440 * Returns true if the file file exists on disk.
441 * @return boolean Whether file file exist on disk.
446 return $this->fileExists
;
449 /** getTransformScript inherited */
450 /** getUnscaledThumb inherited */
451 /** thumbName inherited */
452 /** createThumb inherited */
453 /** getThumbnail inherited */
454 /** transform inherited */
457 * Fix thumbnail files from 1.4 or before, with extreme prejudice
459 function migrateThumbFile( $thumbName ) {
460 $thumbDir = $this->getThumbPath();
461 $thumbPath = "$thumbDir/$thumbName";
462 if ( is_dir( $thumbPath ) ) {
463 // Directory where file should be
464 // This happened occasionally due to broken migration code in 1.5
465 // Rename to broken-*
466 for ( $i = 0; $i < 100 ; $i++
) {
467 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
468 if ( !file_exists( $broken ) ) {
469 rename( $thumbPath, $broken );
473 // Doesn't exist anymore
476 if ( is_file( $thumbDir ) ) {
477 // File where directory should be
479 // Doesn't exist anymore
484 /** getHandler inherited */
485 /** iconThumb inherited */
486 /** getLastError inherited */
489 * Get all thumbnail names previously generated for this file
491 function getThumbnails() {
492 if ( $this->isHashed() ) {
495 $dir = $this->getThumbPath();
497 if ( is_dir( $dir ) ) {
498 $handle = opendir( $dir );
501 while ( false !== ( $file = readdir($handle) ) ) {
502 if ( $file{0} != '.' ) {
517 * Refresh metadata in memcached, but don't touch thumbnails or squid
519 function purgeMetadataCache() {
521 $this->loadFromFile();
522 $this->saveToCache();
526 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
528 function purgeCache( $archiveFiles = array() ) {
531 // Refresh metadata cache
532 $this->purgeMetadataCache();
535 $files = $this->getThumbnails();
536 $dir = $this->getThumbPath();
538 foreach ( $files as $file ) {
540 # Check that the base file name is part of the thumb name
541 # This is a basic sanity check to avoid erasing unrelated directories
542 if ( strpos( $file, $this->getName() ) !== false ) {
543 $url = $this->getThumbUrl( $file );
545 @unlink
( "$dir/$file" );
551 $urls[] = $this->getURL();
552 foreach ( $archiveFiles as $file ) {
553 $urls[] = $this->getArchiveUrl( $file );
555 wfPurgeSquidServers( $urls );
559 /** purgeDescription inherited */
560 /** purgeEverything inherited */
563 * Return the history of this file, line by line.
564 * starts with current version, then old versions.
565 * uses $this->historyLine to check which line to return:
566 * 0 return line for current version
567 * 1 query for old versions, return first one
568 * 2, ... return next old version from above query
572 function nextHistoryLine() {
573 $dbr = $this->repo
->getSlaveDB();
575 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
576 $this->historyRes
= $dbr->select( 'image',
580 'img_user','img_user_text',
584 "'' AS oi_archive_name"
586 array( 'img_name' => $this->title
->getDBkey() ),
589 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
592 } else if ( $this->historyLine
== 1 ) {
593 $this->historyRes
= $dbr->select( 'oldimage',
595 'oi_size AS img_size',
596 'oi_description AS img_description',
597 'oi_user AS img_user',
598 'oi_user_text AS img_user_text',
599 'oi_timestamp AS img_timestamp',
600 'oi_width as img_width',
601 'oi_height as img_height',
604 array( 'oi_name' => $this->title
->getDBkey() ),
606 array( 'ORDER BY' => 'oi_timestamp DESC' )
609 $this->historyLine ++
;
611 return $dbr->fetchObject( $this->historyRes
);
615 * Reset the history pointer to the first element of the history
618 function resetHistory() {
619 $this->historyLine
= 0;
622 /** getFullPath inherited */
623 /** getHashPath inherited */
624 /** getRel inherited */
625 /** getUrlRel inherited */
626 /** getArchivePath inherited */
627 /** getThumbPath inherited */
628 /** getArchiveUrl inherited */
629 /** getThumbUrl inherited */
630 /** getArchiveVirtualUrl inherited */
631 /** getThumbVirtualUrl inherited */
632 /** isHashed inherited */
635 * Record a file upload in the upload log and the image table
637 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
638 $watch = false, $timestamp = false )
640 global $wgUser, $wgUseCopyrightUpload;
642 $dbw = $this->repo
->getMasterDB();
644 // Delete thumbnails and refresh the metadata cache
647 // Fail now if the file isn't there
648 if ( !$this->fileExists
) {
649 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
653 if ( $wgUseCopyrightUpload ) {
654 if ( $license != '' ) {
655 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
657 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
658 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
660 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
662 if ( $license != '' ) {
663 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
664 $textdesc = $filedesc .
665 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
671 if ( $timestamp === false ) {
672 $timestamp = $dbw->timestamp();
676 if (strpos($this->mime
,'/')!==false) {
677 list($major,$minor)= explode('/',$this->mime
,2);
684 # Test to see if the row exists using INSERT IGNORE
685 # This avoids race conditions by locking the row until the commit, and also
686 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
687 $dbw->insert( 'image',
689 'img_name' => $this->getName(),
690 'img_size'=> $this->size
,
691 'img_width' => intval( $this->width
),
692 'img_height' => intval( $this->height
),
693 'img_bits' => $this->bits
,
694 'img_media_type' => $this->media_type
,
695 'img_major_mime' => $major,
696 'img_minor_mime' => $minor,
697 'img_timestamp' => $timestamp,
698 'img_description' => $desc,
699 'img_user' => $wgUser->getID(),
700 'img_user_text' => $wgUser->getName(),
701 'img_metadata' => $this->metadata
,
707 if( $dbw->affectedRows() == 0 ) {
708 # Collision, this is an update of a file
709 # Insert previous contents into oldimage
710 $dbw->insertSelect( 'oldimage', 'image',
712 'oi_name' => 'img_name',
713 'oi_archive_name' => $dbw->addQuotes( $oldver ),
714 'oi_size' => 'img_size',
715 'oi_width' => 'img_width',
716 'oi_height' => 'img_height',
717 'oi_bits' => 'img_bits',
718 'oi_timestamp' => 'img_timestamp',
719 'oi_description' => 'img_description',
720 'oi_user' => 'img_user',
721 'oi_user_text' => 'img_user_text',
722 ), array( 'img_name' => $this->getName() ), __METHOD__
725 # Update the current image row
726 $dbw->update( 'image',
728 'img_size' => $this->size
,
729 'img_width' => intval( $this->width
),
730 'img_height' => intval( $this->height
),
731 'img_bits' => $this->bits
,
732 'img_media_type' => $this->media_type
,
733 'img_major_mime' => $major,
734 'img_minor_mime' => $minor,
735 'img_timestamp' => $timestamp,
736 'img_description' => $desc,
737 'img_user' => $wgUser->getID(),
738 'img_user_text' => $wgUser->getName(),
739 'img_metadata' => $this->metadata
,
740 ), array( /* WHERE */
741 'img_name' => $this->getName()
746 # Update the image count
747 $site_stats = $dbw->tableName( 'site_stats' );
748 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
751 $descTitle = $this->getTitle();
752 $article = new Article( $descTitle );
754 $watch = $watch ||
$wgUser->isWatched( $descTitle );
755 $suppressRC = true; // There's already a log entry, so don't double the RC load
757 if( $descTitle->exists() ) {
758 // TODO: insert a null revision into the page history for this update.
760 $wgUser->addWatch( $descTitle );
763 # Invalidate the cache for the description page
764 $descTitle->invalidateCache();
765 $descTitle->purgeSquid();
767 // New file; create the description page.
768 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
771 # Hooks, hooks, the magic of hooks...
772 wfRunHooks( 'FileUpload', array( $this ) );
775 $log = new LogPage( 'upload' );
776 $log->addEntry( 'upload', $descTitle, $desc );
778 # Commit the transaction now, in case something goes wrong later
779 # The most important thing is that files don't get lost, especially archives
780 $dbw->immediateCommit();
782 # Invalidate cache for all pages using this file
783 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
790 * Move or copy a file to its public location. If a file exists at the
791 * destination, move it to an archive. Returns the archive name on success
792 * or an empty string if it was a new file, and a wikitext-formatted
793 * WikiError object on failure.
795 * The archive name should be passed through to recordUpload for database
798 * @param string $sourcePath Local filesystem path to the source image
799 * @param integer $flags A bitwise combination of:
800 * File::DELETE_SOURCE Delete the source file, i.e. move
802 * @return The archive name on success or an empty string if it was a new
803 * file, and a wikitext-formatted WikiError object on failure.
805 function publish( $srcPath, $flags = 0 ) {
806 $dstPath = $this->getFullPath();
807 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
808 $archivePath = $this->getArchivePath( $archiveName );
809 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
810 $status = $this->repo
->publish( $srcPath, $dstPath, $archivePath, $flags );
811 if ( WikiError
::isError( $status ) ) {
813 } elseif ( $status == 'new' ) {
820 /** getLinksTo inherited */
821 /** getExifData inherited */
822 /** isLocal inherited */
823 /** wasDeleted inherited */
826 * Delete all versions of the file.
828 * Moves the files into an archive directory (or deletes them)
829 * and removes the database rows.
831 * Cache purging is done; logging is caller's responsibility.
834 * @return true on success, false on some kind of failure
836 function delete( $reason, $suppress=false ) {
837 $transaction = new FSTransaction();
838 $urlArr = array( $this->getURL() );
840 if( !FileStore
::lock() ) {
841 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
846 $dbw = $this->repo
->getMasterDB();
849 // Delete old versions
850 $result = $dbw->select( 'oldimage',
851 array( 'oi_archive_name' ),
852 array( 'oi_name' => $this->getName() ) );
854 while( $row = $dbw->fetchObject( $result ) ) {
855 $oldName = $row->oi_archive_name
;
857 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
859 // We'll need to purge this URL from caches...
860 $urlArr[] = $this->getArchiveUrl( $oldName );
862 $dbw->freeResult( $result );
864 // And the current version...
865 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
867 $dbw->immediateCommit();
868 } catch( MWException
$e ) {
869 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
870 $transaction->rollback();
875 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
876 $transaction->commit();
881 $site_stats = $dbw->tableName( 'site_stats' );
882 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
884 $this->purgeEverything( $urlArr );
891 * Delete an old version of the file.
893 * Moves the file into an archive directory (or deletes it)
894 * and removes the database row.
896 * Cache purging is done; logging is caller's responsibility.
899 * @throws MWException or FSException on database or filestore failure
900 * @return true on success, false on some kind of failure
902 function deleteOld( $archiveName, $reason, $suppress=false ) {
903 $transaction = new FSTransaction();
906 if( !FileStore
::lock() ) {
907 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
911 $transaction = new FSTransaction();
913 $dbw = $this->repo
->getMasterDB();
915 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
916 $dbw->immediateCommit();
917 } catch( MWException
$e ) {
918 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
919 $transaction->rollback();
924 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
925 $transaction->commit();
928 $this->purgeDescription();
934 $this->getArchiveUrl( $archiveName ),
936 wfPurgeSquidServers( $urlArr );
942 * Delete the current version of a file.
943 * May throw a database error.
944 * @return true on success, false on failure
946 private function prepareDeleteCurrent( $reason, $suppress=false ) {
947 return $this->prepareDeleteVersion(
948 $this->getFullPath(),
952 'fa_name' => 'img_name',
953 'fa_archive_name' => 'NULL',
954 'fa_size' => 'img_size',
955 'fa_width' => 'img_width',
956 'fa_height' => 'img_height',
957 'fa_metadata' => 'img_metadata',
958 'fa_bits' => 'img_bits',
959 'fa_media_type' => 'img_media_type',
960 'fa_major_mime' => 'img_major_mime',
961 'fa_minor_mime' => 'img_minor_mime',
962 'fa_description' => 'img_description',
963 'fa_user' => 'img_user',
964 'fa_user_text' => 'img_user_text',
965 'fa_timestamp' => 'img_timestamp' ),
966 array( 'img_name' => $this->getName() ),
972 * Delete a given older version of a file.
973 * May throw a database error.
974 * @return true on success, false on failure
976 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
977 $oldpath = $this->getArchivePath() .
978 DIRECTORY_SEPARATOR
. $archiveName;
979 return $this->prepareDeleteVersion(
984 'fa_name' => 'oi_name',
985 'fa_archive_name' => 'oi_archive_name',
986 'fa_size' => 'oi_size',
987 'fa_width' => 'oi_width',
988 'fa_height' => 'oi_height',
989 'fa_metadata' => 'NULL',
990 'fa_bits' => 'oi_bits',
991 'fa_media_type' => 'NULL',
992 'fa_major_mime' => 'NULL',
993 'fa_minor_mime' => 'NULL',
994 'fa_description' => 'oi_description',
995 'fa_user' => 'oi_user',
996 'fa_user_text' => 'oi_user_text',
997 'fa_timestamp' => 'oi_timestamp' ),
999 'oi_name' => $this->getName(),
1000 'oi_archive_name' => $archiveName ),
1006 * Do the dirty work of backing up an image row and its file
1007 * (if $wgSaveDeletedFiles is on) and removing the originals.
1009 * Must be run while the file store is locked and a database
1010 * transaction is open to avoid race conditions.
1012 * @return FSTransaction
1014 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1015 global $wgUser, $wgSaveDeletedFiles;
1017 // Dupe the file into the file store
1018 if( file_exists( $path ) ) {
1019 if( $wgSaveDeletedFiles ) {
1022 $store = FileStore
::get( $group );
1023 $key = FileStore
::calculateKey( $path, $this->getExtension() );
1024 $transaction = $store->insert( $key, $path,
1025 FileStore
::DELETE_ORIGINAL
);
1029 $transaction = FileStore
::deleteFile( $path );
1032 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1035 $transaction = new FSTransaction(); // empty
1038 if( $transaction === false ) {
1040 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1041 throw new MWException( "Could not archive and delete file $path" );
1045 // Bitfields to further supress the file content
1046 // Note that currently, live files are stored elsewhere
1047 // and cannot be partially deleted
1050 $bitfield |
= self
::DELETED_FILE
;
1051 $bitfield |
= self
::DELETED_COMMENT
;
1052 $bitfield |
= self
::DELETED_USER
;
1053 $bitfield |
= self
::DELETED_RESTRICTED
;
1056 $dbw = $this->repo
->getMasterDB();
1057 $storageMap = array(
1058 'fa_storage_group' => $dbw->addQuotes( $group ),
1059 'fa_storage_key' => $dbw->addQuotes( $key ),
1061 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1062 'fa_deleted_timestamp' => $dbw->timestamp(),
1063 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1064 'fa_deleted' => $bitfield);
1065 $allFields = array_merge( $storageMap, $fieldMap );
1068 if( $wgSaveDeletedFiles ) {
1069 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1071 $dbw->delete( $table, $where, $fname );
1072 } catch( DBQueryError
$e ) {
1073 // Something went horribly wrong!
1074 // Leave the file as it was...
1075 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
1076 $transaction->rollback();
1080 return $transaction;
1084 * Restore all or specified deleted revisions to the given file.
1085 * Permissions and logging are left to the caller.
1087 * May throw database exceptions on error.
1089 * @param $versions set of record ids of deleted items to restore,
1090 * or empty to restore all revisions.
1091 * @return the number of file revisions restored if successful,
1092 * or false on failure
1094 function restore( $versions=array(), $Unsuppress=false ) {
1097 if( !FileStore
::lock() ) {
1098 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
1102 $transaction = new FSTransaction();
1104 $dbw = $this->repo
->getMasterDB();
1107 // Re-confirm whether this file presently exists;
1108 // if no we'll need to create an file record for the
1109 // first item we restore.
1110 $exists = $dbw->selectField( 'image', '1',
1111 array( 'img_name' => $this->getName() ),
1114 // Fetch all or selected archived revisions for the file,
1115 // sorted from the most recent to the oldest.
1116 $conditions = array( 'fa_name' => $this->getName() );
1118 $conditions['fa_id'] = $versions;
1121 $result = $dbw->select( 'filearchive', '*',
1124 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1126 if( $dbw->numRows( $result ) < count( $versions ) ) {
1127 // There's some kind of conflict or confusion;
1128 // we can't restore everything we were asked to.
1129 wfDebug( __METHOD__
.": couldn't find requested items\n" );
1131 FileStore
::unlock();
1135 if( $dbw->numRows( $result ) == 0 ) {
1137 wfDebug( __METHOD__
.": nothing to do\n" );
1139 FileStore
::unlock();
1144 while( $row = $dbw->fetchObject( $result ) ) {
1145 if ( $Unsuppress ) {
1146 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1147 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1148 // Skip restoring file revisions that the user cannot restore
1152 $store = FileStore
::get( $row->fa_storage_group
);
1154 wfDebug( __METHOD__
.": skipping row with no file.\n" );
1158 $restoredImage = new self( Title
::makeTitle( NS_IMAGE
, $row->fa_name
), $this->repo
);
1160 if( $revisions == 1 && !$exists ) {
1161 $destPath = $restoredImage->getFullPath();
1162 $destDir = dirname( $destPath );
1163 if ( !is_dir( $destDir ) ) {
1164 wfMkdirParents( $destDir );
1167 // We may have to fill in data if this was originally
1168 // an archived file revision.
1169 if( is_null( $row->fa_metadata
) ) {
1170 $tempFile = $store->filePath( $row->fa_storage_key
);
1172 $magic = MimeMagic
::singleton();
1173 $mime = $magic->guessMimeType( $tempFile, true );
1174 $media_type = $magic->getMediaType( $tempFile, $mime );
1175 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
1176 $handler = MediaHandler
::getHandler( $mime );
1178 $metadata = $handler->getMetadata( false, $tempFile );
1183 $metadata = $row->fa_metadata
;
1184 $major_mime = $row->fa_major_mime
;
1185 $minor_mime = $row->fa_minor_mime
;
1186 $media_type = $row->fa_media_type
;
1191 'img_name' => $row->fa_name
,
1192 'img_size' => $row->fa_size
,
1193 'img_width' => $row->fa_width
,
1194 'img_height' => $row->fa_height
,
1195 'img_metadata' => $metadata,
1196 'img_bits' => $row->fa_bits
,
1197 'img_media_type' => $media_type,
1198 'img_major_mime' => $major_mime,
1199 'img_minor_mime' => $minor_mime,
1200 'img_description' => $row->fa_description
,
1201 'img_user' => $row->fa_user
,
1202 'img_user_text' => $row->fa_user_text
,
1203 'img_timestamp' => $row->fa_timestamp
);
1205 $archiveName = $row->fa_archive_name
;
1206 if( $archiveName == '' ) {
1207 // This was originally a current version; we
1208 // have to devise a new archive name for it.
1209 // Format is <timestamp of archiving>!<name>
1211 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
1212 '!' . $row->fa_name
;
1214 $destDir = $restoredImage->getArchivePath();
1215 if ( !is_dir( $destDir ) ) {
1216 wfMkdirParents( $destDir );
1218 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
1220 $table = 'oldimage';
1222 'oi_name' => $row->fa_name
,
1223 'oi_archive_name' => $archiveName,
1224 'oi_size' => $row->fa_size
,
1225 'oi_width' => $row->fa_width
,
1226 'oi_height' => $row->fa_height
,
1227 'oi_bits' => $row->fa_bits
,
1228 'oi_description' => $row->fa_description
,
1229 'oi_user' => $row->fa_user
,
1230 'oi_user_text' => $row->fa_user_text
,
1231 'oi_timestamp' => $row->fa_timestamp
);
1234 $dbw->insert( $table, $fields, __METHOD__
);
1235 // @todo this delete is not totally safe, potentially
1236 $dbw->delete( 'filearchive',
1237 array( 'fa_id' => $row->fa_id
),
1240 // Check if any other stored revisions use this file;
1241 // if so, we shouldn't remove the file from the deletion
1242 // archives so they will still work.
1243 $useCount = $dbw->selectField( 'filearchive',
1246 'fa_storage_group' => $row->fa_storage_group
,
1247 'fa_storage_key' => $row->fa_storage_key
),
1249 if( $useCount == 0 ) {
1250 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1251 $flags = FileStore
::DELETE_ORIGINAL
;
1256 $transaction->add( $store->export( $row->fa_storage_key
,
1257 $destPath, $flags ) );
1260 $dbw->immediateCommit();
1261 } catch( MWException
$e ) {
1262 wfDebug( __METHOD__
." caught error, aborting\n" );
1263 $transaction->rollback();
1268 $transaction->commit();
1269 FileStore
::unlock();
1271 if( $revisions > 0 ) {
1273 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
1275 // Update site_stats
1276 $site_stats = $dbw->tableName( 'site_stats' );
1277 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1279 $this->purgeEverything();
1281 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
1282 $this->purgeDescription();
1289 /** isMultipage inherited */
1290 /** pageCount inherited */
1291 /** scaleHeight inherited */
1292 /** getImageSize inherited */
1295 * Get the URL of the file description page.
1297 function getDescriptionUrl() {
1298 return $this->title
->getLocalUrl();
1302 * Get the HTML text of the description page
1303 * This is not used by ImagePage for local files, since (among other things)
1304 * it skips the parser cache.
1306 function getDescriptionText() {
1308 $revision = Revision
::newFromTitle( $this->title
);
1309 if ( !$revision ) return false;
1310 $text = $revision->getText();
1311 if ( !$text ) return false;
1312 $html = $wgParser->parse( $text, new ParserOptions
);
1316 function getTimestamp() {
1318 return $this->timestamp
;
1320 } // LocalFile class
1323 * Backwards compatibility class
1325 class Image
extends LocalFile
{
1326 function __construct( $title ) {
1327 $repo = RepoGroup
::singleton()->getLocalRepo();
1328 parent
::__construct( $title, $repo );
1332 * Wrapper for wfFindFile(), for backwards-compatibility only
1333 * Do not use in core code.
1336 function newFromTitle( $title, $time = false ) {
1337 $img = wfFindFile( $title, $time );
1339 $img = wfLocalFile( $title );
1345 * Return the URL of an image, provided its name.
1347 * Backwards-compatibility for extensions.
1348 * Note that fromSharedDirectory will only use the shared path for files
1349 * that actually exist there now, and will return local paths otherwise.
1351 * @param string $name Name of the image, without the leading "Image:"
1352 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1353 * @return string URL of $name image
1356 static function imageUrl( $name, $fromSharedDirectory = false ) {
1358 if( $fromSharedDirectory ) {
1359 $image = wfFindFile( $name );
1362 $image = wfLocalFile( $name );
1364 return $image->getUrl();
1369 * Aliases for backwards compatibility with 1.6
1371 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1372 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1373 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1374 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);