3 * @defgroup FileAbstraction File abstraction
6 * Represents files in a repository.
10 * Base code for files.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
28 * @ingroup FileAbstraction
32 * Implements some public methods and some protected utility functions which
33 * are required by multiple child classes. Contains stub functionality for
34 * unimplemented public methods.
36 * Stub functions which should be overridden are marked with STUB. Some more
37 * concrete functions are also typically overridden by child classes.
39 * Note that only the repo object knows what its file class is called. You should
40 * never name a file class explictly outside of the repo class. Instead use the
41 * repo's factory functions to generate file objects, for example:
43 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
45 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
48 * @ingroup FileAbstraction
50 abstract class File
implements IDBAccessObject
{
51 // Bitfield values akin to the Revision deletion constants
52 const DELETED_FILE
= 1;
53 const DELETED_COMMENT
= 2;
54 const DELETED_USER
= 4;
55 const DELETED_RESTRICTED
= 8;
57 /** Force rendering in the current process */
60 * Force rendering even if thumbnail already exist and using RENDER_NOW
61 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
63 const RENDER_FORCE
= 2;
65 const DELETE_SOURCE
= 1;
67 // Audience options for File::getDescription()
69 const FOR_THIS_USER
= 2;
72 // Options for File::thumbName()
73 const THUMB_FULL_NAME
= 1;
76 * Some member variables can be lazy-initialised using __get(). The
77 * initialisation function for these variables is always a function named
78 * like getVar(), where Var is the variable name with upper-case first
81 * The following variables are initialised in this way in this base class:
82 * name, extension, handler, path, canRender, isSafeFile,
83 * transformScript, hashPath, pageCount, url
85 * Code within this class should generally use the accessor function
86 * directly, since __get() isn't re-entrant and therefore causes bugs that
87 * depend on initialisation order.
91 * The following member variables are not lazy-initialised
94 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
97 /** @var Title|string|bool */
100 /** @var string Text of last error */
101 protected $lastError;
103 /** @var string Main part of the title, with underscores (Title::getDBkey) */
104 protected $redirected;
107 protected $redirectedTitle;
109 /** @var FSFile|bool False if undefined */
112 /** @var MediaHandler */
115 /** @var string The URL corresponding to one of the four basic zones */
118 /** @var string File extension */
119 protected $extension;
121 /** @var string The name of a file from its title object */
124 /** @var string The storage path corresponding to one of the zones */
127 /** @var string Relative path including trailing slash */
130 /** @var string Number of pages of a multipage document, or false for
131 * documents which aren't multipage documents
133 protected $pageCount;
135 /** @var string URL of transformscript (for example thumb.php) */
136 protected $transformScript;
139 protected $redirectTitle;
141 /** @var bool Whether the output of transform() for this file is likely to be valid. */
142 protected $canRender;
144 /** @var bool Whether this media file is in a format that is unlikely to
145 * contain viruses or malicious content
147 protected $isSafeFile;
149 /** @var string Required Repository class type */
150 protected $repoClass = 'FileRepo';
152 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
153 protected $tmpBucketedThumbCache = array();
156 * Call this constructor from child classes.
158 * Both $title and $repo are optional, though some functions
159 * may return false or throw exceptions if they are not set.
160 * Most subclasses will want to call assertRepoDefined() here.
162 * @param Title|string|bool $title
163 * @param FileRepo|bool $repo
165 function __construct( $title, $repo ) {
166 // Some subclasses do not use $title, but set name/title some other way
167 if ( $title !== false ) {
168 $title = self
::normalizeTitle( $title, 'exception' );
170 $this->title
= $title;
175 * Given a string or Title object return either a
176 * valid Title object with namespace NS_FILE or null
178 * @param Title|string $title
179 * @param string|bool $exception Use 'exception' to throw an error on bad titles
180 * @throws MWException
183 static function normalizeTitle( $title, $exception = false ) {
185 if ( $ret instanceof Title
) {
186 # Normalize NS_MEDIA -> NS_FILE
187 if ( $ret->getNamespace() == NS_MEDIA
) {
188 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
189 # Sanity check the title namespace
190 } elseif ( $ret->getNamespace() !== NS_FILE
) {
194 # Convert strings to Title objects
195 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
197 if ( !$ret && $exception !== false ) {
198 throw new MWException( "`$title` is not a valid file title." );
204 function __get( $name ) {
205 $function = array( $this, 'get' . ucfirst( $name ) );
206 if ( !is_callable( $function ) ) {
209 $this->$name = call_user_func( $function );
216 * Normalize a file extension to the common form, and ensure it's clean.
217 * Extensions with non-alphanumeric characters will be discarded.
219 * @param string $ext (without the .)
222 static function normalizeExtension( $ext ) {
223 $lower = strtolower( $ext );
230 if ( isset( $squish[$lower] ) ) {
231 return $squish[$lower];
232 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
240 * Checks if file extensions are compatible
242 * @param File $old Old file
243 * @param string $new New name
247 static function checkExtensionCompatibility( File
$old, $new ) {
248 $oldMime = $old->getMimeType();
249 $n = strrpos( $new, '.' );
250 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
251 $mimeMagic = MimeMagic
::singleton();
253 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
257 * Upgrade the database row if there is one
258 * Called by ImagePage
261 function upgradeRow() {
265 * Split an internet media type into its two components; if not
266 * a two-part name, set the minor type to 'unknown'.
268 * @param string $mime "text/html" etc
269 * @return array ("text", "html") etc
271 public static function splitMime( $mime ) {
272 if ( strpos( $mime, '/' ) !== false ) {
273 return explode( '/', $mime, 2 );
275 return array( $mime, 'unknown' );
280 * Callback for usort() to do file sorts by name
284 * @return int Result of name comparison
286 public static function compare( File
$a, File
$b ) {
287 return strcmp( $a->getName(), $b->getName() );
291 * Return the name of this file
295 public function getName() {
296 if ( !isset( $this->name
) ) {
297 $this->assertRepoDefined();
298 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
305 * Get the file extension, e.g. "svg"
309 function getExtension() {
310 if ( !isset( $this->extension
) ) {
311 $n = strrpos( $this->getName(), '.' );
312 $this->extension
= self
::normalizeExtension(
313 $n ?
substr( $this->getName(), $n +
1 ) : '' );
316 return $this->extension
;
320 * Return the associated title object
324 public function getTitle() {
329 * Return the title used to find this file
333 public function getOriginalTitle() {
334 if ( $this->redirected
) {
335 return $this->getRedirectedTitle();
342 * Return the URL of the file
346 public function getUrl() {
347 if ( !isset( $this->url
) ) {
348 $this->assertRepoDefined();
349 $ext = $this->getExtension();
350 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
357 * Return a fully-qualified URL to the file.
358 * Upload URL paths _may or may not_ be fully qualified, so
359 * we check. Local paths are assumed to belong on $wgServer.
363 public function getFullUrl() {
364 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
370 public function getCanonicalUrl() {
371 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
377 function getViewURL() {
378 if ( $this->mustRender() ) {
379 if ( $this->canRender() ) {
380 return $this->createThumb( $this->getWidth() );
382 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
383 ' (' . $this->getMimeType() . "), but can't!\n" );
385 return $this->getURL(); #hm... return NULL?
388 return $this->getURL();
393 * Return the storage path to the file. Note that this does
394 * not mean that a file actually exists under that location.
396 * This path depends on whether directory hashing is active or not,
397 * i.e. whether the files are all found in the same directory,
398 * or in hashed paths like /images/3/3c.
400 * Most callers don't check the return value, but ForeignAPIFile::getPath
403 * @return string|bool ForeignAPIFile::getPath can return false
405 public function getPath() {
406 if ( !isset( $this->path
) ) {
407 $this->assertRepoDefined();
408 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
415 * Get an FS copy or original of this file and return the path.
416 * Returns false on failure. Callers must not alter the file.
417 * Temporary files are cleared automatically.
419 * @return string|bool False on failure
421 public function getLocalRefPath() {
422 $this->assertRepoDefined();
423 if ( !isset( $this->fsFile
) ) {
424 $starttime = microtime( true );
425 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
426 RequestContext
::getMain()->getStats()->timing( 'media.thumbnail.generate.fetchoriginal', microtime( true ) - $starttime );
428 if ( !$this->fsFile
) {
429 $this->fsFile
= false; // null => false; cache negative hits
433 return ( $this->fsFile
)
434 ?
$this->fsFile
->getPath()
439 * Return the width of the image. Returns false if the width is unknown
443 * Overridden by LocalFile, UnregisteredLocalFile
448 public function getWidth( $page = 1 ) {
453 * Return the height of the image. Returns false if the height is unknown
457 * Overridden by LocalFile, UnregisteredLocalFile
460 * @return bool|int False on failure
462 public function getHeight( $page = 1 ) {
467 * Return the smallest bucket from $wgThumbnailBuckets which is at least
468 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
469 * will always be bigger than $desiredWidth.
471 * @param int $desiredWidth
475 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
476 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
478 $imageWidth = $this->getWidth( $page );
480 if ( $imageWidth === false ) {
484 if ( $desiredWidth > $imageWidth ) {
488 if ( !$wgThumbnailBuckets ) {
492 $sortedBuckets = $wgThumbnailBuckets;
494 sort( $sortedBuckets );
496 foreach ( $sortedBuckets as $bucket ) {
497 if ( $bucket >= $imageWidth ) {
501 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
506 // Image is bigger than any available bucket
511 * Returns ID or name of user who uploaded the file
514 * @param string $type 'text' or 'id'
517 public function getUser( $type = 'text' ) {
522 * Get the duration of a media file in seconds
526 public function getLength() {
527 $handler = $this->getHandler();
529 return $handler->getLength( $this );
536 * Return true if the file is vectorized
540 public function isVectorized() {
541 $handler = $this->getHandler();
543 return $handler->isVectorized( $this );
550 * Gives a (possibly empty) list of languages to render
553 * If the file doesn't have translations, or if the file
554 * format does not support that sort of thing, returns
560 public function getAvailableLanguages() {
561 $handler = $this->getHandler();
563 return $handler->getAvailableLanguages( $this );
570 * In files that support multiple language, what is the default language
571 * to use if none specified.
573 * @return string Lang code, or null if filetype doesn't support multiple languages.
576 public function getDefaultRenderLanguage() {
577 $handler = $this->getHandler();
579 return $handler->getDefaultRenderLanguage( $this );
586 * Will the thumbnail be animated if one would expect it to be.
588 * Currently used to add a warning to the image description page
590 * @return bool False if the main image is both animated
591 * and the thumbnail is not. In all other cases must return
592 * true. If image is not renderable whatsoever, should
595 public function canAnimateThumbIfAppropriate() {
596 $handler = $this->getHandler();
598 // We cannot handle image whatsoever, thus
599 // one would not expect it to be animated
603 if ( $this->allowInlineDisplay()
604 && $handler->isAnimatedImage( $this )
605 && !$handler->canAnimateThumbnail( $this )
607 // Image is animated, but thumbnail isn't.
608 // This is unexpected to the user.
611 // Image is not animated, so one would
612 // not expect thumb to be
619 * Get handler-specific metadata
620 * Overridden by LocalFile, UnregisteredLocalFile
624 public function getMetadata() {
629 * Like getMetadata but returns a handler independent array of common values.
630 * @see MediaHandler::getCommonMetaArray()
631 * @return array|bool Array or false if not supported
634 public function getCommonMetaArray() {
635 $handler = $this->getHandler();
641 return $handler->getCommonMetaArray( $this );
645 * get versioned metadata
647 * @param array|string $metadata Array or string of (serialized) metadata
648 * @param int $version Version number.
649 * @return array Array containing metadata, or what was passed to it on fail
650 * (unserializing if not array)
652 public function convertMetadataVersion( $metadata, $version ) {
653 $handler = $this->getHandler();
654 if ( !is_array( $metadata ) ) {
655 // Just to make the return type consistent
656 $metadata = unserialize( $metadata );
659 return $handler->convertMetadataVersion( $metadata, $version );
666 * Return the bit depth of the file
667 * Overridden by LocalFile
671 public function getBitDepth() {
676 * Return the size of the image file, in bytes
677 * Overridden by LocalFile, UnregisteredLocalFile
681 public function getSize() {
686 * Returns the MIME type of the file.
687 * Overridden by LocalFile, UnregisteredLocalFile
692 function getMimeType() {
693 return 'unknown/unknown';
697 * Return the type of the media in the file.
698 * Use the value returned by this function with the MEDIATYPE_xxx constants.
699 * Overridden by LocalFile,
703 function getMediaType() {
704 return MEDIATYPE_UNKNOWN
;
708 * Checks if the output of transform() for this file is likely
709 * to be valid. If this is false, various user elements will
710 * display a placeholder instead.
712 * Currently, this checks if the file is an image format
713 * that can be converted to a format
714 * supported by all browsers (namely GIF, PNG and JPEG),
715 * or if it is an SVG image and SVG conversion is enabled.
719 function canRender() {
720 if ( !isset( $this->canRender
) ) {
721 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this ) && $this->exists();
724 return $this->canRender
;
728 * Accessor for __get()
731 protected function getCanRender() {
732 return $this->canRender();
736 * Return true if the file is of a type that can't be directly
737 * rendered by typical browsers and needs to be re-rasterized.
739 * This returns true for everything but the bitmap types
740 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
741 * also return true for any non-image formats.
745 function mustRender() {
746 return $this->getHandler() && $this->handler
->mustRender( $this );
750 * Alias for canRender()
754 function allowInlineDisplay() {
755 return $this->canRender();
759 * Determines if this media file is in a format that is unlikely to
760 * contain viruses or malicious content. It uses the global
761 * $wgTrustedMediaFormats list to determine if the file is safe.
763 * This is used to show a warning on the description page of non-safe files.
764 * It may also be used to disallow direct [[media:...]] links to such files.
766 * Note that this function will always return true if allowInlineDisplay()
767 * or isTrustedFile() is true for this file.
771 function isSafeFile() {
772 if ( !isset( $this->isSafeFile
) ) {
773 $this->isSafeFile
= $this->getIsSafeFileUncached();
776 return $this->isSafeFile
;
780 * Accessor for __get()
784 protected function getIsSafeFile() {
785 return $this->isSafeFile();
793 protected function getIsSafeFileUncached() {
794 global $wgTrustedMediaFormats;
796 if ( $this->allowInlineDisplay() ) {
799 if ( $this->isTrustedFile() ) {
803 $type = $this->getMediaType();
804 $mime = $this->getMimeType();
805 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
807 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
808 return false; #unknown type, not trusted
810 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
814 if ( $mime === "unknown/unknown" ) {
815 return false; #unknown type, not trusted
817 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
825 * Returns true if the file is flagged as trusted. Files flagged that way
826 * can be linked to directly, even if that is not allowed for this type of
829 * This is a dummy function right now and always returns false. It could be
830 * implemented to extract a flag from the database. The trusted flag could be
831 * set on upload, if the user has sufficient privileges, to bypass script-
832 * and html-filters. It may even be coupled with cryptographics signatures
837 function isTrustedFile() {
838 #this could be implemented to check a flag in the database,
839 #look for signatures, etc
844 * Load any lazy-loaded file object fields from source
846 * This is only useful when setting $flags
848 * Overridden by LocalFile to actually query the DB
850 * @param integer $flags Bitfield of File::READ_* constants
852 public function load( $flags = 0 ) {
856 * Returns true if file exists in the repository.
858 * Overridden by LocalFile to avoid unnecessary stat calls.
860 * @return bool Whether file exists in the repository.
862 public function exists() {
863 return $this->getPath() && $this->repo
->fileExists( $this->path
);
867 * Returns true if file exists in the repository and can be included in a page.
868 * It would be unsafe to include private images, making public thumbnails inadvertently
870 * @return bool Whether file exists in the repository and is includable.
872 public function isVisible() {
873 return $this->exists();
879 function getTransformScript() {
880 if ( !isset( $this->transformScript
) ) {
881 $this->transformScript
= false;
883 $script = $this->repo
->getThumbScriptUrl();
885 $this->transformScript
= wfAppendQuery( $script, array( 'f' => $this->getName() ) );
890 return $this->transformScript
;
894 * Get a ThumbnailImage which is the same size as the source
896 * @param array $handlerParams
900 function getUnscaledThumb( $handlerParams = array() ) {
901 $hp =& $handlerParams;
902 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
903 $width = $this->getWidth( $page );
905 return $this->iconThumb();
907 $hp['width'] = $width;
908 // be sure to ignore any height specification as well (bug 62258)
909 unset( $hp['height'] );
911 return $this->transform( $hp );
915 * Return the file name of a thumbnail with the specified parameters.
916 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
917 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
919 * @param array $params Handler-specific parameters
920 * @param int $flags Bitfield that supports THUMB_* constants
923 public function thumbName( $params, $flags = 0 ) {
924 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
925 ?
$this->repo
->nameForThumb( $this->getName() )
928 return $this->generateThumbName( $name, $params );
932 * Generate a thumbnail file name from a name and specified parameters
934 * @param string $name
935 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
938 public function generateThumbName( $name, $params ) {
939 if ( !$this->getHandler() ) {
942 $extension = $this->getExtension();
943 list( $thumbExt, ) = $this->getHandler()->getThumbType(
944 $extension, $this->getMimeType(), $params );
945 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $name;
946 if ( $thumbExt != $extension ) {
947 $thumbName .= ".$thumbExt";
954 * Create a thumbnail of the image having the specified width/height.
955 * The thumbnail will not be created if the width is larger than the
956 * image's width. Let the browser do the scaling in this case.
957 * The thumbnail is stored on disk and is only computed if the thumbnail
958 * file does not exist OR if it is older than the image.
961 * Keeps aspect ratio of original image. If both width and height are
962 * specified, the generated image will be no bigger than width x height,
963 * and will also have correct aspect ratio.
965 * @param int $width Maximum width of the generated thumbnail
966 * @param int $height Maximum height of the image (optional)
970 public function createThumb( $width, $height = -1 ) {
971 $params = array( 'width' => $width );
972 if ( $height != -1 ) {
973 $params['height'] = $height;
975 $thumb = $this->transform( $params );
976 if ( !$thumb ||
$thumb->isError() ) {
980 return $thumb->getUrl();
984 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
986 * @param string $thumbPath Thumbnail storage path
987 * @param string $thumbUrl Thumbnail URL
988 * @param array $params
990 * @return MediaTransformOutput
992 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
993 global $wgIgnoreImageErrors;
995 $handler = $this->getHandler();
996 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
997 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
999 return new MediaTransformError( 'thumbnail_error',
1000 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
1005 * Transform a media file
1007 * @param array $params An associative array of handler-specific parameters.
1008 * Typical keys are width, height and page.
1009 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1010 * @return MediaTransformOutput|bool False on failure
1012 function transform( $params, $flags = 0 ) {
1013 global $wgThumbnailEpoch;
1016 if ( !$this->canRender() ) {
1017 $thumb = $this->iconThumb();
1018 break; // not a bitmap or renderable image, don't try
1021 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
1022 $descriptionUrl = $this->getDescriptionUrl();
1023 if ( $descriptionUrl ) {
1024 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
1027 $handler = $this->getHandler();
1028 $script = $this->getTransformScript();
1029 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
1030 // Use a script to transform on client request, if possible
1031 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1037 $normalisedParams = $params;
1038 $handler->normaliseParams( $this, $normalisedParams );
1040 $thumbName = $this->thumbName( $normalisedParams );
1041 $thumbUrl = $this->getThumbUrl( $thumbName );
1042 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1044 if ( $this->repo
) {
1045 // Defer rendering if a 404 handler is set up...
1046 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
1047 wfDebug( __METHOD__
. " transformation deferred.\n" );
1048 // XXX: Pass in the storage path even though we are not rendering anything
1049 // and the path is supposed to be an FS path. This is due to getScalerType()
1050 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1051 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1054 // Check if an up-to-date thumbnail already exists...
1055 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
1056 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
1057 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
1058 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1059 // XXX: Pass in the storage path even though we are not rendering anything
1060 // and the path is supposed to be an FS path. This is due to getScalerType()
1061 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1062 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1063 $thumb->setStoragePath( $thumbPath );
1066 } elseif ( $flags & self
::RENDER_FORCE
) {
1067 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1070 // If the backend is ready-only, don't keep generating thumbnails
1071 // only to return transformation errors, just return the error now.
1072 if ( $this->repo
->getReadOnlyReason() !== false ) {
1073 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1078 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1081 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1083 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1087 return is_object( $thumb ) ?
$thumb : false;
1091 * Generates a thumbnail according to the given parameters and saves it to storage
1092 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1093 * @param array $transformParams
1095 * @return bool|MediaTransformOutput
1097 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1098 global $wgIgnoreImageErrors;
1100 $stats = RequestContext
::getMain()->getStats();
1102 $handler = $this->getHandler();
1104 $normalisedParams = $transformParams;
1105 $handler->normaliseParams( $this, $normalisedParams );
1107 $thumbName = $this->thumbName( $normalisedParams );
1108 $thumbUrl = $this->getThumbUrl( $thumbName );
1109 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1111 $tmpThumbPath = $tmpFile->getPath();
1113 if ( $handler->supportsBucketing() ) {
1114 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1117 $starttime = microtime( true );
1119 // Actually render the thumbnail...
1120 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1121 $tmpFile->bind( $thumb ); // keep alive with $thumb
1123 $stats->timing( 'media.thumbnail.generate.transform', microtime( true ) - $starttime );
1125 if ( !$thumb ) { // bad params?
1127 } elseif ( $thumb->isError() ) { // transform error
1128 $this->lastError
= $thumb->toText();
1129 // Ignore errors if requested
1130 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1131 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1133 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1134 // Copy the thumbnail from the file system into storage...
1136 $starttime = microtime( true );
1138 $disposition = $this->getThumbDisposition( $thumbName );
1139 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1140 if ( $status->isOK() ) {
1141 $thumb->setStoragePath( $thumbPath );
1143 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1146 $stats->timing( 'media.thumbnail.generate.store', microtime( true ) - $starttime );
1148 // Give extensions a chance to do something with this thumbnail...
1149 Hooks
::run( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1152 wfDebugLog( 'thumbnailaccess', time() . ' ' . $thumbPath . ' ' . filesize( $tmpThumbPath ) . ' Generated ' );
1158 * Generates chained bucketed thumbnails if needed
1159 * @param array $params
1161 * @return bool Whether at least one bucket was generated
1163 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1165 ||
!isset( $params['physicalWidth'] )
1166 ||
!isset( $params['physicalHeight'] )
1167 ||
!( $bucket = $this->getThumbnailBucket( $params['physicalWidth'] ) )
1168 ||
$bucket == $params['physicalWidth'] ) {
1172 $bucketPath = $this->getBucketThumbPath( $bucket );
1174 if ( $this->repo
->fileExists( $bucketPath ) ) {
1178 $starttime = microtime( true );
1180 $params['physicalWidth'] = $bucket;
1181 $params['width'] = $bucket;
1183 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1185 $bucketName = $this->getBucketThumbName( $bucket );
1187 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1193 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1195 $buckettime = microtime( true ) - $starttime;
1197 if ( !$thumb ||
$thumb->isError() ) {
1201 $this->tmpBucketedThumbCache
[$bucket] = $tmpFile->getPath();
1202 // For the caching to work, we need to make the tmp file survive as long as
1203 // this object exists
1204 $tmpFile->bind( $this );
1206 RequestContext
::getMain()->getStats()->timing( 'media.thumbnail.generate.bucket', $buckettime );
1212 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1213 * @param array $params
1214 * @return array Source path and width/height of the source
1216 public function getThumbnailSource( $params ) {
1218 && $this->getHandler()->supportsBucketing()
1219 && isset( $params['physicalWidth'] )
1220 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1222 if ( $this->getWidth() != 0 ) {
1223 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1228 // Try to avoid reading from storage if the file was generated by this script
1229 if ( isset( $this->tmpBucketedThumbCache
[$bucket] ) ) {
1230 $tmpPath = $this->tmpBucketedThumbCache
[$bucket];
1232 if ( file_exists( $tmpPath ) ) {
1236 'height' => $bucketHeight
1241 $bucketPath = $this->getBucketThumbPath( $bucket );
1243 if ( $this->repo
->fileExists( $bucketPath ) ) {
1244 $fsFile = $this->repo
->getLocalReference( $bucketPath );
1248 'path' => $fsFile->getPath(),
1250 'height' => $bucketHeight
1256 // Thumbnailing a very large file could result in network saturation if
1257 // everyone does it at once.
1258 if ( $this->getSize() >= 1e7
) { // 10MB
1260 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1262 'doWork' => function () use ( $that ) {
1263 return $that->getLocalRefPath();
1267 $srcPath = $work->execute();
1269 $srcPath = $this->getLocalRefPath();
1275 'width' => $this->getWidth(),
1276 'height' => $this->getHeight()
1281 * Returns the repo path of the thumb for a given bucket
1282 * @param int $bucket
1285 protected function getBucketThumbPath( $bucket ) {
1286 $thumbName = $this->getBucketThumbName( $bucket );
1287 return $this->getThumbPath( $thumbName );
1291 * Returns the name of the thumb for a given bucket
1292 * @param int $bucket
1295 protected function getBucketThumbName( $bucket ) {
1296 return $this->thumbName( array( 'physicalWidth' => $bucket ) );
1300 * Creates a temp FS file with the same extension and the thumbnail
1301 * @param string $thumbPath Thumbnail path
1302 * @return TempFSFile
1304 protected function makeTransformTmpFile( $thumbPath ) {
1305 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1306 return TempFSFile
::factory( 'transform_', $thumbExt );
1310 * @param string $thumbName Thumbnail name
1311 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1312 * @return string Content-Disposition header value
1314 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1315 $fileName = $this->name
; // file name to suggest
1316 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1317 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1318 $fileName .= ".$thumbExt";
1321 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1325 * Hook into transform() to allow migration of thumbnail files
1327 * Overridden by LocalFile
1328 * @param string $thumbName
1330 function migrateThumbFile( $thumbName ) {
1334 * Get a MediaHandler instance for this file
1336 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1337 * or false if none found
1339 function getHandler() {
1340 if ( !isset( $this->handler
) ) {
1341 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1344 return $this->handler
;
1348 * Get a ThumbnailImage representing a file type icon
1350 * @return ThumbnailImage
1352 function iconThumb() {
1353 global $wgResourceBasePath, $IP;
1354 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1355 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1357 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1358 foreach ( $try as $icon ) {
1359 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1360 $params = array( 'width' => 120, 'height' => 120 );
1362 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1370 * Get last thumbnailing error.
1374 function getLastError() {
1375 return $this->lastError
;
1379 * Get all thumbnail names previously generated for this file
1381 * Overridden by LocalFile
1384 function getThumbnails() {
1389 * Purge shared caches such as thumbnails and DB data caching
1391 * Overridden by LocalFile
1392 * @param array $options Options, which include:
1393 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1395 function purgeCache( $options = array() ) {
1399 * Purge the file description page, but don't go after
1400 * pages using the file. Use when modifying file history
1401 * but not the current data.
1403 function purgeDescription() {
1404 $title = $this->getTitle();
1406 $title->invalidateCache();
1407 $title->purgeSquid();
1412 * Purge metadata and all affected pages when the file is created,
1413 * deleted, or majorly updated.
1415 function purgeEverything() {
1416 // Delete thumbnails and refresh file metadata cache
1417 $this->purgeCache();
1418 $this->purgeDescription();
1420 // Purge cache of all pages using this file
1421 $title = $this->getTitle();
1423 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1424 $update->doUpdate();
1429 * Return a fragment of the history of file.
1432 * @param int $limit Limit of rows to return
1433 * @param string $start Only revisions older than $start will be returned
1434 * @param string $end Only revisions newer than $end will be returned
1435 * @param bool $inc Include the endpoints of the time range
1439 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1444 * Return the history of this file, line by line. Starts with current version,
1445 * then old versions. Should return an object similar to an image/oldimage
1449 * Overridden in LocalFile
1452 public function nextHistoryLine() {
1457 * Reset the history pointer to the first element of the history.
1458 * Always call this function after using nextHistoryLine() to free db resources
1460 * Overridden in LocalFile.
1462 public function resetHistory() {
1466 * Get the filename hash component of the directory including trailing slash,
1468 * If the repository is not hashed, returns an empty string.
1472 function getHashPath() {
1473 if ( !isset( $this->hashPath
) ) {
1474 $this->assertRepoDefined();
1475 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1478 return $this->hashPath
;
1482 * Get the path of the file relative to the public zone root.
1483 * This function is overridden in OldLocalFile to be like getArchiveRel().
1488 return $this->getHashPath() . $this->getName();
1492 * Get the path of an archived file relative to the public zone root
1494 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1498 function getArchiveRel( $suffix = false ) {
1499 $path = 'archive/' . $this->getHashPath();
1500 if ( $suffix === false ) {
1501 $path = substr( $path, 0, -1 );
1510 * Get the path, relative to the thumbnail zone root, of the
1511 * thumbnail directory or a particular file if $suffix is specified
1513 * @param bool|string $suffix If not false, the name of a thumbnail file
1516 function getThumbRel( $suffix = false ) {
1517 $path = $this->getRel();
1518 if ( $suffix !== false ) {
1519 $path .= '/' . $suffix;
1526 * Get urlencoded path of the file relative to the public zone root.
1527 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1531 function getUrlRel() {
1532 return $this->getHashPath() . rawurlencode( $this->getName() );
1536 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1537 * or a specific thumb if the $suffix is given.
1539 * @param string $archiveName The timestamped name of an archived image
1540 * @param bool|string $suffix If not false, the name of a thumbnail file
1543 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1544 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1545 if ( $suffix === false ) {
1546 $path = substr( $path, 0, -1 );
1555 * Get the path of the archived file.
1557 * @param bool|string $suffix If not false, the name of an archived file.
1560 function getArchivePath( $suffix = false ) {
1561 $this->assertRepoDefined();
1563 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1567 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1569 * @param string $archiveName The timestamped name of an archived image
1570 * @param bool|string $suffix If not false, the name of a thumbnail file
1573 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1574 $this->assertRepoDefined();
1576 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1577 $this->getArchiveThumbRel( $archiveName, $suffix );
1581 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1583 * @param bool|string $suffix If not false, the name of a thumbnail file
1586 function getThumbPath( $suffix = false ) {
1587 $this->assertRepoDefined();
1589 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1593 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1595 * @param bool|string $suffix If not false, the name of a media file
1598 function getTranscodedPath( $suffix = false ) {
1599 $this->assertRepoDefined();
1601 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1605 * Get the URL of the archive directory, or a particular file if $suffix is specified
1607 * @param bool|string $suffix If not false, the name of an archived file
1610 function getArchiveUrl( $suffix = false ) {
1611 $this->assertRepoDefined();
1612 $ext = $this->getExtension();
1613 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1614 if ( $suffix === false ) {
1615 $path = substr( $path, 0, -1 );
1617 $path .= rawurlencode( $suffix );
1624 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1626 * @param string $archiveName The timestamped name of an archived image
1627 * @param bool|string $suffix If not false, the name of a thumbnail file
1630 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1631 $this->assertRepoDefined();
1632 $ext = $this->getExtension();
1633 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1634 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1635 if ( $suffix === false ) {
1636 $path = substr( $path, 0, -1 );
1638 $path .= rawurlencode( $suffix );
1645 * Get the URL of the zone directory, or a particular file if $suffix is specified
1647 * @param string $zone Name of requested zone
1648 * @param bool|string $suffix If not false, the name of a file in zone
1649 * @return string Path
1651 function getZoneUrl( $zone, $suffix = false ) {
1652 $this->assertRepoDefined();
1653 $ext = $this->getExtension();
1654 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1655 if ( $suffix !== false ) {
1656 $path .= '/' . rawurlencode( $suffix );
1663 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1665 * @param bool|string $suffix If not false, the name of a thumbnail file
1666 * @return string Path
1668 function getThumbUrl( $suffix = false ) {
1669 return $this->getZoneUrl( 'thumb', $suffix );
1673 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1675 * @param bool|string $suffix If not false, the name of a media file
1676 * @return string Path
1678 function getTranscodedUrl( $suffix = false ) {
1679 return $this->getZoneUrl( 'transcoded', $suffix );
1683 * Get the public zone virtual URL for a current version source file
1685 * @param bool|string $suffix If not false, the name of a thumbnail file
1688 function getVirtualUrl( $suffix = false ) {
1689 $this->assertRepoDefined();
1690 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1691 if ( $suffix !== false ) {
1692 $path .= '/' . rawurlencode( $suffix );
1699 * Get the public zone virtual URL for an archived version source file
1701 * @param bool|string $suffix If not false, the name of a thumbnail file
1704 function getArchiveVirtualUrl( $suffix = false ) {
1705 $this->assertRepoDefined();
1706 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1707 if ( $suffix === false ) {
1708 $path = substr( $path, 0, -1 );
1710 $path .= rawurlencode( $suffix );
1717 * Get the virtual URL for a thumbnail file or directory
1719 * @param bool|string $suffix If not false, the name of a thumbnail file
1722 function getThumbVirtualUrl( $suffix = false ) {
1723 $this->assertRepoDefined();
1724 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1725 if ( $suffix !== false ) {
1726 $path .= '/' . rawurlencode( $suffix );
1735 function isHashed() {
1736 $this->assertRepoDefined();
1738 return (bool)$this->repo
->getHashLevels();
1742 * @throws MWException
1744 function readOnlyError() {
1745 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1749 * Record a file upload in the upload log and the image table
1751 * Overridden by LocalFile
1752 * @param string $oldver
1753 * @param string $desc
1754 * @param string $license
1755 * @param string $copyStatus
1756 * @param string $source
1757 * @param bool $watch
1758 * @param string|bool $timestamp
1759 * @param null|User $user User object or null to use $wgUser
1761 * @throws MWException
1763 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1764 $watch = false, $timestamp = false, User
$user = null
1766 $this->readOnlyError();
1770 * Move or copy a file to its public location. If a file exists at the
1771 * destination, move it to an archive. Returns a FileRepoStatus object with
1772 * the archive name in the "value" member on success.
1774 * The archive name should be passed through to recordUpload for database
1777 * Options to $options include:
1778 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1780 * @param string $srcPath Local filesystem path to the source image
1781 * @param int $flags A bitwise combination of:
1782 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1783 * @param array $options Optional additional parameters
1784 * @return FileRepoStatus On success, the value member contains the
1785 * archive name, or an empty string if it was a new file.
1788 * Overridden by LocalFile
1790 function publish( $srcPath, $flags = 0, array $options = array() ) {
1791 $this->readOnlyError();
1795 * @param bool|IContextSource $context Context to use (optional)
1798 function formatMetadata( $context = false ) {
1799 if ( !$this->getHandler() ) {
1803 return $this->getHandler()->formatMetadata( $this, $context );
1807 * Returns true if the file comes from the local file repository.
1811 function isLocal() {
1812 return $this->repo
&& $this->repo
->isLocal();
1816 * Returns the name of the repository.
1820 function getRepoName() {
1821 return $this->repo ?
$this->repo
->getName() : 'unknown';
1825 * Returns the repository
1827 * @return FileRepo|LocalRepo|bool
1829 function getRepo() {
1834 * Returns true if the image is an old version
1844 * Is this file a "deleted" file in a private archive?
1847 * @param int $field One of DELETED_* bitfield constants
1850 function isDeleted( $field ) {
1855 * Return the deletion bitfield
1859 function getVisibility() {
1864 * Was this file ever deleted from the wiki?
1868 function wasDeleted() {
1869 $title = $this->getTitle();
1871 return $title && $title->isDeletedQuick();
1875 * Move file to the new title
1877 * Move current, old version and all thumbnails
1878 * to the new filename. Old file is deleted.
1880 * Cache purging is done; checks for validity
1881 * and logging are caller's responsibility
1883 * @param Title $target New file name
1884 * @return FileRepoStatus
1886 function move( $target ) {
1887 $this->readOnlyError();
1891 * Delete all versions of the file.
1893 * Moves the files into an archive directory (or deletes them)
1894 * and removes the database rows.
1896 * Cache purging is done; logging is caller's responsibility.
1898 * @param string $reason
1899 * @param bool $suppress Hide content from sysops?
1900 * @param User|null $user
1901 * @return bool Boolean on success, false on some kind of failure
1903 * Overridden by LocalFile
1905 function delete( $reason, $suppress = false, $user = null ) {
1906 $this->readOnlyError();
1910 * Restore all or specified deleted revisions to the given file.
1911 * Permissions and logging are left to the caller.
1913 * May throw database exceptions on error.
1915 * @param array $versions Set of record ids of deleted items to restore,
1916 * or empty to restore all revisions.
1917 * @param bool $unsuppress Remove restrictions on content upon restoration?
1918 * @return int|bool The number of file revisions restored if successful,
1919 * or false on failure
1921 * Overridden by LocalFile
1923 function restore( $versions = array(), $unsuppress = false ) {
1924 $this->readOnlyError();
1928 * Returns 'true' if this file is a type which supports multiple pages,
1929 * e.g. DJVU or PDF. Note that this may be true even if the file in
1930 * question only has a single page.
1934 function isMultipage() {
1935 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1939 * Returns the number of pages of a multipage document, or false for
1940 * documents which aren't multipage documents
1944 function pageCount() {
1945 if ( !isset( $this->pageCount
) ) {
1946 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1947 $this->pageCount
= $this->handler
->pageCount( $this );
1949 $this->pageCount
= false;
1953 return $this->pageCount
;
1957 * Calculate the height of a thumbnail using the source and destination width
1959 * @param int $srcWidth
1960 * @param int $srcHeight
1961 * @param int $dstWidth
1965 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1966 // Exact integer multiply followed by division
1967 if ( $srcWidth == 0 ) {
1970 return round( $srcHeight * $dstWidth / $srcWidth );
1975 * Get an image size array like that returned by getImageSize(), or false if it
1976 * can't be determined. Loads the image size directly from the file ignoring caches.
1978 * @note Use getWidth()/getHeight() instead of this method unless you have a
1979 * a good reason. This method skips all caches.
1981 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
1982 * @return array The width, followed by height, with optionally more things after
1984 function getImageSize( $filePath ) {
1985 if ( !$this->getHandler() ) {
1989 return $this->getHandler()->getImageSize( $this, $filePath );
1993 * Get the URL of the image description page. May return false if it is
1994 * unknown or not applicable.
1998 function getDescriptionUrl() {
1999 if ( $this->repo
) {
2000 return $this->repo
->getDescriptionUrl( $this->getName() );
2007 * Get the HTML text of the description page, if available
2009 * @param bool|Language $lang Optional language to fetch description in
2012 function getDescriptionText( $lang = false ) {
2013 global $wgMemc, $wgLang;
2014 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
2020 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2022 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
2023 wfDebug( "Attempting to get the description from cache..." );
2024 $key = $this->repo
->getLocalCacheKey(
2025 'RemoteFileDescription',
2030 $obj = $wgMemc->get( $key );
2032 wfDebug( "success!\n" );
2036 wfDebug( "miss\n" );
2038 wfDebug( "Fetching shared description from $renderUrl\n" );
2039 $res = Http
::get( $renderUrl, array(), __METHOD__
);
2040 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
2041 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
2051 * Get description of file revision
2054 * @param int $audience One of:
2055 * File::FOR_PUBLIC to be displayed to all users
2056 * File::FOR_THIS_USER to be displayed to the given user
2057 * File::RAW get the description regardless of permissions
2058 * @param User $user User object to check for, only if FOR_THIS_USER is
2059 * passed to the $audience parameter
2062 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2067 * Get the 14-character timestamp of the file upload
2069 * @return string|bool TS_MW timestamp or false on failure
2071 function getTimestamp() {
2072 $this->assertRepoDefined();
2074 return $this->repo
->getFileTimestamp( $this->getPath() );
2078 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2079 * Returns false if the file does not have a description page, or retrieving the timestamp
2080 * would be expensive.
2082 * @return string|bool
2084 public function getDescriptionTouched() {
2089 * Get the SHA-1 base 36 hash of the file
2093 function getSha1() {
2094 $this->assertRepoDefined();
2096 return $this->repo
->getFileSha1( $this->getPath() );
2100 * Get the deletion archive key, "<sha1>.<ext>"
2104 function getStorageKey() {
2105 $hash = $this->getSha1();
2109 $ext = $this->getExtension();
2110 $dotExt = $ext === '' ?
'' : ".$ext";
2112 return $hash . $dotExt;
2116 * Determine if the current user is allowed to view a particular
2117 * field of this file, if it's marked as deleted.
2120 * @param User $user User object to check, or null to use $wgUser
2123 function userCan( $field, User
$user = null ) {
2128 * @return array HTTP header name/value map to use for HEAD/GET request responses
2130 function getStreamHeaders() {
2131 $handler = $this->getHandler();
2133 return $handler->getStreamHeaders( $this->getMetadata() );
2142 function getLongDesc() {
2143 $handler = $this->getHandler();
2145 return $handler->getLongDesc( $this );
2147 return MediaHandler
::getGeneralLongDesc( $this );
2154 function getShortDesc() {
2155 $handler = $this->getHandler();
2157 return $handler->getShortDesc( $this );
2159 return MediaHandler
::getGeneralShortDesc( $this );
2166 function getDimensionsString() {
2167 $handler = $this->getHandler();
2169 return $handler->getDimensionsString( $this );
2178 function getRedirected() {
2179 return $this->redirected
;
2183 * @return Title|null
2185 function getRedirectedTitle() {
2186 if ( $this->redirected
) {
2187 if ( !$this->redirectTitle
) {
2188 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
2191 return $this->redirectTitle
;
2198 * @param string $from
2201 function redirectedFrom( $from ) {
2202 $this->redirected
= $from;
2208 function isMissing() {
2213 * Check if this file object is small and can be cached
2216 public function isCacheable() {
2221 * Assert that $this->repo is set to a valid FileRepo instance
2222 * @throws MWException
2224 protected function assertRepoDefined() {
2225 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2226 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2231 * Assert that $this->title is set to a Title
2232 * @throws MWException
2234 protected function assertTitleDefined() {
2235 if ( !( $this->title
instanceof Title
) ) {
2236 throw new MWException( "A Title object is not set for this File.\n" );
2241 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2244 public function isExpensiveToThumbnail() {
2245 $handler = $this->getHandler();
2246 return $handler ?
$handler->isExpensiveToThumbnail( $this ) : false;
2250 * Whether the thumbnails created on the same server as this code is running.
2254 public function isTransformedLocally() {