Some HipHop fixes:
[lhc/web/wiklou.git] / includes / filerepo / File.php
index c964d5a..0b5e374 100644 (file)
@@ -1,4 +1,10 @@
 <?php
+/**
+ * Base code for files.
+ *
+ * @file
+ * @ingroup FileRepo
+ */
 
 /**
  * Implements some public methods and some protected utility functions which
@@ -46,7 +52,23 @@ abstract class File {
        /**
         * The following member variables are not lazy-initialised
         */
-       var $repo, $title, $lastError, $redirected, $redirectedTitle;
+
+       /**
+        * @var LocalRepo
+        */
+       var $repo;
+
+       /**
+        * @var Title
+        */
+       var $title;
+
+       var $lastError, $redirected, $redirectedTitle;
+
+       /**
+        * @var MediaHandler
+        */
+       protected $handler;
 
        /**
         * Call this constructor from child classes
@@ -116,10 +138,10 @@ abstract 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 {
@@ -151,9 +173,10 @@ abstract class File {
 
        /**
         * Return the associated title object
+        * @return Title
         */
        public function getTitle() { return $this->title; }
-       
+
        /**
         * Return the title used to find this file
         */
@@ -177,7 +200,8 @@ abstract class File {
         * 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
+        *
+        * @return String
         */
        public function getFullUrl() {
                return wfExpandUrl( $this->getUrl() );
@@ -205,7 +229,8 @@ abstract 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.
+       * Most callers don't check the return value, but ForeignAPIFile::getPath
+       * returns false.
        */
        public function getPath() {
                if ( !isset( $this->path ) ) {
@@ -216,8 +241,11 @@ abstract class File {
 
        /**
        * Alias for getPath()
+       *
+       * @deprecated since 1.18 Use getPath().
        */
        public function getFullPath() {
+               wfDeprecated( __METHOD__ );
                return $this->getPath();
        }
 
@@ -259,6 +287,19 @@ abstract class File {
                }
        }
 
+       /**
+        *  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
@@ -266,6 +307,26 @@ abstract class File {
         */
        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
@@ -415,9 +476,8 @@ abstract class File {
         * 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() {
+       public function isVisible() {
                return $this->exists();
        }
 
@@ -437,35 +497,40 @@ abstract 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
+        * @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";
                }
@@ -484,8 +549,8 @@ abstract 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)
+        * @param $width Integer: maximum width of the generated thumbnail
+        * @param $height Integer: maximum height of the image (optional)
         */
        public function createThumb( $width, $height = -1 ) {
                $params = array( 'width' => $width );
@@ -497,39 +562,16 @@ abstract 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       Deprecated
-        *
-        * @return ThumbnailImage or null on failure
-        *
-        * @deprecated use transform()
-        */
-       public function getThumbnail( $width, $height=-1, $render = true ) {
-               $params = array( 'width' => $width );
-               if ( $height != -1 ) {
-                       $params['height'] = $height;
-               }
-               return $this->transform( $params, 0 );
-       }
-
        /**
         * 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 {
@@ -539,6 +581,12 @@ abstract class File {
                                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, if possible
@@ -554,16 +602,21 @@ abstract class File {
                        $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 );
 
@@ -576,9 +629,9 @@ abstract class File {
                                        $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
                                }
                        }
-                       
-                       // Purge. Useful in the event of Core -> Squid connection failure or squid 
-                       // purge collisions from elsewhere during failure. Don't keep triggering for 
+
+                       // 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 ) );
@@ -598,6 +651,7 @@ abstract class File {
 
        /**
         * Get a MediaHandler instance for this file
+        * @return MediaHandler
         */
        function getHandler() {
                if ( !isset( $this->handler ) ) {
@@ -831,19 +885,18 @@ abstract class File {
 
        /**
         * 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.
+        * 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:
+        * @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
@@ -852,46 +905,6 @@ abstract 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 = array() ) {
-               wfProfileIn( __METHOD__ );
-
-               // Note: use local DB not repo DB, we want to know local links
-               if ( count( $options ) > 0 ) {
-                       $db = wfGetDB( DB_MASTER );
-               } else {
-                       $db = wfGetDB( DB_SLAVE );
-               }
-               $linkCache = LinkCache::singleton();
-
-               $encName = $db->addQuotes( $this->getName() );
-               $res = $db->select( array( 'page', 'imagelinks'), 
-                                                       array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
-                                                       array( 'page_id' => 'il_from', 'il_to' => $encName ),
-                                                       __METHOD__,
-                                                       $options );
-
-               $retVal = array();
-               if ( $db->numRows( $res ) ) {
-                       while ( $row = $db->fetchObject( $res ) ) {
-                               if ( $titleObj = Title::newFromRow( $row ) ) {
-                                       $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
-                                       $retVal[] = $titleObj;
-                               }
-                       }
-               }
-               $db->freeResult( $res );
-               wfProfileOut( __METHOD__ );
-               return $retVal;
-       }
-
        function formatMetadata() {
                if ( !$this->getHandler() ) {
                        return false;
@@ -905,7 +918,8 @@ abstract class File {
         * @return bool
         */
        function isLocal() {
-               return $this->getRepoName() == 'local';
+               $repo = $this->getRepo();
+               return $repo && $repo->isLocal();
        }
 
        /**
@@ -916,6 +930,7 @@ abstract class File {
        function getRepoName() {
                return $this->repo ? $this->repo->getName() : 'unknown';
        }
+
        /*
         * Returns the repository
         */
@@ -938,11 +953,11 @@ abstract class File {
        function isDeleted( $field ) {
                return false;
        }
-       
+
        /**
         * Return the deletion bitfield
         * STUB
-        */     
+        */
        function getVisibility() {
                return 0;
        }
@@ -981,8 +996,8 @@ abstract class File {
         *
         * Cache purging is done; logging is caller's responsibility.
         *
-        * @param $reason
-        * @param $suppress, hide content from sysops?
+        * @param $reason String
+        * @param $suppress Boolean: hide content from sysops?
         * @return true on success, false on some kind of failure
         * STUB
         * Overridden by LocalFile
@@ -999,7 +1014,7 @@ abstract 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?
+        * @param $unsuppress remove restrictions on content upon restoration?
         * @return the number of file revisions restored if successful,
         *         or false on failure
         * STUB
@@ -1010,8 +1025,9 @@ abstract class File {
        }
 
        /**
-        * 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
         */
@@ -1020,7 +1036,7 @@ abstract class File {
        }
 
        /**
-        * 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() {
@@ -1047,11 +1063,11 @@ abstract class File {
        }
 
        /**
-        * 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() ) {
@@ -1080,7 +1096,7 @@ abstract class File {
                if ( $renderUrl ) {
                        if ( $this->repo->descriptionCacheExpiry > 0 ) {
                                wfDebug("Attempting to get the description from cache...");
-                               $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(), 
+                               $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
                                                                        $this->getName() );
                                $obj = $wgMemc->get($key);
                                if ($obj) {
@@ -1137,15 +1153,15 @@ abstract class File {
                }
                $ext = $this->getExtension();
                $dotExt = $ext === '' ? '' : ".$ext";
-               return $hash . $dotExt;                         
+               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;
@@ -1154,9 +1170,9 @@ abstract class File {
        /**
         * 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__ );
@@ -1168,7 +1184,16 @@ abstract class File {
                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'] );
 
@@ -1189,7 +1214,7 @@ abstract class File {
 
                        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'] = '';
@@ -1263,11 +1288,12 @@ abstract class File {
        function getRedirected() {
                return $this->redirected;
        }
-       
+
        function getRedirectedTitle() {
                if ( $this->redirected ) {
-                       if ( !$this->redirectTitle )
+                       if ( !$this->redirectTitle ) {
                                $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
+                       }
                        return $this->redirectTitle;
                }
        }