* extension=extensions/php_exif.dll
*/
-if ($wgShowEXIF)
- require_once('Exif.php');
-
/**
* Bump this number when serialized cache records may be incompatible.
*/
/**
* Obsolete factory function, use constructor
+ * @deprecated
*/
function newFromTitle( $title ) {
return new Image( $title );
function Image( $title ) {
if( !is_object( $title ) ) {
- wfDebugDieBacktrace( 'Image constructor given bogus title.' );
+ throw new MWException( 'Image constructor given bogus title.' );
}
$this->title =& $title;
$this->name = $title->getDBkey();
$this->metadata = serialize ( array() ) ;
$n = strrpos( $this->name, '.' );
- $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
+ $this->extension = Image::normalizeExtension( $n ?
+ substr( $this->name, $n + 1 ) : '' );
$this->historyLine = 0;
$this->dataLoaded = false;
}
+
+ /**
+ * Normalize a file extension to the common form, and ensure it's clean.
+ * Extensions with non-alphanumeric characters will be discarded.
+ *
+ * @param $ext string (without the .)
+ * @return string
+ */
+ static function normalizeExtension( $ext ) {
+ $lower = strtolower( $ext );
+ $squish = array(
+ 'htm' => 'html',
+ 'jpeg' => 'jpg',
+ 'mpeg' => 'mpg',
+ 'tiff' => 'tif' );
+ if( isset( $squish[$lower] ) ) {
+ return $squish[$lower];
+ } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
+ return $lower;
+ } else {
+ return '';
+ }
+ }
+
/**
* Get the memcached keys
* Returns an array, first element is the local cache key, second is the shared cache key, if there is one
$this->dataLoaded = true;
- if ($this->fileExists && $wgShowEXIF) $this->metadata = serialize ( $this->retrieveExifData() ) ;
- else $this->metadata = serialize ( array() ) ;
+ $this->metadata = serialize( $this->retrieveExifData( $this->imagePath ) );
if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
else $this->bits = 0;
$this->checkDBSchema($dbw);
- if (strpos($this->mime,'/')!==false) {
- list($major,$minor)= explode('/',$this->mime,2);
- }
- else {
- $major= $this->mime;
- $minor= "unknown";
- }
+ list( $major, $minor ) = self::splitMime( $this->mime );
wfDebug("$fname: upgrading ".$this->name." to 1.5 schema\n");
}
wfProfileOut( $fname );
}
+
+ /**
+ * Split an internet media type into its two components; if not
+ * a two-part name, set the minor type to 'unknown'.
+ *
+ * @param $mime "text/html" etc
+ * @return array ("text", "html") etc
+ */
+ static function splitMime( $mime ) {
+ if( strpos( $mime, '/' ) !== false ) {
+ return explode( '/', $mime, 2 );
+ } else {
+ return array( $mime, 'unknown' );
+ }
+ }
/**
* Return the name of this image
*
* @param integer $width maximum width of the generated thumbnail
* @param integer $height maximum height of the image (optional)
- * @return ThumbnailImage
+ * @return ThumbnailImage or null on failure
* @public
*/
function getThumbnail( $width, $height=-1 ) {
}
else $thumb= NULL; #not a bitmap or renderable image, don't try.
- if( is_null( $thumb ) ) {
- $thumb = $this->iconThumb();
- }
return $thumb;
}
* Returns an object which can return the pathname, URL, and physical
* pixel size of the thumbnail -- or null on failure.
*
- * @return ThumbnailImage
+ * @return ThumbnailImage or null on failure
* @private
*/
function renderThumb( $width, $useScript = true ) {
- global $wgUseSquid, $wgInternalServer;
+ global $wgUseSquid;
global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
$fname = 'Image::renderThumb';
unlink( $thumbPath );
} else {
// This should have been dealt with already
- wfDebugDieBacktrace( "Directory where image should be: $thumbPath" );
+ throw new MWException( "Directory where image should be: $thumbPath" );
}
}
// Rename the old image into the new location
$this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
if ( $this->lastError === true ) {
$done = true;
+ } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
+ // Log the error but output anyway.
+ // With luck it's a transitory error...
+ $done = true;
}
# Purge squid
# This has to be done after the image is updated and present for all machines on NFS,
# or else the old version might be stored into the squid again
if ( $wgUseSquid ) {
- if ( substr( $url, 0, 4 ) == 'http' ) {
- $urlArr = array( $url );
- } else {
- $urlArr = array( $wgInternalServer.$url );
- }
+ $urlArr = array( $url );
wfPurgeSquidServers($urlArr);
}
}
$this->load();
$err = false;
+ $cmd = "";
+ $retval = 0;
+
if( $this->mime === "image/svg" ) {
#Right now we have only SVG
$wgSVGConverters[$wgSVGConverter] );
wfProfileIn( 'rsvg' );
wfDebug( "reallyRenderThumb SVG: $cmd\n" );
- $err = wfShellExec( $cmd );
+ $err = wfShellExec( $cmd, $retval );
wfProfileOut( 'rsvg' );
}
} elseif ( $wgUseImageMagick ) {
$cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
" {$quality} -background white -size {$width} ".
wfEscapeShellArg($this->imagePath) .
+ // Coalesce is needed to scale animated GIFs properly (bug 1017).
+ ' -coalesce ' .
// For the -resize option a "!" is needed to force exact size,
// or ImageMagick may decide your ratio is wrong and slice off
// a pixel.
wfEscapeShellArg($thumbPath) . " 2>&1";
wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
wfProfileIn( 'convert' );
- $err = wfShellExec( $cmd );
+ $err = wfShellExec( $cmd, $retval );
wfProfileOut( 'convert' );
} elseif( $wgCustomConvertCommand ) {
# Use a custom convert command
$cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
wfProfileIn( 'convert' );
- $err = wfShellExec( $cmd );
+ $err = wfShellExec( $cmd, $retval );
wfProfileOut( 'convert' );
} else {
# Use PHP's builtin GD library functions.
#
if( file_exists( $thumbPath ) ) {
$thumbstat = stat( $thumbPath );
- if( $thumbstat['size'] == 0 ) {
+ if( $thumbstat['size'] == 0 || $retval != 0 ) {
+ wfDebugLog( 'thumbnail',
+ sprintf( 'Removing bad %d-byte thumbnail "%s"',
+ $thumbstat['size'], $thumbPath ) );
unlink( $thumbPath );
- } else {
- // All good
- $err = true;
}
}
- if ( $err !== true ) {
+ if ( $retval != 0 ) {
+ wfDebugLog( 'thumbnail',
+ sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
+ wfHostname(), $retval, trim($err), $cmd ) );
return wfMsg( 'thumbnail_error', $err );
} else {
return true;
* Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
*/
function purgeCache( $archiveFiles = array(), $shared = false ) {
- global $wgInternalServer, $wgUseSquid;
+ global $wgUseSquid;
// Refresh metadata cache
$this->purgeMetadataCache();
$urls = array();
foreach ( $files as $file ) {
if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
- $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
+ $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory );
@unlink( "$dir/$file" );
}
}
// Purge the squid
if ( $wgUseSquid ) {
- $urls[] = $wgInternalServer . $this->getViewURL();
+ $urls[] = $this->getViewURL();
foreach ( $archiveFiles as $file ) {
- $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
+ $urls[] = wfImageArchiveUrl( $file );
}
wfPurgeSquidServers( $urls );
}
}
+
+ /**
+ * Purge the image description page, but don't go after
+ * pages using the image. Use when modifying file history
+ * but not the current data.
+ */
+ function purgeDescription() {
+ $page = Title::makeTitle( NS_IMAGE, $this->name );
+ $page->invalidateCache();
+ }
+
+ /**
+ * Purge metadata and all affected pages when the image is created,
+ * deleted, or majorly updated. A set of additional URLs may be
+ * passed to purge, such as specific image files which have changed.
+ * @param $urlArray array
+ */
+ function purgeEverything( $urlArr=array() ) {
+ // Delete thumbnails and refresh image metadata cache
+ $this->purgeCache();
+ $this->purgeDescription();
+
+ // Purge cache of all pages using this image
+ $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
+ $update->doUpdate();
+ }
function checkDBSchema(&$db) {
global $wgCheckDBSchema;
}
# img_name must be unique
if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
- wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
+ throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
}
- #new fields must exist
+ # new fields must exist
+ #
+ # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
+ # if the fields are missing, the database will loudly report a query error, the first time you try to do
+ # something. The only reason I put the above schema check in was because the absence of that particular
+ # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
+ # uploads. -- TS
+ /*
if ( !$db->fieldExists( 'image', 'img_media_type' )
|| !$db->fieldExists( 'image', 'img_metadata' )
|| !$db->fieldExists( 'image', 'img_width' ) ) {
- wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
- }
+ throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
+ }
+ */
}
/**
* Record an image upload in the upload log and the image table
*/
function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
- global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
+ global $wgUser, $wgUseCopyrightUpload;
$fname = 'Image::recordUpload';
$dbw =& wfGetDB( DB_MASTER );
$fname,
'IGNORE'
);
- $descTitle = $this->getTitle();
- $purgeURLs = array();
if( $dbw->affectedRows() == 0 ) {
# Collision, this is an update of an image
$dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
}
+ $descTitle = $this->getTitle();
$article = new Article( $descTitle );
$minor = false;
$watch = $watch || $wgUser->isWatched( $descTitle );
# Invalidate the cache for the description page
$descTitle->invalidateCache();
- $purgeURLs[] = $descTitle->getInternalURL();
+ $descTitle->purgeSquid();
} else {
// New image; create the description page.
$article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
}
- # Invalidate cache for all pages using this image
- $linksTo = $this->getLinksTo();
-
- if ( $wgUseSquid ) {
- $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
- array_push( $wgPostCommitUpdateList, $u );
- }
- Title::touchArray( $linksTo );
-
+ # Add the log entry
$log = new LogPage( 'upload' );
$log->addEntry( 'upload', $descTitle, $desc );
+ # Commit the transaction now, in case something goes wrong later
+ # The most important thing is that images don't get lost, especially archives
+ $dbw->immediateCommit();
+
+ # Invalidate cache for all pages using this image
+ $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
+ $update->doUpdate();
+
return true;
}
* Also adds their IDs to the link cache
*
* This is mostly copied from Title::getLinksTo()
+ *
+ * @deprecated Use HTMLCacheUpdate, this function uses too much memory
*/
function getLinksTo( $options = '' ) {
$fname = 'Image::getLinksTo';
wfProfileOut( $fname );
return $retVal;
}
+
/**
- * Retrive Exif data from the database
- *
- * Retrive Exif data from the database and prune unrecognized tags
+ * Retrive Exif data from the file and prune unrecognized tags
* and/or tags with invalid contents
*
+ * @param $filename
* @return array
*/
- function retrieveExifData() {
+ private function retrieveExifData( $filename ) {
+ global $wgShowEXIF;
+
+ /*
if ( $this->getMimeType() !== "image/jpeg" )
return array();
+ */
- $exif = new Exif( $this->imagePath );
- return $exif->getFilteredData();
+ if( $wgShowEXIF && file_exists( $filename ) ) {
+ $exif = new Exif( $filename );
+ return $exif->getFilteredData();
+ }
+
+ return array();
}
function getExifData() {
return;
# Get EXIF data from image
- $exif = $this->retrieveExifData();
+ $exif = $this->retrieveExifData( $this->imagePath );
if ( count( $exif ) ) {
$exif['MEDIAWIKI_EXIF_VERSION'] = $version;
$this->metadata = serialize( $exif );
* @return bool
*/
function wasDeleted() {
- $dbw =& wfGetDB( DB_MASTER );
- $del = $dbw->selectField( 'archive', 'COUNT(*) AS count', array( 'ar_namespace' => NS_IMAGE, 'ar_title' => $this->title->getDBkey() ), 'Image::wasDeleted' );
- return $del > 0;
+ $title = Title::makeTitle( NS_IMAGE, $this->name );
+ return ( $title->isDeleted() > 0 );
+ }
+
+ /**
+ * Delete all versions of the image.
+ *
+ * Moves the files into an archive directory (or deletes them)
+ * and removes the database rows.
+ *
+ * Cache purging is done; logging is caller's responsibility.
+ *
+ * @param $reason
+ * @return true on success, false on some kind of failure
+ */
+ function delete( $reason ) {
+ $fname = __CLASS__ . '::' . __FUNCTION__;
+ $transaction = new FSTransaction();
+ $urlArr = array( $this->getURL() );
+
+ if( !FileStore::lock() ) {
+ wfDebug( "$fname: failed to acquire file store lock, aborting\n" );
+ return false;
+ }
+
+ try {
+ $dbw = wfGetDB( DB_MASTER );
+ $dbw->begin();
+
+ // Delete old versions
+ $result = $dbw->select( 'oldimage',
+ array( 'oi_archive_name' ),
+ array( 'oi_name' => $this->name ) );
+
+ while( $row = $dbw->fetchObject( $result ) ) {
+ $oldName = $row->oi_archive_name;
+
+ $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
+
+ // We'll need to purge this URL from caches...
+ $urlArr[] = wfImageArchiveUrl( $oldName );
+ }
+ $dbw->freeResult( $result );
+
+ // And the current version...
+ $transaction->add( $this->prepareDeleteCurrent( $reason ) );
+
+ $dbw->immediateCommit();
+ } catch( MWException $e ) {
+ wfDebug( "$fname: db error, rolling back file transactions\n" );
+ $transaction->rollback();
+ FileStore::unlock();
+ throw $e;
+ }
+
+ wfDebug( "$fname: deleted db items, applying file transactions\n" );
+ $transaction->commit();
+ FileStore::unlock();
+
+
+ // Update site_stats
+ $site_stats = $dbw->tableName( 'site_stats' );
+ $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", $fname );
+
+ $this->purgeEverything( $urlArr );
+
+ return true;
+ }
+
+
+ /**
+ * Delete an old version of the image.
+ *
+ * Moves the file into an archive directory (or deletes it)
+ * and removes the database row.
+ *
+ * Cache purging is done; logging is caller's responsibility.
+ *
+ * @param $reason
+ * @throws MWException or FSException on database or filestore failure
+ * @return true on success, false on some kind of failure
+ */
+ function deleteOld( $archiveName, $reason ) {
+ $fname = __CLASS__ . '::' . __FUNCTION__;
+ $transaction = new FSTransaction();
+ $urlArr = array();
+
+ if( !FileStore::lock() ) {
+ wfDebug( "$fname: failed to acquire file store lock, aborting\n" );
+ return false;
+ }
+
+ $transaction = new FSTransaction();
+ try {
+ $dbw = wfGetDB( DB_MASTER );
+ $dbw->begin();
+ $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
+ $dbw->immediateCommit();
+ } catch( MWException $e ) {
+ wfDebug( "$fname: db error, rolling back file transaction\n" );
+ $transaction->rollback();
+ FileStore::unlock();
+ throw $e;
+ }
+
+ wfDebug( "$fname: deleted db items, applying file transaction\n" );
+ $transaction->commit();
+ FileStore::unlock();
+
+ $this->purgeDescription();
+
+ // Squid purging
+ global $wgUseSquid;
+ if ( $wgUseSquid ) {
+ $urlArr = array(
+ wfImageArchiveUrl( $archiveName ),
+ $page->getInternalURL()
+ );
+ wfPurgeSquidServers( $urlArr );
+ }
+ return true;
+ }
+
+ /**
+ * Delete the current version of a file.
+ * May throw a database error.
+ * @return true on success, false on failure
+ */
+ private function prepareDeleteCurrent( $reason ) {
+ $fname = __CLASS__ . '::' . __FUNCTION__;
+ return $this->prepareDeleteVersion(
+ $this->getFullPath(),
+ $reason,
+ 'image',
+ array(
+ 'fa_name' => 'img_name',
+ 'fa_archive_name' => 'NULL',
+ 'fa_size' => 'img_size',
+ 'fa_width' => 'img_width',
+ 'fa_height' => 'img_height',
+ 'fa_metadata' => 'img_metadata',
+ 'fa_bits' => 'img_bits',
+ 'fa_media_type' => 'img_media_type',
+ 'fa_major_mime' => 'img_major_mime',
+ 'fa_minor_mime' => 'img_minor_mime',
+ 'fa_description' => 'img_description',
+ 'fa_user' => 'img_user',
+ 'fa_user_text' => 'img_user_text',
+ 'fa_timestamp' => 'img_timestamp' ),
+ array( 'img_name' => $this->name ),
+ $fname );
}
+ /**
+ * Delete a given older version of a file.
+ * May throw a database error.
+ * @return true on success, false on failure
+ */
+ private function prepareDeleteOld( $archiveName, $reason ) {
+ $fname = __CLASS__ . '::' . __FUNCTION__;
+ $oldpath = wfImageArchiveDir( $this->name ) .
+ DIRECTORY_SEPARATOR . $archiveName;
+ return $this->prepareDeleteVersion(
+ $oldpath,
+ $reason,
+ 'oldimage',
+ array(
+ 'fa_name' => 'oi_name',
+ 'fa_archive_name' => 'oi_archive_name',
+ 'fa_size' => 'oi_size',
+ 'fa_width' => 'oi_width',
+ 'fa_height' => 'oi_height',
+ 'fa_metadata' => 'NULL',
+ 'fa_bits' => 'oi_bits',
+ 'fa_media_type' => 'NULL',
+ 'fa_major_mime' => 'NULL',
+ 'fa_minor_mime' => 'NULL',
+ 'fa_description' => 'oi_description',
+ 'fa_user' => 'oi_user',
+ 'fa_user_text' => 'oi_user_text',
+ 'fa_timestamp' => 'oi_timestamp' ),
+ array(
+ 'oi_name' => $this->name,
+ 'oi_archive_name' => $archiveName ),
+ $fname );
+ }
+
+ /**
+ * Do the dirty work of backing up an image row and its file
+ * (if $wgSaveDeletedFiles is on) and removing the originals.
+ *
+ * Must be run while the file store is locked and a database
+ * transaction is open to avoid race conditions.
+ *
+ * @return FSTransaction
+ */
+ private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
+ global $wgUser, $wgSaveDeletedFiles;
+
+ // Dupe the file into the file store
+ if( file_exists( $path ) ) {
+ if( $wgSaveDeletedFiles ) {
+ $group = 'deleted';
+
+ $store = FileStore::get( $group );
+ $key = FileStore::calculateKey( $path, $this->extension );
+ $transaction = $store->insert( $key, $path,
+ FileStore::DELETE_ORIGINAL );
+ } else {
+ $group = null;
+ $key = null;
+ $transaction = FileStore::deleteFile( $path );
+ }
+ } else {
+ wfDebug( "$fname deleting already-missing '$path'; moving on to database\n" );
+ $group = null;
+ $key = null;
+ $transaction = new FSTransaction(); // empty
+ }
+
+ if( $transaction === false ) {
+ // Fail to restore?
+ wfDebug( "$fname: import to file store failed, aborting\n" );
+ throw new MWException( "Could not archive and delete file $path" );
+ return false;
+ }
+
+ $dbw = wfGetDB( DB_MASTER );
+ $storageMap = array(
+ 'fa_storage_group' => $dbw->addQuotes( $group ),
+ 'fa_storage_key' => $dbw->addQuotes( $key ),
+
+ 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
+ 'fa_deleted_timestamp' => $dbw->timestamp(),
+ 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
+ $allFields = array_merge( $storageMap, $fieldMap );
+
+ try {
+ if( $wgSaveDeletedFiles ) {
+ $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
+ }
+ $dbw->delete( $table, $where, $fname );
+ } catch( DBQueryError $e ) {
+ // Something went horribly wrong!
+ // Leave the file as it was...
+ wfDebug( "$fname: database error, rolling back file transaction\n" );
+ $transaction->rollback();
+ throw $e;
+ }
+
+ return $transaction;
+ }
+
+ /**
+ * Restore all or specified deleted revisions to the given file.
+ * Permissions and logging are left to the caller.
+ *
+ * May throw database exceptions on error.
+ *
+ * @param $versions set of record ids of deleted items to restore,
+ * or empty to restore all revisions.
+ * @return the number of file revisions restored if successful,
+ * or false on failure
+ */
+ function restore( $versions=array() ) {
+ $fname = __CLASS__ . '::' . __FUNCTION__;
+ if( !FileStore::lock() ) {
+ wfDebug( "$fname could not acquire filestore lock\n" );
+ return false;
+ }
+
+ $transaction = new FSTransaction();
+ try {
+ $dbw = wfGetDB( DB_MASTER );
+ $dbw->begin();
+
+ // Re-confirm whether this image presently exists;
+ // if no we'll need to create an image record for the
+ // first item we restore.
+ $exists = $dbw->selectField( 'image', '1',
+ array( 'img_name' => $this->name ),
+ $fname );
+
+ // Fetch all or selected archived revisions for the file,
+ // sorted from the most recent to the oldest.
+ $conditions = array( 'fa_name' => $this->name );
+ if( $versions ) {
+ $conditions['fa_id'] = $versions;
+ }
+
+ $result = $dbw->select( 'filearchive', '*',
+ $conditions,
+ $fname,
+ array( 'ORDER BY' => 'fa_timestamp DESC' ) );
+
+ if( $dbw->numRows( $result ) < count( $versions ) ) {
+ // There's some kind of conflict or confusion;
+ // we can't restore everything we were asked to.
+ wfDebug( "$fname: couldn't find requested items\n" );
+ $dbw->rollback();
+ FileStore::unlock();
+ return false;
+ }
+
+ if( $dbw->numRows( $result ) == 0 ) {
+ // Nothing to do.
+ wfDebug( "$fname: nothing to do\n" );
+ $dbw->rollback();
+ FileStore::unlock();
+ return true;
+ }
+
+ $revisions = 0;
+ while( $row = $dbw->fetchObject( $result ) ) {
+ $revisions++;
+ $store = FileStore::get( $row->fa_storage_group );
+ if( !$store ) {
+ wfDebug( "$fname: skipping row with no file.\n" );
+ continue;
+ }
+
+ if( $revisions == 1 && !$exists ) {
+ $destPath = wfImageDir( $row->fa_name ) .
+ DIRECTORY_SEPARATOR .
+ $row->fa_name;
+
+ // We may have to fill in data if this was originally
+ // an archived file revision.
+ if( is_null( $row->fa_metadata ) ) {
+ $tempFile = $store->filePath( $row->fa_storage_key );
+ $metadata = serialize( $this->retrieveExifData( $tempFile ) );
+
+ $magic = wfGetMimeMagic();
+ $mime = $magic->guessMimeType( $tempFile, true );
+ $media_type = $magic->getMediaType( $tempFile, $mime );
+ list( $major_mime, $minor_mime ) = self::splitMime( $mime );
+ } else {
+ $metadata = $row->fa_metadata;
+ $major_mime = $row->fa_major_mime;
+ $minor_mime = $row->fa_minor_mime;
+ $media_type = $row->fa_media_type;
+ }
+
+ $table = 'image';
+ $fields = array(
+ 'img_name' => $row->fa_name,
+ 'img_size' => $row->fa_size,
+ 'img_width' => $row->fa_width,
+ 'img_height' => $row->fa_height,
+ 'img_metadata' => $metadata,
+ 'img_bits' => $row->fa_bits,
+ 'img_media_type' => $media_type,
+ 'img_major_mime' => $major_mime,
+ 'img_minor_mime' => $minor_mime,
+ 'img_description' => $row->fa_description,
+ 'img_user' => $row->fa_user,
+ 'img_user_text' => $row->fa_user_text,
+ 'img_timestamp' => $row->fa_timestamp );
+ } else {
+ $archiveName = $row->fa_archive_name;
+ if( $archiveName == '' ) {
+ // This was originally a current version; we
+ // have to devise a new archive name for it.
+ // Format is <timestamp of archiving>!<name>
+ $archiveName =
+ wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
+ '!' . $row->fa_name;
+ }
+ $destPath = wfImageArchiveDir( $row->fa_name ) .
+ DIRECTORY_SEPARATOR . $archiveName;
+
+ $table = 'oldimage';
+ $fields = array(
+ 'oi_name' => $row->fa_name,
+ 'oi_archive_name' => $archiveName,
+ 'oi_size' => $row->fa_size,
+ 'oi_width' => $row->fa_width,
+ 'oi_height' => $row->fa_height,
+ 'oi_bits' => $row->fa_bits,
+ 'oi_description' => $row->fa_description,
+ 'oi_user' => $row->fa_user,
+ 'oi_user_text' => $row->fa_user_text,
+ 'oi_timestamp' => $row->fa_timestamp );
+ }
+
+ $dbw->insert( $table, $fields, $fname );
+ /// @fixme this delete is not totally safe, potentially
+ $dbw->delete( 'filearchive',
+ array( 'fa_id' => $row->fa_id ),
+ $fname );
+
+ // Check if any other stored revisions use this file;
+ // if so, we shouldn't remove the file from the deletion
+ // archives so they will still work.
+ $useCount = $dbw->selectField( 'filearchive',
+ 'COUNT(*)',
+ array(
+ 'fa_storage_group' => $row->fa_storage_group,
+ 'fa_storage_key' => $row->fa_storage_key ),
+ $fname );
+ if( $useCount == 0 ) {
+ wfDebug( "$fname: nothing else using {$row->fa_storage_key}, will deleting after\n" );
+ $flags = FileStore::DELETE_ORIGINAL;
+ } else {
+ $flags = 0;
+ }
+
+ $transaction->add( $store->export( $row->fa_storage_key,
+ $destPath, $flags ) );
+ }
+
+ $dbw->immediateCommit();
+ } catch( MWException $e ) {
+ wfDebug( "$fname caught error, aborting\n" );
+ $transaction->rollback();
+ throw $e;
+ }
+
+ $transaction->commit();
+ FileStore::unlock();
+
+ if( $revisions > 0 ) {
+ if( !$exists ) {
+ wfDebug( "$fname restored $revisions items, creating a new current\n" );
+
+ // Update site_stats
+ $site_stats = $dbw->tableName( 'site_stats' );
+ $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
+
+ $this->purgeEverything();
+ } else {
+ wfDebug( "$fname restored $revisions as archived versions\n" );
+ $this->purgeDescription();
+ }
+ }
+
+ return $revisions;
+ }
+
} //class