Some HipHop fixes:
[lhc/web/wiklou.git] / includes / filerepo / File.php
index 1ddb7f1..0b5e374 100644 (file)
@@ -1,17 +1,21 @@
 <?php
-
 /**
- * Base file class. Do not instantiate.
+ * Base code for files.
  *
- * Implements some public methods and some protected utility functions which 
- * are required by multiple child classes. Contains stub functionality for 
+ * @file
+ * @ingroup FileRepo
+ */
+
+/**
+ * Implements some public methods and some protected utility functions which
+ * are required by multiple child classes. Contains stub functionality for
  * unimplemented public methods.
  *
- * Stub functions which should be overridden are marked with STUB. Some more 
+ * Stub functions which should be overridden are marked with STUB. Some more
  * concrete functions are also typically overridden by child classes.
  *
  * Note that only the repo object knows what its file class is called. You should
- * never name a file class explictly outside of the repo class. Instead use the 
+ * never name a file class explictly outside of the repo class. Instead use the
  * repo's factory functions to generate file objects, for example:
  *
  * RepoGroup::singleton()->getLocalRepo()->newFile($title);
@@ -19,9 +23,9 @@
  * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
  * in most cases.
  *
- * @addtogroup FileRepo
+ * @ingroup FileRepo
  */
-class File {
+abstract class File {
        const DELETED_FILE = 1;
        const DELETED_COMMENT = 2;
        const DELETED_USER = 4;
@@ -30,17 +34,17 @@ class File {
 
        const DELETE_SOURCE = 1;
 
-       /** 
-        * Some member variables can be lazy-initialised using __get(). The 
+       /**
+        * Some member variables can be lazy-initialised using __get(). The
         * initialisation function for these variables is always a function named
-        * like getVar(), where Var is the variable name with upper-case first 
+        * like getVar(), where Var is the variable name with upper-case first
         * letter.
         *
         * The following variables are initialised in this way in this base class:
-        *    name, extension, handler, path, canRender, isSafeFile, 
+        *    name, extension, handler, path, canRender, isSafeFile,
         *    transformScript, hashPath, pageCount, url
         *
-        * Code within this class should generally use the accessor function 
+        * Code within this class should generally use the accessor function
         * directly, since __get() isn't re-entrant and therefore causes bugs that
         * depend on initialisation order.
         */
@@ -48,7 +52,23 @@ class File {
        /**
         * The following member variables are not lazy-initialised
         */
-       var $repo, $title, $lastError;
+
+       /**
+        * @var LocalRepo
+        */
+       var $repo;
+
+       /**
+        * @var Title
+        */
+       var $title;
+
+       var $lastError, $redirected, $redirectedTitle;
+
+       /**
+        * @var MediaHandler
+        */
+       protected $handler;
 
        /**
         * Call this constructor from child classes
@@ -81,7 +101,8 @@ class File {
                        'htm' => 'html',
                        'jpeg' => 'jpg',
                        'mpeg' => 'mpg',
-                       'tiff' => 'tif' );
+                       'tiff' => 'tif',
+                       'ogv' => 'ogg' );
                if( isset( $squish[$lower] ) ) {
                        return $squish[$lower];
                } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
@@ -91,6 +112,21 @@ class File {
                }
        }
 
+       /**
+        * Checks if file extensions are compatible
+        *
+        * @param $old File Old file
+        * @param $new string New name
+        */
+       static function checkExtensionCompatibility( File $old, $new ) {
+               $oldMime = $old->getMimeType();
+               $n = strrpos( $new, '.' );
+               $newExt = self::normalizeExtension(
+                       $n ? substr( $new, $n + 1 ) : '' );
+               $mimeMagic = MimeMagic::singleton();
+               return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
+       }
+
        /**
         * Upgrade the database row if there is one
         * Called by ImagePage
@@ -102,26 +138,25 @@ class File {
         * 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
+        * @param string $mime "text/html" etc
         * @return array ("text", "html") etc
         */
-       static function splitMime( $mime ) {
+       public static function splitMime( $mime ) {
                if( strpos( $mime, '/' ) !== false ) {
                        return explode( '/', $mime, 2 );
                } else {
                        return array( $mime, 'unknown' );
                }
        }
-       
+
        /**
         * Return the name of this file
-        * @public
         */
-       function getName() {
+       public function getName() {
                if ( !isset( $this->name ) ) {
                        $this->name = $this->repo->getNameFromTitle( $this->title );
                }
-               return $this->name; 
+               return $this->name;
        }
 
        /**
@@ -130,7 +165,7 @@ class File {
        function getExtension() {
                if ( !isset( $this->extension ) ) {
                        $n = strrpos( $this->getName(), '.' );
-                       $this->extension = self::normalizeExtension( 
+                       $this->extension = self::normalizeExtension(
                                $n ? substr( $this->getName(), $n + 1 ) : '' );
                }
                return $this->extension;
@@ -138,19 +173,38 @@ class File {
 
        /**
         * Return the associated title object
-        * @public
+        * @return Title
         */
-       function getTitle() { return $this->title; }
+       public function getTitle() { return $this->title; }
+
+       /**
+        * Return the title used to find this file
+        */
+       public function getOriginalTitle() {
+               if ( $this->redirected )
+                       return $this->getRedirectedTitle();
+               return $this->title;
+       }
 
        /**
         * Return the URL of the file
-        * @public
         */
-       function getUrl() { 
+       public function getUrl() {
                if ( !isset( $this->url ) ) {
                        $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
                }
-               return $this->url; 
+               return $this->url;
+       }
+
+       /**
+        * Return a fully-qualified URL to the file.
+        * Upload URL paths _may or may not_ be fully qualified, so
+        * we check. Local paths are assumed to belong on $wgServer.
+        *
+        * @return String
+        */
+       public function getFullUrl() {
+               return wfExpandUrl( $this->getUrl() );
        }
 
        function getViewURL() {
@@ -175,11 +229,10 @@ class File {
        * i.e. whether the files are all found in the same directory,
        * or in hashed paths like /images/3/3c.
        *
-       * May return false if the file is not locally accessible.
-       *
-       * @public
+       * Most callers don't check the return value, but ForeignAPIFile::getPath
+       * returns false.
        */
-       function getPath() {
+       public function getPath() {
                if ( !isset( $this->path ) ) {
                        $this->path = $this->repo->getZonePath('public') . '/' . $this->getRel();
                }
@@ -188,46 +241,105 @@ class File {
 
        /**
        * Alias for getPath()
-       * @public
+       *
+       * @deprecated since 1.18 Use getPath().
        */
-       function getFullPath() {
+       public function getFullPath() {
+               wfDeprecated( __METHOD__ );
                return $this->getPath();
        }
 
        /**
-        * Return the width of the image. Returns false if the width is unknown 
+        * Return the width of the image. Returns false if the width is unknown
         * or undefined.
         *
         * STUB
         * Overridden by LocalFile, UnregisteredLocalFile
-        * @public
         */
-       function getWidth( $page = 1 ) { return false; }
+       public function getWidth( $page = 1 ) { return false; }
 
        /**
-        * Return the height of the image. Returns false if the height is unknown 
+        * Return the height of the image. Returns false if the height is unknown
         * or undefined
         *
         * STUB
         * Overridden by LocalFile, UnregisteredLocalFile
-        * @public
         */
-       function getHeight( $page = 1 ) { return false; }
+       public function getHeight( $page = 1 ) { return false; }
+
+       /**
+        * Returns ID or name of user who uploaded the file
+        * STUB
+        *
+        * @param $type string 'text' or 'id'
+        */
+       public function getUser( $type='text' ) { return null; }
+
+       /**
+        * Get the duration of a media file in seconds
+        */
+       public function getLength() {
+               $handler = $this->getHandler();
+               if ( $handler ) {
+                       return $handler->getLength( $this );
+               } else {
+                       return 0;
+               }
+       }
+
+       /**
+        *  Return true if the file is vectorized
+        */
+       public function isVectorized() {
+               $handler = $this->getHandler();
+               if ( $handler ) {
+                       return $handler->isVectorized( $this );
+               } else {
+                       return false;
+               }
+       }
+
 
        /**
         * Get handler-specific metadata
         * Overridden by LocalFile, UnregisteredLocalFile
         * STUB
         */
-       function getMetadata() { return false; }
+       public function getMetadata() { return false; }
+
+       /**
+       * get versioned metadata
+       *
+       * @param $metadata Mixed Array or String of (serialized) metadata
+       * @param $version integer version number.
+       * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
+       */
+       public function convertMetadataVersion($metadata, $version) {
+               $handler = $this->getHandler();
+               if ( !is_array( $metadata ) ) {
+                       //just to make the return type consistant
+                       $metadata = unserialize( $metadata );
+               }
+               if ( $handler ) {
+                       return $handler->convertMetadataVersion( $metadata, $version );
+               } else {
+                       return $metadata;
+               }
+       }
+
+       /**
+        * Return the bit depth of the file
+        * Overridden by LocalFile
+        * STUB
+        */
+       public function getBitDepth() { return 0; }
 
        /**
         * Return the size of the image file, in bytes
         * Overridden by LocalFile, UnregisteredLocalFile
         * STUB
-        * @public
         */
-       function getSize() { return false; }
+       public function getSize() { return false; }
 
        /**
         * Returns the mime type of the file.
@@ -245,7 +357,9 @@ class File {
        function getMediaType() { return MEDIATYPE_UNKNOWN; }
 
        /**
-        * Checks if the file can be presented to the browser as a bitmap.
+        * Checks if the output of transform() for this file is likely
+        * to be valid. If this is false, various user elements will
+        * display a placeholder instead.
         *
         * Currently, this checks if the file is an image format
         * that can be converted to a format
@@ -254,7 +368,7 @@ class File {
         */
        function canRender() {
                if ( !isset( $this->canRender ) ) {
-                       $this->canRender = $this->getHandler() && $this->handler->canRender();
+                       $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
                }
                return $this->canRender;
        }
@@ -277,16 +391,11 @@ class File {
         * @return bool
         */
        function mustRender() {
-               return $this->getHandler() && $this->handler->mustRender();
+               return $this->getHandler() && $this->handler->mustRender( $this );
        }
 
        /**
-        * Determines if this media file may be shown inline on a page.
-        *
-        * This is currently synonymous to canRender(), but this could be
-        * extended to also allow inline display of other media,
-        * like flash animations or videos. If you do so, please keep in mind that
-        * that could be a security risk.
+        * Alias for canRender()
         */
        function allowInlineDisplay() {
                return $this->canRender();
@@ -309,7 +418,7 @@ class File {
                }
                return $this->isSafeFile;
        }
-       
+
        /** Accessor for __get() */
        protected function getIsSafeFile() {
                return $this->isSafeFile();
@@ -355,14 +464,23 @@ class File {
         * Returns true if file exists in the repository.
         *
         * Overridden by LocalFile to avoid unnecessary stat calls.
-        * 
+        *
         * @return boolean Whether file exists in the repository.
-        * @public
         */
-       function exists() {
+       public function exists() {
                return $this->getPath() && file_exists( $this->path );
        }
 
+       /**
+        * Returns true if file exists in the repository and can be included in a page.
+        * It would be unsafe to include private images, making public thumbnails inadvertently
+        *
+        * @return boolean Whether file exists in the repository and is includable.
+        */
+       public function isVisible() {
+               return $this->exists();
+       }
+
        function getTransformScript() {
                if ( !isset( $this->transformScript ) ) {
                        $this->transformScript = false;
@@ -379,35 +497,40 @@ class File {
        /**
         * Get a ThumbnailImage which is the same size as the source
         */
-       function getUnscaledThumb( $page = false ) {
+       function getUnscaledThumb( $handlerParams = array() ) {
+               $hp =& $handlerParams;
+               $page = isset( $hp['page'] ) ? $hp['page'] : false;
                $width = $this->getWidth( $page );
                if ( !$width ) {
                        return $this->iconThumb();
                }
-               if ( $page ) {
-                       $params = array(
-                               'page' => $page,
-                               'width' => $this->getWidth( $page )
-                       );
-               } else {
-                       $params = array( 'width' => $this->getWidth() );
-               }
-               return $this->transform( $params );
+               $hp['width'] = $width;
+               return $this->transform( $hp );
        }
 
        /**
         * Return the file name of a thumbnail with the specified parameters
         *
-        * @param array $params Handler-specific parameters
-        * @private
+        * @param $params Array: handler-specific parameters
+        * @private -ish
         */
        function thumbName( $params ) {
+               return $this->generateThumbName( $this->getName(), $params );
+       }
+
+       /**
+        * Generate a thumbnail file name from a name and specified parameters
+        *
+        * @param string $name
+        * @param array $params Parameters which will be passed to MediaHandler::makeParamString
+        */
+       function generateThumbName( $name, $params ) {
                if ( !$this->getHandler() ) {
                        return null;
                }
                $extension = $this->getExtension();
-               list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType() );
-               $thumbName = $this->handler->makeParamString( $params ) . '-' . $this->getName();
+               list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
+               $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
                if ( $thumbExt != $extension ) {
                        $thumbName .= ".$thumbExt";
                }
@@ -426,11 +549,10 @@ class File {
         * specified, the generated image will be no bigger than width x height,
         * and will also have correct aspect ratio.
         *
-        * @param integer $width        maximum width of the generated thumbnail
-        * @param integer $height       maximum height of the image (optional)
-        * @public
+        * @param $width Integer: maximum width of the generated thumbnail
+        * @param $height Integer: maximum height of the image (optional)
         */
-       function createThumb( $width, $height = -1 ) {
+       public function createThumb( $width, $height = -1 ) {
                $params = array( 'width' => $width );
                if ( $height != -1 ) {
                        $params['height'] = $height;
@@ -440,74 +562,61 @@ class File {
                return $thumb->getUrl();
        }
 
-       /**
-        * As createThumb, but returns a ThumbnailImage object. This can
-        * provide access to the actual file, the real size of the thumb,
-        * and can produce a convenient <img> tag for you.
-        *
-        * For non-image formats, this may return a filetype-specific icon.
-        *
-        * @param integer $width        maximum width of the generated thumbnail
-        * @param integer $height       maximum height of the image (optional)
-        * @param boolean $render       True to render the thumbnail if it doesn't exist,
-        *                              false to just return the URL
-        *
-        * @return ThumbnailImage or null on failure
-        * @public
-        *
-        * @deprecated use transform()
-        */
-       function getThumbnail( $width, $height=-1, $render = true ) {
-               $params = array( 'width' => $width );
-               if ( $height != -1 ) {
-                       $params['height'] = $height;
-               }
-               $flags = $render ? self::RENDER_NOW : 0;
-               return $this->transform( $params, $flags );
-       }
-
        /**
         * Transform a media file
         *
-        * @param array $params An associative array of handler-specific parameters. Typical 
-        *                      keys are width, height and page.
-        * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
-        * @return MediaTransformOutput
+        * @param $params Array: an associative array of handler-specific parameters.
+        *                Typical keys are width, height and page.
+        * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
+        * @return MediaTransformOutput | false
         */
        function transform( $params, $flags = 0 ) {
-               global $wgUseSquid, $wgIgnoreImageErrors;
+               global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
 
                wfProfileIn( __METHOD__ );
                do {
-                       if ( !$this->getHandler() || !$this->handler->canRender() ) {
+                       if ( !$this->canRender() ) {
                                // not a bitmap or renderable image, don't try.
                                $thumb = $this->iconThumb();
                                break;
                        }
 
+                       // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
+                       $descriptionUrl =  $this->getDescriptionUrl();
+                       if ( $descriptionUrl ) {
+                               $params['descriptionUrl'] = $wgServer . $descriptionUrl;
+                       }
+
                        $script = $this->getTransformScript();
                        if ( $script && !($flags & self::RENDER_NOW) ) {
-                               // Use a script to transform on client request
+                               // Use a script to transform on client request, if possible
                                $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
-                               break;
+                               if( $thumb ) {
+                                       break;
+                               }
                        }
 
                        $normalisedParams = $params;
                        $this->handler->normaliseParams( $this, $normalisedParams );
-                       $thumbName = $this->thumbName( $normalisedParams );     
+                       $thumbName = $this->thumbName( $normalisedParams );
                        $thumbPath = $this->getThumbPath( $thumbName );
                        $thumbUrl = $this->getThumbUrl( $thumbName );
 
-                       if ( $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
+                       if ( $this->repo && $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
                                $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
                                break;
                        }
 
                        wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
                        $this->migrateThumbFile( $thumbName );
-                       if ( file_exists( $thumbPath ) ) {
-                               $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
-                               break;
+                       if ( file_exists( $thumbPath )) {
+                               $thumbTime = filemtime( $thumbPath );
+                               if ( $thumbTime !== FALSE &&
+                                       gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
+
+                                       $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
+                                       break;
+                               }
                        }
                        $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
 
@@ -520,27 +629,31 @@ class File {
                                        $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
                                }
                        }
-                       
-                       if ( $wgUseSquid ) {
-                               wfPurgeSquidServers( array( $thumbUrl ) );
+
+                       // Purge. Useful in the event of Core -> Squid connection failure or squid
+                       // purge collisions from elsewhere during failure. Don't keep triggering for
+                       // "thumbs" which have the main image URL though (bug 13776)
+                       if ( $wgUseSquid && ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL()) ) {
+                               SquidUpdate::purge( array( $thumbUrl ) );
                        }
                } while (false);
 
                wfProfileOut( __METHOD__ );
-               return $thumb;
+               return is_object( $thumb ) ? $thumb : false;
        }
 
-       /** 
+       /**
         * Hook into transform() to allow migration of thumbnail files
         * STUB
         * Overridden by LocalFile
         */
-       function migrateThumbFile() {}
+       function migrateThumbFile( $thumbName ) {}
 
        /**
         * Get a MediaHandler instance for this file
+        * @return MediaHandler
         */
-       function getHandler() { 
+       function getHandler() {
                if ( !isset( $this->handler ) ) {
                        $this->handler = MediaHandler::getHandler( $this->getMimeType() );
                }
@@ -559,7 +672,7 @@ class File {
                        $path = '/common/images/icons/' . $icon;
                        $filepath = $wgStyleDirectory . $path;
                        if( file_exists( $filepath ) ) {
-                               return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
+                               return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
                        }
                }
                return null;
@@ -585,7 +698,7 @@ class File {
         * STUB
         * Overridden by LocalFile
         */
-       function purgeCache( $archiveFiles = array() ) {}
+       function purgeCache() {}
 
        /**
         * Purge the file description page, but don't go after
@@ -599,14 +712,12 @@ class File {
                        $title->purgeSquid();
                }
        }
-       
+
        /**
         * Purge metadata and all affected pages when the file is created,
-        * deleted, or majorly updated. A set of additional URLs may be
-        * passed to purge, such as specific file files which have changed.
-        * @param $urlArray array
+        * deleted, or majorly updated.
         */
-       function purgeEverything( $urlArr=array() ) {
+       function purgeEverything() {
                // Delete thumbnails and refresh file metadata cache
                $this->purgeCache();
                $this->purgeDescription();
@@ -620,25 +731,37 @@ class File {
        }
 
        /**
-        * Return the history of this file, line by line. Starts with current version, 
-        * then old versions. Should return an object similar to an image/oldimage 
+        * Return a fragment of the history of file.
+        *
+        * STUB
+        * @param $limit integer Limit of rows to return
+        * @param $start timestamp Only revisions older than $start will be returned
+        * @param $end timestamp Only revisions newer than $end will be returned
+        * @param $inc bool Include the endpoints of the time range
+        */
+       function getHistory($limit = null, $start = null, $end = null, $inc=true) {
+               return array();
+       }
+
+       /**
+        * Return the history of this file, line by line. Starts with current version,
+        * then old versions. Should return an object similar to an image/oldimage
         * database row.
         *
-        * @public
         * STUB
         * Overridden in LocalFile
         */
-       function nextHistoryLine() {
+       public function nextHistoryLine() {
                return false;
        }
 
        /**
-        * Reset the history pointer to the first element of the history
-        * @public
+        * Reset the history pointer to the first element of the history.
+        * Always call this function after using nextHistoryLine() to free db resources
         * STUB
         * Overridden in LocalFile.
         */
-       function resetHistory() {}
+       public function resetHistory() {}
 
        /**
         * Get the filename hash component of the directory including trailing slash,
@@ -666,9 +789,9 @@ class File {
                return $this->getHashPath() . rawurlencode( $this->getName() );
        }
 
-       /** Get the path of the archive directory, or a particular file if $suffix is specified */
-       function getArchivePath( $suffix = false ) {
-               $path = $this->repo->getZonePath('public') . '/archive/' . $this->getHashPath();
+       /** Get the relative path for an archive file */
+       function getArchiveRel( $suffix = false ) {
+               $path = 'archive/' . $this->getHashPath();
                if ( $suffix === false ) {
                        $path = substr( $path, 0, -1 );
                } else {
@@ -677,9 +800,14 @@ class File {
                return $path;
        }
 
+       /** Get the path of the archive directory, or a particular file if $suffix is specified */
+       function getArchivePath( $suffix = false ) {
+               return $this->repo->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
+       }
+
        /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
        function getThumbPath( $suffix = false ) {
-               $path = $this->repo->getZonePath('public') . '/thumb/' . $this->getRel();
+               $path = $this->repo->getZonePath('thumb') . '/' . $this->getRel();
                if ( $suffix !== false ) {
                        $path .= '/' . $suffix;
                }
@@ -699,7 +827,7 @@ class File {
 
        /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
        function getThumbUrl( $suffix = false ) {
-               $path = $this->repo->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
+               $path = $this->repo->getZoneUrl('thumb') . '/' . $this->getUrlRel();
                if ( $suffix !== false ) {
                        $path .= '/' . rawurlencode( $suffix );
                }
@@ -719,7 +847,7 @@ class File {
 
        /** Get the virtual URL for a thumbnail file or directory */
        function getThumbVirtualUrl( $suffix = false ) {
-               $path = $this->repo->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
+               $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
                if ( $suffix !== false ) {
                        $path .= '/' . rawurlencode( $suffix );
                }
@@ -733,7 +861,7 @@ class File {
                        $path .= '/' . rawurlencode( $suffix );
                }
                return $path;
-       }       
+       }
 
        /**
         * @return bool
@@ -751,25 +879,24 @@ class File {
         * STUB
         * Overridden by LocalFile
         */
-       function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) { 
-               $this->readOnlyError(); 
+       function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
+               $this->readOnlyError();
        }
 
        /**
-        * Move or copy a file to its public location. If a file exists at the  
-        * destination, move it to an archive. Returns the archive name on success 
-        * or an empty string if it was a new file, and a wikitext-formatted 
-        * WikiError object on failure. 
+        * Move or copy a file to its public location. If a file exists at the
+        * destination, move it to an archive. Returns a FileRepoStatus object with
+        * the archive name in the "value" member on success.
         *
         * The archive name should be passed through to recordUpload for database
         * registration.
         *
-        * @param string $sourcePath Local filesystem path to the source image
-        * @param integer $flags A bitwise combination of:
-        *     File::DELETE_SOURCE    Delete the source file, i.e. move 
+        * @param $srcPath String: local filesystem path to the source image
+        * @param $flags Integer: a bitwise combination of:
+        *     File::DELETE_SOURCE    Delete the source file, i.e. move
         *         rather than copy
-        * @return The archive name on success or an empty string if it was a new 
-        *     file, and a wikitext-formatted WikiError object on failure. 
+        * @return FileRepoStatus object. On success, the value member contains the
+        *     archive name, or an empty string if it was a new file.
         *
         * STUB
         * Overridden by LocalFile
@@ -778,60 +905,11 @@ class File {
                $this->readOnlyError();
        }
 
-       /**
-        * Get an array of Title objects which are articles which use this file
-        * 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 = '' ) {
-               wfProfileIn( __METHOD__ );
-
-               // Note: use local DB not repo DB, we want to know local links
-               if ( $options ) {
-                       $db = wfGetDB( DB_MASTER );
-               } else {
-                       $db = wfGetDB( DB_SLAVE );
-               }
-               $linkCache =& LinkCache::singleton();
-
-               list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
-               $encName = $db->addQuotes( $this->getName() );
-               $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
-               $res = $db->query( $sql, __METHOD__ );
-
-               $retVal = array();
-               if ( $db->numRows( $res ) ) {
-                       while ( $row = $db->fetchObject( $res ) ) {
-                               if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
-                                       $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
-                                       $retVal[] = $titleObj;
-                               }
-                       }
-               }
-               $db->freeResult( $res );
-               wfProfileOut( __METHOD__ );
-               return $retVal;
-       }
-
-       function getExifData() {
-               if ( !$this->getHandler() || $this->handler->getMetadataType( $this ) != 'exif' ) {
-                       return array();
-               }
-               $metadata = $this->getMetadata();
-               if ( !$metadata ) {
-                       return array();
-               }
-               $exif = unserialize( $metadata );
-               if ( !$exif ) {
-                       return array();
+       function formatMetadata() {
+               if ( !$this->getHandler() ) {
+                       return false;
                }
-               unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
-               $format = new FormatExif( $exif );
-
-               return $format->getFormattedData();
+               return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
        }
 
        /**
@@ -839,8 +917,25 @@ class File {
         *
         * @return bool
         */
-       function isLocal() { 
-               return $this->repo && $this->repo->getName() == 'local'; 
+       function isLocal() {
+               $repo = $this->getRepo();
+               return $repo && $repo->isLocal();
+       }
+
+       /**
+        * Returns the name of the repository.
+        *
+        * @return string
+        */
+       function getRepoName() {
+               return $this->repo ? $this->repo->getName() : 'unknown';
+       }
+
+       /*
+        * Returns the repository
+        */
+       function getRepo() {
+               return $this->repo;
        }
 
        /**
@@ -859,6 +954,14 @@ class File {
                return false;
        }
 
+       /**
+        * Return the deletion bitfield
+        * STUB
+        */
+       function getVisibility() {
+               return 0;
+       }
+
        /**
         * Was this file ever deleted from the wiki?
         *
@@ -866,9 +969,25 @@ class File {
         */
        function wasDeleted() {
                $title = $this->getTitle();
-               return $title && $title->isDeleted() > 0;
+               return $title && $title->isDeletedQuick();
        }
 
+       /**
+        * Move file to the new title
+        *
+        * Move current, old version and all thumbnails
+        * to the new filename. Old file is deleted.
+        *
+        * Cache purging is done; checks for validity
+        * and logging are caller's responsibility
+        *
+        * @param $target Title New file name
+        * @return FileRepoStatus object.
+        */
+        function move( $target ) {
+               $this->readOnlyError();
+        }
+
        /**
         * Delete all versions of the file.
         *
@@ -877,12 +996,13 @@ class File {
         *
         * Cache purging is done; logging is caller's responsibility.
         *
-        * @param $reason
+        * @param $reason String
+        * @param $suppress Boolean: hide content from sysops?
         * @return true on success, false on some kind of failure
         * STUB
         * Overridden by LocalFile
         */
-       function delete( $reason, $suppress=false ) {
+       function delete( $reason, $suppress = false ) {
                $this->readOnlyError();
        }
 
@@ -894,32 +1014,34 @@ class File {
         *
         * @param $versions set of record ids of deleted items to restore,
         *                    or empty to restore all revisions.
+        * @param $unsuppress remove restrictions on content upon restoration?
         * @return the number of file revisions restored if successful,
         *         or false on failure
         * STUB
         * Overridden by LocalFile
         */
-       function restore( $versions=array(), $Unsuppress=false ) {
+       function restore( $versions=array(), $unsuppress=false ) {
                $this->readOnlyError();
        }
 
        /**
-        * Returns 'true' if this image is a multipage document, e.g. a DJVU
-        * document.
+        * Returns 'true' if this file is a type which supports multiple pages,
+        * e.g. DJVU or PDF. Note that this may be true even if the file in
+        * question only has a single page.
         *
         * @return Bool
         */
        function isMultipage() {
-               return $this->getHandler() && $this->handler->isMultiPage();
+               return $this->getHandler() && $this->handler->isMultiPage( $this );
        }
 
        /**
-        * Returns the number of pages of a multipage document, or NULL for
+        * Returns the number of pages of a multipage document, or false for
         * documents which aren't multipage documents
         */
        function pageCount() {
                if ( !isset( $this->pageCount ) ) {
-                       if ( $this->getHandler() && $this->handler->isMultiPage() ) {
+                       if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
                                $this->pageCount = $this->handler->pageCount( $this );
                        } else {
                                $this->pageCount = false;
@@ -939,13 +1061,13 @@ class File {
                        return round( $srcHeight * $dstWidth / $srcWidth );
                }
        }
-       
+
        /**
-        * Get an image size array like that returned by getimagesize(), or false if it 
+        * Get an image size array like that returned by getImageSize(), or false if it
         * can't be determined.
         *
-        * @param string $fileName The filename
-        * @return array
+        * @param $fileName String: The filename
+        * @return Array
         */
        function getImageSize( $fileName ) {
                if ( !$this->getHandler() ) {
@@ -966,56 +1088,112 @@ class File {
         * Get the HTML text of the description page, if available
         */
        function getDescriptionText() {
+               global $wgMemc, $wgLang;
                if ( !$this->repo->fetchDescription ) {
                        return false;
                }
-               $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName() );
+               $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
                if ( $renderUrl ) {
+                       if ( $this->repo->descriptionCacheExpiry > 0 ) {
+                               wfDebug("Attempting to get the description from cache...");
+                               $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
+                                                                       $this->getName() );
+                               $obj = $wgMemc->get($key);
+                               if ($obj) {
+                                       wfDebug("success!\n");
+                                       return $obj;
+                               }
+                               wfDebug("miss\n");
+                       }
                        wfDebug( "Fetching shared description from $renderUrl\n" );
-                       return Http::get( $renderUrl );
+                       $res = Http::get( $renderUrl );
+                       if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
+                               $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
+                       }
+                       return $res;
                } else {
                        return false;
                }
        }
 
        /**
-        * Get the 14-character timestamp of the file upload, or false if 
+        * Get discription of file revision
+        * STUB
         */
-       function getTimestmap() {
+       function getDescription() {
+               return null;
+       }
+
+       /**
+        * Get the 14-character timestamp of the file upload, or false if
+        * it doesn't exist
+        */
+       function getTimestamp() {
                $path = $this->getPath();
                if ( !file_exists( $path ) ) {
                        return false;
                }
-               return wfTimestamp( filemtime( $path ) );
+               return wfTimestamp( TS_MW, filemtime( $path ) );
+       }
+
+       /**
+        * Get the SHA-1 base 36 hash of the file
+        */
+       function getSha1() {
+               return self::sha1Base36( $this->getPath() );
+       }
+
+       /**
+        * Get the deletion archive key, <sha1>.<ext>
+        */
+       function getStorageKey() {
+               $hash = $this->getSha1();
+               if ( !$hash ) {
+                       return false;
+               }
+               $ext = $this->getExtension();
+               $dotExt = $ext === '' ? '' : ".$ext";
+               return $hash . $dotExt;
        }
-       
+
        /**
         * Determine if the current user is allowed to view a particular
         * field of this file, if it's marked as deleted.
         * STUB
-        * @param int $field                                    
-        * @return bool
+        * @param $field Integer
+        * @return Boolean
         */
        function userCan( $field ) {
                return true;
        }
 
        /**
-        * Get an associative array containing information about a file in the local filesystem\
+        * Get an associative array containing information about a file in the local filesystem.
         *
-        * @param string $path Absolute local filesystem path
-        * @param mixed $ext The file extension, or true to extract it from the filename. 
-        *                   Set it to false to ignore the extension.
+        * @param $path String: absolute local filesystem path
+        * @param $ext Mixed: the file extension, or true to extract it from the filename.
+        *             Set it to false to ignore the extension.
         */
        static function getPropsFromPath( $path, $ext = true ) {
                wfProfileIn( __METHOD__ );
                wfDebug( __METHOD__.": Getting file info for $path\n" );
-               $info = array( 'fileExists' => file_exists( $path ) );
+               $info = array(
+                       'fileExists' => file_exists( $path ) && !is_dir( $path )
+               );
                $gis = false;
                if ( $info['fileExists'] ) {
                        $magic = MimeMagic::singleton();
 
-                       $info['mime'] = $magic->guessMimeType( $path, $ext );
+                       if ( $ext === true ) {
+                               $i = strrpos( $path, '.' );
+                               $ext = strtolower( $i ? substr( $path, $i + 1 ) : '' );
+                       }
+
+                       # mime type according to file contents
+                       $info['file-mime'] = $magic->guessMimeType( $path, false );
+                       # logical mime type
+                       $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
+
                        list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
                        $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
 
@@ -1026,18 +1204,20 @@ class File {
                        $handler = MediaHandler::getHandler( $info['mime'] );
                        if ( $handler ) {
                                $tempImage = (object)array();
-                               $gis = $handler->getImageSize( $tempImage, $path );
                                $info['metadata'] = $handler->getMetadata( $tempImage, $path );
+                               $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
                        } else {
                                $gis = false;
                                $info['metadata'] = '';
                        }
+                       $info['sha1'] = self::sha1Base36( $path );
 
                        wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
                } else {
-                       $info['mime'] = NULL;
+                       $info['mime'] = null;
                        $info['media_type'] = MEDIATYPE_UNKNOWN;
                        $info['metadata'] = '';
+                       $info['sha1'] = '';
                        wfDebug(__METHOD__.": $path NOT FOUND!\n");
                }
                if( $gis ) {
@@ -1057,6 +1237,79 @@ class File {
                wfProfileOut( __METHOD__ );
                return $info;
        }
-}
 
-?>
+       /**
+        * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
+        * encoding, zero padded to 31 digits.
+        *
+        * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
+        * fairly neatly.
+        *
+        * Returns false on failure
+        */
+       static function sha1Base36( $path ) {
+               wfSuppressWarnings();
+               $hash = sha1_file( $path );
+               wfRestoreWarnings();
+               if ( $hash === false ) {
+                       return false;
+               } else {
+                       return wfBaseConvert( $hash, 16, 36, 31 );
+               }
+       }
+
+       function getLongDesc() {
+               $handler = $this->getHandler();
+               if ( $handler ) {
+                       return $handler->getLongDesc( $this );
+               } else {
+                       return MediaHandler::getGeneralLongDesc( $this );
+               }
+       }
+
+       function getShortDesc() {
+               $handler = $this->getHandler();
+               if ( $handler ) {
+                       return $handler->getShortDesc( $this );
+               } else {
+                       return MediaHandler::getGeneralShortDesc( $this );
+               }
+       }
+
+       function getDimensionsString() {
+               $handler = $this->getHandler();
+               if ( $handler ) {
+                       return $handler->getDimensionsString( $this );
+               } else {
+                       return '';
+               }
+       }
+
+       function getRedirected() {
+               return $this->redirected;
+       }
+
+       function getRedirectedTitle() {
+               if ( $this->redirected ) {
+                       if ( !$this->redirectTitle ) {
+                               $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
+                       }
+                       return $this->redirectTitle;
+               }
+       }
+
+       function redirectedFrom( $from ) {
+               $this->redirected = $from;
+       }
+
+       function isMissing() {
+               return false;
+       }
+}
+/**
+ * Aliases for backwards compatibility with 1.6
+ */
+define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
+define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
+define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
+define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );